Integrate reviewed demo budget changes and refresh census envelope
14 files changed,
+797
−18
docs/superpowers/notes/census-proposal-demo-slice-adopt.md+26 −0docs/superpowers/notes/census-proposal-security-review-mitigations.md+1 −1internal/demobuild/budget.go+143 −0internal/demobuild/budget_rootrunner_linux_test.go+146 −0internal/demobuild/budget_test.go+190 −0internal/demobuild/worker.go+34 −8internal/demobuild/worker_test.go+2 −2internal/host/demo_slice_adopt_linux_test.go+172 −0internal/host/runsc_update_dirs_linux_test.go+4 −0internal/host/systemunits.go+58 −2internal/host/systemunits_test.go+5 −3internal/provision/testdata/plan14-root-reads-chain.tsv+2 −1internal/provision/testdata/plan14-root-reads-demo-slice-adopt.tsv+13 −0internal/provision/testdata/plan14-root-reads-security-review-mitigations.tsv+1 −1
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| new file mode 100644 |
| index 000000000..479b6729c |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-demo-slice-adopt.md |
| @@ -0,0 +1,26 @@ |
| +# Census approval: demo-slice-adopt |
| + |
| +Ruling `census-ruling-demo-slice-adopt`. The independent reviewer approves or rejects every change below, 2 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `internal/demobuild/worker.go` `Worker.Build` | body | unchanged (1) | Before admission, call the admit hook (nil = reconcileBudget); a pending budget change (errBudgetPending) is retried every 2 s until the job deadline, any other error fails at once. reconcileBudget reads the fixed build slice's systemctl show budget, its cgroup limit files and cgroup.events under the fixed root cgroup path, and list-jobs (a listing at the capture limit defers); only with buildPurge held exclusively, the slice empty and no build or slice job queued does it run systemctl stop on the fixed slice name. No tenant, app or agent input names a path or unit. | |
| +| `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 name). A definite difference is a reinstall (existing write loop + daemon-reload). No live budget change, no new path, input or write target. | |
| + |
| +Envelopes re-pinned: `internal/demobuild`, `internal/host`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
| + |
| +Recorded dispositions, which each change must still satisfy: |
| + |
| +- `internal/demobuild/worker.go` `Worker.Build`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-agent-start-demo-1;basis=Holds the build/purge read lock through cleanup; existing bounded source read remains. |
| +- `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. |
| + |
| +New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff: |
| + |
| +- new `internal/demobuild/budget.go:budgetSlicePopulated`: reads +file:ReadFile; written legacy, accepted-legacy, frozen |
| +- new `internal/demobuild/budget.go:kernelBudgetMatches`: reads +file:Lstat, +file:ReadFile; written legacy, accepted-legacy, frozen |
| + |
| +Seal: `250e3ba91e1bc5fcd6be5cc2bafce4c7d6645d2d2f0c080913b99f01b1d19129` → `707018faaa1fee3b47abb78389ae7854264e76621cc316889061adb69bf13e10`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-demo-slice-adopt.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/notes/census-proposal-security-review-mitigations.md b/docs/superpowers/notes/census-proposal-security-review-mitigations.md| index c34fa90bc..4dc8d1814 100644 |
| --- a/docs/superpowers/notes/census-proposal-security-review-mitigations.md |
| +++ b/docs/superpowers/notes/census-proposal-security-review-mitigations.md |
| @@ -23,6 +23,6 @@ New dispositions, which census-propose wrote and the reviewer checks against the |
| - new `internal/activator/backend_exec.go:ExecBackend.residentLayoutRefusal`: reads +registry:GoodVersion, +registry:ServingVersion, +whole:Route; written legacy, accepted-legacy, frozen |
| - reads `internal/provision/reconcile.go:RouteFor`: +registry:Stateless; keeps authority, task C,E3 |
| -Seal: `250e3ba91e1bc5fcd6be5cc2bafce4c7d6645d2d2f0c080913b99f01b1d19129` → `d0f9e4412c80fd81f1264a38d70df5e0ed4bbcb3a4cb848388da8ad1d4661a1e`. |
| +Seal: `707018faaa1fee3b47abb78389ae7854264e76621cc316889061adb69bf13e10` → `a6f3f9eec4aac5ea88f20d0e52eaa0651fce80c0d49b60883ff61ceade33d288`. |
| Overlay: `internal/provision/testdata/plan14-root-reads-security-review-mitigations.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/internal/demobuild/budget.go b/internal/demobuild/budget.go| new file mode 100644 |
| index 000000000..f30ebc63d |
| --- /dev/null |
| +++ b/internal/demobuild/budget.go |
| @@ -0,0 +1,143 @@ |
| +package demobuild |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "os" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/execsandbox" |
| +) |
| + |
| +// budgetSlice holds every native and gVisor build unit. |
| +const budgetSlice = "carlos-demo-builds.slice" |
| + |
| +// errBudgetPending marks a deferral: the budget change waits for running |
| +// work. Build retries it until the job's deadline (budgetRetry apart); every |
| +// other ErrBuild stays a build failure. |
| +var errBudgetPending = errors.New("build budget change pending") |
| + |
| +// budgetRetry is how long Build waits between admission attempts while a |
| +// budget change is pending. |
| +var budgetRetry = 2 * time.Second |
| + |
| +// reconcileBudget runs before a build is admitted. It is the only place a |
| +// build budget reaches the kernel after the slice was first started. |
| +// |
| +// systemd sets a slice's cgroup limits when the slice starts. daemon-reload |
| +// after the adopt pass re-renders the unit (a sandbox switch, a concurrency |
| +// change) updates systemd's view only, and the running slice keeps its old |
| +// limits (root-runner witness, systemd 257). So, when the kernel limits |
| +// differ from the rendered budget: |
| +// - with builds, snapshots or purges running, or anything left in the |
| +// slice, the build is deferred (ErrBuild, retryable): a running build |
| +// never has its budget changed under it; |
| +// - otherwise the empty slice is stopped, and the next build unit starts |
| +// it again on the budget systemd now has loaded. |
| +// |
| +// A slice whose loaded configuration is itself stale (no adopt pass since |
| +// host.env changed) fails assertBudget first and is left alone: stopping it |
| +// would only restart it on the same stale budget. |
| +func (w *Worker) reconcileBudget(ctx context.Context) error { |
| + if err := w.assertBudget(ctx); err != nil { |
| + return err |
| + } |
| + n, family := cap(w.slots), w.SandboxFamily() |
| + if ok, err := kernelBudgetMatches(n, family); err != nil || ok { |
| + return err |
| + } |
| + // Builds hold buildPurge for reading; snapshots and purges hold it |
| + // outright. Holding it here means none of them is in flight in this |
| + // process, and processLock means no other worker process exists. |
| + if !w.buildPurge.TryLock() { |
| + return fmt.Errorf("%w: %w: waits for running builds", ErrBuild, errBudgetPending) |
| + } |
| + defer w.buildPurge.Unlock() |
| + if ok, err := kernelBudgetMatches(n, family); err != nil || ok { |
| + return err |
| + } |
| + populated, err := budgetSlicePopulated() |
| + if err != nil { |
| + return err |
| + } |
| + if populated { |
| + return fmt.Errorf("%w: %w: waits for an empty build slice", ErrBuild, errBudgetPending) |
| + } |
| + jobs, err := systemctl(ctx, "list-jobs", "--no-legend", "--no-pager") |
| + if err != nil { |
| + return err |
| + } |
| + // Absence needs the whole job list: one the capture may have cut at its |
| + // limit could hide a queued build start, so it defers like a busy slice. |
| + if len(jobs) >= systemctlCaptureLimit { |
| + return fmt.Errorf("%w: %w: job list too long to prove nothing is queued", ErrBuild, errBudgetPending) |
| + } |
| + for _, line := range strings.Split(jobs, "\n") { |
| + if f := strings.Fields(line); len(f) >= 2 && (f[1] == budgetSlice || strings.HasPrefix(f[1], "carlos-demo-build@") || strings.HasPrefix(f[1], "carlos-demo-build-gvisor@")) { |
| + return fmt.Errorf("%w: %w: waits for queued %s", ErrBuild, errBudgetPending, f[1]) |
| + } |
| + } |
| + if _, err := systemctl(ctx, "stop", budgetSlice); err != nil { |
| + return err |
| + } |
| + out, err := systemctl(ctx, "show", budgetSlice, "-p", "ActiveState") |
| + if err != nil { |
| + return err |
| + } |
| + if state := showProperties(out)["ActiveState"]; state != "inactive" { |
| + return fmt.Errorf("%w: build slice %s after stop", ErrBuild, state) |
| + } |
| + return nil |
| +} |
| + |
| +// kernelBudgetMatches compares the build slice's cgroup limits with the |
| +// budget for n slots of family. No cgroup (the slice is not running) is a |
| +// match: the next start applies whatever systemd has loaded. |
| +func kernelBudgetMatches(n int, family execsandbox.Family) (bool, error) { |
| + p := SlicePropertiesFor(n, family) |
| + if p == nil { |
| + return false, ErrBuild |
| + } |
| + if _, err := os.Lstat(buildCgroupRoot); errors.Is(err, os.ErrNotExist) { |
| + return true, nil |
| + } else if err != nil { |
| + return false, err |
| + } |
| + want := map[string]string{ |
| + "memory.max": strconv.FormatInt(p["MemoryMax"], 10), |
| + "memory.swap.max": "0", |
| + "pids.max": strconv.FormatInt(p["TasksMax"], 10), |
| + "cpu.max": strconv.FormatInt(p["CPUQuota"]*1000, 10) + " 100000", |
| + } |
| + for name, value := range want { |
| + b, err := os.ReadFile(filepath.Join(buildCgroupRoot, name)) |
| + if err != nil { |
| + return false, err |
| + } |
| + if strings.TrimSpace(string(b)) != value { |
| + return false, nil |
| + } |
| + } |
| + return true, nil |
| +} |
| + |
| +// budgetSlicePopulated reads the slice's cgroup.events. No cgroup is empty. |
| +func budgetSlicePopulated() (bool, error) { |
| + b, err := os.ReadFile(filepath.Join(buildCgroupRoot, "cgroup.events")) |
| + if errors.Is(err, os.ErrNotExist) { |
| + return false, nil |
| + } |
| + if err != nil { |
| + return false, err |
| + } |
| + for _, line := range strings.Split(string(b), "\n") { |
| + if f := strings.Fields(line); len(f) == 2 && f[0] == "populated" { |
| + return f[1] != "0", nil |
| + } |
| + } |
| + return false, fmt.Errorf("%w: build slice cgroup.events has no populated line", ErrBuild) |
| +} |
diff --git a/internal/demobuild/budget_rootrunner_linux_test.go b/internal/demobuild/budget_rootrunner_linux_test.go| new file mode 100644 |
| index 000000000..a3b6bdcc6 |
| --- /dev/null |
| +++ b/internal/demobuild/budget_rootrunner_linux_test.go |
| @@ -0,0 +1,146 @@ |
| +//go:build linux && rootrunner |
| + |
| +package demobuild |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/execsandbox" |
| +) |
| + |
| +// TestRootBuildBudgetReconcile: on real systemd, the build worker's |
| +// reconciler brings an active build slice with a stale kernel budget to the |
| +// loaded one, in both directions of a sandbox switch. It defers (retryable |
| +// DEMO-BUILD) while anything runs in the slice and never touches a running |
| +// one; once the slice is empty it stops it, and the next unit in the slice |
| +// starts it on the new budget. |
| +func TestRootBuildBudgetReconcile(t *testing.T) { |
| + if os.Geteuid() != 0 { |
| + t.Fatal("needs root") |
| + } |
| + if _, err := os.Lstat(filepath.Join("/etc/systemd/system", budgetSlice)); err == nil { |
| + t.Fatal("refusing: a real build slice is installed here") |
| + } |
| + unitPath := filepath.Join("/run/systemd/system", budgetSlice) |
| + 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)) |
| + } |
| + install := func(family execsandbox.Family) { |
| + t.Helper() |
| + p := SlicePropertiesFor(1, family) |
| + body := "[Unit]\nDescription=carlos offline demo build budget\n\n[Slice]\nMemoryMax=" + strconv.FormatInt(p["MemoryMax"], 10) + "\nMemorySwapMax=0\nTasksMax=" + strconv.FormatInt(p["TasksMax"], 10) + "\nCPUQuota=" + strconv.FormatInt(p["CPUQuota"], 10) + "%\nCPUWeight=10\n" |
| + if err := os.WriteFile(unitPath, []byte(body), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + run("systemctl", "daemon-reload") |
| + } |
| + const sleeper = "carlos-rr-build-sleeper" |
| + startSleeper := func() { |
| + t.Helper() |
| + run("systemd-run", "--unit="+sleeper, "--slice="+budgetSlice, "--property=Type=exec", "/bin/sleep", "600") |
| + time.Sleep(500 * time.Millisecond) |
| + } |
| + stopSleeper := func() { |
| + t.Helper() |
| + run("systemctl", "stop", sleeper+".service") |
| + time.Sleep(500 * time.Millisecond) |
| + } |
| + kernel := func() string { |
| + t.Helper() |
| + var parts []string |
| + for _, f := range []string{"memory.max", "memory.swap.max", "pids.max", "cpu.max"} { |
| + b, err := os.ReadFile(filepath.Join(buildCgroupRoot, f)) |
| + if err != nil { |
| + t.Fatalf("%s: %v", f, err) |
| + } |
| + parts = append(parts, f+"="+strings.TrimSpace(string(b))) |
| + } |
| + return strings.Join(parts, " ") |
| + } |
| + t.Cleanup(func() { |
| + _ = exec.Command("systemctl", "stop", sleeper+".service", budgetSlice).Run() |
| + _ = os.Remove(unitPath) |
| + _ = exec.Command("systemctl", "daemon-reload").Run() |
| + }) |
| + ctx := context.Background() |
| + |
| + install(execsandbox.FamilySystemd) |
| + startSleeper() |
| + if ok, err := kernelBudgetMatches(1, execsandbox.FamilySystemd); err != nil || !ok { |
| + t.Fatalf("baseline: %v %v (%s)", ok, err, kernel()) |
| + } |
| + for _, step := range []struct{ from, to execsandbox.Family }{ |
| + {execsandbox.FamilySystemd, execsandbox.FamilyGVisor}, |
| + {execsandbox.FamilyGVisor, execsandbox.FamilySystemd}, |
| + } { |
| + w := &Worker{family: step.to, slots: make(chan struct{}, 1)} |
| + install(step.to) // the adopt pass: file + daemon-reload |
| + before := kernel() |
| + t.Logf("%s -> %s, after reload only: %s", step.from, step.to, before) |
| + if ok, _ := kernelBudgetMatches(1, step.to); ok { |
| + t.Fatalf("reload alone moved the kernel budget; the witness premise is gone: %s", before) |
| + } |
| + |
| + // A build (here the sleeper) still runs in the slice: defer. |
| + err := w.reconcileBudget(ctx) |
| + if !errors.Is(err, ErrBuild) { |
| + t.Fatalf("busy slice: want a DEMO-BUILD deferral, got %v", err) |
| + } |
| + if kernel() != before || run("systemctl", "is-active", sleeper+".service") != "active" { |
| + t.Fatalf("busy slice was touched: %s", kernel()) |
| + } |
| + t.Logf("busy slice deferred: %v", err) |
| + |
| + // The slice empties. systemd may re-apply the loaded budget itself |
| + // when the last unit leaves (seen on 257); either way the |
| + // reconciler must leave the slice on the loaded budget. |
| + stopSleeper() |
| + ok, _ := kernelBudgetMatches(1, step.to) |
| + t.Logf("slice emptied: kernel %s (already on the new budget: %v)", kernel(), ok) |
| + if err := w.reconcileBudget(ctx); err != nil { |
| + t.Fatalf("empty slice: %v", err) |
| + } |
| + // The stop branch on real systemd: an empty, active slice whose |
| + // kernel limits are stale (the state the reload left on the box). |
| + startSleeper() |
| + stopSleeper() |
| + old := SlicePropertiesFor(1, step.from) |
| + for name, v := range map[string]string{"memory.max": strconv.FormatInt(old["MemoryMax"], 10), "pids.max": strconv.FormatInt(old["TasksMax"], 10)} { |
| + if err := os.WriteFile(filepath.Join(buildCgroupRoot, name), []byte(v), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if ok, _ := kernelBudgetMatches(1, step.to); ok { |
| + t.Fatalf("could not stage stale limits: %s", kernel()) |
| + } |
| + if err := w.reconcileBudget(ctx); err != nil { |
| + t.Fatalf("empty stale slice: %v", err) |
| + } |
| + if out, _ := exec.Command("systemctl", "is-active", budgetSlice).CombinedOutput(); strings.TrimSpace(string(out)) != "inactive" { |
| + t.Fatalf("empty stale slice not stopped: %s", out) |
| + } |
| + t.Logf("empty stale slice stopped") |
| + startSleeper() |
| + if ok, err := kernelBudgetMatches(1, step.to); err != nil || !ok { |
| + t.Fatalf("restarted slice: %v %v (%s)", ok, err, kernel()) |
| + } |
| + t.Logf("restarted on the %s budget: %s", step.to, kernel()) |
| + // Converged: a further admission check changes nothing. |
| + if err := w.reconcileBudget(ctx); err != nil || run("systemctl", "is-active", sleeper+".service") != "active" { |
| + t.Fatalf("converged slice: %v", err) |
| + } |
| + } |
| +} |
diff --git a/internal/demobuild/budget_test.go b/internal/demobuild/budget_test.go| new file mode 100644 |
| index 000000000..ef4c07e7e |
| --- /dev/null |
| +++ b/internal/demobuild/budget_test.go |
| @@ -0,0 +1,190 @@ |
| +package demobuild |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "errors" |
| + "fmt" |
| + "os" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/execsandbox" |
| +) |
| + |
| +// budgetFixture: a worker with one slot in family, a fake build slice cgroup |
| +// holding kernel limits for kernelFamily, and a fake systemctl whose loaded |
| +// budget is the rendered one for loadedFamily. |
| +type budgetFixture struct { |
| + w *Worker |
| + calls []string |
| + jobs string |
| + active string |
| + stopErr error |
| +} |
| + |
| +func newBudgetFixture(t *testing.T, family, loadedFamily execsandbox.Family, kernelFamily execsandbox.Family, populated bool) *budgetFixture { |
| + t.Helper() |
| + f := &budgetFixture{active: "inactive"} |
| + f.w = &Worker{family: family, slots: make(chan struct{}, 1)} |
| + oldRoot, oldCtl := buildCgroupRoot, systemctl |
| + t.Cleanup(func() { buildCgroupRoot, systemctl = oldRoot, oldCtl }) |
| + buildCgroupRoot = filepath.Join(t.TempDir(), "carlos-demo-builds.slice") |
| + if kernelFamily != "" { |
| + if err := os.MkdirAll(buildCgroupRoot, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + k := SlicePropertiesFor(1, kernelFamily) |
| + pop := "0" |
| + if populated { |
| + pop = "1" |
| + } |
| + for name, v := range map[string]string{ |
| + "memory.max": strconv.FormatInt(k["MemoryMax"], 10), "memory.swap.max": "0", |
| + "pids.max": strconv.FormatInt(k["TasksMax"], 10), "cpu.max": "50000 100000", |
| + "cgroup.events": "populated " + pop + "\nfrozen 0\n", |
| + } { |
| + if err := os.WriteFile(filepath.Join(buildCgroupRoot, name), []byte(v+"\n"), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + } |
| + loaded := SlicePropertiesFor(1, loadedFamily) |
| + systemctl = func(_ context.Context, args ...string) (string, error) { |
| + f.calls = append(f.calls, strings.Join(args, " ")) |
| + switch { |
| + case args[0] == "show" && strings.Contains(strings.Join(args, " "), "MemoryMax"): |
| + return "MemoryMax=" + strconv.FormatInt(loaded["MemoryMax"], 10) + "\nMemorySwapMax=0\nTasksMax=" + strconv.FormatInt(loaded["TasksMax"], 10) + "\nCPUQuotaPerSecUSec=500ms\n", nil |
| + case args[0] == "show": |
| + return "ActiveState=" + f.active + "\n", nil |
| + case args[0] == "list-jobs": |
| + return f.jobs, nil |
| + case args[0] == "stop": |
| + if f.stopErr != nil { |
| + return "", f.stopErr |
| + } |
| + // Stopping the slice removes its cgroup. |
| + if err := os.RemoveAll(buildCgroupRoot); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + return "", nil |
| + } |
| + return f |
| +} |
| + |
| +func (f *budgetFixture) stopped() bool { |
| + for _, c := range f.calls { |
| + if c == "stop "+budgetSlice { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +func TestReconcileBudget(t *testing.T) { |
| + gv, sd := execsandbox.FamilyGVisor, execsandbox.FamilySystemd |
| + for _, tc := range []struct { |
| + name string |
| + family, loaded, kn execsandbox.Family |
| + populated, busy bool |
| + jobs string |
| + active string |
| + stopErr error |
| + wantErr, wantStop bool |
| + }{ |
| + {name: "kernel matches", family: gv, loaded: gv, kn: gv}, |
| + {name: "slice not running", family: gv, loaded: gv}, |
| + {name: "stale kernel, empty slice is stopped", family: gv, loaded: gv, kn: sd, wantStop: true}, |
| + {name: "stale kernel back to systemd", family: sd, loaded: sd, kn: gv, wantStop: true}, |
| + {name: "stale config is left for adopt", family: gv, loaded: sd, kn: sd, wantErr: true}, |
| + {name: "builds running defer", family: gv, loaded: gv, kn: sd, busy: true, wantErr: true}, |
| + {name: "populated slice defers", family: gv, loaded: gv, kn: sd, populated: true, wantErr: true}, |
| + {name: "queued build defers", family: gv, loaded: gv, kn: sd, jobs: "12 carlos-demo-build@aa_1.service start waiting\n", wantErr: true}, |
| + {name: "queued slice job defers", family: gv, loaded: gv, kn: sd, jobs: "13 carlos-demo-builds.slice stop running\n", wantErr: true}, |
| + {name: "truncated job list defers", family: gv, loaded: gv, kn: sd, jobs: strings.Repeat("1 other.service start waiting\n", systemctlCaptureLimit/30+1), wantErr: true}, |
| + {name: "stop fails", family: gv, loaded: gv, kn: sd, stopErr: errors.New("bus"), wantErr: true, wantStop: true}, |
| + {name: "still active after stop", family: gv, loaded: gv, kn: sd, active: "active", wantErr: true, wantStop: true}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + f := newBudgetFixture(t, tc.family, tc.loaded, tc.kn, tc.populated) |
| + f.jobs, f.stopErr = tc.jobs, tc.stopErr |
| + if tc.active != "" { |
| + f.active = tc.active |
| + } |
| + if tc.busy { |
| + f.w.buildPurge.RLock() |
| + defer f.w.buildPurge.RUnlock() |
| + } |
| + err := f.w.reconcileBudget(context.Background()) |
| + if (err != nil) != tc.wantErr { |
| + t.Fatalf("err %v, calls %v", err, f.calls) |
| + } |
| + if tc.wantErr && !errors.Is(err, ErrBuild) && tc.stopErr == nil { |
| + t.Fatalf("a deferral must be a retryable DEMO-BUILD: %v", err) |
| + } |
| + pending := tc.busy || tc.populated || tc.jobs != "" |
| + if errors.Is(err, errBudgetPending) != pending { |
| + t.Fatalf("pending=%v for %v", errors.Is(err, errBudgetPending), err) |
| + } |
| + if f.stopped() != tc.wantStop { |
| + t.Fatalf("stopped=%v, calls %v", f.stopped(), f.calls) |
| + } |
| + if !tc.wantStop && tc.stopErr == nil { |
| + for _, c := range f.calls { |
| + if strings.HasPrefix(c, "stop") || strings.HasPrefix(c, "set-property") { |
| + t.Fatalf("changed the slice: %v", f.calls) |
| + } |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// A pending budget change keeps the job waiting, not failed: Build retries |
| +// admission until the job's deadline. Any other admission error fails at once. |
| +func TestBuildWaitsOutPendingBudget(t *testing.T) { |
| + old := budgetRetry |
| + budgetRetry = 5 * time.Millisecond |
| + t.Cleanup(func() { budgetRetry = old }) |
| + pending := fmt.Errorf("%w: %w: test", ErrBuild, errBudgetPending) |
| + |
| + w, j, priv, src := workerFixture(t) |
| + tries := 0 |
| + w.admit = func(context.Context) error { |
| + if tries++; tries < 3 { |
| + return pending |
| + } |
| + return nil |
| + } |
| + ran := false |
| + w.run = func(context.Context, string, Lock) (BuildOutput, error) { ran = true; return BuildOutput{}, nil } |
| + wire, _ := SignJob(priv, j) |
| + if _, err := w.Build(context.Background(), wire, bytes.NewReader(src)); err != nil || !ran || tries != 3 { |
| + t.Fatalf("err=%v ran=%v tries=%d", err, ran, tries) |
| + } |
| + |
| + w, j, priv, src = workerFixture(t) |
| + w.admit = func(context.Context) error { return pending } |
| + w.run = func(context.Context, string, Lock) (BuildOutput, error) { |
| + t.Fatal("ran while pending") |
| + return BuildOutput{}, nil |
| + } |
| + wire, _ = SignJob(priv, j) |
| + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) |
| + defer cancel() |
| + if _, err := w.Build(ctx, wire, bytes.NewReader(src)); !errors.Is(err, errBudgetPending) { |
| + t.Fatalf("a budget still pending at the deadline: %v", err) |
| + } |
| + |
| + w, j, priv, src = workerFixture(t) |
| + calls := 0 |
| + w.admit = func(context.Context) error { calls++; return ErrBuild } |
| + wire, _ = SignJob(priv, j) |
| + if _, err := w.Build(context.Background(), wire, bytes.NewReader(src)); !errors.Is(err, ErrBuild) || calls != 1 { |
| + t.Fatalf("a real admission failure must not retry: %v after %d", err, calls) |
| + } |
| +} |
diff --git a/internal/demobuild/worker.go b/internal/demobuild/worker.go| index e6b531f97..29c3c4cf2 100644 |
| --- a/internal/demobuild/worker.go |
| +++ b/internal/demobuild/worker.go |
| @@ -44,12 +44,16 @@ type Worker struct { |
| proof func(context.Context) error |
| prepare func(context.Context, string, Source) (func() error, error) |
| run func(context.Context, string, Lock) (BuildOutput, error) |
| - processLock *os.File |
| - mu sync.Mutex |
| - poisoned bool |
| - ready bool |
| - initMu sync.Mutex |
| - initDone bool |
| + // admit runs before a build is admitted; nil is reconcileBudget, the |
| + // production check. Unit tests that stand in prepare and run stand this |
| + // in too. |
| + admit func(context.Context) error |
| + processLock *os.File |
| + mu sync.Mutex |
| + poisoned bool |
| + ready bool |
| + initMu sync.Mutex |
| + initDone bool |
| snapshotPoisoned bool |
| } |
| @@ -209,10 +213,32 @@ func (w *Worker) Build(ctx context.Context, wire []byte, source io.Reader) (out |
| if err != nil { |
| return out, err |
| } |
| - w.buildPurge.RLock() |
| - defer w.buildPurge.RUnlock() |
| + // Before admission: a budget the kernel does not have yet reaches the |
| + // slice only while nothing runs in it (budget.go). |
| ctx, cancel := context.WithDeadline(ctx, j.Deadline) |
| defer cancel() |
| + admit := w.admit |
| + if admit == nil { |
| + admit = w.reconcileBudget |
| + } |
| + // A pending budget change waits for running work to finish; the job |
| + // keeps its place until its own deadline rather than failing. |
| + for { |
| + err := admit(ctx) |
| + if err == nil { |
| + break |
| + } |
| + if !errors.Is(err, errBudgetPending) { |
| + return out, err |
| + } |
| + select { |
| + case <-ctx.Done(): |
| + return out, err |
| + case <-time.After(budgetRetry): |
| + } |
| + } |
| + w.buildPurge.RLock() |
| + defer w.buildPurge.RUnlock() |
| select { |
| case w.slots <- struct{}{}: |
| defer func() { <-w.slots }() |
diff --git a/internal/demobuild/worker_test.go b/internal/demobuild/worker_test.go| index 45890f632..e0cc2ba04 100644 |
| --- a/internal/demobuild/worker_test.go |
| +++ b/internal/demobuild/worker_test.go |
| @@ -31,7 +31,7 @@ func workerFixture(t *testing.T) (*Worker, Job, ed25519.PrivateKey, []byte) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - w := &Worker{removeSandbox: func(string) error { return nil }, ready: true, cfg: demo.Config{Account: "shop", Fleet: "demo", Domain: "example.com", BuildConcurrency: 1}, box: "box-1", pub: pub, lock: testLock(t), digest: strings.Repeat("b", 64), root: t.TempDir(), slots: make(chan struct{}, 1), proof: func(context.Context) error { return nil }} |
| + w := &Worker{removeSandbox: func(string) error { return nil }, ready: true, cfg: demo.Config{Account: "shop", Fleet: "demo", Domain: "example.com", BuildConcurrency: 1}, box: "box-1", pub: pub, lock: testLock(t), digest: strings.Repeat("b", 64), root: t.TempDir(), slots: make(chan struct{}, 1), proof: func(context.Context) error { return nil }, admit: func(context.Context) error { return nil }} |
| w.prepare = func(context.Context, string, Source) (func() error, error) { return func() error { return nil }, nil } |
| w.run = func(context.Context, string, Lock) (BuildOutput, error) { return BuildOutput{}, nil } |
| j := Job{ID: base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{1}, 32)), DemoID: base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{2}, 16)), Account: "shop", App: "tmp-demo-bright-otter-42", Host: "bright-otter-42.example.com", Lifetime: "life-1", Fleet: "demo", Box: "box-1", SourceSHA256: v.SHA256, BundleSHA256: w.digest, Generation: 1, Attempt: 1, Deadline: time.Now().UTC().Add(time.Minute)} |
| @@ -142,7 +142,7 @@ func TestDemoBuildSlotsAndReplay(t *testing.T) { |
| t.Fatal("replayed completed attempt") |
| } |
| // A new process reads the same durable marker before it opens source. |
| - w2 := &Worker{ready: true, cfg: w.cfg, box: w.box, pub: w.pub, lock: w.lock, digest: w.digest, root: w.root, slots: make(chan struct{}, 1), proof: w.proof, prepare: w.prepare, run: w.run} |
| + w2 := &Worker{ready: true, cfg: w.cfg, box: w.box, pub: w.pub, lock: w.lock, digest: w.digest, root: w.root, slots: make(chan struct{}, 1), proof: w.proof, prepare: w.prepare, run: w.run, admit: w.admit} |
| if _, err := w2.Build(context.Background(), wire, neverRead{t}); err == nil { |
| t.Fatal("replayed after root restart") |
| } |
diff --git a/internal/host/demo_slice_adopt_linux_test.go b/internal/host/demo_slice_adopt_linux_test.go| new file mode 100644 |
| index 000000000..0fcefa7bc |
| --- /dev/null |
| +++ b/internal/host/demo_slice_adopt_linux_test.go |
| @@ -0,0 +1,172 @@ |
| +package host |
| + |
| +import ( |
| + "errors" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "strconv" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/demobuild" |
| + "github.com/carlosframework/platform/internal/execsandbox" |
| +) |
| + |
| +// A demo build box switched from systemd to gVisor in host.env changes no |
| +// unit but the build budget slice. One adopt pass must re-render it and |
| +// reload systemd; before this, the pass returned as already armed and every |
| +// gVisor build refused at its budget check (v0.34.35 dev witness). |
| +func TestAdoptRerendersDemoBuildSliceOnSandboxFlip(t *testing.T) { |
| + root := t.TempDir() |
| + etc, opt := filepath.Join(root, "etc"), filepath.Join(root, "opt/carlos") |
| + unitDir := filepath.Join(etc, "systemd/system") |
| + for _, dir := range []string{unitDir, filepath.Join(etc, "carlos")} { |
| + if err := os.MkdirAll(dir, 0755); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + const demoEnv = "CARLOS_DEMO_BOX=1\nCARLOS_DEMO_ACCOUNT=shop\nCARLOS_DEMO_FLEET=demo\nCARLOS_DEMO_DOMAIN=example.com\nCARLOS_DEMO_BUILD_WORKER=1\nCARLOS_DEMO_BUILD_CONCURRENCY=1\nCARLOS_DEMO_TOOLCHAIN_DIR=/opt/demo-toolchain\n" |
| + envPath := filepath.Join(etc, "carlos/host.env") |
| + writeEnv := func(mode string) { |
| + t.Helper() |
| + if err := os.WriteFile(envPath, []byte("CARLOS_EXEC_SANDBOX="+mode+"\n"+demoEnv), 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + writeEnv("systemd") |
| + settings, err := readClaimUnitSettings(envPath) |
| + if err != nil || !settings.demo.BuildWorker { |
| + t.Fatalf("settings: %+v %v", settings, err) |
| + } |
| + // An armed systemd-mode box: every unit as this build renders it. |
| + for _, name := range systemUnitFiles { |
| + raw, err := unitsFS.ReadFile("units/" + name) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(filepath.Join(unitDir, name), claimUnitContent(name, raw, settings), 0644); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + 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) |
| + } |
| + return "disabled", systemctlExit(1) |
| + } |
| + if args[0] == "is-active" { |
| + return "active", nil |
| + } |
| + return "enabled", nil |
| + } |
| + var calls [][]string |
| + reloadFails := false |
| + call := func(args ...string) (string, error) { |
| + calls = append(calls, args) |
| + 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) |
| + 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" |
| + } |
| + if want(execsandbox.FamilySystemd) == want(execsandbox.FamilyGVisor) { |
| + t.Fatal("the two families size the slice alike; this test proves nothing") |
| + } |
| + readSlice := func() string { |
| + t.Helper() |
| + b, err := os.ReadFile(slicePath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return string(b) |
| + } |
| + |
| + ensureSystemUnits(etc, lock, call, probe, t.Logf) |
| + if len(calls) != 0 { |
| + t.Fatalf("armed systemd box changed units: %v", calls) |
| + } |
| + if !strings.Contains(readSlice(), want(execsandbox.FamilySystemd)) { |
| + t.Fatalf("baseline slice: %s", readSlice()) |
| + } |
| + |
| + writeEnv("gvisor") |
| + ensureSystemUnits(etc, lock, call, probe, t.Logf) |
| + if got := readSlice(); !strings.Contains(got, want(execsandbox.FamilyGVisor)) { |
| + t.Fatalf("one pass after the flip left the slice at:\n%s", got) |
| + } |
| + 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) |
| + } |
| + calls = nil |
| + ensureSystemUnits(etc, lock, call, probe, t.Logf) |
| + if len(calls) != 0 { |
| + t.Fatalf("second pass on the flipped box changed units again: %v", calls) |
| + } |
| + |
| + writeEnv("systemd") |
| + ensureSystemUnits(etc, lock, call, probe, t.Logf) |
| + 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) |
| + } |
| + |
| +} |
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/systemunits.go b/internal/host/systemunits.go| index 1c5ba3d06..79e480172 100644 |
| --- a/internal/host/systemunits.go |
| +++ b/internal/host/systemunits.go |
| @@ -34,7 +34,10 @@ var ensureSystemArmed = []string{systemUpdatePathUnit, systemRecoverUnit, instan |
| // carlos-dbread.socket and its service template are the db-read worker's |
| // (db region forward spec §8.3): installed and the socket armed here, the |
| // template never started. |
| -var systemUnitFiles = []string{"carlos-runsc.service", instancectl.UnitPrefixGVisor + ".service", "carlos-instance-gvisor-probe.service", "carlos-demo-build-gvisor@.service", "carlos-system-update.path", "carlos-system-update.service", systemRecoverUnit, instanceControlSocket, "carlos-instance-control.service", dbReadSocketUnit, "carlos-dbread@.service", "carlos-demo-build@.service", "carlos-demo-builds.slice"} |
| +// demoBuildsSlice is the demo build budget, rendered per box by claimUnitContent. |
| +const demoBuildsSlice = "carlos-demo-builds.slice" |
| + |
| +var systemUnitFiles = []string{"carlos-runsc.service", instancectl.UnitPrefixGVisor + ".service", "carlos-instance-gvisor-probe.service", "carlos-demo-build-gvisor@.service", "carlos-system-update.path", "carlos-system-update.service", systemRecoverUnit, instanceControlSocket, "carlos-instance-control.service", dbReadSocketUnit, "carlos-dbread@.service", "carlos-demo-build@.service", demoBuildsSlice} |
| // ensureSystemUnits is the second belt of spec §7: a box the roll script |
| // forgot to arm is armed within the hour by the root adopt pass. It |
| @@ -200,6 +203,35 @@ func ensureSystemUnitsWithGuard(etcDir, lockPath string, systemctl, probe func(a |
| return |
| } |
| controlChanged := settingsErr == nil && (claimSettings.enabled || claimSettings.demo.BoxMode() || claimControlRendered(installed)) && (err != nil || !bytes.Equal(installed, claimUnitContent(claimControlUnit, control, claimSettings))) |
| + // The demo build budget slice is rendered from host.env too: the build |
| + // concurrency and the effective exec sandbox size it. A host.env change |
| + // alone (a box switched to gVisor) touches no other unit, so without this |
| + // comparison the pass would return as already armed and leave the slice |
| + // sized for the old sandbox, and every build would refuse at its budget |
| + // check. A missing slice is already a reinstall (missing). |
| + sliceChanged := false |
| + if settingsErr == nil { |
| + sliceRaw, err := unitsFS.ReadFile("units/" + demoBuildsSlice) |
| + if err != nil { |
| + logf("adopt: system units: %v", err) |
| + return |
| + } |
| + sliceInstalled, err := os.ReadFile(filepath.Join(unitDir, demoBuildsSlice)) |
| + if err != nil && !os.IsNotExist(err) { |
| + logf("adopt: demo build slice: %v", err) |
| + return |
| + } |
| + want := claimUnitContent(demoBuildsSlice, sliceRaw, claimSettings) |
| + 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. |
| dbrDark := !*dbrActive && (dbrEnabled == nil || !*dbrEnabled) |
| @@ -212,7 +244,7 @@ func ensureSystemUnitsWithGuard(etcDir, lockPath string, systemctl, probe func(a |
| return |
| } |
| } |
| - if !demoChanged && !missing && !controlChanged && *isActive && isEnabled != nil && *isEnabled && *ctlActive && dbrSettled { |
| + if !demoChanged && !missing && !controlChanged && !sliceChanged && *isActive && isEnabled != nil && *isEnabled && *ctlActive && dbrSettled { |
| return |
| } |
| if err := os.MkdirAll(unitDir, 0o755); err != nil { |
| @@ -295,3 +327,27 @@ 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"] |
| +} |
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 b7c4f5ec1..01fd1a9f3 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -141,4 +141,5 @@ plan14-root-reads-region-ha-held-build.tsv beb085e4c6cdb3d430d12a8dc3c93f25cc3fa |
| plan14-root-reads-fixedbox-health-alarms.tsv 0f7153571df8c1b4b50c31f57efcfdf60c71a12c80fd935fb3ea202fa0201dd5 |
| plan14-root-reads-fixed-host-ignore-user-data.tsv 250e3ba91e1bc5fcd6be5cc2bafce4c7d6645d2d2f0c080913b99f01b1d19129 |
| plan14-root-reads-deploy-edge-718.tsv 250e3ba91e1bc5fcd6be5cc2bafce4c7d6645d2d2f0c080913b99f01b1d19129 |
| -plan14-root-reads-security-review-mitigations.tsv d0f9e4412c80fd81f1264a38d70df5e0ed4bbcb3a4cb848388da8ad1d4661a1e |
| +plan14-root-reads-demo-slice-adopt.tsv 707018faaa1fee3b47abb78389ae7854264e76621cc316889061adb69bf13e10 |
| +plan14-root-reads-security-review-mitigations.tsv a6f3f9eec4aac5ea88f20d0e52eaa0651fce80c0d49b60883ff61ceade33d288 |
diff --git a/internal/provision/testdata/plan14-root-reads-demo-slice-adopt.tsv b/internal/provision/testdata/plan14-root-reads-demo-slice-adopt.tsv| new file mode 100644 |
| index 000000000..bca83f8b8 |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-demo-slice-adopt.tsv |
| @@ -0,0 +1,13 @@ |
| +# 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. |
| +# 1 body, 1 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +# 2 new dispositions: 0 reads re-frozen at their disposition with the claim, 2 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other. |
| +@legacy 43550b6e48cc4c57755d999ad44c7a7ed9369b6c53ce89fc59eb00c0e187ddab internal/demobuild/worker.go Worker.Build legacy accepted-legacy accepted-legacy;rev3=census-ruling-agent-start-demo-1;basis=Holds the build/purge read lock through cleanup; existing bounded source read remains.;rev3=census-ruling-demo-slice-adopt;basis=Before admission, call the admit hook (nil = reconcileBudget); a pending budget change (errBudgetPending) is retried every 2 s until the job deadline, any other error fails at once. reconcileBudget reads the fixed build slice's systemctl show budget, its cgroup limit files and cgroup.events under the fixed root cgroup path, and list-jobs (a listing at the capture limit defers); only with buildPurge held exclusively, the slice empty and no build or slice job queued does it run systemctl stop on the fixed slice name. No tenant, app or agent input names a path or unit. file:ReadAll@1087 be01e7c25a520d79132c28cb1bc6ac274139643981a5f7d415cd876e333c2da8 |
| +@legacy bf0fab994b0fd42b2af18b70e21c4b8cbe3b4dfe8e0e9988f246f0ea9275afb6 internal/demobuild/budget.go budgetSlicePopulated legacy accepted-legacy accepted-legacy;rev3=census-ruling-demo-slice-adopt;basis=New. Reads cgroup.events under the fixed build slice cgroup path (buildCgroupRoot); absent = empty; a file without a populated line refuses. file:ReadFile@55 60e72229ce907ec9eb953caf4d35c56416153a10f9e73520b55571c2e11b7ca2 |
| +@legacy 4b52c494b53f26d262697e10cfd31bad182f2c54c1b56e529b9b930fa439c936 internal/demobuild/budget.go kernelBudgetMatches legacy accepted-legacy accepted-legacy;rev3=census-ruling-demo-slice-adopt;basis=New. Reads memory.max, memory.swap.max, pids.max and cpu.max under the fixed build slice cgroup path and compares them with SlicePropertiesFor; absent cgroup = slice not running = match; read errors refuse. file:Lstat@168,file:ReadFile@591 fc138916d7510dd62066c8bafa97c8c4b7bf9a108537862f73f9bfbdcd2853c8 |
| +@legacy 55e6adc18f848f6049ffc4504debbacd1f5704dc1f9eac798bc74d2d09b83196 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 name). A definite difference is a reinstall (existing write loop + daemon-reload). No live budget change, no new path, input or write target. file:OpenFile@985,file:ReadFile@5626,file:ReadFile@5759,file:ReadFile@6647,file:ReadFile@6789,file:ReadFile@8548,file:Stat@5535 134e8105086fb29df32933f0ef26e664c0f08b7b8667a909838f2bde0c0fecfb |
| +internal/demobuild/worker.go Worker.Build legacy accepted-legacy accepted-legacy;rev3=census-ruling-agent-start-demo-1;basis=Holds the build/purge read lock through cleanup; existing bounded source read remains.;rev3=census-ruling-demo-slice-adopt;basis=Before admission, call the admit hook (nil = reconcileBudget); a pending budget change (errBudgetPending) is retried every 2 s until the job deadline, any other error fails at once. reconcileBudget reads the fixed build slice's systemctl show budget, its cgroup limit files and cgroup.events under the fixed root cgroup path, and list-jobs (a listing at the capture limit defers); only with buildPurge held exclusively, the slice empty and no build or slice job queued does it run systemctl stop on the fixed slice name. No tenant, app or agent input names a path or unit. file:ReadAll@1087 be01e7c25a520d79132c28cb1bc6ac274139643981a5f7d415cd876e333c2da8 |
| +internal/demobuild/budget.go budgetSlicePopulated legacy accepted-legacy accepted-legacy;rev3=census-ruling-demo-slice-adopt;basis=New. Reads cgroup.events under the fixed build slice cgroup path (buildCgroupRoot); absent = empty; a file without a populated line refuses. file:ReadFile@55 60e72229ce907ec9eb953caf4d35c56416153a10f9e73520b55571c2e11b7ca2 |
| +internal/demobuild/budget.go kernelBudgetMatches legacy accepted-legacy accepted-legacy;rev3=census-ruling-demo-slice-adopt;basis=New. Reads memory.max, memory.swap.max, pids.max and cpu.max under the fixed build slice cgroup path and compares them with SlicePropertiesFor; absent cgroup = slice not running = match; read errors refuse. file:Lstat@168,file:ReadFile@591 fc138916d7510dd62066c8bafa97c8c4b7bf9a108537862f73f9bfbdcd2853c8 |
| +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 name). A definite difference is a reinstall (existing write loop + daemon-reload). No live budget change, no new path, input or write target. file:OpenFile@985,file:ReadFile@5626,file:ReadFile@5759,file:ReadFile@6647,file:ReadFile@6789,file:ReadFile@8548,file:Stat@5535 134e8105086fb29df32933f0ef26e664c0f08b7b8667a909838f2bde0c0fecfb |
| +@coverage internal/demobuild 64b77e1e6fd5dfa470fd4ab98f82b8b1df689ffde04eedbb757cb6ad627fac52 |
| +@coverage internal/host 88889b9888f3bec0a97e22581c486a81cd33951a8b2148299788ce5abe0512f6 |
diff --git a/internal/provision/testdata/plan14-root-reads-security-review-mitigations.tsv b/internal/provision/testdata/plan14-root-reads-security-review-mitigations.tsv| index 960d9e9a7..a62452423 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-security-review-mitigations.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-security-review-mitigations.tsv |
| @@ -11,5 +11,5 @@ internal/provision/reconcile.go RouteFor authority C,E3 rev3=census-ruling-self- |
| internal/activator/backend_exec.go ExecBackend.spawnChildFrom legacy accepted-legacy accepted-legacy;rev3=census-ruling-zddr3;basis=Census ruling zddr3: changed legacy row (comment-only change describing the shim placement); the same class as the accepted-legacy Manager.startIn and placementLive under fix1-merge-review (existing agent delegated-cgroup management remains legacy); no root decision; no registry, /data, release or claim reads. Boundary: the agent's own delegated cgroup subtree (including its scratch probe child), /proc/self, and pipes to and from its own parent, running as carlos.;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos (the flat start body): the same change as seedChild: ensureAdminTokenFor(ctx, rt, paths) for the token (the same flat path), the key's producer carrying the HA mint decision, and launchEnvLayer(ctx, rt) for the env and key layer the replica gate reads; a non-HA host's token, key and env are produced and read as before; +whole:Route; only adds refusals for HA hosts;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Use the verified generation/launch mode to remove CARLOS_DB after environment merges and omit the binary --db argument where applicable. Existing runtime, layout, secrets and exec gates remain; route reads are mode projection only.;rev3=census-ruling-edge-page-cache-1;basis=the control listener is now built with the whole route (edge.ListenControl(controlSocket, rt, ...)), the +whole:Route site; it computes the launch inputs once from the build it execs by path (a staged exe's caller-named build, or the gate-resolved pinned version; "" for an unpinned live link) and fileEnv it already read, keeps them on the childProc, and for a live-link spawn publishes them to the in-memory cache (NoteProcessInputs) beside the existing purge; no new file read;rev3=census-ruling-gvisor-demos;basis=Task 5: gate launch using startup-captured mode and existing route/role/layout before preparation or execution; migrate structured root start identity and reject mismatches. Unsupported gVisor paths refuse; native behavior and existing root authority checks retained. No new root read source. Merge2 e8a1ddde: retain main build parameter, pinned live identity, launchInputs from captured build/environment, and current-process input publication. edge.ListenControl now receives the whole Route as main requires (+whole:Route); no new filesystem or storage input. Branch sandboxLaunch remains before preparation and spawn; existing direct primitive gate unchanged.;rev3=census-ruling-security-review-mitigations;basis=Enforce the unchanged never-served resident refusal once at the shared flat/foreign primary binary spawn sink, before placement, live-link/token/env/control preparation or execution. Covers plain, generation and staged Service wakes; existing served/explicit-flat exemptions and other gates retained. No new filesystem/store source. file:Command@11357,registry:Host@12640,registry:Host@13001,registry:Host@13095,registry:Host@258,registry:Host@4214,registry:Host@4269,registry:Host@4349,registry:Host@4563,registry:Stateless@11288,whole:Route@11180,whole:Route@11329,whole:Route@11737,whole:Route@13392,whole:Route@13484,whole:Route@1527,whole:Route@189,whole:Route@1944,whole:Route@2305,whole:Route@287,whole:Route@4447,whole:Route@4757,whole:Route@476,whole:Route@6828,whole:Route@9093 62a25da95d4b4b98122648e98d7348f1159f50077e7cfb8d282d811627580dfd |
| @coverage . a8a543b00d620367c1c8cd92405990fa80f17cb24f064272a73b3b0181f0c482 |
| @coverage internal/activator e70ae33ab4b4fc57bada29629ddb3b3292a98265f28e861406f63e62be616755 |
| -@coverage internal/host fe9701b64f3f99a1d875e1db22ec275734c810442fec4172dd20b36628f56352 |
| +@coverage internal/host 7f8ae4cdb0dfe0bb2d6780500ad16c32b94fad06d6b8ac5ac28170208ade8ee1 |
| @coverage internal/provision a18e60c5f5e1369c16ffeb3ca53169110ff12c0cf11125d4698bd7f0ebb020b3 |