carlos / platform Public

Merge remote-tracking branch 'origin/main' into retire-app-lock-407

claude agent, operated by paul@keymail.dev 0cef04b7f810367f23e28c8be649bc0edfa69cf7 parent 8932c39parent d7ae1d7
18 files changed, +1,033 −15
  • docs/superpowers/notes/census-proposal-remote-metrics-nested.md +28 −0
  • docs/superpowers/notes/remote-instance-metrics.md +83 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-remote-metrics-nested-census.md +19 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-remote-metrics-nested-r1.md +31 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-remote-metrics-nested-r2.md +31 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-remote-metrics-nested.md +101 −0
  • internal/host/agent.go +26 −1
  • internal/host/agentalerts_test.go +1 −1
  • internal/host/metrics_loop.go +65 −13
  • internal/host/metrics_nested.go +140 −0
  • internal/host/metrics_nested_linux.go +23 −0
  • internal/host/metrics_nested_linux_test.go +334 −0
  • internal/host/metrics_nested_other.go +7 −0
  • internal/host/metrics_nested_rootrunner_linux_test.go +86 −0
  • internal/host/metrics_nested_test.go +34 −0
  • internal/host/metrics_probes.go +8 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-remote-metrics-nested.tsv +15 −0

CI passed — run details

diff --git a/docs/superpowers/notes/census-proposal-remote-metrics-nested.md b/docs/superpowers/notes/census-proposal-remote-metrics-nested.md
new file mode 100644
index 000000000..9e3150280
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-remote-metrics-nested.md
@@ -0,0 +1,28 @@
+# Census approval: remote-metrics-nested
+
+Ruling `census-ruling-remote-metrics-nested`. The independent reviewer approves or rejects every change below, 4 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/host/agent.go` `runAgent` | body | unchanged (6) | main's body (merged origin/main acfa4f80, under main's own census rulings) plus: snapshots the nested layout (snapshotNestedUnits over /sys/fs/cgroup/carlos.slice/carlos-instances.slice) once at start, before the activator, and hands the metrics loop a unitSources struct (stamped units, routeHostNames, that root and the snapshot); reads nothing new itself |
+| `internal/host/metrics_loop.go` `sampler.tick` | body | unchanged (1) | clears the tenant tag of a reading marked leftover (a nested unit present at agent start) before CarryTags, and takes no CPU delta when a nested reading's set of cgroups changed since the previous tick; no read added |
+
+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. Escalate 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. An escalation goes to the census owner as a decision.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `internal/host/agent.go` `runAgent`: authority, task B,C,D,F. Basis: rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): builds the box's lifetime judge once (newBoxJudge, nil with host claims on) and hands it to the seed placement, the moves and runs workers and every loop it starts; read sites unchanged, offsets moved; B,C,D,F authority retained; self-serve moves 1 Task 8: derives the box's lifetimes switch from the judge once (lifetimes := boxJudge != nil) and hands it to the edges file loop; read sites unchanged, offsets moved;rev3=census-ruling-plans-4d-lapse;basis=arms two more plans hooks from the same snapshot: e.SetPlanDisabledFor(planDisabledFor) beside SetPlanGovernedFor, and svc.SetDisabledFor(planDisabledRoute) beside SetMaxRunFor (plans 4d); the reads live in those units (plans-4d-units decision); read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 9b81d97b (with main's plan rate ceiling, edge request records, regional box names, self-serve moves plan 1, plans 4d-1 lapse and its other later changes under main's own census rulings) plus the rootfs placement wiring in the activator start: an agentRootfs built from eb.NestedOK, CARLOS_DEPLOYMENT_SINGLE_TENANT, CARLOS_POOLS, the claim flag, swapArming's answer, the control client's /ready/rootfs and, on a fleet box whose identity resolved, fleetOwnerCheck over the deploy store main already opens for the fleet label (fleetStore), then arm and armedRootfs.Store; this body reads nothing new itself; the closures it wires read later, at a rootfs wake and each status tick: GET /ready/rootfs over the control socket, NestedOK's checks, and release.FleetOwnerKey for the judged row's own account and this box's fleet from the deploy store;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Tasks 7 and 11, #329 plan 3 Task 7 and plan 1 Task 7's policy cache: the control client is built once and handed to eb.Control, to the status tick (egressStatus) and to a new egressNudgeLoop goroutine; armSizeSource(svc, "/sys/fs/cgroup") after the activator Service; armPolicyCache() after armChangeIndex; statusLoop takes egressStatus. The reads are those units' own (decision rows); this body reads nothing new: the same five sites, offsets moved, in the agent; B,C,D,F authority retained.;rev3=census-ruling-remote-instance-metrics;basis=builds the metrics loop's owners closure (metricsOwners over the agent's registry, the activator and cgm.Leftover) when an activator exists and hands it to metricsLoop; reads nothing new itself;rev3=census-ruling-edge-asset-cache-3;basis=adds file:Statfs. runAgent keeps its authority (B,C,D,F). The new site is assetcache.Statfs, an exported assetcache.FS interface value (var Statfs FS = statfsFS{}), not a function value and not a call in runAgent: the ready hook passes it to armEdgeAssetCache as the store's filesystem, and armEdgeAssetCache calls its Space method on the configured data directory (dataDir(): $CARLOS_DATA_DIR, else /data), which calls unix.Statfs there (statfsFS.Space, accepted legacy at census-ruling-edge-asset-cache-2). No request-supplied pathname reaches it.
+- `internal/host/metrics_loop.go` `sampler.tick`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-remote-instance-metrics;basis=calls the owners probe before and after the unit read and tags readings with metrics.TagUnits and metrics.CarryTags; no read added
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `internal/host/agent.go:routeHostNames`: reads +registry:Host, +whole:Route ×2; written legacy, accepted-legacy, frozen
+- new `internal/host/metrics_nested.go:nestedUnitReadings`: reads +file:ReadDir; written legacy, accepted-legacy, frozen
+- new `internal/host/metrics_nested.go:snapshotNestedUnits`: reads +file:ReadDir ×2; written legacy, accepted-legacy, frozen
+- new `internal/host/metrics_nested_linux.go:cgroupID`: reads +file:Stat; written legacy, accepted-legacy, frozen
+
+Seal: `f723ddc14e3c03c0d55b6f0c949567a2c9325e0b5d491e0649fe548b2c0c282d` → `e923841657499fc729713abdd750cbd2d6019fc4db677b540be0fab4d2a160e4`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-remote-metrics-nested.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/remote-instance-metrics.md b/docs/superpowers/notes/remote-instance-metrics.md
index dda421d65..52859a9ec 100644
--- a/docs/superpowers/notes/remote-instance-metrics.md
+++ b/docs/superpowers/notes/remote-instance-metrics.md
@@ -295,3 +295,86 @@ instances are all on other boxes, because remote readings were cut; with
untagged samples it now reads the existing "no recent data" (the sweep
was read and nothing in it is this tenant's), and the test says so.
`ResourcesUnavailable` means a failed sweep or no instance at all.
+
+## Follow-up: nested instances (branch remote-metrics-nested)
+
+The release agent found that 4dc5902d gave no readings to nested
+(isolated exec) instances, and a box running only nested instances
+(every instance on it) showed only its platform services in its chunks.
+
+**Root cause.** The sampler read `carlos-*.service` cgroups directly under
+`system.slice` and `carlos.slice`, plus the children of `system-*.slice`.
+A nested host's units (`carlos-instance@`, `-gen@`, `-sidecar@`, `-seed@`,
+`-cmd@`, the rootfs templates) run two slices deeper, at
+`carlos.slice/carlos-instances.slice/carlos-instances-<id>.slice/<unit>`
+(`instancectl.SliceName`). Nothing read there, so nested instances had no
+readings on any box, the console's own box (local rows) included.
+
+**Now.** Each tick reads, for every host the registry has a route for,
+the unit cgroups in its nested slice (`nestedUnitReadings`), sums them
+(a field only when every unit has it; peaks are not summed) and
+publishes the sum as `carlos-exec@<host>`, the name a flat host reports
+under, so the console's per-host match and tenant filter need no change.
+A host read in both layouts in one tick (a layout change in flight) has
+no reading that tick. The reading names the cgroups it summed (unit and cgroup id), and
+the sampler takes no CPU delta between two readings of different sets: a
+unit that went or came makes the difference of two sums wrong. Unit
+cgroups, never the slice: systemd makes a unit's cgroup new
+at each start, while the slice keeps the charges of units that stopped,
+an earlier tenant's included.
+
+Tags follow the rule above unchanged: the activator's entries
+(`putEntryLocked`, `Tenancies`: one tenant ever for the host in this
+agent's life), the registry row agreeing, the reads before and after the
+cgroup read, and the previous tick (`CarryTags`). The nested layout's
+leftover is per unit: before the activator can start anything, the agent
+records the cgroup ids (inodes, never reused while the box is up) of
+every unit then in the layout (`snapshotNestedUnits`). Nested units are
+`BindsTo=carlos-edge.service`, so a previous agent's units stop with it,
+but a stop can still be in flight; a reading that includes one of those
+units, or a unit whose id cannot be read, or any reading after a layout
+that could not be listed, is never vouched. Once that unit goes, the
+first reading is still untagged (its CPU delta starts from the leftover's
+counter) and the next is tagged.
+
+**Request budget.** No new request: the same chunk, one more entry per
+nested instance. On the box, two more registry listings and one directory
+listing per route host per minute, all local.
+
+**Tests.** `internal/host/metrics_nested_test.go`: a real activator waking
+and stopping through a stand-in backend, a real registry, the nested
+cgroup tree laid out as systemd does, the sampler's tick and flush: a
+nested instance is sampled, summed and tagged; a reused hostname under the
+nested layout is never tagged; an agent restart with a unit still there
+is untagged until it goes; an unlistable layout vouches nothing.
+`TestRootRunnerNestedUnitsAreSampled` (root runner, real systemd units in
+the real slice tree via systemd-run): readings have CPU and memory, a unit
+the snapshot held is a leftover, and the same unit started again is a new
+id. Passed in run 20261026T194200-02064e. Mutations: 8, all killed.
+
+**Still not sampled.** Unit-backed `carlos-app@` tenants (systemd starts
+them, including by socket activation, and they can outlive the agent) and
+instances that never sleep (no activator entry vouches for them).
+
+### Nested branch review rounds
+
+Round 1 (Astra, 139e04ca): NOT READY.
+
+- P1 (platform-specific test expectations, not the tenant family): the
+ nested tests needed Linux cgroup ids and would fail on a Mac. They are
+ now `metrics_nested_linux_test.go`; the pure sum test stays everywhere.
+- P2 (CPU counter continuity): a CPU delta between two sums over
+ different unit sets was wrong (a command unit that went made the run
+ unit's 50% read 17%). Fixed: readings name their cgroups and no delta is
+ taken across a change (`TestNestedCPUDeltaOverTheSameUnits`, exact
+ values; mutant killed).
+- Census: the reviewer approved all six units and the `internal/host`
+ envelope.
+
+Round 2 (Astra, 67934c7d): READY AFTER FIXES. Round 1's P1 resolved; its
+P2 partly: summing a host's flat and nested readings during a layout
+overlap still mixed cgroup sets. That is the second round in the CPU
+continuity family, so under stopping rule 2 the overlap summing was cut
+rather than patched again: a host read in both layouts in one tick has no
+reading that tick (`TestMergeNestedCutsAnOverlap`). Census: the changed
+units and envelope approved. The branch review stops here.
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-remote-metrics-nested-census.md b/docs/superpowers/reviews/CODEX-FINDINGS-remote-metrics-nested-census.md
new file mode 100644
index 000000000..d543dd041
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-remote-metrics-nested-census.md
@@ -0,0 +1,19 @@
+Census approval for `8db8720522b7188d81a7b383da644cc2fbb76cd2`, limited to changes since `67934c7d`; the whole-branch review remains closed at round 2.
+
+Confirmed: merging `acfa4f80` preserved this branch’s code. All ten branch-modified Go files retain identical added/deleted lines relative to their respective bases. Every Go change introduced by the merge matches main’s patch exactly.
+
+| Unit or envelope | Verdict and evidence |
+|---|---|
+| `runAgent` | **APPROVE.** The fixed-root snapshot at [agent.go:286](/home/paulca/amadan.net/carlos/platform-remote-metrics-nested/internal/host/agent.go:286) and metrics wiring remain unchanged. The added asset-cache wiring comes entirely from main. Authority disposition retained. |
+| `sampler.tick` | **APPROVE.** Unchanged since the prior approval: membership comparison at [metrics_loop.go:108](/home/paulca/amadan.net/carlos/platform-remote-metrics-nested/internal/host/metrics_loop.go:108), leftover refusal and tag handling remain intact. |
+| `routeHostNames` | **APPROVE.** Unchanged registry enumeration at [agent.go:3952](/home/paulca/amadan.net/carlos/platform-remote-metrics-nested/internal/host/agent.go:3952). `legacy/accepted-legacy` retained. |
+| `nestedUnitReadings` | **APPROVE.** Unchanged reader, identity checks and membership tracking at [metrics_nested.go:80](/home/paulca/amadan.net/carlos/platform-remote-metrics-nested/internal/host/metrics_nested.go:80). `legacy/accepted-legacy` retained. |
+| `snapshotNestedUnits` | **APPROVE.** Unchanged enumeration and refusal to vouch after failures at [metrics_nested.go:38](/home/paulca/amadan.net/carlos/platform-remote-metrics-nested/internal/host/metrics_nested.go:38). `legacy/accepted-legacy` retained. |
+| `cgroupID` | **APPROVE.** Unchanged read-only stat and failure handling at [metrics_nested_linux.go:13](/home/paulca/amadan.net/carlos/platform-remote-metrics-nested/internal/host/metrics_nested_linux.go:13). `legacy/accepted-legacy` retained. |
+| `internal/host` envelope | **APPROVE.** The branch’s only production-code change is [mergeNested’s overlap deletion](/home/paulca/amadan.net/carlos/platform-remote-metrics-nested/internal/host/metrics_loop.go:893). It changes in-memory readings, adds no root access and weakens no check. Main’s changes remain under main’s rulings. |
+
+**Round-2 P2: resolved** — overlap readings are omitted, previous counters are discarded at [metrics_loop.go:156](/home/paulca/amadan.net/carlos/platform-remote-metrics-nested/internal/host/metrics_loop.go:156), and [TestMergeNestedCutsAnOverlap](/home/paulca/amadan.net/carlos/platform-remote-metrics-nested/internal/host/metrics_nested_test.go:20) guards the refusal.
+
+Source inspection only; no tests run, files edited or subagents spawned.
+
+APPROVE (all)
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-remote-metrics-nested-r1.md b/docs/superpowers/reviews/CODEX-FINDINGS-remote-metrics-nested-r1.md
new file mode 100644
index 000000000..01a9208f7
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-remote-metrics-nested-r1.md
@@ -0,0 +1,31 @@
+Reviewed round **1 of 3**, commit `139e04ca70384a6bb637278415d723f69b063284`, against merge base `4dc5902d4f244a3de346b258660950472df9b07a`.
+
+1. **P1 — Section 4: the new tests fail on non-Linux platforms.**
+ **Fault family: platform-specific test expectations.**
+ [metrics_nested_test.go:197](/home/paulca/amadan.net/carlos/platform-remote-metrics-nested/internal/host/metrics_nested_test.go:197) has no Linux build constraint or platform skip, but requires a tagged reading at line 207. On Darwin, [metrics_nested_other.go:7](/home/paulca/amadan.net/carlos/platform-remote-metrics-nested/internal/host/metrics_nested_other.go:7) always returns `ok=false`; `nestedUnitReadings` consequently marks every reading leftover, and the sampler removes its owner. `TestNestedReusedHostname` fails for the same reason; the clean-start assertion in `TestNestedSnapshotUnreadable` also contradicts the non-Linux implementation.
+
+ **Failure scenario:** running these tests on a Mac fails despite the production stub behaving as intended. **Fix:** restrict the cgroup-identity integration tests to Linux, retaining the pure `sumUnitRaw` test across platforms.
+
+2. **P2 — Section 2: CPU deltas subtract counters from different sets of cgroups.**
+ **Fault family: CPU counter continuity.**
+ [metrics_nested.go:101](/home/paulca/amadan.net/carlos/platform-remote-metrics-nested/internal/host/metrics_nested.go:101) collapses currently present units into one cumulative counter; [metrics_loop.go:109](/home/paulca/amadan.net/carlos/platform-remote-metrics-nested/internal/host/metrics_loop.go:109) subtracts the previous host total without retaining the contributing cgroup identities.
+
+ **Failure scenario:** one tick reads a run unit at 100 CPU-seconds and a command unit at 20. Sixty seconds later, the command’s cgroup has disappeared and the run unit reads 130. The sampler reports `(130−120)/60 = 16.7%`, although the surviving run unit alone consumed 50%. The aggregate remains increasing, so the existing counter-reset check does not catch it. Generation retirement and unit recreation have the same problem.
+
+ **Fix:** retain the contributing cgroup IDs and invalidate/rebaseline CPU whenever that set changes, or calculate deltas per cgroup lifetime before aggregation. Add an exact-value test where a disappearing unit’s counter is smaller than the surviving unit’s increase. Memory can remain an instantaneous sum.
+
+Census verdicts below concern the recorded authority and read boundaries; they do not clear the functional findings above.
+
+| Unit or envelope | Verdict and evidence |
+|---|---|
+| `runAgent` | **APPROVE.** [agent.go:282](/home/paulca/amadan.net/carlos/platform-remote-metrics-nested/internal/host/agent.go:282) snapshots the fixed cgroup root before activator construction; the metrics wiring preserves its existing authority disposition. |
+| `sampler.tick` | **APPROVE.** [metrics_loop.go:117](/home/paulca/amadan.net/carlos/platform-remote-metrics-nested/internal/host/metrics_loop.go:117) removes leftover tags before `CarryTags`; no new privileged read or authority. |
+| `routeHostNames` | **APPROVE.** [agent.go:3939](/home/paulca/amadan.net/carlos/platform-remote-metrics-nested/internal/host/agent.go:3939) reads the agent’s registry and returns hostnames. `legacy/accepted-legacy` fits. |
+| `nestedUnitReadings` | **APPROVE.** [metrics_nested.go:78](/home/paulca/amadan.net/carlos/platform-remote-metrics-nested/internal/host/metrics_nested.go:78) reads host-derived paths beneath the fixed cgroup root through the agent’s sampler. No root authority is added. |
+| `snapshotNestedUnits` | **APPROVE.** [metrics_nested.go:36](/home/paulca/amadan.net/carlos/platform-remote-metrics-nested/internal/host/metrics_nested.go:36) performs read-only enumeration and refuses vouching after enumeration or identity failures. |
+| `cgroupID` | **APPROVE.** [metrics_nested_linux.go:13](/home/paulca/amadan.net/carlos/platform-remote-metrics-nested/internal/host/metrics_nested_linux.go:13) performs a read-only stat; failures return no identity. |
+| `internal/host` envelope | **APPROVE.** Reviewed the changed wiring, readers, aggregation and non-Linux stub, including [metrics_loop.go:878](/home/paulca/amadan.net/carlos/platform-remote-metrics-nested/internal/host/metrics_loop.go:878). No added root execution, write authority or store request. |
+
+`git diff --check` passed. Targeted Go tests could not start because the sandbox refused creation of Go’s work directory. The non-Linux failure is established by source inspection, not execution. Root-runner and mutation results were not independently rerun. No files changed.
+
+**NOT READY**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-remote-metrics-nested-r2.md b/docs/superpowers/reviews/CODEX-FINDINGS-remote-metrics-nested-r2.md
new file mode 100644
index 000000000..faf985038
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-remote-metrics-nested-r2.md
@@ -0,0 +1,31 @@
+- Round 1 P1 — **Resolved:** cgroup identity tests are now Linux-only; the pure aggregation test remains cross-platform.
+- Round 1 P2 — **Partly resolved:** nested-only readings track membership, but combining flat and nested readings loses it.
+
+Reviewed commit `67934c7d9522a336a2eb3f3c8f0c902809e5c28d` against merge base `4dc5902d4f244a3de346b258660950472df9b07a`, round **2 of 3**.
+
+1. **P2 — Section 2: merged readings still subtract counters from different cgroup sets.**
+ **Fault family: CPU counter continuity.**
+
+ [mergeNested, metrics_loop.go:892](/home/paulca/amadan.net/carlos/platform-remote-metrics-nested/internal/host/metrics_loop.go:892) combines flat and nested readings using `sumUnitRaw`. That function leaves `members` empty ([metrics_nested.go:130](/home/paulca/amadan.net/carlos/platform-remote-metrics-nested/internal/host/metrics_nested.go:130)), discarding the nested identities. The sampler therefore accepts the previous counter when both membership strings are empty ([metrics_loop.go:108](/home/paulca/amadan.net/carlos/platform-remote-metrics-nested/internal/host/metrics_loop.go:108)).
+
+ **Failure scenario:** during the explicitly supported layout overlap, one tick reads flat CPU at 100 seconds plus nested CPU at 20. Sixty seconds later, the nested cgroup is gone and flat CPU reads 130. Both readings have empty membership, so CPU reports `(130−120)/60 = 16.7%`, although the surviving flat cgroup consumed 50%.
+
+ **Fix:** preserve the complete contributing set through aggregation, including flat participation, and rebaseline whenever it changes. Add an exact-value regression covering mixed-to-flat readings. The current regression supplies an empty exec root ([metrics_nested_linux_test.go:150](/home/paulca/amadan.net/carlos/platform-remote-metrics-nested/internal/host/metrics_nested_linux_test.go:150)), so it misses this path.
+
+ This is the second consecutive round in this fault family. Stopping rule 2 applies: choose a gate refusing overlapping layouts, remove overlap aggregation, or enforce membership continuity centrally with a guard test. I recommend the third option.
+
+Census verdicts concern authority and read boundaries; they do not clear the functional finding above.
+
+| Unit or envelope | Verdict and evidence |
+|---|---|
+| `nestedUnitReadings` | **APPROVE.** [metrics_nested.go:95](/home/paulca/amadan.net/carlos/platform-remote-metrics-nested/internal/host/metrics_nested.go:95) retains the existing read-only identity lookup and leftover checks; the revision records and sorts those identities. `legacy/accepted-legacy` remains appropriate. |
+| `sampler.tick` | **APPROVE.** [metrics_loop.go:108](/home/paulca/amadan.net/carlos/platform-remote-metrics-nested/internal/host/metrics_loop.go:108) compares in-memory membership before calculating CPU. Leftover tag removal still precedes `CarryTags`. No new privileged read or authority. |
+| `internal/host` envelope | **APPROVE.** Reviewed the changed wiring, readers, aggregation and platform-specific tests. [metrics_loop.go:651](/home/paulca/amadan.net/carlos/platform-remote-metrics-nested/internal/host/metrics_loop.go:651) adds local sampling only; no new store request, root execution or write authority. |
+
+Round-one census approvals for the other units stand. No additional P1 or P3 findings.
+
+Changed Go files pass formatting and whitespace checks. Targeted tests could not start because the sandbox refused Go’s work-directory creation. Root-runner and mutation results were not independently rerun. No files changed.
+
+No P1 remains: this review stops here; address the P2 under the stopping rules without reopening a whole-branch round.
+
+**READY AFTER FIXES**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-remote-metrics-nested.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-remote-metrics-nested.md
new file mode 100644
index 000000000..4cf9d1439
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-remote-metrics-nested.md
@@ -0,0 +1,101 @@
+# Review brief: branch remote-metrics-nested, round 2 of 3
+
+Repo carlos/platform, branch `remote-metrics-nested`, commit named in the
+reviewer's prompt.
+Under review: the diff `origin/main..<commit>` (merge base 4dc5902d, which
+merged remote-instance-metrics).
+Authorities: the code on main at the merge base, and
+`docs/superpowers/notes/remote-instance-metrics.md` (its rules were
+reviewed on that branch: note rounds 1-2, branch rounds 1-2; findings
+`docs/superpowers/reviews/CODEX-FINDINGS-remote-instance-metrics-*.md`).
+This branch adds the section "Follow-up: nested instances". Do not review
+against unmerged branches; if this work needs one, say so as a P1 and stop.
+
+You are an independent reviewer. Read the note's new section, then the
+diff, and check every claim against the code.
+
+## Fixed: do not re-argue
+
+- Paul's rulings for this work: boxes tag samples with the instance's
+ tenant and the console shows a remote sample only with the matching tag;
+ untagged samples never show remotely; local rows keep today's behaviour
+ (they accept untagged readings); no new per-box polling.
+- The tag rule merged in 4dc5902d (one tenant ever per host in the
+ agent's life via putEntryLocked/Tenancies, the registry row agreeing,
+ reads before and after, CarryTags, leftovers). Raise it again only with
+ new evidence that a nested reading can carry the wrong tenant.
+
+## What to check
+
+Fault family: **tenant identity of samples**. Name it beside every
+finding in that family.
+
+1. Root cause: is it right that nested units were never sampled, and are
+ all of a nested host's processes under
+ `carlos.slice/carlos-instances.slice/<SliceName(host)>/<unit>`? Check
+ `internal/instancectl` (names.go, server.go, gen.go), the unit templates
+ in `internal/host/units`, and `internal/activator`. Is any nested unit
+ of a host placed elsewhere, or anything of another host or tenant
+ placed in that slice?
+2. `nestedUnitReadings`, `snapshotNestedUnits`, `cgroupID`, `sumUnitRaw`,
+ `mergeNested` (`internal/host/metrics_nested*.go`, `metrics_loop.go`)
+ and the wiring in `agent.go` (the snapshot is taken before the
+ activator can start anything). Can a nested reading be tagged while it
+ includes a process or charge of another tenant, or of a unit this agent
+ did not start? Is summing unit cgroups (not the slice) sound for CPU
+ deltas and memory? Cgroup id reuse?
+3. Do every nested unit's spawns go through activator entries, so the
+ one-tenant rule covers them (instance-control starts them at the
+ agent's request)? Check instance-control paths that start units for a
+ host without an entry (moves, maintenance, probes, sweeps).
+4. Tests: production-wired where the note says; a nested instance sampled
+ and tagged; a reused hostname under the nested layout; an agent
+ restart with a unit in flight; the root-runner test. Mutations: 8, all
+ killed.
+5. Request budget: no new store request.
+6. **Census (the reviewer decides every class).** Card
+ `docs/superpowers/notes/census-proposal-remote-metrics-nested.md`: give
+ approve or reject, citing lines, for each unit (2 changed, 4 new) and
+ the `internal/host` envelope, per AGENTS.md "The census: the reviewer
+ decides".
+
+## Round 2
+
+Earlier round: round 1,
+`docs/superpowers/reviews/CODEX-FINDINGS-remote-metrics-nested-r1.md` (a
+P1 on non-Linux test expectations, a P2 on CPU deltas across changing
+unit sets). First give one line per P1 and P2 from round 1: resolved,
+partly, or not. Carry every unresolved or partly resolved finding forward
+at its current severity, then add new findings. The verdict covers
+everything outstanding. Give census verdicts again only for units the
+fixes changed (`nestedUnitReadings`, `sampler.tick`, the `internal/host`
+envelope); round 1's others stand.
+
+## 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. (The
+ census, and review of any newly changed security, root, termination
+ or production-storage behaviour, still check the fix; see AGENTS.md,
+ "Stopping rules".)
+- **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 section or task, the problem,
+the evidence (file:line, verified), the failure scenario, a concrete
+fix and the invariant or trust boundary it breaks (that is its fault
+family). Then the census verdicts. 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.
diff --git a/internal/host/agent.go b/internal/host/agent.go
index 5bee5292a..7c524ba99 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -280,6 +280,10 @@ func runAgent(args []string, buildClaims ClaimFactory) {
} else {
cgm = cgroup.Setup(log.Printf)
}
+ // What the nested layout holds before this agent can start anything:
+ // the metrics sampler never vouches a reading that includes one of
+ // these units (remote instance metrics, nested follow-up).
+ nestedAtStart := snapshotNestedUnits(cgroupInstancesSliceDir)
// Alert sinks and the operator paging hook (moves spec §13), built from
// the sink env alone and armed here, before armMovesPass and before any
@@ -917,7 +921,12 @@ func runAgent(args []string, buildClaims ClaimFactory) {
if svc != nil {
owners = func() map[string]metrics.Vouch { return metricsOwners(reg, svc, cgm.Leftover) }
}
- go metricsLoop(cgm.Root(), func() []string { return stampedUnitNames(reg) }, owners, alerts)
+ go metricsLoop(cgm.Root(), unitSources{
+ stamped: func() []string { return stampedUnitNames(reg) },
+ nestedHosts: func() []string { return routeHostNames(reg) },
+ nestedRoot: cgroupInstancesSliceDir,
+ nestedAtStart: nestedAtStart,
+ }, owners, alerts)
go configSyncLoop(reg, svc, dd, claims.Writes)
go configGenLoop(reg, svc, dd, claims.Writes)
go socketAdvisoryLoop(reg, svc)
@@ -3937,6 +3946,22 @@ func retentionLoop(reg *registry.Registry, buildStates func() (map[string]status
// and the agent are not. The names are returned sorted so the slice handed
// down each tick is stable (nothing below depends on the order; a stable one
// just makes a log or a test diff mean something).
+// routeHostNames is every host the registry has a route for: the sampler
+// reads each one's nested slice, if it has one (nestedUnitReadings). A read
+// failure returns nil: this tick's nested readings are lost, nothing else.
+func routeHostNames(reg *registry.Registry) []string {
+ routes, err := reg.List()
+ if err != nil {
+ log.Printf("agent: metrics: read route hosts: %v", err)
+ return nil
+ }
+ out := make([]string, 0, len(routes))
+ for _, rt := range routes {
+ out = append(out, rt.Host)
+ }
+ return out
+}
+
func stampedUnitNames(reg *registry.Registry) []string {
routes, err := reg.List()
if err != nil {
diff --git a/internal/host/agentalerts_test.go b/internal/host/agentalerts_test.go
index d0debe5c2..8778b0f07 100644
--- a/internal/host/agentalerts_test.go
+++ b/internal/host/agentalerts_test.go
@@ -47,7 +47,7 @@ func TestStuckMarkBeforeMetricsReachesTheSink(t *testing.T) {
if _, _, err := openStatusStore(context.Background(), os.Getenv); err == nil {
t.Fatal("fixture: the metrics store opened")
}
- metricsLoop(t.TempDir(), nil, nil, sinks)
+ metricsLoop(t.TempDir(), unitSources{}, nil, sinks)
}
h := newRevertHarness(t)
diff --git a/internal/host/metrics_loop.go b/internal/host/metrics_loop.go
index b963933f8..a45982ed6 100644
--- a/internal/host/metrics_loop.go
+++ b/internal/host/metrics_loop.go
@@ -63,6 +63,7 @@ type sampler struct {
prevCPU *metrics.CPUCounters
prevUnit map[string]*int64 // unit -> cpu usec at previous tick
prevOwner map[string]*metrics.Owner // unit -> owner vouched at previous tick (nil: none)
+ prevMembers map[string]string // unit -> the cgroups its previous reading summed (unitRaw.members)
prevAt time.Time
buf []metrics.Sample
writtenHours map[string]bool // hour -> this process has written/merged it at least once
@@ -97,12 +98,14 @@ func (sm *sampler) tick(p sampleProbes) {
var unitSamples map[string]metrics.UnitSample
var newPrevUnit map[string]*int64
+ var newPrevMembers map[string]string
if units != nil {
unitSamples = make(map[string]metrics.UnitSample, len(units))
newPrevUnit = make(map[string]*int64, len(units))
+ newPrevMembers = make(map[string]string, len(units))
for name, u := range units {
var prevUsec *int64
- if sm.prevUnit != nil {
+ if sm.prevUnit != nil && sm.prevMembers[name] == u.members {
prevUsec = sm.prevUnit[name]
}
unitSamples[name] = metrics.UnitSample{
@@ -113,8 +116,18 @@ func (sm *sampler) tick(p sampleProbes) {
WriteBytes: u.writeBytes,
}
newPrevUnit[name] = u.cpuUsec
+ newPrevMembers[name] = u.members
}
metrics.TagUnits(unitSamples, before, after)
+ // A nested reading that includes a unit this agent did not start
+ // is not vouched, whoever the activator says holds the host now.
+ for name, u := range units {
+ if u.leftover {
+ s := unitSamples[name]
+ s.Owner = nil
+ unitSamples[name] = s
+ }
+ }
}
// The CPU fraction above is a delta from the previous tick's counter:
// a reading keeps its tag only if that tick vouched the same tenant.
@@ -141,6 +154,7 @@ func (sm *sampler) tick(p sampleProbes) {
sm.prevCPU = curCPU
sm.prevUnit = newPrevUnit
+ sm.prevMembers = newPrevMembers
sm.prevAt = now
}
@@ -619,18 +633,32 @@ func httpPostWebhook(url string, body []byte) error { return alerting.PostJSON(u
// start, and a route stamped this afternoon would go unsampled until the next
// restart. A nil func means "no stamped units" — the darwin/dev shape, and
// what every test double passes.
-func realSampleProbes(execRoot string, stampedUnits func() []string, owners func() map[string]metrics.Vouch) sampleProbes {
+// unitSources is the sampler's registry and layout inputs: the bespoke
+// units stamped on routes, the hosts whose nested slices to read, and what
+// the nested layout held when the agent started (nestedStart). nil funcs
+// are none.
+type unitSources struct {
+ stamped func() []string
+ nestedHosts func() []string
+ nestedRoot string
+ nestedAtStart nestedStart
+}
+
+func realSampleProbes(execRoot string, src unitSources, owners func() map[string]metrics.Vouch) sampleProbes {
return sampleProbes{
procStat: readProcStat,
loadavg: readLoadAvg,
memFrac: readMemFrac,
diskFrac: readDiskFrac,
units: func() map[string]unitRaw {
- var stamped []string
- if stampedUnits != nil {
- stamped = stampedUnits()
+ var stamped, nested []string
+ if src.stamped != nil {
+ stamped = src.stamped()
+ }
+ if src.nestedHosts != nil {
+ nested = src.nestedHosts()
}
- return realUnitReadings(execRoot, stamped)
+ return mergeNested(realUnitReadings(execRoot, stamped), nestedUnitReadings(src.nestedRoot, nested, src.nestedAtStart))
},
owners: owners,
now: time.Now,
@@ -761,11 +789,12 @@ func BoxLabel() string { return metricsBoxLabel(os.Getenv, readMachineID()) }
// at the 60s tick cadence); alertTick runs every tick, since a threshold
// breach deserves faster detection than a metrics flush does.
//
-// stampedUnits is the sweep's one registry seam (agent.go's
-// stampedUnitNames): the bespoke units to sample alongside the carlos- ones,
-// re-read once per tick so a freshly stamped route is picked up within a
-// minute. It is a func, not the registry handle, so this loop keeps its "no
-// state but a bucket and /proc" shape; nil = none.
+// src is the sweep's registry seams (agent.go): the bespoke units to sample
+// alongside the carlos- ones (stampedUnitNames) and the hosts whose nested
+// slices to read (routeHostNames), re-read once per tick so a freshly
+// stamped or minted route is picked up within a minute, plus the nested
+// layout as it was at agent start. Funcs, not the registry handle, so this
+// loop keeps its "no state but a bucket and /proc" shape; nil = none.
//
// owners tags each exec cgroup's reading with the tenant the box vouches
// for (metricsOwners, agent.go's wiring); nil tags nothing.
@@ -773,7 +802,7 @@ func BoxLabel() string { return metricsBoxLabel(os.Getenv, readMachineID()) }
// sinks are the agent's alert sinks, built and armed for paging by runAgent
// at startup (armAgentAlerts); the loop delivers its alerts on them and
// never builds or arms its own. nil delivers nowhere.
-func metricsLoop(execRoot string, stampedUnits func() []string, owners func() map[string]metrics.Vouch, sinks *alertSinks) {
+func metricsLoop(execRoot string, src unitSources, owners func() map[string]metrics.Vouch, sinks *alertSinks) {
// This loop is always on and shares a process with the agent that serves
// this box's traffic, so a panic in it — an unreadable cgroup shape, a
// nil no one expected — must not take the box down with it. Monitoring
@@ -821,7 +850,7 @@ func metricsLoop(execRoot string, stampedUnits func() []string, owners func() ma
log.Printf("agent: metrics loop armed (60s ticks, 5min flush), publishing to %s", target)
sm := &sampler{}
- probes := realSampleProbes(execRoot, stampedUnits, owners)
+ probes := realSampleProbes(execRoot, src, owners)
tick := 0
// One watch for the life of the loop: its memory of what it has already
// alerted is what keeps a standing refusal from paging every minute.
@@ -847,3 +876,26 @@ func metricsLoop(execRoot string, stampedUnits func() []string, owners func() ma
}
}
}
+
+// mergeNested adds nested hosts' readings to the flat scan's. A host
+// with both in one tick (a layout change in flight) gets no reading that
+// tick: summing two layouts' counters made CPU deltas across unit sets
+// that come and go (Astra, nested branch rounds 1 and 2), so the overlap
+// is cut rather than reconciled. It is transient: the next tick reads
+// whichever layout is left.
+func mergeNested(flat, nested map[string]unitRaw) map[string]unitRaw {
+ if len(nested) == 0 {
+ return flat
+ }
+ if flat == nil {
+ flat = make(map[string]unitRaw, len(nested))
+ }
+ for name, n := range nested {
+ if _, both := flat[name]; both {
+ delete(flat, name)
+ continue
+ }
+ flat[name] = n
+ }
+ return flat
+}
diff --git a/internal/host/metrics_nested.go b/internal/host/metrics_nested.go
new file mode 100644
index 000000000..03005c835
--- /dev/null
+++ b/internal/host/metrics_nested.go
@@ -0,0 +1,140 @@
+package host
+
+import (
+ "errors"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "sort"
+ "strconv"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/cgroup"
+ "github.com/carlosframework/platform/internal/instancectl"
+)
+
+// cgroupInstancesSliceDir is the nested layout's parent slice
+// (instancectl's parentSlices under the cgroup root): every nested host has
+// its slice, carlos-instances-<id>.slice, below it, and its units (run,
+// generations, sidecar, seed, cmd, rootfs) below that. The sampler's unit
+// scans read only system.slice and carlos.slice's own children, so before
+// this no nested instance had a reading at all, on any box.
+const cgroupInstancesSliceDir = "/sys/fs/cgroup/carlos.slice/carlos-instances.slice"
+
+// nestedStart is what the nested layout held when this agent started,
+// taken before the activator can start anything: the cgroup ids of every
+// unit then under a host's slice. Nested units are bound to carlos-edge
+// (BindsTo=), so a previous agent's units stop with it, but a stop can
+// still be in flight when this agent starts. A reading that includes one
+// of them is never vouched (unitRaw.leftover). unswept says the layout
+// could not be listed, so nothing in it is known to be this agent's.
+type nestedStart struct {
+ ids map[uint64]bool
+ unswept bool
+}
+
+// snapshotNestedUnits records root's unit cgroups for nestedStart. A box
+// with no nested layout (root absent) holds none.
+func snapshotNestedUnits(root string) nestedStart {
+ slices, err := os.ReadDir(root)
+ if err != nil {
+ if errors.Is(err, fs.ErrNotExist) {
+ return nestedStart{}
+ }
+ return nestedStart{unswept: true}
+ }
+ st := nestedStart{ids: map[uint64]bool{}}
+ for _, s := range slices {
+ if !s.IsDir() || !strings.HasSuffix(s.Name(), ".slice") {
+ continue
+ }
+ units, err := os.ReadDir(filepath.Join(root, s.Name()))
+ if err != nil {
+ st.unswept = true
+ continue
+ }
+ for _, u := range units {
+ if !u.IsDir() || !strings.HasSuffix(u.Name(), ".service") {
+ continue
+ }
+ id, ok := cgroupID(filepath.Join(root, s.Name(), u.Name()))
+ if !ok {
+ st.unswept = true
+ continue
+ }
+ st.ids[id] = true
+ }
+ }
+ return st
+}
+
+// nestedUnitReadings reads each host's nested units and sums them into one
+// reading per host, keyed carlos-exec@<host>: the name a flat host's
+// processes report under, so the console's per-host match and its tenant
+// filter need no change. It reads the unit cgroups, never the host's
+// slice: a unit's cgroup is new at each start, while the slice keeps the
+// charges of units that stopped, an earlier tenant's included. A host with
+// no slice (not nested here) is skipped. The reading is a leftover when
+// any unit in it was there when the agent started, its id cannot be read,
+// or the start could not be swept.
+func nestedUnitReadings(root string, hosts []string, start nestedStart) map[string]unitRaw {
+ out := map[string]unitRaw{}
+ for _, host := range hosts {
+ dir := filepath.Join(root, instancectl.SliceName(host))
+ units, err := os.ReadDir(dir)
+ if err != nil {
+ continue
+ }
+ var parts []unitRaw
+ var members []string
+ leftover := start.unswept
+ for _, u := range units {
+ if !u.IsDir() || !strings.HasSuffix(u.Name(), ".service") {
+ continue
+ }
+ ud := filepath.Join(dir, u.Name())
+ id, ok := cgroupID(ud)
+ if !ok || start.ids[id] {
+ leftover = true
+ }
+ members = append(members, u.Name()+"#"+strconv.FormatUint(id, 10))
+ parts = append(parts, readUnitRaw(ud))
+ }
+ if len(parts) == 0 {
+ continue
+ }
+ sum := sumUnitRaw(parts)
+ sum.leftover = leftover
+ sort.Strings(members)
+ sum.members = strings.Join(members, ",")
+ out[cgroup.ExecName(host)] = sum
+ }
+ return out
+}
+
+// sumUnitRaw adds readings of one host's cgroups. A field is summed only
+// when every part has it: a partial CPU sum would make a wrong delta. The
+// peak is left unset, since peaks of different cgroups do not add.
+func sumUnitRaw(parts []unitRaw) unitRaw {
+ add := func(get func(unitRaw) *int64) *int64 {
+ var total int64
+ for _, p := range parts {
+ v := get(p)
+ if v == nil {
+ return nil
+ }
+ total += *v
+ }
+ return &total
+ }
+ out := unitRaw{
+ cpuUsec: add(func(u unitRaw) *int64 { return u.cpuUsec }),
+ memBytes: add(func(u unitRaw) *int64 { return u.memBytes }),
+ readBytes: add(func(u unitRaw) *int64 { return u.readBytes }),
+ writeBytes: add(func(u unitRaw) *int64 { return u.writeBytes }),
+ }
+ for _, p := range parts {
+ out.leftover = out.leftover || p.leftover
+ }
+ return out
+}
diff --git a/internal/host/metrics_nested_linux.go b/internal/host/metrics_nested_linux.go
new file mode 100644
index 000000000..f601ea65c
--- /dev/null
+++ b/internal/host/metrics_nested_linux.go
@@ -0,0 +1,23 @@
+//go:build linux
+
+package host
+
+import (
+ "os"
+ "syscall"
+)
+
+// cgroupID is dir's inode, which on cgroup v2 is the cgroup's id: never
+// reused while the box is up, so a unit started again under the same name
+// is a new id. ok is false when it cannot be read.
+func cgroupID(dir string) (uint64, bool) {
+ fi, err := os.Stat(dir)
+ if err != nil {
+ return 0, false
+ }
+ st, ok := fi.Sys().(*syscall.Stat_t)
+ if !ok {
+ return 0, false
+ }
+ return st.Ino, true
+}
diff --git a/internal/host/metrics_nested_linux_test.go b/internal/host/metrics_nested_linux_test.go
new file mode 100644
index 000000000..af2c58e73
--- /dev/null
+++ b/internal/host/metrics_nested_linux_test.go
@@ -0,0 +1,334 @@
+//go:build linux
+
+package host
+
+// Nested (isolated exec) instances in the metrics sweep, end to end on one
+// box: a real registry, a real activator waking and stopping through a
+// stand-in backend, the nested layout's cgroup tree as instance-control
+// lays it out (carlos-instances-<id>.slice/<unit>, written here into a temp
+// root), the sampler's tick and flush, and the chunk the console reads.
+// The real tree under systemd is TestRootRunnerNestedUnitsAreSampled.
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strconv"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/cgroup"
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/metrics"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// nestedBackend starts nothing real: the wake's process is a plannedProc,
+// and its units are whatever the test writes into the cgroup tree.
+type nestedBackend struct{}
+
+func (nestedBackend) Acquire(context.Context, registry.Route) (activator.Lease, error) {
+ return plannedLease{}, nil
+}
+func (nestedBackend) Restore(context.Context, registry.Route) (bool, error) { return false, nil }
+func (nestedBackend) Seed(context.Context, registry.Route) error { return nil }
+func (nestedBackend) Start(context.Context, registry.Route) (activator.Proc, string, error) {
+ return &plannedProc{}, "v1", nil
+}
+func (nestedBackend) NextDue(context.Context, registry.Route) (int64, error) { return 0, nil }
+func (nestedBackend) HasSidecar(registry.Route) bool { return false }
+func (nestedBackend) StartSidecar(context.Context, registry.Route) (activator.Proc, error) {
+ return nil, errors.New("no sidecar")
+}
+func (nestedBackend) StartWorker(context.Context, registry.Route, map[string]string) (activator.Proc, string, error) {
+ return nil, "", errors.New("no worker")
+}
+
+const nestedHost = "eu.shop.example.com"
+
+// nestedBox is one box: its registry, its activator and its nested root.
+type nestedBox struct {
+ reg *registry.Registry
+ svc *activator.Service
+ root string
+ socket string
+ start nestedStart
+ sm *sampler
+ at time.Time
+}
+
+func newNestedBox(t *testing.T) *nestedBox {
+ t.Helper()
+ reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { reg.Close() })
+ b := &nestedBox{reg: reg, root: t.TempDir(), socket: healthySocket(t), sm: &sampler{},
+ at: time.Date(2026, 10, 26, 20, 0, 0, 0, time.UTC)}
+ b.restartAgent(t)
+ return b
+}
+
+// restartAgent is a new agent on the box: a fresh activator, and the
+// nested layout snapshotted before it can start anything (runAgent's
+// order).
+func (b *nestedBox) restartAgent(t *testing.T) {
+ t.Helper()
+ b.start = snapshotNestedUnits(b.root)
+ b.svc = activator.New(activator.Config{Bucket: "hib", Idle: time.Hour}, nestedBackend{}, b.reg)
+ b.svc.Routes = b.reg
+ svc := b.svc
+ t.Cleanup(func() { svc.Shutdown(context.Background()) })
+ b.sm = &sampler{}
+}
+
+// mint is the provision pass minting host for acct's app on this box.
+func (b *nestedBox) mint(t *testing.T, acct string) {
+ t.Helper()
+ if err := b.reg.Upsert(registry.Route{Host: nestedHost, Kind: "instance", Account: acct, App: "shop",
+ Socket: b.socket, Hibernate: true, Provisioned: true, Status: "ready"}); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// wake serves one request: the activator wakes the host for its row.
+func (b *nestedBox) wake(t *testing.T) {
+ t.Helper()
+ rt, err := b.reg.Get(nestedHost)
+ if err != nil || rt == nil {
+ t.Fatalf("route: %+v %v", rt, err)
+ }
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodGet, "http://"+nestedHost+"/", nil)
+ if !b.svc.ServeHTTP(rec, req, *rt, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {})) || rec.Code != http.StatusOK {
+ t.Fatalf("wake = %d %s", rec.Code, rec.Body)
+ }
+}
+
+// stop puts every entry down, as a retirement or an idle sleep does.
+func (b *nestedBox) stop(t *testing.T) {
+ t.Helper()
+ b.svc.RetireExcept(map[string]bool{})
+ deadline := time.Now().Add(5 * time.Second)
+ for !b.svc.Quiesced(nestedHost) {
+ if time.Now().After(deadline) {
+ t.Fatal("the entry did not stop")
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+}
+
+// unit writes (or rewrites) one unit cgroup of host's slice, as systemd
+// does for a unit instance-control starts.
+func (b *nestedBox) unit(t *testing.T, unit string, usec, mem int64) string {
+ t.Helper()
+ dir := filepath.Join(b.root, instancectl.SliceName(nestedHost), unit)
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ for name, body := range map[string]string{
+ "cpu.stat": "usage_usec " + strconv.FormatInt(usec, 10) + "\n",
+ "memory.current": strconv.FormatInt(mem, 10) + "\n",
+ } {
+ if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ return dir
+}
+
+// tick is one sampler tick and flush through production code; it returns
+// the host's reading as the chunk carries it.
+func (b *nestedBox) tick(t *testing.T) metrics.UnitSample {
+ t.Helper()
+ b.at = b.at.Add(time.Minute)
+ f := 0.4
+ src := unitSources{nestedHosts: func() []string { return routeHostNames(b.reg) }, nestedRoot: b.root, nestedAtStart: b.start}
+ p := realSampleProbes("", src, func() map[string]metrics.Vouch { return metricsOwners(b.reg, b.svc, nil) })
+ p.procStat = func() *metrics.CPUCounters { return nil }
+ p.loadavg = func() (*float64, *float64, *float64) { return nil, nil, nil }
+ p.memFrac = func() *float64 { return &f }
+ p.diskFrac = func() *float64 { return &f }
+ at := b.at
+ p.now = func() time.Time { return at }
+ // The real probe also scans the box's own system.slice; only the
+ // nested tree under test is read here.
+ units := p.units
+ p.units = func() map[string]unitRaw {
+ out := map[string]unitRaw{}
+ for k, v := range units() {
+ if k == cgroup.ExecName(nestedHost) {
+ out[k] = v
+ }
+ }
+ return out
+ }
+ b.sm.tick(p)
+ store := release.NewDirStore(t.TempDir())
+ if err := metricsFlush(context.Background(), store, "box-b", b.sm, at); err != nil {
+ t.Fatal(err)
+ }
+ body, _, err := store.Get(context.Background(), metrics.RawKey("box-b", metrics.HourOf(at)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var chunk metrics.RawChunk
+ if err := json.Unmarshal(body, &chunk); err != nil {
+ t.Fatal(err)
+ }
+ return chunk.Samples[len(chunk.Samples)-1].Units[cgroup.ExecName(nestedHost)]
+}
+
+func owner(u metrics.UnitSample) string {
+ if u.Owner == nil {
+ return ""
+ }
+ return u.Owner.Account + "/" + u.Owner.App
+}
+
+// TestNestedInstanceIsSampledAndTagged: a nested instance's units are
+// read from its slice, summed into one reading under carlos-exec@<host>,
+// and tagged with its tenant once two ticks of the same entry agree.
+func TestNestedInstanceIsSampledAndTagged(t *testing.T) {
+ b := newNestedBox(t)
+ b.mint(t, "bdn")
+ b.wake(t)
+ b.unit(t, instancectl.UnitName(instancectl.RoleRun, nestedHost), 1_000_000, 3<<20)
+ b.unit(t, instancectl.UnitName(instancectl.RoleSidecar, nestedHost), 500_000, 1<<20)
+ first := b.tick(t)
+ if first.MemBytes == nil || *first.MemBytes != 4<<20 {
+ t.Fatalf("nested reading = %+v, want the two units' memory summed (4 MB)", first)
+ }
+ if owner(first) != "bdn/shop" {
+ t.Fatalf("first reading owner = %q, want bdn/shop", owner(first))
+ }
+ b.unit(t, instancectl.UnitName(instancectl.RoleRun, nestedHost), 4_000_000, 3<<20)
+ second := b.tick(t)
+ if second.CPUFrac == nil || owner(second) != "bdn/shop" {
+ t.Fatalf("second reading = cpu %v owner %q, want a CPU fraction tagged bdn/shop", second.CPUFrac, owner(second))
+ }
+}
+
+// TestNestedReusedHostname: the hostname was the rival's on this box, then
+// this account's. Its units are new cgroups, but the host has had two
+// tenants in this agent's life, so nothing is vouched until the agent
+// restarts; after a restart, a unit still there from before the restart is
+// a leftover, and only a reading wholly of units this agent started is
+// tagged.
+func TestNestedReusedHostname(t *testing.T) {
+ b := newNestedBox(t)
+ b.mint(t, "rival")
+ b.wake(t)
+ old := b.unit(t, instancectl.UnitName(instancectl.RoleRun, nestedHost), 9_000_000, 11<<20)
+ if u := b.tick(t); owner(u) != "rival/shop" {
+ t.Fatalf("predecessor's reading owner = %q, want rival/shop", owner(u))
+ }
+ b.stop(t)
+ if err := os.RemoveAll(old); err != nil {
+ t.Fatal(err)
+ }
+ if err := b.reg.Delete(nestedHost); err != nil {
+ t.Fatal(err)
+ }
+ b.mint(t, "bdn")
+ b.wake(t)
+ b.unit(t, instancectl.UnitName(instancectl.RoleRun, nestedHost), 200_000, 2<<20)
+ for i := 0; i < 2; i++ {
+ if u := b.tick(t); u.Owner != nil {
+ t.Fatalf("tick %d after the hostname changed tenant: owner %q, want none", i, owner(u))
+ }
+ }
+
+ // The agent restarts while the unit is still there (its stop in
+ // flight): a leftover until it goes.
+ b.restartAgent(t)
+ b.wake(t)
+ if u := b.tick(t); u.Owner != nil || u.MemBytes == nil {
+ t.Fatalf("reading with a unit from before the restart = owner %q mem %v, want a reading, untagged", owner(u), u.MemBytes)
+ }
+ // The new generation's unit starts, then the old one goes. (Created
+ // first because a temp filesystem may hand a removed dir's inode to the
+ // next one; cgroupfs never reuses a cgroup id.)
+ b.unit(t, instancectl.GenUnitName(nestedHost, 1), 100_000, 2<<20)
+ if err := os.RemoveAll(filepath.Join(b.root, instancectl.SliceName(nestedHost), instancectl.UnitName(instancectl.RoleRun, nestedHost))); err != nil {
+ t.Fatal(err)
+ }
+ // Its first reading's CPU delta starts from the leftover's counter
+ // (CarryTags); the next is wholly this agent's units.
+ if u := b.tick(t); u.Owner != nil {
+ t.Fatalf("first reading after the leftover went = owner %q, want none", owner(u))
+ }
+ if u := b.tick(t); owner(u) != "bdn/shop" {
+ t.Fatalf("reading of a unit this agent started = owner %q, want bdn/shop", owner(u))
+ }
+}
+
+// TestNestedSnapshotUnreadable: when the nested layout cannot be listed at
+// agent start, nothing in it is known to be this agent's.
+func TestNestedSnapshotUnreadable(t *testing.T) {
+ if st := snapshotNestedUnits(filepath.Join(t.TempDir(), "absent")); st.unswept || len(st.ids) != 0 {
+ t.Fatalf("a box with no nested layout = %+v, want clean", st)
+ }
+ root := t.TempDir()
+ if err := os.MkdirAll(filepath.Join(root, "carlos-instances-x.slice"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chmod(root, 0o300); err != nil {
+ t.Fatal(err)
+ }
+ defer os.Chmod(root, 0o755) //nolint:errcheck
+ if _, err := os.ReadDir(root); err == nil {
+ t.Skip("listable without read permission (running as root?)")
+ }
+ if st := snapshotNestedUnits(root); !st.unswept {
+ t.Fatal("an unlistable nested layout counted as swept")
+ }
+ b := &nestedBox{root: t.TempDir()}
+ b.unit(t, instancectl.UnitName(instancectl.RoleRun, nestedHost), 1, 1)
+ got := nestedUnitReadings(b.root, []string{nestedHost}, nestedStart{unswept: true})
+ if r, ok := got[cgroup.ExecName(nestedHost)]; !ok || !r.leftover {
+ t.Fatalf("a reading after an unswept start = %+v, want a leftover", got)
+ }
+ if r := nestedUnitReadings(b.root, []string{nestedHost}, nestedStart{})[cgroup.ExecName(nestedHost)]; r.leftover {
+ t.Fatal("a reading after a clean start is a leftover")
+ }
+}
+
+// TestNestedCPUDeltaOverTheSameUnits (Astra, nested branch round 1, P2):
+// a nested reading is a sum over the host's unit cgroups, so a delta
+// between two sums is right only when both read the same cgroups. Tick 1
+// reads the run unit at 100 s and a command unit at 20 s; by tick 2 the
+// command's cgroup is gone and the run unit reads 130 s. (130-120)/60 would
+// say 17%; the run unit alone used 50%. No delta is taken across the
+// change, and the next tick's is the run unit's own.
+func TestNestedCPUDeltaOverTheSameUnits(t *testing.T) {
+ b := newNestedBox(t)
+ b.mint(t, "bdn")
+ b.wake(t)
+ run := instancectl.UnitName(instancectl.RoleRun, nestedHost)
+ b.unit(t, run, 100_000_000, 1<<20)
+ cmd := b.unit(t, instancectl.UnitName(instancectl.RoleCmd, nestedHost), 20_000_000, 1<<20)
+ b.tick(t)
+ if err := os.RemoveAll(cmd); err != nil {
+ t.Fatal(err)
+ }
+ b.unit(t, run, 130_000_000, 1<<20)
+ if u := b.tick(t); u.CPUFrac != nil {
+ t.Fatalf("CPU across a unit that went = %v, want none", *u.CPUFrac)
+ }
+ b.unit(t, run, 160_000_000, 1<<20)
+ u := b.tick(t)
+ if u.CPUFrac == nil || *u.CPUFrac < 0.499 || *u.CPUFrac > 0.501 {
+ t.Fatalf("CPU over the same unit = %v, want 0.5", u.CPUFrac)
+ }
+ if owner(u) != "bdn/shop" {
+ t.Fatalf("owner = %q", owner(u))
+ }
+}
diff --git a/internal/host/metrics_nested_other.go b/internal/host/metrics_nested_other.go
new file mode 100644
index 000000000..d5ff512e4
--- /dev/null
+++ b/internal/host/metrics_nested_other.go
@@ -0,0 +1,7 @@
+//go:build !linux
+
+package host
+
+// cgroupID has no cgroup to name off Linux: nested instances are a Linux
+// layout, and nothing read here is ever vouched.
+func cgroupID(string) (uint64, bool) { return 0, false }
diff --git a/internal/host/metrics_nested_rootrunner_linux_test.go b/internal/host/metrics_nested_rootrunner_linux_test.go
new file mode 100644
index 000000000..8eb4948af
--- /dev/null
+++ b/internal/host/metrics_nested_rootrunner_linux_test.go
@@ -0,0 +1,86 @@
+//go:build linux && rootrunner
+
+package host
+
+import (
+ "context"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/cgroup"
+ "github.com/carlosframework/platform/internal/instancectl"
+)
+
+// TestRootRunnerNestedUnitsAreSampled runs a unit where instance-control
+// puts a nested host's run unit (systemd-run into its per-host slice, so
+// systemd makes carlos.slice/carlos-instances.slice/<host slice>/<unit>)
+// and reads it with the production reader from the production root. The
+// reading has CPU and memory; it is not a leftover when started after the
+// snapshot, and is one when the snapshot already held it.
+func TestRootRunnerNestedUnitsAreSampled(t *testing.T) {
+ if os.Geteuid() != 0 {
+ t.Fatal("needs root")
+ }
+ const host = "rr.nested.example.com"
+ unit := instancectl.UnitName(instancectl.RoleRun, host)
+ slice := instancectl.SliceName(host)
+ before := snapshotNestedUnits(cgroupInstancesSliceDir)
+ if before.unswept {
+ t.Fatalf("snapshot before the unit = %+v", before)
+ }
+ out, err := exec.Command("systemd-run", "--unit="+unit, "--slice="+slice, "--property=MemoryAccounting=yes",
+ "--property=CPUAccounting=yes", "/bin/sh", "-c", "i=0; while [ $i -lt 2000000 ]; do i=$((i+1)); done; sleep 120").CombinedOutput()
+ if err != nil {
+ t.Fatalf("systemd-run: %v %s", err, out)
+ }
+ t.Cleanup(func() { exec.Command("systemctl", "stop", unit).Run() }) //nolint:errcheck
+ dir := filepath.Join(cgroupInstancesSliceDir, slice, unit)
+ deadline := time.Now().Add(10 * time.Second)
+ for {
+ if _, err := os.Stat(filepath.Join(dir, "cpu.stat")); err == nil {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("the unit's cgroup %s did not appear", dir)
+ }
+ time.Sleep(100 * time.Millisecond)
+ }
+ time.Sleep(time.Second)
+
+ got := nestedUnitReadings(cgroupInstancesSliceDir, []string{host, "flat.example.com"}, before)
+ r, ok := got[cgroup.ExecName(host)]
+ if !ok || len(got) != 1 {
+ t.Fatalf("readings = %+v, want one for %s", got, host)
+ }
+ if r.cpuUsec == nil || *r.cpuUsec <= 0 || r.memBytes == nil || *r.memBytes <= 0 {
+ t.Fatalf("reading = cpu %v mem %v, want both", r.cpuUsec, r.memBytes)
+ }
+ if r.leftover {
+ t.Fatal("a unit started after the snapshot is a leftover")
+ }
+ after := snapshotNestedUnits(cgroupInstancesSliceDir)
+ if !nestedUnitReadings(cgroupInstancesSliceDir, []string{host}, after)[cgroup.ExecName(host)].leftover {
+ t.Fatal("a unit the snapshot held is not a leftover")
+ }
+
+ // The unit stops and starts again under the same name: a new cgroup id,
+ // so no longer the snapshot's.
+ if out, err := exec.Command("systemctl", "stop", unit).CombinedOutput(); err != nil {
+ t.Fatalf("stop: %v %s", err, out)
+ }
+ if out, err := exec.Command("systemd-run", "--unit="+unit, "--slice="+slice, "/bin/sleep", "120").CombinedOutput(); err != nil {
+ t.Fatalf("systemd-run again: %v %s", err, out)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ for ctx.Err() == nil {
+ if r, ok := nestedUnitReadings(cgroupInstancesSliceDir, []string{host}, after)[cgroup.ExecName(host)]; ok && !r.leftover {
+ return
+ }
+ time.Sleep(100 * time.Millisecond)
+ }
+ t.Fatal("a restarted unit kept the earlier cgroup's id")
+}
diff --git a/internal/host/metrics_nested_test.go b/internal/host/metrics_nested_test.go
new file mode 100644
index 000000000..2e7a0f578
--- /dev/null
+++ b/internal/host/metrics_nested_test.go
@@ -0,0 +1,34 @@
+package host
+
+import "testing"
+
+// TestSumUnitRaw: a field is summed only when every unit has it.
+func TestSumUnitRaw(t *testing.T) {
+ one, two := int64(1), int64(2)
+ s := sumUnitRaw([]unitRaw{{cpuUsec: &one, memBytes: &one}, {cpuUsec: &two}})
+ if s.cpuUsec == nil || *s.cpuUsec != 3 || s.memBytes != nil || s.memPeakBytes != nil {
+ t.Fatalf("sum = %+v", s)
+ }
+ if !sumUnitRaw([]unitRaw{{}, {leftover: true}}).leftover {
+ t.Fatal("a leftover part did not make the sum a leftover")
+ }
+}
+
+// TestMergeNestedCutsAnOverlap: a host read in both layouts in one tick
+// (a layout change in flight) has no reading that tick, rather than a sum
+// whose CPU delta would mix cgroup sets (Astra, nested branch round 2).
+func TestMergeNestedCutsAnOverlap(t *testing.T) {
+ one := int64(1)
+ flat := map[string]unitRaw{"carlos-exec@both.example.com": {cpuUsec: &one}, "carlos-exec@flat.example.com": {cpuUsec: &one}}
+ nested := map[string]unitRaw{"carlos-exec@both.example.com": {cpuUsec: &one, members: "a#1"}, "carlos-exec@nested.example.com": {cpuUsec: &one, members: "b#2"}}
+ got := mergeNested(flat, nested)
+ if _, ok := got["carlos-exec@both.example.com"]; ok {
+ t.Fatalf("an overlapping host kept a reading: %+v", got["carlos-exec@both.example.com"])
+ }
+ if _, ok := got["carlos-exec@flat.example.com"]; !ok {
+ t.Fatal("a flat host lost its reading")
+ }
+ if n, ok := got["carlos-exec@nested.example.com"]; !ok || n.members != "b#2" {
+ t.Fatalf("a nested host's reading = %+v", n)
+ }
+}
diff --git a/internal/host/metrics_probes.go b/internal/host/metrics_probes.go
index 6ebe91951..0cbe5101e 100644
--- a/internal/host/metrics_probes.go
+++ b/internal/host/metrics_probes.go
@@ -205,6 +205,14 @@ type unitRaw struct {
memPeakBytes *int64
readBytes *int64
writeBytes *int64
+ // leftover marks a nested host's reading that includes a unit this
+ // agent did not start (nestedUnitReadings): never vouched.
+ leftover bool
+ // members names the cgroups a summed nested reading was read from
+ // (unit and cgroup id each), "" for a single cgroup. The sampler takes
+ // no CPU delta across two readings of different members: a unit that
+ // went or came would make the difference of two sums wrong.
+ members string
}
// readUnitRaw reads a unit's resource usage from the cgroup v2 files in
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index ac8565edc..52e5d6cf2 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -4,3 +4,4 @@ plan14-root-reads-c2-root-exec-inputs.tsv 0ef813eebfb1a2e2812d897c4f0b5fd7f75e3e
plan14-root-reads-label-case-running-tile.tsv 0ef813eebfb1a2e2812d897c4f0b5fd7f75e3e39c7602cf64d1634e8374327af
plan14-root-reads-remote-instance-metrics.tsv ed0d770a827bdb37a87d21e5c8efb259ca0de88457b0cb3202ebb006fc0cd032
plan14-root-reads-edge-asset-cache-3.tsv f723ddc14e3c03c0d55b6f0c949567a2c9325e0b5d491e0649fe548b2c0c282d
+plan14-root-reads-remote-metrics-nested.tsv e923841657499fc729713abdd750cbd2d6019fc4db677b540be0fab4d2a160e4
diff --git a/internal/provision/testdata/plan14-root-reads-remote-metrics-nested.tsv b/internal/provision/testdata/plan14-root-reads-remote-metrics-nested.tsv
new file mode 100644
index 000000000..8189f2fd1
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-remote-metrics-nested.tsv
@@ -0,0 +1,15 @@
+# Census overlay remote-metrics-nested, written by census-propose (#369). census-ruling-remote-metrics-nested, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-remote-metrics-nested.md.
+# 2 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 4 new dispositions: 0 reads re-frozen at their disposition with the claim, 4 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+@legacy eb93ad3343e07652959273596a2366e438e70284b79cc6d7f96d26f8da0ca45a internal/host/metrics_loop.go sampler.tick legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-remote-instance-metrics;basis=calls the owners probe before and after the unit read and tags readings with metrics.TagUnits and metrics.CarryTags; no read added;rev3=census-ruling-remote-metrics-nested;basis=clears the tenant tag of a reading marked leftover (a nested unit present at agent start) before CarryTags, and takes no CPU delta when a nested reading's set of cgroups changed since the previous tick; no read added file:ReadBytes@1093 1263e19712bffa735063f32113ff378d9b8ba59b7568cdbb550d29ac0880ec4b
+@legacy 4732421e39880404f16930726c01362c30d092a4869c8ee7e9a9b963fc9be0f5 internal/host/agent.go routeHostNames legacy accepted-legacy accepted-legacy;rev3=census-ruling-remote-metrics-nested;basis=new: lists the agent's own registry for its route hosts (as stampedUnitNames does each tick) for the nested slice reads; no file path, nothing written registry:Host@261,whole:Route@203,whole:Route@232 9d2f7f2de05da66145e8e229b5dca737593b3ebfd6455fa83791fe1bb869c711
+@legacy acfac81e4b52ab4b08a326c9f9da947939ef4192b0ce0680a3d52c3abf509f06 internal/host/metrics_nested.go nestedUnitReadings legacy accepted-legacy accepted-legacy;rev3=census-ruling-remote-metrics-nested;basis=new: as the agent (user carlos), lists each route host's nested slice dir under the fixed cgroupfs root (path from instancectl.SliceName of a registry host, which escapes everything but [A-Za-z0-9:_.]) and reads its unit cgroups' cpu.stat, memory.current, memory.peak and io.stat through readUnitRaw, as the sampler already does for other units, and names the cgroups it summed (unit and cgroup id); read-only, world-readable cgroupfs files; root never calls it file:ReadDir@226 442f0e537ceb7cf207dba4d22f36c72b25f84057ee78a191d0eef0928e179605
+@legacy fdba9404918aa1ff51552f42cb6c917393981f78dbdba238bec34ce19e1e1387 internal/host/metrics_nested.go snapshotNestedUnits legacy accepted-legacy accepted-legacy;rev3=census-ruling-remote-metrics-nested;basis=new: as the agent, once at start, lists the fixed nested layout root and its slices and records each unit cgroup's inode; read-only; root never calls it file:ReadDir@370,file:ReadDir@68 19a49124d843519691de7b4dce2adb0e727cc637974c2c9f375e35d10ea6430e
+@legacy cb395998f3fc6f6bd8660c377171c199bf5282bfa4c8401729983a5b170926cf internal/host/metrics_nested_linux.go cgroupID legacy accepted-legacy accepted-legacy;rev3=census-ruling-remote-metrics-nested;basis=new: stats a cgroup dir for its inode (the cgroup id); read-only; root never calls it file:Stat@55 a42cbf096d2fc142026a764ddb19788e500fee5f197eec5cfd88e158735b8b4b
+internal/host/agent.go runAgent authority B,C,D,F rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): builds the box's lifetime judge once (newBoxJudge, nil with host claims on) and hands it to the seed placement, the moves and runs workers and every loop it starts; read sites unchanged, offsets moved; B,C,D,F authority retained; self-serve moves 1 Task 8: derives the box's lifetimes switch from the judge once (lifetimes := boxJudge != nil) and hands it to the edges file loop; read sites unchanged, offsets moved;rev3=census-ruling-plans-4d-lapse;basis=arms two more plans hooks from the same snapshot: e.SetPlanDisabledFor(planDisabledFor) beside SetPlanGovernedFor, and svc.SetDisabledFor(planDisabledRoute) beside SetMaxRunFor (plans 4d); the reads live in those units (plans-4d-units decision); read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 9b81d97b (with main's plan rate ceiling, edge request records, regional box names, self-serve moves plan 1, plans 4d-1 lapse and its other later changes under main's own census rulings) plus the rootfs placement wiring in the activator start: an agentRootfs built from eb.NestedOK, CARLOS_DEPLOYMENT_SINGLE_TENANT, CARLOS_POOLS, the claim flag, swapArming's answer, the control client's /ready/rootfs and, on a fleet box whose identity resolved, fleetOwnerCheck over the deploy store main already opens for the fleet label (fleetStore), then arm and armedRootfs.Store; this body reads nothing new itself; the closures it wires read later, at a rootfs wake and each status tick: GET /ready/rootfs over the control socket, NestedOK's checks, and release.FleetOwnerKey for the judged row's own account and this box's fleet from the deploy store;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Tasks 7 and 11, #329 plan 3 Task 7 and plan 1 Task 7's policy cache: the control client is built once and handed to eb.Control, to the status tick (egressStatus) and to a new egressNudgeLoop goroutine; armSizeSource(svc, "/sys/fs/cgroup") after the activator Service; armPolicyCache() after armChangeIndex; statusLoop takes egressStatus. The reads are those units' own (decision rows); this body reads nothing new: the same five sites, offsets moved, in the agent; B,C,D,F authority retained.;rev3=census-ruling-remote-instance-metrics;basis=builds the metrics loop's owners closure (metricsOwners over the agent's registry, the activator and cgm.Leftover) when an activator exists and hands it to metricsLoop; reads nothing new itself;rev3=census-ruling-edge-asset-cache-3;basis=adds file:Statfs. runAgent keeps its authority (B,C,D,F). The new site is assetcache.Statfs, an exported assetcache.FS interface value (var Statfs FS = statfsFS{}), not a function value and not a call in runAgent: the ready hook passes it to armEdgeAssetCache as the store's filesystem, and armEdgeAssetCache calls its Space method on the configured data directory (dataDir(): $CARLOS_DATA_DIR, else /data), which calls unix.Statfs there (statfsFS.Space, accepted legacy at census-ruling-edge-asset-cache-2). No request-supplied pathname reaches it.;rev3=census-ruling-remote-metrics-nested;basis=main's body (merged origin/main acfa4f80, under main's own census rulings) plus: snapshots the nested layout (snapshotNestedUnits over /sys/fs/cgroup/carlos.slice/carlos-instances.slice) once at start, before the activator, and hands the metrics loop a unitSources struct (stamped units, routeHostNames, that root and the snapshot); reads nothing new itself file:Exec@15646,file:Open@1150,file:Statfs@41567,registry:App@10927,whole:Route@10919,whole:Route@25822 a27cffeba736d7d29a44436a58a3838f4356f2c657edb296ff2e1034367f66fd
+internal/host/metrics_loop.go sampler.tick legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-remote-instance-metrics;basis=calls the owners probe before and after the unit read and tags readings with metrics.TagUnits and metrics.CarryTags; no read added;rev3=census-ruling-remote-metrics-nested;basis=clears the tenant tag of a reading marked leftover (a nested unit present at agent start) before CarryTags, and takes no CPU delta when a nested reading's set of cgroups changed since the previous tick; no read added file:ReadBytes@1093 1263e19712bffa735063f32113ff378d9b8ba59b7568cdbb550d29ac0880ec4b
+internal/host/agent.go routeHostNames legacy accepted-legacy accepted-legacy;rev3=census-ruling-remote-metrics-nested;basis=new: lists the agent's own registry for its route hosts (as stampedUnitNames does each tick) for the nested slice reads; no file path, nothing written registry:Host@261,whole:Route@203,whole:Route@232 9d2f7f2de05da66145e8e229b5dca737593b3ebfd6455fa83791fe1bb869c711
+internal/host/metrics_nested.go nestedUnitReadings legacy accepted-legacy accepted-legacy;rev3=census-ruling-remote-metrics-nested;basis=new: as the agent (user carlos), lists each route host's nested slice dir under the fixed cgroupfs root (path from instancectl.SliceName of a registry host, which escapes everything but [A-Za-z0-9:_.]) and reads its unit cgroups' cpu.stat, memory.current, memory.peak and io.stat through readUnitRaw, as the sampler already does for other units, and names the cgroups it summed (unit and cgroup id); read-only, world-readable cgroupfs files; root never calls it file:ReadDir@226 442f0e537ceb7cf207dba4d22f36c72b25f84057ee78a191d0eef0928e179605
+internal/host/metrics_nested.go snapshotNestedUnits legacy accepted-legacy accepted-legacy;rev3=census-ruling-remote-metrics-nested;basis=new: as the agent, once at start, lists the fixed nested layout root and its slices and records each unit cgroup's inode; read-only; root never calls it file:ReadDir@370,file:ReadDir@68 19a49124d843519691de7b4dce2adb0e727cc637974c2c9f375e35d10ea6430e
+internal/host/metrics_nested_linux.go cgroupID legacy accepted-legacy accepted-legacy;rev3=census-ruling-remote-metrics-nested;basis=new: stats a cgroup dir for its inode (the cgroup id); read-only; root never calls it file:Stat@55 a42cbf096d2fc142026a764ddb19788e500fee5f197eec5cfd88e158735b8b4b
+@coverage internal/host 026587506366d20179289bfb603b33569d439f68ff792e5206799a3580ca11d0