carlos / platform Public

Merge remote-tracking branch 'origin/main' into ppv2-operator-copy

# Conflicts:
#	internal/provision/testdata/plan14-root-reads-chain.tsv
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev a209a48a8292a3d916526120cc0597f310716818 parent 4a6c492parent ded2dab
17 files changed, +736 −22
  • docs/site/cli.md +2 −0
  • docs/superpowers/notes/census-claims-instance-gomemlimit-991.tsv +4 −0
  • docs/superpowers/notes/census-proposal-instance-gomemlimit-991.md +27 −0
  • docs/superpowers/notes/census-proposal-ppv2-operator-copy.md +1 −1
  • docs/superpowers/reviews/CODEX-FINDINGS-INSTANCE-GOMEMLIMIT-991-FIXES.md +22 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-INSTANCE-GOMEMLIMIT-991-R1.md +39 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-INSTANCE-GOMEMLIMIT-991-FIXES.md +13 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-INSTANCE-GOMEMLIMIT-991.md +41 −0
  • internal/activator/backend_exec.go +33 −6
  • internal/activator/containment.go +7 −7
  • internal/activator/gomemlimit.go +40 −0
  • internal/activator/gomemlimit_test.go +411 −0
  • internal/activator/unitproc_test.go +5 −0
  • internal/cgroup/cgroup.go +26 −0
  • internal/cgroup/cgroup_test.go +51 −7
  • internal/provision/testdata/plan14-root-reads-chain.tsv +2 −1
  • internal/provision/testdata/plan14-root-reads-instance-gomemlimit-991.tsv +12 −0

CI passed — run details

Intent

Human

<task-notification> <task-id>be23qvhou</task-id> <tool-use-id>toolu_01NLfZDuvQsiz2JSoX9Es3RU</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/a0025b5e-60c7-44a1-8f2f-0568a41826c3/tasks/be23qvhou.output</output-file> <status>completed</status> <summary>Background command "Wait for the census review verdict" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>bzfa4i9ef</task-id> <tool-use-id>toolu_011ffa5ZuERPGX16gwh2G3UP</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/a0025b5e-60c7-44a1-8f2f-0568a41826c3/tasks/bzfa4i9ef.output</output-file> <status>completed</status> <summary>Background command "Wait for CI on the new tip" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>b2tfp5xct</task-id> <tool-use-id>toolu_013xQG39e2rGJeyz6X1RNfhx</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/a0025b5e-60c7-44a1-8f2f-0568a41826c3/tasks/b2tfp5xct.output</output-file> <status>completed</status> <summary>Background command "Push the merged tip and wait for CI" completed (exit code 0)</summary> </task-notification>

Attributed to this commit: 11.8 g CO₂e (1,487,600 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on ppv2-operator-copy, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/docs/site/cli.md b/docs/site/cli.md
index 1826d00cb..e72a1fce5 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -1213,6 +1213,8 @@ no bundle can override:
| `CARLOS_PURGE` | `header` when the edge honours a `Carlos-Purge` response header, including `all` for every host of the instance |
| `CARLOS_ADMIN_TOKEN` | a secret shared with this one instance: the platform presents it when it calls your app, and your app presents it on `CARLOS_CONTROL_SOCKET` |
+A binary instance with an applied memory cap also gets `GOMEMLIMIT`, set to 80% of its memory size, unless your app’s config or `<host>.env` sets a value for it. Seeds, `carlos run` commands, rootfs apps and instances run under gVisor don’t get it.
+
The box keeps a sealed copy of each instance's `<host>.env`. It also keeps sealed copies of the `instance.key` and `report.token` files an app keeps at the top of its own directory. These copies are stored in the region's data bucket. Each copy is sealed to the box's secrets key and bound to your app. Only a box that can already read your app's secrets can open it. When a box starts an instance whose `<host>.env` is missing, it puts the sealed copy back first. This keeps the instance's `CARLOS_ADMIN_TOKEN` and `CARLOS_INSTANCE_KEY` instead of giving it new ones. A file that is there is never replaced. You can edit other values in `<host>.env`. The box seals the new contents within a minute. `CARLOS_ADMIN_TOKEN`, `CARLOS_INSTANCE_KEY`, `instance.key` and `report.token` cannot change once sealed. If the box finds a different value, it refuses to start the instance and raises an alert. Deleting the file does not reset it. A box without the secrets key a copy was sealed to will not start that instance. This includes a box whose key was changed. Put the old key back.
A seed (the `--seed` command of `carlos instances enable`) runs with the same
diff --git a/docs/superpowers/notes/census-claims-instance-gomemlimit-991.tsv b/docs/superpowers/notes/census-claims-instance-gomemlimit-991.tsv
new file mode 100644
index 000000000..ff89abddd
--- /dev/null
+++ b/docs/superpowers/notes/census-claims-instance-gomemlimit-991.tsv
@@ -0,0 +1,4 @@
+internal/activator/backend_exec.go:ExecBackend.spawnUnitFrom #991: the agent as carlos (nested start): resolves the zero tier once (b.tier(rt), the existing live-tier read), adds GOMEMLIMIT=GoMemLimitOf(tier.MemoryMax) to the launch file env unless the app's fileEnv already names it (withGoMemLimit; skipped under gVisor, where root supplies its own and drops any launch value), passes that same tier to startRole, and logs it. No new read source; root still validates memory_max against the size table; read sites unchanged.
+internal/activator/backend_exec.go:ExecBackend.spawnChildFrom #991: the agent as carlos (flat exec child): resolves the zero tier once with the existing b.tier(rt) live-tier read (the +whole:Route site) and passes it to spawnInCgroupAtTier, which previously made the same read itself. Inside the build closure (which the cgroup manager calls after writing the limits) it asks cgroup.Manager.Capped(host, child, tier), a read of memory.max in the agent's own delegated cgroup subtree, and only when that reads back as the tier adds GOMEMLIMIT=GoMemLimitOf(tier.MemoryMax) to the child env, unless the app's fileEnv names it. No delegation, a cgroup that could not be made, or a failed memory.max write gives no default (Astra R1 P2-1). Containment behaviour unchanged; no gate moved or weakened; no registry, /data, release or store read added.
+internal/activator/containment.go:ExecBackend.startRole #991: the zero-tier default (b.tier(rt)) is applied once at the top instead of in each branch, and generation 0 with no exe now honours a non-zero tier its caller already read (spawnUnitFrom) instead of re-reading the live tier; every caller with exe nil passed a zero tier before, so the value root is asked for is unchanged. The -whole:Route x2 sites are the two folded b.tier(rt) calls. Claim refusal and sandbox gate unchanged.
+internal/cgroup/cgroup.go:Manager.Capped #991 (Astra R1 P2-1): new, the agent as carlos: reads <root>/carlos-exec@<host>[/<child>]/memory.max in the agent's own delegated cgroup subtree and compares it with the limit a start asked for; nil manager, zero limit, a child name isChildName refuses, or an unreadable or unparsable file answer false. Read only: it writes nothing, starts nothing, and changes no start; its one caller (spawnChildFrom's build closure) uses it only to decide whether to add the GOMEMLIMIT default to the child env.
diff --git a/docs/superpowers/notes/census-proposal-instance-gomemlimit-991.md b/docs/superpowers/notes/census-proposal-instance-gomemlimit-991.md
new file mode 100644
index 000000000..8de0c5af8
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-instance-gomemlimit-991.md
@@ -0,0 +1,27 @@
+# Census approval: instance-gomemlimit-991
+
+Ruling `census-ruling-instance-gomemlimit-991`. The independent reviewer approves or rejects every change below, 1 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/activator/backend_exec.go` `ExecBackend.spawnUnitFrom` | body | unchanged (31) | #991: the agent as carlos (nested start): resolves the zero tier once (b.tier(rt), the existing live-tier read), adds GOMEMLIMIT=GoMemLimitOf(tier.MemoryMax) to the launch file env unless the app's fileEnv already names it (withGoMemLimit; skipped under gVisor, where root supplies its own and drops any launch value), passes that same tier to startRole, and logs it. No new read source; root still validates memory_max against the size table; read sites unchanged. |
+| `internal/activator/backend_exec.go` `ExecBackend.spawnChildFrom` | sites | +whole:Route | #991: the agent as carlos (flat exec child): resolves the zero tier once with the existing b.tier(rt) live-tier read (the +whole:Route site) and passes it to spawnInCgroupAtTier, which previously made the same read itself. Inside the build closure (which the cgroup manager calls after writing the limits) it asks cgroup.Manager.Capped(host, child, tier), a read of memory.max in the agent's own delegated cgroup subtree, and only when that reads back as the tier adds GOMEMLIMIT=GoMemLimitOf(tier.MemoryMax) to the child env, unless the app's fileEnv names it. No delegation, a cgroup that could not be made, or a failed memory.max write gives no default (Astra R1 P2-1). Containment behaviour unchanged; no gate moved or weakened; no registry, /data, release or store read added. |
+| `internal/activator/containment.go` `ExecBackend.startRole` | sites | -whole:Route ×2 | #991: the zero-tier default (b.tier(rt)) is applied once at the top instead of in each branch, and generation 0 with no exe now honours a non-zero tier its caller already read (spawnUnitFrom) instead of re-reading the live tier; every caller with exe nil passed a zero tier before, so the value root is asked for is unchanged. The -whole:Route x2 sites are the two folded b.tier(rt) calls. Claim refusal and sandbox gate unchanged. |
+
+Envelopes re-pinned: `internal/activator`, `internal/cgroup`.
+
+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/activator/backend_exec.go` `ExecBackend.spawnUnitFrom`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-carlos-run;basis=Re-digested at the pre-land merge: the body includes main's own change under census ruling 292, with no further change from this branch. the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body; it calls prepareKeyedAt and keeps the launch environment and its key layer on the generation's handle; read sites unchanged, offsets moved;rev3=census-ruling-wake-latency-2;basis=times the launch's steps with time.Now() (build, prepare, launch file, gate, root start) and adds them to its existing "started" journal line; no read added or moved;rev3=census-ruling-rootfs-apps-2;basis=the unit names in its error and log lines go through runUnitName, and newUnitProcFor's new error (a role with no unit to observe) fails the start as markStartUncertain after root started the unit; the binary spawn is otherwise unchanged, a rootfs row never reaches it (nestedGate refuses one); no read added;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=computes the page cache launch inputs once (launchInputs: sha256 over the staged or pinned exe's Version and the fileEnv this spawn already read; "" with no exe, since root binds the movable live link) and keeps them on the unit handle (up.inputs); no new file, registry or bucket read; read sites unchanged (29); no read added;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 launchInputs computed from the captured file environment and pinned/staged build and store them on the handle, alongside branch sandbox gate, validated root StartResponse Unit/Sandbox/InvocationID and all uncertain-start cleanup. No new direct read.;rev3=census-ruling-fix-silent-start-kill-861;basis=#861: one log line before killFailedGen naming the host, the generation unit (runUnitName) and the error already in hand; the +registry:Host sites are those two arguments to log.Printf; no new read source, behaviour unchanged
+- `internal/activator/backend_exec.go` `ExecBackend.spawnChildFrom`: legacy, task accepted-legacy. Basis: 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.
+- `internal/activator/containment.go` `ExecBackend.startRole`: authority, task E2. Basis: E40: claim-enabled raw backend refuses unsupported direct, placed and legacy-control launches before spawn. Claims-off body unchanged. TestPlan14GenerationBackendDirectBoundary, TestPlan14GenerationBackendControlBoundary, TestPlan14GenerationBackendAuxiliaryBoundary; each guard has an independent behavioral mutation. Agent-side refusal is not root reservation or containment evidence.;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.
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `internal/cgroup/cgroup.go:Manager.Capped`: reads +file:ReadFile; written legacy, accepted-legacy, frozen
+
+Seal: `07b748a749084fdaf61c5087a6edfca8a79273962822ce551dd4d42b0d20c063` → `19c9f395547d998f4b5e87e89c0dfa3b5f012d177a87eb5010a8c4defac305dc`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-instance-gomemlimit-991.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/census-proposal-ppv2-operator-copy.md b/docs/superpowers/notes/census-proposal-ppv2-operator-copy.md
index 1c4fa8e29..9142a7aa1 100644
--- a/docs/superpowers/notes/census-proposal-ppv2-operator-copy.md
+++ b/docs/superpowers/notes/census-proposal-ppv2-operator-copy.md
@@ -6,6 +6,6 @@ Envelopes re-pinned: `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.
-Seal: `07b748a749084fdaf61c5087a6edfca8a79273962822ce551dd4d42b0d20c063` → `07b748a749084fdaf61c5087a6edfca8a79273962822ce551dd4d42b0d20c063`.
+Seal: `19c9f395547d998f4b5e87e89c0dfa3b5f012d177a87eb5010a8c4defac305dc` → `19c9f395547d998f4b5e87e89c0dfa3b5f012d177a87eb5010a8c4defac305dc`.
Overlay: `internal/provision/testdata/plan14-root-reads-ppv2-operator-copy.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-INSTANCE-GOMEMLIMIT-991-FIXES.md b/docs/superpowers/reviews/CODEX-FINDINGS-INSTANCE-GOMEMLIMIT-991-FIXES.md
new file mode 100644
index 000000000..e9f35e877
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-INSTANCE-GOMEMLIMIT-991-FIXES.md
@@ -0,0 +1,22 @@
+Reviewed only `3a28687a..e529ff4097366ca68d965973c000f669e4c32837`, within round 1’s existing budget. **No new P1 or P2 findings.**
+
+| Changed census unit or envelope | Verdict |
+|---|---|
+| `Manager.Capped` — new `legacy / accepted-legacy` | **APPROVED.** [cgroup.go:459](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/instance-gomemlimit-991/internal/cgroup/cgroup.go:459) reads the agent’s delegated `memory.max`, validates child names and compares the captured limit. It grants no authority. |
+| `ExecBackend.spawnChildFrom` — re-claimed `legacy / accepted-legacy` | **APPROVED.** [backend_exec.go:2689](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/instance-gomemlimit-991/internal/activator/backend_exec.go:2689) constructs each attempt’s environment after limit application. The helper copies the map, so a retry cannot retain an injected value from the previous attempt. |
+| `internal/activator` envelope | **APPROVED.** The production change only conditions default injection; the remaining changes are regression tests. |
+| `internal/cgroup` envelope | **APPROVED.** The new read-only helper and tests leave placement and termination primitives unchanged. |
+
+`spawnUnitFrom` and `startRole` are unchanged within this diff; their round-one approvals stand.
+
+Containment, start identity, refusal gates and termination handling remain unchanged. The added read runs as the agent (`carlos`), using its existing delegated cgroup path; it introduces **no new root read of tenant-writable state**.
+
+**P3 — Failed PID-move fallback can retain the default.** At [cgroup.go:844](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/instance-gomemlimit-991/internal/cgroup/cgroup.go:844), environment construction precedes process start and the subsequent PID move. If that move fails, the process keeps its default despite never entering the capped group. **Acceptable as P3:** this preserves the existing unfenced flat fallback, changes no security gate or cleanup behavior, and affects the provenance of a soft runtime limit. Generation starts and fenced flat starts refuse this fallback.
+
+- **P2 1: Resolved**, except for that explicitly accepted P3; absent delegation, failed group creation and unapplied `memory.max` now omit the default.
+- **P2 3: Resolved.** Changing-tier tests assert one read and matching environment/cap values; generation zero also tests a supplied tier with zero live reads.
+- **P2 4: Resolved.** Documentation scopes the new default and lists excluded launch types; gVisor retains its separate root-supplied value.
+
+`git diff --check` passed. Targeted regression and census tests could not start: the read-only sandbox denied Go’s build directory under `$TMPDIR`; `GOCACHE` was unset. These approvals therefore rest on source inspection. No files were edited, no full suites ran, and no subagents were spawned.
+
+**READY**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-INSTANCE-GOMEMLIMIT-991-R1.md b/docs/superpowers/reviews/CODEX-FINDINGS-INSTANCE-GOMEMLIMIT-991-R1.md
new file mode 100644
index 000000000..17a4bda45
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-INSTANCE-GOMEMLIMIT-991-R1.md
@@ -0,0 +1,39 @@
+Reviewed `7e0c953..75e0c87fe2768781df78d1f6e495c8c5155d0ad6`, round 1 of 3. No P1 found. Four P2 findings follow.
+
+1. **P2 — Uncapped flat fallbacks still receive the default.**
+ [backend_exec.go:2608](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/instance-gomemlimit-991/internal/activator/backend_exec.go:2608) treats a non-nil cgroup manager as proof that the requested limit applies. However, [cgroup.go:599](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/instance-gomemlimit-991/internal/cgroup/cgroup.go:599) falls back to a plain start when group creation fails, and line 607 ignores limit-write errors for ordinary flat starts. Those children receive a default derived from a cap they never acquired.
+ **Fix:** carry the actual containment outcome into environment construction and omit the injected default on uncapped fallbacks. Add a regression covering failed group creation or `memory.max` application.
+ **Invariant:** the default derives from the cap applied to this start, not merely the requested tier.
+
+2. **P2 — Claim-backed binary launches miss the default.**
+ [claim_snapshot.go:224](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/instance-gomemlimit-991/internal/activator/claim_snapshot.go:224) constructs the environment without `withGoMemLimit`, then independently records the limit at line 231. [claimproduction.go:590](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/instance-gomemlimit-991/internal/host/claimproduction.go:590) forwards both. The root launcher preserves that environment at [claimlaunch_authority.go:64](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/instance-gomemlimit-991/internal/host/claimlaunch_authority.go:64) and starts the capped unit. With claims enabled and no app override, this binary instance receives no default.
+ **Fix:** compose the default from the captured launch limit for claim-backed serving launches too, keeping move pins independent of platform defaults and preserving launch identity/adoption checks.
+ **Invariant:** every in-scope capped binary instance launch receives the default.
+
+3. **P2 — Tests do not protect against rereading the live tier.**
+ Every nested test case sets a fixed `rt.Size` at [gomemlimit_test.go:189](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/instance-gomemlimit-991/internal/activator/gomemlimit_test.go:189). Reverting [containment.go:374](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/instance-gomemlimit-991/internal/activator/containment.go:374) to `b.tier(rt).MemoryMax` would therefore leave these tests passing. The flat cases likewise use fixed sizes. A second live-tier read could return a different value without these tests detecting the regression.
+ **Fix:** inject a tier provider that returns different limits on successive calls, assert one read, and compare the launch environment with the applied/requested cap. Include an explicit supplied-tier case for generation zero.
+ **Invariant:** environment construction and containment use one captured tier.
+
+4. **P2 — The documentation overstates the default’s scope.**
+ [cli.md:1216](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/instance-gomemlimit-991/docs/site/cli.md:1216) promises the default for instances generally. Lines 1220–1223 then say seeds and `carlos run` receive the same environment. They do not receive this default; rootfs launches also omit it, and gVisor retains root’s fixed value rather than this calculation or an app override.
+ **Fix:** explicitly limit the statement to capped native binary serving processes and clarify the seed, command, rootfs and gVisor exceptions.
+ **Invariant:** documented launch behavior matches the implemented scope.
+
+No P3 findings.
+
+## Census verdict
+
+These approvals concern the submitted changes’ classes, claims and authority boundaries; they do not dismiss the functional findings above.
+
+| Unit or envelope | Verdict |
+|---|---|
+| `ExecBackend.spawnUnitFrom` — **body**, retained `legacy / accepted-legacy` | **APPROVED.** [backend_exec.go:2904](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/instance-gomemlimit-991/internal/activator/backend_exec.go:2904) captures the tier and changes child environment composition. The same tier reaches `startRole` at line 2961. Existing launch gates, start-identity validation and termination handling remain intact. |
+| `ExecBackend.spawnChildFrom` — **sites**, retained `legacy / accepted-legacy` | **APPROVED.** [backend_exec.go:2605](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/instance-gomemlimit-991/internal/activator/backend_exec.go:2605) moves the existing tier lookup to the caller; line 2692 passes it onward. The additional whole-route site introduces no new read source or authority. |
+| `ExecBackend.startRole` — **sites**, retained `authority / E2` | **APPROVED.** [containment.go:359](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/instance-gomemlimit-991/internal/activator/containment.go:359) retains sandbox and claim refusals before dispatch, folds the tier lookups, and preserves the supplied tier across start variants. |
+| `internal/activator` envelope | **APPROVED.** The new [helper:32](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/instance-gomemlimit-991/internal/activator/gomemlimit.go:32) performs map lookup and child-environment composition only. No new privileged input source or weakened check. |
+| `internal/cgroup` envelope | **APPROVED.** [cgroup.go:167](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/instance-gomemlimit-991/internal/cgroup/cgroup.go:167) adds only the specified arithmetic; containment behavior is unchanged. |
+
+`git diff --check` passed. Targeted tests could not start because the read-only sandbox denied Go’s build directory. Census tests were not executed. Network restrictions also prevented reading discussion #991; its correction was assessed as recorded in the brief. No files were edited.
+
+**READY AFTER FIXES**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-INSTANCE-GOMEMLIMIT-991-FIXES.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-INSTANCE-GOMEMLIMIT-991-FIXES.md
new file mode 100644
index 000000000..cd23fbe1a
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-INSTANCE-GOMEMLIMIT-991-FIXES.md
@@ -0,0 +1,13 @@
+# Review brief: #991 round 1 P2 fixes, census and root check (same round budget)
+
+Repo carlos/platform, branch `instance-gomemlimit-991`, commit e529ff4097366ca68d965973c000f669e4c32837.
+Under review: ONLY the diff `3a28687a..e529ff4097366ca68d965973c000f669e4c32837` (fixes for round 1's P2s 1, 3 and 4 in `docs/superpowers/reviews/CODEX-FINDINGS-INSTANCE-GOMEMLIMIT-991-R1.md`). P2 2 (claim-backed launches) was declined by the controller: claims are shelved and switched off everywhere; it is a follow-up, do not re-raise it.
+
+This is not a new review round (AGENTS.md stopping rule 1). Two checks only:
+
+1. **Census:** the re-proposed overlay `internal/provision/testdata/plan14-root-reads-instance-gomemlimit-991.tsv` and card `docs/superpowers/notes/census-proposal-instance-gomemlimit-991.md`, which add the new unit `cgroup.Manager.Capped` and re-claim `ExecBackend.spawnChildFrom`. Give APPROVED or REFUSED per changed unit, as in round 1.
+2. **Root and termination behaviour newly changed by the fix:** does building the flat child's env inside the spawn's build closure, and reading memory.max back via `Manager.Capped`, change containment, start identity, refusal or termination behaviour in any way? Any new root read of a path a tenant can write? Is the remaining gap (flat PID-move fallback failing after start leaves the default) acceptable as a P3?
+
+Also confirm in one line each whether round 1's P2 1, 3 and 4 are resolved.
+
+Severity as in round 1 (P1 blocks; P2 fixed without another round; P3 follow-up). End with READY, READY AFTER FIXES or NOT READY. Do not edit files, do not run full suites (targeted `go test -run` fine, GOCACHE unset), do not spawn subagents.
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-INSTANCE-GOMEMLIMIT-991.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-INSTANCE-GOMEMLIMIT-991.md
new file mode 100644
index 000000000..f0a003f02
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-INSTANCE-GOMEMLIMIT-991.md
@@ -0,0 +1,41 @@
+# Review brief: instance GOMEMLIMIT default (#991), branch, round 1 of 3
+
+Repo carlos/platform, branch `instance-gomemlimit-991`, commit 75e0c87fe2768781df78d1f6e495c8c5155d0ad6.
+Under review: the diff `7e0c953ee6a9beb42b690fa7694afafdcd88a1ea..75e0c87fe2768781df78d1f6e495c8c5155d0ad6` (three commits: code and tests, census overlay, one docs sentence).
+Authorities: AGENTS.md on main (Build & test, the census section, Rules this repo has paid for); amadan discussion #991 (the goal and its correction reply). Do not review against unmerged branches (stateless-scale-1-memory-env adds CARLOS_MEMORY_MIB for rootfs and is NOT an authority; this branch deliberately leaves rootfsenv.go alone).
+
+You are an independent reviewer. Read the diff, then the code it names, and check every claim against that code.
+
+## Fixed: do not re-argue
+
+- Scope is GOMEMLIMIT only, binary instances only (flat exec child and nested unit). GOMAXPROCS is out (nested slices get CPUQuota from the size; Go 1.25+ reads cpu.max). Rootfs, co-spawned sidecars, sidecar members, seeds and carlos run are out of scope for this branch.
+- Value: memory.max/10*8 bytes, from the same tier the cgroup or nested slice gets for that start. An app-set GOMEMLIMIT (app config or <host>.env, any value including empty) wins verbatim.
+- gVisor-run instances keep root's fixed value (internal/instanceexec/sandbox.go gvisorLauncher).
+
+## What to check
+
+1. Every binary launch path: does the value always match the memory.max applied to that very start (no second read of a live tier that can differ, e.g. across a resize or a swap)? Is any path left setting nothing where it should, or setting it where the child is uncapped?
+2. The startRole signature change (containment.go): did reading the tier once at the caller change behaviour for any caller, including generations above 0, swaps, staged starts and HA/claim starts? Root and termination behaviour must be unchanged.
+3. Override rule: is "the app set it" detected from the right layers (default bundle, named environment, <host>.env), and never from a platform-owned variable? Can a tenant use this to influence anything root reads? (It shouldn't: it's a child env var.)
+4. LaunchLayers / move env pins excluding the default: correct, and does it leave any move or adoption check comparing envs that now differ between old and new agents?
+5. Tests: would each fail if its guard were removed? Any test that passes either way?
+6. Census: `docs/superpowers/notes/census-proposal-instance-gomemlimit-991.md` and `internal/provision/testdata/plan14-root-reads-instance-gomemlimit-991.tsv`. You are the census reviewer (AGENTS.md, "The census: the reviewer decides"): approve or refuse each changed unit's class and claim, explicitly.
+7. The docs sentence in docs/site/cli.md: accurate to the code (it says the box sets GOMEMLIMIT for instances; check it doesn't overclaim for rootfs, seeds or carlos run).
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work. Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not raise a P2 to P1 to keep the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the problem, the evidence (file:line, verified), the failure scenario, a concrete fix and the invariant or trust boundary it breaks. Then a "Census verdict" section: APPROVED or REFUSED per unit. End with exactly one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another round.
+- **NOT READY**: one or more P1s, listed.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites; targeted `go test -run` on the touched packages is fine (leave GOCACHE unset).
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go
index 2959a2e4f..7e03b62bd 100644
--- a/internal/activator/backend_exec.go
+++ b/internal/activator/backend_exec.go
@@ -2597,6 +2597,16 @@ func (b *ExecBackend) spawnChildFrom(ctx context.Context, rt registry.Route, soc
// both are live for exec-backed instances, and converging them is deferred
// (spec §10.3).
childVars := b.agentOwnedVars(rt, controlSocket, fileEnv, ctl != nil)
+ // The limit this spawn's cgroup takes, read once (b.tier reads the live
+ // build's manifest) and handed to the spawn below. GOMEMLIMIT follows
+ // it only when the cap was applied (#991): build runs after the cgroup
+ // manager has written the limits, and Capped reads back the child's
+ // memory.max. No delegation, a cgroup that could not be made, or a
+ // memory.max write that failed leaves the child uncapped, with no
+ // default.
+ if tier == (cgroup.Limit{}) {
+ tier = b.tier(rt)
+ }
// Record the build we're about to exec — read the symlink immediately before
// the start so it names the version the kernel will resolve. Reading it here,
// rather than back in wake() after the health wait, closes a real window: a
@@ -2682,7 +2692,11 @@ func (b *ExecBackend) spawnChildFrom(ctx context.Context, rt registry.Route, soc
argv = b.statelessArgv(rt, bin, sock)
}
cmd := exec.Command(argv[0], argv[1:]...)
- cmd.Env = childEnv(childVars)
+ vars := childVars
+ if b.Cgroups.Capped(host, child, tier) {
+ vars = withGoMemLimit(childVars, fileEnv, tier)
+ }
+ cmd.Env = childEnv(vars)
// The child logs through the agent's own stderr/stdout (journald
// under systemd); there's no per-instance unit to own a log stream
// anymore. With Logs set the same bytes are ALSO teed line-wise
@@ -2889,6 +2903,17 @@ func (b *ExecBackend) spawnUnitFrom(ctx context.Context, rt registry.Route, sock
return nil, "", err
}
childVars := b.agentOwnedVars(rt, sock+".control", fileEnv, ctl != nil)
+ // The limit root is asked to start the unit at (startRole), read once
+ // and handed to it below, so GOMEMLIMIT is derived from the memory.max
+ // the unit runs under (#991). Under gVisor root supplies its own fixed
+ // value and drops any the launch file carries (instance-exec's
+ // gvisorLauncher), so none is written.
+ if tier == (cgroup.Limit{}) {
+ tier = b.tier(rt)
+ }
+ if b.SandboxEffective != execsandbox.EffectiveGVisor {
+ childVars = withGoMemLimit(childVars, fileEnv, tier)
+ }
argv := []string{b.liveLink(rt.Host), "--socket", sock, "--db", p.dbPath}
if rt.Stateless {
argv = b.statelessArgv(rt, b.liveLink(rt.Host), sock)
@@ -2992,11 +3017,7 @@ func (b *ExecBackend) spawnUnitFrom(ctx context.Context, rt registry.Route, sock
// families gone before this failed wake releases its lease.
return fail(markLegacyStartUncertain(markStartUncertain(fmt.Errorf("%s: %w", rt.Host, exitedUnobserved{unit: inv.Unit}))))
}
- started := tier
- if started == (cgroup.Limit{}) {
- started = b.tier(rt)
- }
- log.Printf("activator: %s: started %s memory.max=%d (%s)", rt.Host, inv.Unit, started.MemoryMax, steps.String())
+ log.Printf("activator: %s: started %s memory.max=%d (%s)", rt.Host, inv.Unit, tier.MemoryMax, steps.String())
up, err := b.newUnitProcFor(rt, instancectl.RoleRun, gen, p, inv, ctl, logs)
if err != nil {
// Root has started the unit by now, so the build may have run.
@@ -3326,6 +3347,12 @@ func (b *ExecBackend) instanceEnvParts(rt registry.Route) (cfgEnv, ownEnv map[st
// is computed over exactly this env, so a target compares what would run,
// not a reconstruction of it. The values are raw: the caller HMACs them
// and must never log or return them.
+//
+// One spawn-time default is left out on purpose: GOMEMLIMIT
+// (withGoMemLimit, #991). It follows the size and the box's cgroup, not
+// the instance's layers, and an app-set value is in fileEnv and so here
+// already; pinning the default would refuse every move between a box that
+// sets it and one whose agent predates it.
func (b *ExecBackend) LaunchEnvironment(rt registry.Route) (map[string]string, []string, error) {
env, _, shadowed, err := b.LaunchLayers(rt)
return env, shadowed, err
diff --git a/internal/activator/containment.go b/internal/activator/containment.go
index d3cf6231d..125df502f 100644
--- a/internal/activator/containment.go
+++ b/internal/activator/containment.go
@@ -363,26 +363,26 @@ func (b *ExecBackend) startRole(ctx context.Context, rt registry.Route, role ins
if b.Cfg.HostWrites.Enabled {
return instancectl.StartResponse{}, ErrClaimIsolationUnavailable
}
+ // Zero is the live tier. A caller that read it already (spawnUnitFrom,
+ // whose launch file's GOMEMLIMIT follows it) passes what it read, so
+ // root is asked for that limit, not a second read of the live build.
+ if tier == (cgroup.Limit{}) {
+ tier = b.tier(rt)
+ }
if gen == 0 {
if exe == nil {
- return b.Control.Start(ctx, rt.Host, role, b.tier(rt).MemoryMax)
+ return b.Control.Start(ctx, rt.Host, role, tier.MemoryMax)
}
xc, err := b.stagedExeControl()
if err != nil {
return instancectl.StartResponse{}, fmt.Errorf("%s: not started on %s: %w", rt.Host, exe.Version, err)
}
- if tier == (cgroup.Limit{}) {
- tier = b.tier(rt)
- }
return xc.StartExe(ctx, rt.Host, role, tier.MemoryMax, *exe)
}
gc, err := b.genControl()
if err != nil {
return instancectl.StartResponse{}, err
}
- if tier == (cgroup.Limit{}) {
- tier = b.tier(rt)
- }
if exe != nil {
// The staged artifact's own tier, not the live link's.
return gc.StartGenExe(ctx, rt.Host, gen, tier.MemoryMax, *exe)
diff --git a/internal/activator/gomemlimit.go b/internal/activator/gomemlimit.go
new file mode 100644
index 000000000..99f23b34e
--- /dev/null
+++ b/internal/activator/gomemlimit.go
@@ -0,0 +1,40 @@
+package activator
+
+import (
+ "strconv"
+
+ "github.com/carlosframework/platform/internal/cgroup"
+)
+
+// goMemLimitVar is the Go runtime's soft memory limit. An instance's cgroup
+// caps it (memory.max from its size, memory.high at 90 percent), but a Go
+// runtime that is not told the cap keeps GOGC's headroom and meets the
+// throttle or the OOM killer before its collector works hard (#991).
+const goMemLimitVar = "GOMEMLIMIT"
+
+// withGoMemLimit is childVars with GOMEMLIMIT defaulted for a binary
+// instance's run process whose cgroup memory.max is limit.MemoryMax:
+// cgroup.GoMemLimitOf, 80 percent, in bytes.
+//
+// It is a DEFAULT, never agent-owned: when fileEnv (the app's own layers,
+// the rendered config and the instance's <host>.env) names GOMEMLIMIT at
+// all, childVars is returned as it is, so the app's value runs verbatim,
+// an empty or unparsable one included. A zero limit is a child the agent
+// does not know to be capped, and gets nothing. The agent's own process
+// environment is not the app's: a GOMEMLIMIT inherited from it (childEnv)
+// is overridden by the default.
+//
+// Only the binary instance run paths call it (spawnChildFrom,
+// spawnUnitFrom). A co-spawned sidecar shares its instance's cgroup, and a
+// rootfs instance runs several processes under one limit, so 80 percent
+// of the cap for each process would overcommit it. Seeds, commands and
+// sidecar members (StartWorkerStaged) are left as they were.
+func withGoMemLimit(childVars, fileEnv map[string]string, limit cgroup.Limit) map[string]string {
+ if limit.MemoryMax <= 0 {
+ return childVars
+ }
+ if _, set := fileEnv[goMemLimitVar]; set {
+ return childVars
+ }
+ return withVar(childVars, goMemLimitVar, strconv.FormatInt(cgroup.GoMemLimitOf(limit.MemoryMax), 10))
+}
diff --git a/internal/activator/gomemlimit_test.go b/internal/activator/gomemlimit_test.go
new file mode 100644
index 000000000..a42f10bbc
--- /dev/null
+++ b/internal/activator/gomemlimit_test.go
@@ -0,0 +1,411 @@
+package activator
+
+import (
+ "context"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/cgroup"
+ "github.com/carlosframework/platform/internal/execsandbox"
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// withGoMemLimit defaults GOMEMLIMIT to 80 percent of the cgroup's
+// memory.max for every size (#991), keeps whatever the app's own layers
+// set verbatim (empty and unparsable included), sets nothing for a child
+// the agent does not know to be capped, and never writes into the maps it
+// is handed.
+func TestWithGoMemLimit(t *testing.T) {
+ want := map[string]string{"small": "214748360", "standard": "429496728", "large": "858993456", "xlarge": "1717986912"}
+ for _, s := range cgroup.Sizes {
+ child := map[string]string{"CARLOS_HOST": "h.example.com"}
+ got := withGoMemLimit(child, map[string]string{"APP": "1"}, s.Limit)
+ if got[goMemLimitVar] != want[s.Name] {
+ t.Errorf("%s: GOMEMLIMIT = %q, want %q", s.Name, got[goMemLimitVar], want[s.Name])
+ }
+ if got["CARLOS_HOST"] != "h.example.com" {
+ t.Errorf("%s: other variables lost: %v", s.Name, got)
+ }
+ if _, leaked := child[goMemLimitVar]; leaked {
+ t.Errorf("%s: the caller's map was written", s.Name)
+ }
+ }
+ small, _ := cgroup.SizeByName("small")
+ for _, app := range []string{"512MiB", "", "lots", " 1GiB", "off"} {
+ // The app's value is already in childVars (agentOwnedVars layers
+ // over fileEnv); the default must leave it exactly as it is.
+ fileEnv := map[string]string{goMemLimitVar: app}
+ got := withGoMemLimit(map[string]string{goMemLimitVar: app}, fileEnv, small.Limit)
+ if v, ok := got[goMemLimitVar]; !ok || v != app {
+ t.Errorf("app set %q: child has %q (set=%v), want the app's value", app, v, ok)
+ }
+ }
+ if got := withGoMemLimit(map[string]string{"A": "1"}, nil, cgroup.Limit{}); len(got) != 1 || got["A"] != "1" {
+ t.Errorf("uncapped child: %v, want no GOMEMLIMIT", got)
+ }
+}
+
+// withoutAgentGoMemLimit clears GOMEMLIMIT from this test process for the
+// test's duration: childEnv hands an exec child the agent's environment,
+// and an inherited value would hide what the spawn set.
+func withoutAgentGoMemLimit(t *testing.T) {
+ t.Helper()
+ t.Setenv(goMemLimitVar, "")
+ if err := os.Unsetenv(goMemLimitVar); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// childEnvFile parses the env(1) dump stageRecordingLiveFullEnv's binary
+// writes.
+func childEnvFile(t *testing.T, path string) map[string]string {
+ t.Helper()
+ child := map[string]string{}
+ for _, line := range strings.Split(waitForFileContent(t, path, 2*time.Second), "\n") {
+ if k, v, ok := strings.Cut(line, "="); ok {
+ child[k] = v
+ }
+ }
+ return child
+}
+
+// A flat instance's exec child carries GOMEMLIMIT at 80 percent of the
+// memory.max its own cgroup was given, for the row's size; an app-set
+// value (here an empty one) runs instead, verbatim; and a child that runs
+// uncapped sets none: no cgroup delegation, a host cgroup that could not
+// be made (the manager's plain start), or a memory.max write that failed
+// (Astra #991 R1 P2-1).
+func TestFlatStartSetsGoMemLimitFromTheChildsCgroup(t *testing.T) {
+ withoutAgentGoMemLimit(t)
+ host := "gomem.example.com"
+ for _, tc := range []struct {
+ name, size, appEnv string
+ delegated bool
+ // breakCgroup, when set, makes the start's cgroup fail under the
+ // fake cgroupfs root before Start.
+ breakCgroup func(t *testing.T, root string)
+ want string // "-": unset; "cgroup": GoMemLimitOf(memory.max)
+ }{
+ {name: "small", size: "small", delegated: true, want: "cgroup"},
+ {name: "large", size: "large", delegated: true, want: "cgroup"},
+ {name: "app sets it empty", size: "large", appEnv: "GOMEMLIMIT=\n", delegated: true, want: ""},
+ {name: "app sets its own", size: "small", appEnv: "GOMEMLIMIT=100MiB\n", delegated: true, want: "100MiB"},
+ {name: "uncapped", size: "large", want: "-"},
+ {name: "cgroup cannot be made", size: "large", delegated: true, want: "-", breakCgroup: func(t *testing.T, root string) {
+ // A file where the host's cgroup goes: MkdirAll fails, and the
+ // flat start falls back to a plain, uncapped start.
+ if err := os.WriteFile(filepath.Join(root, cgroup.ExecName(host)), nil, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }},
+ {name: "memory.max write fails", size: "large", delegated: true, want: "-", breakCgroup: func(t *testing.T, root string) {
+ // A directory where memory.max goes: the write fails, and the
+ // flat start runs the child uncapped.
+ if err := os.MkdirAll(filepath.Join(root, cgroup.ExecName(host), "memory.max"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ b := testExecBackend(t)
+ root := t.TempDir()
+ if tc.delegated {
+ for _, f := range []string{"cgroup.procs", "cgroup.subtree_control"} {
+ if err := os.WriteFile(filepath.Join(root, f), nil, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ m, err := cgroup.SetupAt(root, t.Logf)
+ if err != nil {
+ t.Fatal(err)
+ }
+ b.Cgroups = m
+ }
+ if tc.breakCgroup != nil {
+ tc.breakCgroup(t, root)
+ }
+ _, envPath := stageRecordingLiveFullEnv(t, b, host, "v1")
+ if tc.appEnv != "" {
+ if err := os.WriteFile(filepath.Join(b.DataDir, host+".config.env"), []byte(tc.appEnv), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ rt := registry.Route{Host: host, Kind: "instance", Size: tc.size, Socket: filepath.Join(t.TempDir(), "instance.sock")}
+ ctx, cancel := recordedCtx(2*time.Second, envPath)
+ defer cancel()
+ proc, _, _ := b.Start(ctx, rt) // the fake binary never binds; a health-wait error is expected
+ if proc != nil {
+ defer proc.Stop(context.Background())
+ }
+ got, set := childEnvFile(t, envPath)[goMemLimitVar]
+ want := tc.want
+ if want == "cgroup" {
+ raw, err := os.ReadFile(filepath.Join(root, cgroup.ExecName(host), "memory.max"))
+ if err != nil {
+ t.Fatalf("memory.max not written: %v", err)
+ }
+ max, err := strconv.ParseInt(string(raw), 10, 64)
+ if err != nil {
+ t.Fatal(err)
+ }
+ size, _ := cgroup.SizeByName(tc.size)
+ if max != size.Limit.MemoryMax {
+ t.Fatalf("memory.max = %d, want the %s size's %d", max, tc.size, size.Limit.MemoryMax)
+ }
+ want = strconv.FormatInt(cgroup.GoMemLimitOf(max), 10)
+ }
+ switch {
+ case want == "-" && set:
+ t.Fatalf("uncapped child has GOMEMLIMIT=%q, want none", got)
+ case want != "-" && (!set || got != want):
+ t.Fatalf("child GOMEMLIMIT = %q (set=%v), want %q", got, set, want)
+ }
+ })
+ }
+}
+
+// nestedLaunchEnv is the environment spawnUnitFrom wrote to the run unit's
+// launch file (generation 0).
+func nestedLaunchEnv(t *testing.T, b *ExecBackend, rt registry.Route) map[string]string {
+ t.Helper()
+ raw, err := os.ReadFile(filepath.Join(provision.InstanceDir(b.DataDir, rt.Host), "launch.run.json"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var l instancectl.Launch
+ if err := json.Unmarshal(raw, &l); err != nil {
+ t.Fatal(err)
+ }
+ env := map[string]string{}
+ for _, kv := range l.Env {
+ if k, v, ok := strings.Cut(kv, "="); ok {
+ env[k] = v
+ }
+ }
+ return env
+}
+
+// A nested instance's launch file carries GOMEMLIMIT at 80 percent of the
+// memory_max root is asked to start the unit at (the slice's memory.max),
+// for the row's size; an app-set value runs instead, verbatim.
+func TestNestedStartSetsGoMemLimitFromTheTierRootApplies(t *testing.T) {
+ withoutAgentGoMemLimit(t)
+ for _, tc := range []struct {
+ name, size, appEnv, want string // want "": GoMemLimitOf(memory_max)
+ }{
+ {name: "small", size: "small"},
+ {name: "xlarge", size: "xlarge"},
+ {name: "app sets its own", size: "large", appEnv: "GOMEMLIMIT=odd value\n", want: "odd value"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ ctl := &fakeControl{inv: "inv1"}
+ unit := &fakeUnit{}
+ b, rt := nestedBackend(t, ctl, unit)
+ rt.Size = tc.size
+ if tc.appEnv != "" {
+ dir := provision.InstanceDir(b.DataDir, rt.Host)
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, rt.Host+".config.env"), []byte(tc.appEnv), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ var stopServing func()
+ ctl.onStart = func() { stopServing = serveOK(t, rt.Socket) }
+ defer func() {
+ if stopServing != nil {
+ stopServing()
+ }
+ }()
+ unit.set("active", "inv1", true, true)
+ p, _, err := b.Start(context.Background(), rt)
+ if err != nil {
+ t.Fatalf("Start: %v", err)
+ }
+ defer func() {
+ unit.set("inactive", "inv1", false, false)
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+ _ = p.Stop(ctx)
+ }()
+ ctl.mu.Lock()
+ maxes := append([]int64(nil), ctl.startMaxes...)
+ ctl.mu.Unlock()
+ size, _ := cgroup.SizeByName(tc.size)
+ if len(maxes) != 1 || maxes[0] != size.Limit.MemoryMax {
+ t.Fatalf("root was asked for memory_max %v, want [%d]", maxes, size.Limit.MemoryMax)
+ }
+ want := tc.want
+ if want == "" {
+ want = strconv.FormatInt(cgroup.GoMemLimitOf(maxes[0]), 10)
+ }
+ if got, set := nestedLaunchEnv(t, b, rt)[goMemLimitVar]; !set || got != want {
+ t.Fatalf("launch GOMEMLIMIT = %q (set=%v), want %q", got, set, want)
+ }
+ })
+ }
+}
+
+// Under gVisor the launch file carries no GOMEMLIMIT: root supplies its
+// own fixed value to the sandbox and drops any the launch names
+// (instance-exec's gvisorLauncher), so the agent writes none.
+func TestNestedGVisorStartLeavesGoMemLimitToRoot(t *testing.T) {
+ withoutAgentGoMemLimit(t)
+ b, rt := nestedBackend(t, &fakeControl{}, &fakeUnit{})
+ rt.Host = "bright-otter-42.ex.co"
+ rt.Account, rt.App = "bab", "tmp-demo-bright-otter-42"
+ rt.Provisioned, rt.Region, rt.Assigned = true, "fleet/demo", "demo-1"
+ rt.DemoID, rt.DemoHost, rt.DemoLifetime = "AAAAAAAAAAAAAAAAAAAAAA", rt.Host, "life-1"
+ rt.DemoExpiresAt = time.Now().Add(time.Hour).Unix()
+ rt.DBPath = provision.NestedDBPath(b.DataDir, rt.Host)
+ rt.Socket = filepath.Join(b.RunDirOverride, "instances", rt.Host, "app.sock")
+ stageLive(t, b, rt.Host, "v1")
+ b.SandboxEffective = execsandbox.EffectiveGVisor
+ // Root's answer names the wrong family, so the start fails after the
+ // launch file is written, before any handle exists to clean up.
+ b.Control = sandboxAnswerControl{fakeControl: &fakeControl{}, answer: instancectl.StartResponse{
+ Unit: instancectl.GVisorUnitName(rt.Host), Sandbox: execsandbox.EffectiveSystemd, InvocationID: "started"}}
+ if p, _, err := b.spawnUnitFrom(context.Background(), rt, rt.Socket, 0, nil, cgroup.Limit{}); p != nil || err == nil {
+ t.Fatalf("start: %v, %v; want the mismatch refusal", p, err)
+ }
+ env := nestedLaunchEnv(t, b, rt)
+ if _, ok := env["CARLOS_HOST"]; !ok {
+ t.Fatalf("launch env is not the instance's: %v", env)
+ }
+ if got, set := env[goMemLimitVar]; set {
+ t.Fatalf("gVisor launch carries GOMEMLIMIT=%q, want none (root's own)", got)
+ }
+}
+
+// tierSequence is a Tier provider answering each size in turn, smallest
+// first: a launch that read the live tier twice would hand its env one
+// size and its cgroup another (Astra #991 R1 P2-3). calls counts reads.
+type tierSequence struct {
+ mu sync.Mutex
+ calls int
+}
+
+func (s *tierSequence) tier(registry.Route) cgroup.Limit {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ l := cgroup.Sizes[s.calls%len(cgroup.Sizes)].Limit
+ s.calls++
+ return l
+}
+
+func (s *tierSequence) reads() int {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.calls
+}
+
+// A flat start reads the live tier once: the cgroup's memory.max and the
+// child's GOMEMLIMIT come from that one read.
+func TestFlatStartReadsTheLiveTierOnce(t *testing.T) {
+ withoutAgentGoMemLimit(t)
+ b := testExecBackend(t)
+ root := t.TempDir()
+ for _, f := range []string{"cgroup.procs", "cgroup.subtree_control"} {
+ if err := os.WriteFile(filepath.Join(root, f), nil, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ m, err := cgroup.SetupAt(root, t.Logf)
+ if err != nil {
+ t.Fatal(err)
+ }
+ b.Cgroups = m
+ seq := &tierSequence{}
+ b.Tier = seq.tier
+ host := "gomem-once.example.com"
+ _, envPath := stageRecordingLiveFullEnv(t, b, host, "v1")
+ rt := registry.Route{Host: host, Kind: "instance", Socket: filepath.Join(t.TempDir(), "instance.sock")}
+ ctx, cancel := recordedCtx(2*time.Second, envPath)
+ defer cancel()
+ proc, _, _ := b.Start(ctx, rt) // the fake binary never binds; a health-wait error is expected
+ if proc != nil {
+ defer proc.Stop(context.Background())
+ }
+ got := childEnvFile(t, envPath)[goMemLimitVar]
+ raw, err := os.ReadFile(filepath.Join(root, cgroup.ExecName(host), "memory.max"))
+ if err != nil {
+ t.Fatalf("memory.max not written: %v", err)
+ }
+ small, _ := cgroup.SizeByName("small")
+ if string(raw) != strconv.FormatInt(small.Limit.MemoryMax, 10) {
+ t.Fatalf("memory.max = %s, want the first read's %d", raw, small.Limit.MemoryMax)
+ }
+ if want := strconv.FormatInt(cgroup.GoMemLimitOf(small.Limit.MemoryMax), 10); got != want {
+ t.Fatalf("child GOMEMLIMIT = %q, want %q (from memory.max)", got, want)
+ }
+ if n := seq.reads(); n != 1 {
+ t.Fatalf("the live tier was read %d times, want 1", n)
+ }
+}
+
+// startNested starts rt's generation-0 run unit through spawnUnitFrom with
+// tier, and stops it at the test's end.
+func startNested(t *testing.T, b *ExecBackend, ctl *fakeControl, unit *fakeUnit, rt registry.Route, tier cgroup.Limit) {
+ t.Helper()
+ unit.set("active", "inv1", true, true)
+ p, _, err := b.spawnUnitFrom(context.Background(), rt, rt.Socket, 0, nil, tier)
+ if err != nil {
+ t.Fatalf("spawnUnitFrom: %v", err)
+ }
+ t.Cleanup(func() {
+ unit.set("inactive", "inv1", false, false)
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+ _ = p.Stop(ctx)
+ })
+}
+
+// A nested start reads the live tier once (zero tier), and a tier its
+// caller supplies at generation 0 is the one root is asked for, with no
+// live read at all: either way the launch file's GOMEMLIMIT matches the
+// memory_max root was asked to apply.
+func TestNestedStartUsesOneTier(t *testing.T) {
+ withoutAgentGoMemLimit(t)
+ large, _ := cgroup.SizeByName("large")
+ small, _ := cgroup.SizeByName("small")
+ for _, tc := range []struct {
+ name string
+ supplied cgroup.Limit
+ wantMax int64
+ wantReads int
+ }{
+ {name: "live tier, read once", wantMax: small.Limit.MemoryMax, wantReads: 1},
+ {name: "supplied tier at generation 0", supplied: large.Limit, wantMax: large.Limit.MemoryMax, wantReads: 0},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ ctl := &fakeControl{inv: "inv1"}
+ unit := &fakeUnit{}
+ b, rt := nestedBackend(t, ctl, unit)
+ seq := &tierSequence{}
+ b.Tier = seq.tier
+ startNested(t, b, ctl, unit, rt, tc.supplied)
+ ctl.mu.Lock()
+ maxes := append([]int64(nil), ctl.startMaxes...)
+ ctl.mu.Unlock()
+ if len(maxes) != 1 || maxes[0] != tc.wantMax {
+ t.Fatalf("root was asked for memory_max %v, want [%d]", maxes, tc.wantMax)
+ }
+ want := strconv.FormatInt(cgroup.GoMemLimitOf(maxes[0]), 10)
+ if got := nestedLaunchEnv(t, b, rt)[goMemLimitVar]; got != want {
+ t.Fatalf("launch GOMEMLIMIT = %q, want %q (from root's memory_max)", got, want)
+ }
+ if n := seq.reads(); n != tc.wantReads {
+ t.Fatalf("the live tier was read %d times, want %d", n, tc.wantReads)
+ }
+ })
+ }
+}
diff --git a/internal/activator/unitproc_test.go b/internal/activator/unitproc_test.go
index 0528d203f..96640e9f1 100644
--- a/internal/activator/unitproc_test.go
+++ b/internal/activator/unitproc_test.go
@@ -28,6 +28,8 @@ type fakeControl struct {
inv string
seed instancectl.SeedResponse
startErr error
+ // startMaxes is the memory_max of every Start, in order.
+ startMaxes []int64
// stopGenErr is what fakeGenControl.StopGen answers.
stopGenErr error
// stopRootfsErr, when set, is what StopRootfs answers for every unit;
@@ -66,6 +68,9 @@ type fakeControl struct {
func (f *fakeControl) rec(s string) { f.mu.Lock(); f.calls = append(f.calls, s); f.mu.Unlock() }
func (f *fakeControl) Start(_ context.Context, host string, role instancectl.Role, max int64) (instancectl.StartResponse, error) {
f.rec("start " + host + " " + string(role))
+ f.mu.Lock()
+ f.startMaxes = append(f.startMaxes, max)
+ f.mu.Unlock()
if f.onStart != nil {
f.onStart()
}
diff --git a/internal/cgroup/cgroup.go b/internal/cgroup/cgroup.go
index c924b28e9..9832a4ccf 100644
--- a/internal/cgroup/cgroup.go
+++ b/internal/cgroup/cgroup.go
@@ -160,6 +160,12 @@ func MaxLimit(a, b Limit) Limit {
// same number.
func HighOf(max int64) int64 { return max / 10 * 9 }
+// GoMemLimitOf is the GOMEMLIMIT a Go process gets by default under a
+// memory.max of max (#991): 80 percent, in bytes, computed as HighOf is.
+// It sits below memory.high (HighOf, 90 percent), so the runtime's
+// collector works hard before the kernel starts throttling the cgroup.
+func GoMemLimitOf(max int64) int64 { return max / 10 * 8 }
+
// ExecOOMScoreAdj is written to every exec child's /proc/<pid>/oom_score_adj
// right after it starts. The kernel's OOM killer — the memcg one that fires
// when carlos-edge.service's own MemoryMax is hit included — scores per
@@ -442,6 +448,26 @@ var placeStart = func(m *Manager, dir string, cmd *exec.Cmd, before func() error
// a seed's first-boot cost and a sidecar's load ARE that instance's work.
func (m *Manager) hostDir(host string) string { return filepath.Join(m.root, ExecName(host)) }
+// Capped reports whether host's cgroup (child "" for the host's own, else
+// that child) holds memory.max at limit.MemoryMax now: what a start's build
+// can ask, since every start calls build after its limits are written, to
+// learn whether the cap it asked for was applied (#991). A flat start that
+// could not make its cgroup (a plain start) or whose memory.max write
+// failed runs uncapped, and answers false, as do a nil manager, a zero
+// limit and an unreadable file. It reads; it never writes or changes a
+// start.
+func (m *Manager) Capped(host, child string, limit Limit) bool {
+ if m == nil || limit.MemoryMax <= 0 || (child != "" && !isChildName(child)) {
+ return false
+ }
+ raw, err := os.ReadFile(filepath.Join(m.hostDir(host), child, "memory.max"))
+ if err != nil {
+ return false
+ }
+ n, err := strconv.ParseInt(strings.TrimSpace(string(raw)), 10, 64)
+ return err == nil && n == limit.MemoryMax
+}
+
// Start runs build() and starts the result inside host's cgroup, with
// limit applied to that cgroup first (memory-pressure spec §2.3). Nil-safe:
// with no manager (or any accounting failure) the child starts exactly as
diff --git a/internal/cgroup/cgroup_test.go b/internal/cgroup/cgroup_test.go
index dd107eabe..a18e14da5 100644
--- a/internal/cgroup/cgroup_test.go
+++ b/internal/cgroup/cgroup_test.go
@@ -464,16 +464,16 @@ func TestTiers(t *testing.T) {
// TestSizeTableIsTheSpecsBytes pins the size table to spec §5.1's numbers,
// byte for byte: each row's MemoryMax, the memory.high HighOf derives from
-// it, its shares, and what SharesOf and SizeOf answer for its limit.
+// it, the GOMEMLIMIT default GoMemLimitOf derives (#991), its shares, and what SharesOf and SizeOf answer for its limit.
func TestSizeTableIsTheSpecsBytes(t *testing.T) {
want := map[string]struct {
- max, high int64
- sh Shares
+ max, high, gomem int64
+ sh Shares
}{
- "small": {268435456, 241591905, Shares{CPUWeight: 50, CPUQuotaPercent: 50, IOWeight: 50}},
- "standard": {536870912, 483183819, Shares{CPUWeight: 100, CPUQuotaPercent: 100, IOWeight: 100}},
- "large": {1073741824, 966367638, Shares{CPUWeight: 100, CPUQuotaPercent: 200, IOWeight: 100}},
- "xlarge": {2147483648, 1932735276, Shares{CPUWeight: 200, CPUQuotaPercent: 400, IOWeight: 200}},
+ "small": {268435456, 241591905, 214748360, Shares{CPUWeight: 50, CPUQuotaPercent: 50, IOWeight: 50}},
+ "standard": {536870912, 483183819, 429496728, Shares{CPUWeight: 100, CPUQuotaPercent: 100, IOWeight: 100}},
+ "large": {1073741824, 966367638, 858993456, Shares{CPUWeight: 100, CPUQuotaPercent: 200, IOWeight: 100}},
+ "xlarge": {2147483648, 1932735276, 1717986912, Shares{CPUWeight: 200, CPUQuotaPercent: 400, IOWeight: 200}},
}
order := []string{"small", "standard", "large", "xlarge"}
if len(Sizes) != len(order) {
@@ -491,6 +491,12 @@ func TestSizeTableIsTheSpecsBytes(t *testing.T) {
if got := HighOf(row.Limit.MemoryMax); got != w.high {
t.Errorf("%s: HighOf = %d, want %d", row.Name, got, w.high)
}
+ if got := GoMemLimitOf(row.Limit.MemoryMax); got != w.gomem {
+ t.Errorf("%s: GoMemLimitOf = %d, want %d", row.Name, got, w.gomem)
+ }
+ if gomem := GoMemLimitOf(row.Limit.MemoryMax); gomem >= w.high {
+ t.Errorf("%s: GoMemLimitOf = %d is not below memory.high %d", row.Name, gomem, w.high)
+ }
if row.Shares != w.sh {
t.Errorf("%s: Shares = %+v, want %+v", row.Name, row.Shares, w.sh)
}
@@ -637,3 +643,41 @@ func TestLeftoverAfterAnUnreadableSweep(t *testing.T) {
t.Error("a retaining setup reported a host as known clean")
}
}
+
+// Capped answers from the memory.max a start's cgroup holds: true only
+// when it reads back as the limit asked for (#991).
+func TestCappedReadsBackMemoryMax(t *testing.T) {
+ root := t.TempDir()
+ m := &Manager{root: root}
+ host := "h.example.com"
+ small := Limit{MemoryMax: 256 << 20}
+ if m.Capped(host, "", small) {
+ t.Error("no cgroup: capped")
+ }
+ dir := filepath.Join(root, ExecName(host))
+ if err := os.MkdirAll(filepath.Join(dir, GenChild(3)), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, "memory.max"), []byte("268435456\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if !m.Capped(host, "", small) {
+ t.Error("memory.max at the limit: not capped")
+ }
+ if m.Capped(host, "", Limit{MemoryMax: 512 << 20}) || m.Capped(host, "", Limit{}) {
+ t.Error("another or a zero limit: capped")
+ }
+ if m.Capped(host, GenChild(3), small) || m.Capped(host, "../x", small) {
+ t.Error("a child with no memory.max, or a bad child name: capped")
+ }
+ if err := os.WriteFile(filepath.Join(dir, GenChild(3), "memory.max"), []byte("max\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if m.Capped(host, GenChild(3), small) {
+ t.Error("memory.max = max: capped")
+ }
+ var none *Manager
+ if none.Capped(host, "", small) {
+ t.Error("nil manager: capped")
+ }
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 5ef8780dd..fb8a47b1c 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -204,4 +204,5 @@ plan14-root-reads-static-site-geo-962.tsv 5e8a72175700a3e60c1e283b133c1ee25e36f2
plan14-root-reads-member-backups-drill-nodb.tsv 07b748a749084fdaf61c5087a6edfca8a79273962822ce551dd4d42b0d20c063
plan14-root-reads-spread-every-schedule-ticks.tsv 07b748a749084fdaf61c5087a6edfca8a79273962822ce551dd4d42b0d20c063
plan14-root-reads-member-backups-2b.tsv 07b748a749084fdaf61c5087a6edfca8a79273962822ce551dd4d42b0d20c063
-plan14-root-reads-ppv2-operator-copy.tsv 07b748a749084fdaf61c5087a6edfca8a79273962822ce551dd4d42b0d20c063
+plan14-root-reads-instance-gomemlimit-991.tsv 19c9f395547d998f4b5e87e89c0dfa3b5f012d177a87eb5010a8c4defac305dc
+plan14-root-reads-ppv2-operator-copy.tsv 19c9f395547d998f4b5e87e89c0dfa3b5f012d177a87eb5010a8c4defac305dc
diff --git a/internal/provision/testdata/plan14-root-reads-instance-gomemlimit-991.tsv b/internal/provision/testdata/plan14-root-reads-instance-gomemlimit-991.tsv
new file mode 100644
index 000000000..19fb5f653
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-instance-gomemlimit-991.tsv
@@ -0,0 +1,12 @@
+# Census overlay instance-gomemlimit-991, written by census-propose (#369). census-ruling-instance-gomemlimit-991, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-instance-gomemlimit-991.md.
+# 1 body, 2 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 1 new dispositions: 0 reads re-frozen at their disposition with the claim, 1 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+@legacy 5f3bd19d75b0c82c9898b86edd1a5c9e757d2c60a5320e904760695cc9e9974a internal/activator/backend_exec.go ExecBackend.spawnUnitFrom legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=Re-digested at the pre-land merge: the body includes main's own change under census ruling 292, with no further change from this branch. the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body; it calls prepareKeyedAt and keeps the launch environment and its key layer on the generation's handle; read sites unchanged, offsets moved;rev3=census-ruling-wake-latency-2;basis=times the launch's steps with time.Now() (build, prepare, launch file, gate, root start) and adds them to its existing "started" journal line; no read added or moved;rev3=census-ruling-rootfs-apps-2;basis=the unit names in its error and log lines go through runUnitName, and newUnitProcFor's new error (a role with no unit to observe) fails the start as markStartUncertain after root started the unit; the binary spawn is otherwise unchanged, a rootfs row never reaches it (nestedGate refuses one); no read added;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=computes the page cache launch inputs once (launchInputs: sha256 over the staged or pinned exe's Version and the fileEnv this spawn already read; "" with no exe, since root binds the movable live link) and keeps them on the unit handle (up.inputs); no new file, registry or bucket read; read sites unchanged (29); no read added;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 launchInputs computed from the captured file environment and pinned/staged build and store them on the handle, alongside branch sandbox gate, validated root StartResponse Unit/Sandbox/InvocationID and all uncertain-start cleanup. No new direct read.;rev3=census-ruling-fix-silent-start-kill-861;basis=#861: one log line before killFailedGen naming the host, the generation unit (runUnitName) and the error already in hand; the +registry:Host sites are those two arguments to log.Printf; no new read source, behaviour unchanged;rev3=census-ruling-instance-gomemlimit-991;basis=#991: the agent as carlos (nested start): resolves the zero tier once (b.tier(rt), the existing live-tier read), adds GOMEMLIMIT=GoMemLimitOf(tier.MemoryMax) to the launch file env unless the app's fileEnv already names it (withGoMemLimit; skipped under gVisor, where root supplies its own and drops any launch value), passes that same tier to startRole, and logs it. No new read source; root still validates memory_max against the size table; read sites unchanged. registry:Host@1308,registry:Host@2277,registry:Host@2382,registry:Host@2513,registry:Host@2970,registry:Host@3929,registry:Host@4290,registry:Host@5058,registry:Host@5644,registry:Host@5909,registry:Host@6066,registry:Host@6087,registry:Host@6308,registry:Host@6493,registry:Host@6888,registry:Host@7149,registry:Host@7258,registry:Host@8257,registry:Host@8351,registry:Stateless@2327,whole:Route@1093,whole:Route@1472,whole:Route@1714,whole:Route@197,whole:Route@2127,whole:Route@2367,whole:Route@4165,whole:Route@431,whole:Route@6141,whole:Route@7338,whole:Route@995 c6f98b3f134b6e732113b58b2a2bd6c33a71abd9bce03694489b9e85780cf870
+@legacy e0c1838ee006dee536d379245b4a754e6b4186ba80a4ecb358f9641b32f9c5c8 internal/cgroup/cgroup.go Manager.Capped legacy accepted-legacy accepted-legacy;rev3=census-ruling-instance-gomemlimit-991;basis=#991 (Astra R1 P2-1): new, the agent as carlos: reads <root>/carlos-exec@<host>[/<child>]/memory.max in the agent's own delegated cgroup subtree and compares it with the limit a start asked for; nil manager, zero limit, a child name isChildName refuses, or an unreadable or unparsable file answer false. Read only: it writes nothing, starts nothing, and changes no start; its one caller (spawnChildFrom's build closure) uses it only to decide whether to add the GOMEMLIMIT default to the child env. file:ReadFile@175 406153daad7add4505a72b9f3249c4c7e0404f0bce79da9e962654827acf4e65
+@legacy dcf4d3402ef80bc359acc631d23b66ee89fd9bf205d6427574c740eff2d4d70a 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.;rev3=census-ruling-instance-gomemlimit-991;basis=#991: the agent as carlos (flat exec child): resolves the zero tier once with the existing b.tier(rt) live-tier read (the +whole:Route site) and passes it to spawnInCgroupAtTier, which previously made the same read itself. Inside the build closure (which the cgroup manager calls after writing the limits) it asks cgroup.Manager.Capped(host, child, tier), a read of memory.max in the agent's own delegated cgroup subtree, and only when that reads back as the tier adds GOMEMLIMIT=GoMemLimitOf(tier.MemoryMax) to the child env, unless the app's fileEnv names it. No delegation, a cgroup that could not be made, or a failed memory.max write gives no default (Astra R1 P2-1). Containment behaviour unchanged; no gate moved or weakened; no registry, /data, release or store read added. file:Command@11850,registry:Host@13246,registry:Host@13607,registry:Host@13701,registry:Host@258,registry:Host@4214,registry:Host@4269,registry:Host@4349,registry:Host@4563,registry:Stateless@11781,whole:Route@11673,whole:Route@11822,whole:Route@12343,whole:Route@13998,whole:Route@14090,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@7354,whole:Route@9586 c5e6834ad262e29560b08ceda9b0982ae2b3ed3d44c1d01513e67f39c0bc4796
+internal/activator/backend_exec.go ExecBackend.spawnUnitFrom legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=Re-digested at the pre-land merge: the body includes main's own change under census ruling 292, with no further change from this branch. the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body; it calls prepareKeyedAt and keeps the launch environment and its key layer on the generation's handle; read sites unchanged, offsets moved;rev3=census-ruling-wake-latency-2;basis=times the launch's steps with time.Now() (build, prepare, launch file, gate, root start) and adds them to its existing "started" journal line; no read added or moved;rev3=census-ruling-rootfs-apps-2;basis=the unit names in its error and log lines go through runUnitName, and newUnitProcFor's new error (a role with no unit to observe) fails the start as markStartUncertain after root started the unit; the binary spawn is otherwise unchanged, a rootfs row never reaches it (nestedGate refuses one); no read added;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=computes the page cache launch inputs once (launchInputs: sha256 over the staged or pinned exe's Version and the fileEnv this spawn already read; "" with no exe, since root binds the movable live link) and keeps them on the unit handle (up.inputs); no new file, registry or bucket read; read sites unchanged (29); no read added;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 launchInputs computed from the captured file environment and pinned/staged build and store them on the handle, alongside branch sandbox gate, validated root StartResponse Unit/Sandbox/InvocationID and all uncertain-start cleanup. No new direct read.;rev3=census-ruling-fix-silent-start-kill-861;basis=#861: one log line before killFailedGen naming the host, the generation unit (runUnitName) and the error already in hand; the +registry:Host sites are those two arguments to log.Printf; no new read source, behaviour unchanged;rev3=census-ruling-instance-gomemlimit-991;basis=#991: the agent as carlos (nested start): resolves the zero tier once (b.tier(rt), the existing live-tier read), adds GOMEMLIMIT=GoMemLimitOf(tier.MemoryMax) to the launch file env unless the app's fileEnv already names it (withGoMemLimit; skipped under gVisor, where root supplies its own and drops any launch value), passes that same tier to startRole, and logs it. No new read source; root still validates memory_max against the size table; read sites unchanged. registry:Host@1308,registry:Host@2277,registry:Host@2382,registry:Host@2513,registry:Host@2970,registry:Host@3929,registry:Host@4290,registry:Host@5058,registry:Host@5644,registry:Host@5909,registry:Host@6066,registry:Host@6087,registry:Host@6308,registry:Host@6493,registry:Host@6888,registry:Host@7149,registry:Host@7258,registry:Host@8257,registry:Host@8351,registry:Stateless@2327,whole:Route@1093,whole:Route@1472,whole:Route@1714,whole:Route@197,whole:Route@2127,whole:Route@2367,whole:Route@4165,whole:Route@431,whole:Route@6141,whole:Route@7338,whole:Route@995 c6f98b3f134b6e732113b58b2a2bd6c33a71abd9bce03694489b9e85780cf870
+internal/cgroup/cgroup.go Manager.Capped legacy accepted-legacy accepted-legacy;rev3=census-ruling-instance-gomemlimit-991;basis=#991 (Astra R1 P2-1): new, the agent as carlos: reads <root>/carlos-exec@<host>[/<child>]/memory.max in the agent's own delegated cgroup subtree and compares it with the limit a start asked for; nil manager, zero limit, a child name isChildName refuses, or an unreadable or unparsable file answer false. Read only: it writes nothing, starts nothing, and changes no start; its one caller (spawnChildFrom's build closure) uses it only to decide whether to add the GOMEMLIMIT default to the child env. file:ReadFile@175 406153daad7add4505a72b9f3249c4c7e0404f0bce79da9e962654827acf4e65
+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.;rev3=census-ruling-instance-gomemlimit-991;basis=#991: the agent as carlos (flat exec child): resolves the zero tier once with the existing b.tier(rt) live-tier read (the +whole:Route site) and passes it to spawnInCgroupAtTier, which previously made the same read itself. Inside the build closure (which the cgroup manager calls after writing the limits) it asks cgroup.Manager.Capped(host, child, tier), a read of memory.max in the agent's own delegated cgroup subtree, and only when that reads back as the tier adds GOMEMLIMIT=GoMemLimitOf(tier.MemoryMax) to the child env, unless the app's fileEnv names it. No delegation, a cgroup that could not be made, or a failed memory.max write gives no default (Astra R1 P2-1). Containment behaviour unchanged; no gate moved or weakened; no registry, /data, release or store read added. file:Command@11850,registry:Host@13246,registry:Host@13607,registry:Host@13701,registry:Host@258,registry:Host@4214,registry:Host@4269,registry:Host@4349,registry:Host@4563,registry:Stateless@11781,whole:Route@11673,whole:Route@11822,whole:Route@12343,whole:Route@13998,whole:Route@14090,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@7354,whole:Route@9586 c5e6834ad262e29560b08ceda9b0982ae2b3ed3d44c1d01513e67f39c0bc4796
+internal/activator/containment.go ExecBackend.startRole authority E2 E40: claim-enabled raw backend refuses unsupported direct, placed and legacy-control launches before spawn. Claims-off body unchanged. TestPlan14GenerationBackendDirectBoundary, TestPlan14GenerationBackendControlBoundary, TestPlan14GenerationBackendAuxiliaryBoundary; each guard has an independent behavioral mutation. Agent-side refusal is not root reservation or containment evidence.;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.;rev3=census-ruling-instance-gomemlimit-991;basis=#991: the zero-tier default (b.tier(rt)) is applied once at the top instead of in each branch, and generation 0 with no exe now honours a non-zero tier its caller already read (spawnUnitFrom) instead of re-reading the live tier; every caller with exe nil passed a zero tier before, so the value root is asked for is unchanged. The -whole:Route x2 sites are the two folded b.tier(rt) calls. Claim refusal and sandbox gate unchanged. registry:Host@1196,registry:Host@1260,registry:Host@740,registry:Host@906,registry:Host@963,whole:Route@218,whole:Route@669 444a009a2f71825d7173cfce41c28497571047e44896ddfbe77fb9d34e3d0d6a
+@coverage internal/activator 8050f2d708e38718681512a6998c42bb3dc1f3648747253cd35eb77da92e3f7f
+@coverage internal/cgroup ed5ff9fcd52f18ed22aab2ed2eaa55272fad4e9c0c87d403d36ba7f7fd8d63ec