carlos / platform Public

host: put a changed demo build budget on the live slice

Astra R1 on 0507790d: daemon-reload changes systemd's view of an
active slice but not its kernel limits. The root-runner witness on
systemd 257 confirmed it (run 20261109T175646-38a709).

- applyDemoSliceBudget sets the rendered budget with systemctl
  set-property --runtime, which reaches the cgroup at once.
- Adopt: apply it before writing the slice; a failure returns before
  the write, so the next pass still sees the difference.
- Adopt: also compare systemd's loaded MemoryMax/TasksMax, so a pass
  whose daemon-reload failed is retried (R1 P2).
- Apply: a changed slice gets the budget after its reload; on failure
  the old file goes back for the adopt pass.

Root witness TestRootDemoSliceBudgetReachesActiveSlice passed on an
active slice in both flip directions (run 20261109T181216-7ed07c).
Census re-proposed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 532ebcf55dbd836180b5c61765be347e718d9f26 parent 0507790
9 files changed, +377 −12
  • docs/superpowers/notes/census-proposal-demo-slice-adopt.md +4 −2
  • internal/host/demo_slice_adopt_linux_test.go +154 −1
  • internal/host/demo_slice_reload_rootrunner_linux_test.go +116 −0
  • internal/host/runsc_update_dirs_linux_test.go +4 −0
  • internal/host/systemapply.go +16 −0
  • internal/host/systemunits.go +71 −1
  • internal/host/systemunits_test.go +5 −3
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −1
  • internal/provision/testdata/plan14-root-reads-demo-slice-adopt.tsv +6 −4

CI passed — run details

diff --git a/docs/superpowers/notes/census-proposal-demo-slice-adopt.md b/docs/superpowers/notes/census-proposal-demo-slice-adopt.md
index 9c8a2f6d1..0ffbcd986 100644
--- a/docs/superpowers/notes/census-proposal-demo-slice-adopt.md
+++ b/docs/superpowers/notes/census-proposal-demo-slice-adopt.md
@@ -4,7 +4,8 @@ Ruling `census-ruling-demo-slice-adopt`. The independent reviewer approves or re
| unit | change | read sites | what changed |
|---|---|---|---|
-| `internal/host/systemunits.go` `ensureSystemUnitsWithGuard` | sites | +file:ReadFile ×2 | Read the embedded carlos-demo-builds.slice and the installed one at the fixed unit path (/etc/systemd/system), compare it with its host.env rendering, and treat a difference as a reinstall (the existing write loop and daemon-reload). No new path, input, systemctl verb or write target; the slice is root-owned and rendered only from the already-parsed claim settings. |
+| `internal/host/systemapply.go` `systemApplier.installUnits` | sites | +file:ReadFile ×2 | Read the installed carlos-demo-builds.slice before the install (fixed root unit path); when the installed slice changed, set its rendered budget on the live slice (systemctl set-property --runtime, fixed name) and on failure write the earlier bytes back. No new path or input; values come from the rendering this function already wrote. |
+| `internal/host/systemunits.go` `ensureSystemUnitsWithGuard` | sites | +file:ReadFile ×2 | Compare the installed carlos-demo-builds.slice (fixed root unit path, embedded unit) with its host.env rendering, and ask systemd for the slice's loaded MemoryMax/TasksMax (systemctl show on the fixed slice name); a definite difference is a reinstall. Before writing, put the rendered budget on the live slice with systemctl set-property --runtime on that fixed name, through the same permit-wrapped systemctl. No new path, input or write target; values come only from the already-parsed claim settings. |
Envelopes re-pinned: `internal/host`.
@@ -12,8 +13,9 @@ Review: a model from the other family than the author reads the branch's diff ag
Recorded dispositions, which each change must still satisfy:
+- `internal/host/systemapply.go` `systemApplier.installUnits`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-agent-start-demo-1;basis=Renders the staged build slice against live root host configuration; preserves it when settings cannot be parsed.;rev3=census-ruling-region-ha-p3b;basis=Require group apply/rollback permit, preserve root Restart=no/nftables drop-in and masks, and skip automatic update/recovery units. Existing staged unit and host.env reads remain; new indirect marker/permit reads are protected and agent receipts are excluded.;rev3=census-ruling-gvisor-demos;basis=Create rootfs/runtime parent directories before controller restart. Existing staged unit and root-owned host.env reads unchanged.
- `internal/host/systemunits.go` `ensureSystemUnitsWithGuard`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p3b;basis=Move unit-repair body here with existing lock/unit/host.env reads; under lock require operator repair permit on groups before writes and each systemctl effect, preserve root masks/drop-in and omit automatic update/recovery units. New indirect protected marker/permit reads, never agent receipt; fixed repair unchanged.;rev3=census-ruling-gvisor-demos;basis=Create runtime/rootfs directories and repair installer plus three measured workload templates without arming them. Existing unit/host.env reads unchanged.;rev3=census-ruling-gvisor-update-dirs;basis=Create the two live sandbox directories (the same fixed ensureSandboxDirectories paths) before the apply lock and the early returns on non-group boxes; group members still create them only after the maintenance permit. A creation error still ends the pass at the original point. Then call refreshControlSandboxRootfs. No new path, input or systemctl verb beyond the try-restart below.
-Seal: `0f7153571df8c1b4b50c31f57efcfdf60c71a12c80fd935fb3ea202fa0201dd5` → `c36402d0312399105904a391eced9f71af8ace17ee82c77d3c7adf830d3d5ea7`.
+Seal: `0f7153571df8c1b4b50c31f57efcfdf60c71a12c80fd935fb3ea202fa0201dd5` → `c793523d694cd0ddd20b9562bd61b69093b613b5faa4a262d5cb3f0c82efa0b5`.
Overlay: `internal/provision/testdata/plan14-root-reads-demo-slice-adopt.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/internal/host/demo_slice_adopt_linux_test.go b/internal/host/demo_slice_adopt_linux_test.go
index 73486055e..113c831e1 100644
--- a/internal/host/demo_slice_adopt_linux_test.go
+++ b/internal/host/demo_slice_adopt_linux_test.go
@@ -1,6 +1,7 @@
package host
import (
+ "errors"
"os"
"path/filepath"
"slices"
@@ -51,7 +52,27 @@ func TestAdoptRerendersDemoBuildSliceOnSandboxFlip(t *testing.T) {
if _, err := installDemoUnitsIn(unitDir, settings.demo); err != nil {
t.Fatal(err)
}
+ // systemd's loaded view of the slice: what the last successful
+ // daemon-reload read from the file.
+ var loaded string
+ slicePath := filepath.Join(unitDir, demoBuildsSlice)
+ load := func() {
+ b, err := os.ReadFile(slicePath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ loaded = ""
+ for _, line := range strings.Split(string(b), "\n") {
+ if strings.HasPrefix(line, "MemoryMax=") || strings.HasPrefix(line, "TasksMax=") {
+ loaded += line + "\n"
+ }
+ }
+ }
+ load()
probe := func(args ...string) (string, error) {
+ if args[0] == "show" && args[1] == demoBuildsSlice {
+ return loaded, nil
+ }
if args[1] == dbReadSocketUnit {
if args[0] == "is-active" {
return "inactive", systemctlExit(3)
@@ -64,12 +85,21 @@ func TestAdoptRerendersDemoBuildSliceOnSandboxFlip(t *testing.T) {
return "enabled", nil
}
var calls [][]string
+ reloadFails, setFails := false, false
call := func(args ...string) (string, error) {
calls = append(calls, args)
+ if args[0] == "set-property" && setFails {
+ return "", errors.New("set-property failed")
+ }
+ if len(args) == 1 && args[0] == "daemon-reload" {
+ if reloadFails {
+ return "", errors.New("daemon-reload failed")
+ }
+ load()
+ }
return "", nil
}
lock := filepath.Join(systemRootDir(opt), systemLockFile)
- slicePath := filepath.Join(unitDir, demoBuildsSlice)
want := func(family execsandbox.Family) string {
p := demobuild.SlicePropertiesFor(1, family)
return "MemoryMax=" + strconv.FormatInt(p["MemoryMax"], 10) + "\nMemorySwapMax=0\nTasksMax=" + strconv.FormatInt(p["TasksMax"], 10) + "\n"
@@ -102,6 +132,15 @@ func TestAdoptRerendersDemoBuildSliceOnSandboxFlip(t *testing.T) {
if !slices.ContainsFunc(calls, func(a []string) bool { return len(a) == 1 && a[0] == "daemon-reload" }) {
t.Fatalf("no daemon-reload after re-rendering the slice: %v", calls)
}
+ // The live slice gets the budget too (daemon-reload leaves an active
+ // slice's kernel limits alone), before the file is written.
+ g := demobuild.SlicePropertiesFor(1, execsandbox.FamilyGVisor)
+ setArgs := []string{"set-property", "--runtime", demoBuildsSlice, "MemoryMax=" + strconv.FormatInt(g["MemoryMax"], 10), "MemorySwapMax=0", "TasksMax=" + strconv.FormatInt(g["TasksMax"], 10), "CPUQuota=" + strconv.FormatInt(g["CPUQuota"], 10) + "%"}
+ setAt := slices.IndexFunc(calls, func(a []string) bool { return slices.Equal(a, setArgs) })
+ reloadAt := slices.IndexFunc(calls, func(a []string) bool { return len(a) == 1 && a[0] == "daemon-reload" })
+ if setAt < 0 || setAt > reloadAt {
+ t.Fatalf("want %v before the reload, got %v", setArgs, calls)
+ }
calls = nil
ensureSystemUnits(etc, lock, call, probe, t.Logf)
@@ -114,4 +153,118 @@ func TestAdoptRerendersDemoBuildSliceOnSandboxFlip(t *testing.T) {
if got := readSlice(); !strings.Contains(got, want(execsandbox.FamilySystemd)) {
t.Fatalf("rollback pass left the slice at:\n%s", got)
}
+
+ // A pass that writes the slice but fails its reload leaves systemd on
+ // the old budget. The next pass must notice from systemd's loaded view
+ // (the file already matches) and reload again; then it goes quiet.
+ writeEnv("gvisor")
+ reloadFails = true
+ calls = nil
+ ensureSystemUnits(etc, lock, call, probe, t.Logf)
+ if got := readSlice(); !strings.Contains(got, want(execsandbox.FamilyGVisor)) {
+ t.Fatalf("failed-reload pass did not write the slice:\n%s", got)
+ }
+ if strings.Contains(loaded, "TasksMax=192") {
+ t.Fatal("fixture: a failed reload changed the loaded view")
+ }
+ reloadFails = false
+ calls = nil
+ ensureSystemUnits(etc, lock, call, probe, t.Logf)
+ if !slices.ContainsFunc(calls, func(a []string) bool { return len(a) == 1 && a[0] == "daemon-reload" }) {
+ t.Fatalf("pass after a failed reload did not reload again: %v", calls)
+ }
+ if !strings.Contains(loaded, "TasksMax=192") {
+ t.Fatalf("loaded view after the retry: %q", loaded)
+ }
+ calls = nil
+ ensureSystemUnits(etc, lock, call, probe, t.Logf)
+ if len(calls) != 0 {
+ t.Fatalf("converged box changed units again: %v", calls)
+ }
+
+ // A live budget that cannot be applied leaves the file as it was, so
+ // the next pass still sees the difference and tries again.
+ writeEnv("systemd")
+ setFails = true
+ calls = nil
+ ensureSystemUnits(etc, lock, call, probe, t.Logf)
+ if got := readSlice(); !strings.Contains(got, want(execsandbox.FamilyGVisor)) {
+ t.Fatalf("slice written although its budget could not be applied:\n%s", got)
+ }
+ setFails = false
+ ensureSystemUnits(etc, lock, call, probe, t.Logf)
+ if got := readSlice(); !strings.Contains(got, want(execsandbox.FamilySystemd)) {
+ t.Fatalf("retry pass left the slice at:\n%s", got)
+ }
+}
+
+// The apply path installs the slice too. A changed budget reaches the live
+// slice; when it cannot, the old file goes back for the adopt pass.
+func TestApplyPutsChangedDemoSliceBudgetOnLiveSlice(t *testing.T) {
+ writeEnv := func(etc string, n int) {
+ t.Helper()
+ if err := os.MkdirAll(filepath.Join(etc, "carlos"), 0755); err != nil {
+ t.Fatal(err)
+ }
+ raw := "CARLOS_DEMO_BOX=1\nCARLOS_DEMO_ACCOUNT=shop\nCARLOS_DEMO_FLEET=demo\nCARLOS_DEMO_DOMAIN=example.com\nCARLOS_DEMO_BUILD_WORKER=1\nCARLOS_DEMO_TOOLCHAIN_DIR=/opt/demo-toolchain\nCARLOS_DEMO_BUILD_CONCURRENCY=" + strconv.Itoa(n) + "\n"
+ if err := os.WriteFile(filepath.Join(etc, "carlos/host.env"), []byte(raw), 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ memLine := func(n int) string { return "MemoryMax=" + strconv.FormatInt(int64(n)*1073741824, 10) + "\n" }
+ stage := t.TempDir()
+ writeEnv(filepath.Join(stage, "etc"), 1)
+ if err := bootstrap(stage, nil); err != nil {
+ t.Fatal(err)
+ }
+ f := newApplyFixture(t, "stable", "v1.0.0")
+ slicePath := filepath.Join(f.a.etcDir, "systemd/system", demoBuildsSlice)
+ readSlice := func() string {
+ t.Helper()
+ b, err := os.ReadFile(slicePath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(b)
+ }
+ setCalls := func() []string {
+ var out []string
+ for _, c := range f.calls {
+ if strings.HasPrefix(c, "systemctl set-property") {
+ out = append(out, c)
+ }
+ }
+ return out
+ }
+ writeEnv(f.a.etcDir, 1)
+ if err := f.a.installUnits(t.Context(), stage, nil); err != nil {
+ t.Fatal(err)
+ }
+ if got := setCalls(); len(got) != 0 {
+ t.Fatalf("first install set a budget with no slice before it: %v", got)
+ }
+
+ writeEnv(f.a.etcDir, 3)
+ f.calls = nil
+ if err := f.a.installUnits(t.Context(), stage, nil); err != nil {
+ t.Fatal(err)
+ }
+ if got := setCalls(); len(got) != 1 || !strings.Contains(got[0], "--runtime "+demoBuildsSlice+" "+strings.TrimSpace(memLine(3))) {
+ t.Fatalf("changed budget not put on the live slice: %v", got)
+ }
+
+ writeEnv(f.a.etcDir, 1)
+ inner := f.a.ops.systemctl
+ f.a.ops.systemctl = func(args ...string) (string, error) {
+ if args[0] == "set-property" {
+ return "", errors.New("set-property failed")
+ }
+ return inner(args...)
+ }
+ if err := f.a.installUnits(t.Context(), stage, nil); err != nil {
+ t.Fatalf("a budget that cannot be applied must not fail the apply: %v", err)
+ }
+ if got := readSlice(); !strings.Contains(got, memLine(3)) {
+ t.Fatalf("old slice not put back for the adopt pass:\n%s", got)
+ }
}
diff --git a/internal/host/demo_slice_reload_rootrunner_linux_test.go b/internal/host/demo_slice_reload_rootrunner_linux_test.go
new file mode 100644
index 000000000..3c1e3ccdc
--- /dev/null
+++ b/internal/host/demo_slice_reload_rootrunner_linux_test.go
@@ -0,0 +1,116 @@
+//go:build linux && rootrunner
+
+package host
+
+import (
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/demo"
+ "github.com/carlosframework/platform/internal/demobuild"
+ "github.com/carlosframework/platform/internal/execsandbox"
+)
+
+// TestRootDemoSliceBudgetReachesActiveSlice: on real systemd, an active
+// carlos-demo-builds.slice keeps its kernel limits across a unit-file
+// rewrite plus daemon-reload. applyDemoSliceBudget (set-property --runtime)
+// must move them, in both directions of a sandbox flip, and the rendered
+// file plus reload must then agree with the kernel.
+func TestRootDemoSliceBudgetReachesActiveSlice(t *testing.T) {
+ if os.Geteuid() != 0 {
+ t.Fatal("needs root")
+ }
+ unitPath := filepath.Join("/run/systemd/system", demoBuildsSlice)
+ if _, err := os.Lstat(filepath.Join("/etc/systemd/system", demoBuildsSlice)); err == nil {
+ t.Fatal("refusing: a real carlos-demo-builds.slice is installed here")
+ }
+ run := func(args ...string) string {
+ t.Helper()
+ out, err := exec.Command(args[0], args[1:]...).CombinedOutput()
+ if err != nil {
+ t.Fatalf("%v: %v: %s", args, err, out)
+ }
+ return strings.TrimSpace(string(out))
+ }
+ systemctl := func(args ...string) (string, error) {
+ out, err := exec.Command("systemctl", args...).CombinedOutput()
+ return string(out), err
+ }
+ raw, err := unitsFS.ReadFile("units/" + demoBuildsSlice)
+ if err != nil {
+ t.Fatal(err)
+ }
+ render := func(family execsandbox.Effective) []byte {
+ cfg := claimUnitSettings{demo: demo.Config{Account: "shop", Fleet: "demo", Domain: "example.com", BuildWorker: true, BuildConcurrency: 1}, sandbox: family}
+ return claimUnitContent(demoBuildsSlice, raw, cfg)
+ }
+ kernel := func() map[string]string {
+ t.Helper()
+ group := strings.TrimPrefix(run("systemctl", "show", "-p", "ControlGroup", "--value", demoBuildsSlice), "/")
+ if group == "" {
+ t.Fatal("slice has no control group")
+ }
+ m := map[string]string{}
+ for _, f := range []string{"memory.max", "memory.swap.max", "pids.max", "cpu.max"} {
+ b, err := os.ReadFile(filepath.Join("/sys/fs/cgroup", group, f))
+ if err != nil {
+ t.Fatalf("%s: %v", f, err)
+ }
+ m[f] = strings.TrimSpace(string(b))
+ }
+ return m
+ }
+ expect := func(family execsandbox.Family, when string) {
+ t.Helper()
+ p := demobuild.SlicePropertiesFor(1, family)
+ k := kernel()
+ t.Logf("%s: kernel %v", when, k)
+ if k["memory.max"] != strconv.FormatInt(p["MemoryMax"], 10) || k["pids.max"] != strconv.FormatInt(p["TasksMax"], 10) || k["memory.swap.max"] != "0" {
+ t.Fatalf("%s: kernel %v, want %s budget", when, k, family)
+ }
+ }
+ install := func(b []byte) {
+ t.Helper()
+ if err := os.WriteFile(unitPath, b, 0644); err != nil {
+ t.Fatal(err)
+ }
+ run("systemctl", "daemon-reload")
+ }
+ t.Cleanup(func() {
+ _ = exec.Command("systemctl", "stop", "carlos-rr-budget-sleeper.service", demoBuildsSlice).Run()
+ _ = os.Remove(unitPath)
+ _ = os.RemoveAll(filepath.Join("/run/systemd/system.control", demoBuildsSlice+".d"))
+ _ = exec.Command("systemctl", "daemon-reload").Run()
+ })
+
+ install(render(execsandbox.EffectiveSystemd))
+ run("systemd-run", "--unit=carlos-rr-budget-sleeper", "--slice="+demoBuildsSlice, "--property=Type=exec", "/bin/sleep", "600")
+ time.Sleep(time.Second)
+ expect(execsandbox.FamilySystemd, "active slice, systemd budget")
+
+ // The failure the dev witness hit: file + reload alone.
+ install(render(execsandbox.EffectiveGVisor))
+ time.Sleep(time.Second)
+ t.Logf("file + reload only: kernel %v (show %s)", kernel(), run("systemctl", "show", demoBuildsSlice, "-p", "MemoryMax,TasksMax"))
+
+ for _, step := range []struct {
+ sandbox execsandbox.Effective
+ family execsandbox.Family
+ }{{execsandbox.EffectiveGVisor, execsandbox.FamilyGVisor}, {execsandbox.EffectiveSystemd, execsandbox.FamilySystemd}, {execsandbox.EffectiveGVisor, execsandbox.FamilyGVisor}} {
+ want := render(step.sandbox)
+ if err := applyDemoSliceBudget(systemctl, want); err != nil {
+ t.Fatal(err)
+ }
+ install(want)
+ time.Sleep(time.Second)
+ expect(step.family, "after applyDemoSliceBudget + file + reload ("+string(step.family)+")")
+ if sliceLoadedDiffers(run("systemctl", "show", demoBuildsSlice, "-p", "MemoryMax,TasksMax"), want) {
+ t.Fatalf("systemd's loaded budget differs from the file after %s", step.family)
+ }
+ }
+}
diff --git a/internal/host/runsc_update_dirs_linux_test.go b/internal/host/runsc_update_dirs_linux_test.go
index 1184569e3..807d3c66c 100644
--- a/internal/host/runsc_update_dirs_linux_test.go
+++ b/internal/host/runsc_update_dirs_linux_test.go
@@ -313,6 +313,10 @@ func TestSandboxUpdateControlRestartForNewRootfs(t *testing.T) {
}
shows := 0
probe := func(args ...string) (string, error) {
+ if args[0] == "show" && args[1] == demoBuildsSlice {
+ // The adopt pass's loaded-budget check; no answer is no difference.
+ return "", nil
+ }
if args[0] == "show" {
if strings.Join(args, " ") != "show -p MainPID,InvocationID,ControlGroup "+claimControlUnit {
t.Errorf("probe %v", args)
diff --git a/internal/host/systemapply.go b/internal/host/systemapply.go
index 0d1814c2d..8cfa542c0 100644
--- a/internal/host/systemapply.go
+++ b/internal/host/systemapply.go
@@ -1,6 +1,7 @@
package host
import (
+ "bytes"
"context"
"crypto/ed25519"
"encoding/json"
@@ -1513,6 +1514,9 @@ func (a *systemApplier) installUnits(ctx context.Context, stagedRoot string, rem
}
os.Remove(filepath.Join(unitDir, u))
}
+ // The slice before this install, so a budget that cannot reach the live
+ // slice can be put back for the adopt pass (below).
+ beforeSlice, beforeSliceErr := os.ReadFile(filepath.Join(unitDir, demoBuildsSlice))
beforeControl, err := os.ReadFile(filepath.Join(unitDir, claimControlUnit))
if err != nil && !errors.Is(err, os.ErrNotExist) {
return err
@@ -1611,6 +1615,18 @@ func (a *systemApplier) installUnits(ctx context.Context, stagedRoot string, rem
if _, err = a.ops.systemctl("daemon-reload"); err != nil {
return err
}
+ // The reload does not move an active slice's kernel limits; a changed
+ // demo build budget goes onto the live slice too. A failure is logged,
+ // not fatal: the old slice file goes back, so the next adopt pass sees
+ // the file differ from its rendering and applies the budget itself.
+ if afterSlice, err := os.ReadFile(filepath.Join(unitDir, demoBuildsSlice)); err == nil && beforeSliceErr == nil && !bytes.Equal(beforeSlice, afterSlice) {
+ if err := applyDemoSliceBudget(a.ops.systemctl, afterSlice); err != nil {
+ a.ops.logf("system apply: demo build slice: %v; left for the adopt pass", err)
+ if err := writeFileDurable(filepath.Join(unitDir, demoBuildsSlice), beforeSlice, 0o644); err != nil {
+ a.ops.logf("system apply: demo build slice: restore: %v", err)
+ }
+ }
+ }
afterControl, err := os.ReadFile(filepath.Join(unitDir, claimControlUnit))
if err != nil && !errors.Is(err, os.ErrNotExist) {
return err
diff --git a/internal/host/systemunits.go b/internal/host/systemunits.go
index 0f30af552..965a9dd24 100644
--- a/internal/host/systemunits.go
+++ b/internal/host/systemunits.go
@@ -3,6 +3,7 @@ package host
import (
"bytes"
"errors"
+ "fmt"
"github.com/carlosframework/platform/internal/instancectl"
"os"
"os/exec"
@@ -210,6 +211,7 @@ func ensureSystemUnitsWithGuard(etcDir, lockPath string, systemctl, probe func(a
// sized for the old sandbox, and every build would refuse at its budget
// check. A missing slice is already a reinstall (missing).
sliceChanged := false
+ var sliceWant []byte
if settingsErr == nil {
sliceRaw, err := unitsFS.ReadFile("units/" + demoBuildsSlice)
if err != nil {
@@ -221,7 +223,17 @@ func ensureSystemUnitsWithGuard(etcDir, lockPath string, systemctl, probe func(a
logf("adopt: demo build slice: %v", err)
return
}
- sliceChanged = err == nil && !bytes.Equal(sliceInstalled, claimUnitContent(demoBuildsSlice, sliceRaw, claimSettings))
+ want := claimUnitContent(demoBuildsSlice, sliceRaw, claimSettings)
+ sliceWant = want
+ sliceChanged = err == nil && !bytes.Equal(sliceInstalled, want)
+ // Matching bytes are not enough: a pass that wrote the slice and then
+ // failed its daemon-reload (or lost its group permit before it) leaves
+ // systemd on the old budget with nothing left to compare. Ask systemd
+ // what it has loaded; only a definite mismatch counts.
+ if err == nil && !sliceChanged {
+ out, _ := probe("show", demoBuildsSlice, "-p", "MemoryMax,TasksMax")
+ sliceChanged = sliceLoadedDiffers(out, want)
+ }
}
dbrEnabled := parseIsEnabled(dbrEnabledOut)
// Dark: neither listening nor enabled for the next boot.
@@ -242,6 +254,16 @@ func ensureSystemUnitsWithGuard(etcDir, lockPath string, systemctl, probe func(a
logf("adopt: system units: %v", err)
return
}
+ // daemon-reload changes systemd's view of an active slice but not its
+ // kernel limits (root-runner witness, systemd 257), so the new budget
+ // goes onto the live slice first. A failure here returns before the
+ // file is written, and the next pass still sees the difference.
+ if sliceChanged {
+ if err := applyDemoSliceBudget(systemctl, sliceWant); err != nil {
+ logf("adopt: demo build slice: %v", err)
+ return
+ }
+ }
for _, u := range systemUnitFiles {
if group && groupAutomaticUnit(u) {
continue
@@ -318,3 +340,51 @@ func systemctlProbe(args ...string) (string, error) {
out, err := exec.Command("systemctl", args...).Output()
return string(out), err
}
+
+// sliceLoadedDiffers reports a definite difference between the budget
+// systemd has loaded for the demo build slice (`systemctl show -p
+// MemoryMax,TasksMax`) and the rendered unit. Output missing either
+// property says nothing and is not a difference.
+func sliceLoadedDiffers(show string, rendered []byte) bool {
+ values := func(text string) map[string]string {
+ m := map[string]string{}
+ for _, line := range strings.Split(text, "\n") {
+ k, v, ok := strings.Cut(strings.TrimSpace(line), "=")
+ if ok && (k == "MemoryMax" || k == "TasksMax") {
+ m[k] = v
+ }
+ }
+ return m
+ }
+ loaded, want := values(show), values(string(rendered))
+ for _, k := range []string{"MemoryMax", "TasksMax"} {
+ if loaded[k] == "" || want[k] == "" {
+ return false
+ }
+ }
+ return loaded["MemoryMax"] != want["MemoryMax"] || loaded["TasksMax"] != want["TasksMax"]
+}
+
+// applyDemoSliceBudget puts the rendered slice's budget onto the live slice
+// with `systemctl set-property --runtime`, which reaches the kernel cgroup
+// at once; daemon-reload alone leaves an active slice's limits as they were.
+// The runtime drop-in it leaves carries the same values as the file and goes
+// at reboot. A rendering without all four properties is refused.
+func applyDemoSliceBudget(systemctl func(args ...string) (string, error), rendered []byte) error {
+ props := map[string]string{}
+ for _, line := range strings.Split(string(rendered), "\n") {
+ k, v, ok := strings.Cut(strings.TrimSpace(line), "=")
+ if ok && (k == "MemoryMax" || k == "MemorySwapMax" || k == "TasksMax" || k == "CPUQuota") {
+ props[k] = v
+ }
+ }
+ args := []string{"set-property", "--runtime", demoBuildsSlice}
+ for _, k := range []string{"MemoryMax", "MemorySwapMax", "TasksMax", "CPUQuota"} {
+ if props[k] == "" {
+ return fmt.Errorf("rendered slice has no %s", k)
+ }
+ args = append(args, k+"="+props[k])
+ }
+ _, err := systemctl(args...)
+ return err
+}
diff --git a/internal/host/systemunits_test.go b/internal/host/systemunits_test.go
index fe5fc01f3..893794da4 100644
--- a/internal/host/systemunits_test.go
+++ b/internal/host/systemunits_test.go
@@ -69,7 +69,8 @@ func TestEnsureSystemUnitsInstallsAndArmsWhatIsMissing(t *testing.T) {
return "", nil
}
ensureSystemUnits(etc, lockPath, systemctl, probe2, t.Logf)
- if len(calls) != 5 {
+ // Five arming questions plus the demo build slice's loaded budget.
+ if len(calls) != 6 || calls[5] != "show "+demoBuildsSlice+" -p MemoryMax,TasksMax" {
t.Fatalf("an armed box got %v", calls)
}
}
@@ -260,10 +261,11 @@ func TestEnsureSystemUnitsRetiresUnitsNoLongerShipped(t *testing.T) {
}
}
- // Nothing left to retire: the armed pass is back to its five questions.
+ // Nothing left to retire: the armed pass is back to its six questions
+ // (the sixth asks systemd for the demo build slice's loaded budget).
calls = nil
ensureSystemUnits(etc, lockPath, systemctl, armed, t.Logf)
- if len(calls) != 5 {
+ if len(calls) != 6 {
t.Fatalf("an armed box with nothing to retire got %v", calls)
}
}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index cab410184..79e83eaa3 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -139,4 +139,4 @@ plan14-root-reads-dns-fresh-lookup-724.tsv 7ac2bde8301c37c7546e9aa19d375f1468fc8
plan14-root-reads-gvisor-update-dirs.tsv 1f1b2fdb569b7be42e75e10d1943d7e512708299364f912c2f72dccf1bd5b678
plan14-root-reads-region-ha-held-build.tsv beb085e4c6cdb3d430d12a8dc3c93f25cc3faf1aa7d62be37698ff9c9c82ecce
plan14-root-reads-fixedbox-health-alarms.tsv 0f7153571df8c1b4b50c31f57efcfdf60c71a12c80fd935fb3ea202fa0201dd5
-plan14-root-reads-demo-slice-adopt.tsv c36402d0312399105904a391eced9f71af8ace17ee82c77d3c7adf830d3d5ea7
+plan14-root-reads-demo-slice-adopt.tsv c793523d694cd0ddd20b9562bd61b69093b613b5faa4a262d5cb3f0c82efa0b5
diff --git a/internal/provision/testdata/plan14-root-reads-demo-slice-adopt.tsv b/internal/provision/testdata/plan14-root-reads-demo-slice-adopt.tsv
index 9ecae87ed..ac526e51d 100644
--- a/internal/provision/testdata/plan14-root-reads-demo-slice-adopt.tsv
+++ b/internal/provision/testdata/plan14-root-reads-demo-slice-adopt.tsv
@@ -1,5 +1,7 @@
# Census overlay demo-slice-adopt, written by census-propose (#369). census-ruling-demo-slice-adopt, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-demo-slice-adopt.md.
-# 0 body, 1 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
-@legacy c2f18832e4429189c15890a43417df4eedff2e0882fdb541ff5cb726ba8b936f internal/host/systemunits.go ensureSystemUnitsWithGuard legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b;basis=Move unit-repair body here with existing lock/unit/host.env reads; under lock require operator repair permit on groups before writes and each systemctl effect, preserve root masks/drop-in and omit automatic update/recovery units. New indirect protected marker/permit reads, never agent receipt; fixed repair unchanged.;rev3=census-ruling-gvisor-demos;basis=Create runtime/rootfs directories and repair installer plus three measured workload templates without arming them. Existing unit/host.env reads unchanged.;rev3=census-ruling-gvisor-update-dirs;basis=Create the two live sandbox directories (the same fixed ensureSandboxDirectories paths) before the apply lock and the early returns on non-group boxes; group members still create them only after the maintenance permit. A creation error still ends the pass at the original point. Then call refreshControlSandboxRootfs. No new path, input or systemctl verb beyond the try-restart below.;rev3=census-ruling-demo-slice-adopt;basis=Read the embedded carlos-demo-builds.slice and the installed one at the fixed unit path (/etc/systemd/system), compare it with its host.env rendering, and treat a difference as a reinstall (the existing write loop and daemon-reload). No new path, input, systemctl verb or write target; the slice is root-owned and rendered only from the already-parsed claim settings. file:OpenFile@985,file:ReadFile@5626,file:ReadFile@5759,file:ReadFile@6647,file:ReadFile@6789,file:ReadFile@8096,file:Stat@5535 869800bbcd443b47e0a4462ed39d1051d4a776fc0498791784c19078a3dda7bc
-internal/host/systemunits.go ensureSystemUnitsWithGuard legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b;basis=Move unit-repair body here with existing lock/unit/host.env reads; under lock require operator repair permit on groups before writes and each systemctl effect, preserve root masks/drop-in and omit automatic update/recovery units. New indirect protected marker/permit reads, never agent receipt; fixed repair unchanged.;rev3=census-ruling-gvisor-demos;basis=Create runtime/rootfs directories and repair installer plus three measured workload templates without arming them. Existing unit/host.env reads unchanged.;rev3=census-ruling-gvisor-update-dirs;basis=Create the two live sandbox directories (the same fixed ensureSandboxDirectories paths) before the apply lock and the early returns on non-group boxes; group members still create them only after the maintenance permit. A creation error still ends the pass at the original point. Then call refreshControlSandboxRootfs. No new path, input or systemctl verb beyond the try-restart below.;rev3=census-ruling-demo-slice-adopt;basis=Read the embedded carlos-demo-builds.slice and the installed one at the fixed unit path (/etc/systemd/system), compare it with its host.env rendering, and treat a difference as a reinstall (the existing write loop and daemon-reload). No new path, input, systemctl verb or write target; the slice is root-owned and rendered only from the already-parsed claim settings. file:OpenFile@985,file:ReadFile@5626,file:ReadFile@5759,file:ReadFile@6647,file:ReadFile@6789,file:ReadFile@8096,file:Stat@5535 869800bbcd443b47e0a4462ed39d1051d4a776fc0498791784c19078a3dda7bc
-@coverage internal/host 6f798596db0d2800638875314233378edea1a127c18c1337669f8518bdf59b9e
+# 0 body, 2 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@legacy c290bc9443ed6ec58d6efb9b5c13ade24fe912e502c2968046862f37dbd557ca internal/host/systemapply.go systemApplier.installUnits legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-agent-start-demo-1;basis=Renders the staged build slice against live root host configuration; preserves it when settings cannot be parsed.;rev3=census-ruling-region-ha-p3b;basis=Require group apply/rollback permit, preserve root Restart=no/nftables drop-in and masks, and skip automatic update/recovery units. Existing staged unit and host.env reads remain; new indirect marker/permit reads are protected and agent receipts are excluded.;rev3=census-ruling-gvisor-demos;basis=Create rootfs/runtime parent directories before controller restart. Existing staged unit and root-owned host.env reads unchanged.;rev3=census-ruling-demo-slice-adopt;basis=Read the installed carlos-demo-builds.slice before the install (fixed root unit path); when the installed slice changed, set its rendered budget on the live slice (systemctl set-property --runtime, fixed name) and on failure write the earlier bytes back. No new path or input; values come from the rendering this function already wrote. file:ReadDir@1722,file:ReadFile@1197,file:ReadFile@1273,file:ReadFile@2313,file:ReadFile@5637,file:ReadFile@6134,file:Stat@2971,file:Stat@4264 2b1a266dd3712e28288d42264e77601cd07bc863c201017958c81daa1e2362a3
+@legacy 7af53abdda5e401d17624a209ca155f9bc7a79d5172bed15b3789d16cc2408b9 internal/host/systemunits.go ensureSystemUnitsWithGuard legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b;basis=Move unit-repair body here with existing lock/unit/host.env reads; under lock require operator repair permit on groups before writes and each systemctl effect, preserve root masks/drop-in and omit automatic update/recovery units. New indirect protected marker/permit reads, never agent receipt; fixed repair unchanged.;rev3=census-ruling-gvisor-demos;basis=Create runtime/rootfs directories and repair installer plus three measured workload templates without arming them. Existing unit/host.env reads unchanged.;rev3=census-ruling-gvisor-update-dirs;basis=Create the two live sandbox directories (the same fixed ensureSandboxDirectories paths) before the apply lock and the early returns on non-group boxes; group members still create them only after the maintenance permit. A creation error still ends the pass at the original point. Then call refreshControlSandboxRootfs. No new path, input or systemctl verb beyond the try-restart below.;rev3=census-ruling-demo-slice-adopt;basis=Compare the installed carlos-demo-builds.slice (fixed root unit path, embedded unit) with its host.env rendering, and ask systemd for the slice's loaded MemoryMax/TasksMax (systemctl show on the fixed slice name); a definite difference is a reinstall. Before writing, put the rendered budget on the live slice with systemctl set-property --runtime on that fixed name, through the same permit-wrapped systemctl. No new path, input or write target; values come only from the already-parsed claim settings. file:OpenFile@985,file:ReadFile@5626,file:ReadFile@5759,file:ReadFile@6669,file:ReadFile@6811,file:ReadFile@9018,file:Stat@5535 cbc353a08921fb509543f92c870a601793a03bad1147bcde8517e0bc30359438
+internal/host/systemapply.go systemApplier.installUnits legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-agent-start-demo-1;basis=Renders the staged build slice against live root host configuration; preserves it when settings cannot be parsed.;rev3=census-ruling-region-ha-p3b;basis=Require group apply/rollback permit, preserve root Restart=no/nftables drop-in and masks, and skip automatic update/recovery units. Existing staged unit and host.env reads remain; new indirect marker/permit reads are protected and agent receipts are excluded.;rev3=census-ruling-gvisor-demos;basis=Create rootfs/runtime parent directories before controller restart. Existing staged unit and root-owned host.env reads unchanged.;rev3=census-ruling-demo-slice-adopt;basis=Read the installed carlos-demo-builds.slice before the install (fixed root unit path); when the installed slice changed, set its rendered budget on the live slice (systemctl set-property --runtime, fixed name) and on failure write the earlier bytes back. No new path or input; values come from the rendering this function already wrote. file:ReadDir@1722,file:ReadFile@1197,file:ReadFile@1273,file:ReadFile@2313,file:ReadFile@5637,file:ReadFile@6134,file:Stat@2971,file:Stat@4264 2b1a266dd3712e28288d42264e77601cd07bc863c201017958c81daa1e2362a3
+internal/host/systemunits.go ensureSystemUnitsWithGuard legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b;basis=Move unit-repair body here with existing lock/unit/host.env reads; under lock require operator repair permit on groups before writes and each systemctl effect, preserve root masks/drop-in and omit automatic update/recovery units. New indirect protected marker/permit reads, never agent receipt; fixed repair unchanged.;rev3=census-ruling-gvisor-demos;basis=Create runtime/rootfs directories and repair installer plus three measured workload templates without arming them. Existing unit/host.env reads unchanged.;rev3=census-ruling-gvisor-update-dirs;basis=Create the two live sandbox directories (the same fixed ensureSandboxDirectories paths) before the apply lock and the early returns on non-group boxes; group members still create them only after the maintenance permit. A creation error still ends the pass at the original point. Then call refreshControlSandboxRootfs. No new path, input or systemctl verb beyond the try-restart below.;rev3=census-ruling-demo-slice-adopt;basis=Compare the installed carlos-demo-builds.slice (fixed root unit path, embedded unit) with its host.env rendering, and ask systemd for the slice's loaded MemoryMax/TasksMax (systemctl show on the fixed slice name); a definite difference is a reinstall. Before writing, put the rendered budget on the live slice with systemctl set-property --runtime on that fixed name, through the same permit-wrapped systemctl. No new path, input or write target; values come only from the already-parsed claim settings. file:OpenFile@985,file:ReadFile@5626,file:ReadFile@5759,file:ReadFile@6669,file:ReadFile@6811,file:ReadFile@9018,file:Stat@5535 cbc353a08921fb509543f92c870a601793a03bad1147bcde8517e0bc30359438
+@coverage internal/host 2bc84d2163f54b05258d0e3520b50452bb3c0c3b0e90982c6b1d1b79f308557d