carlos / platform Public

remote-instance-metrics: boxes tag instance metrics with their tenant; the console shows CPU and memory for instances on other boxes

Squashed from remote-instance-metrics into main.
claude agent, operated by paul@keymail.dev 4dc5902d4f244a3de346b258660950472df9b07a parent f7644a9
37 files changed, +2,254 −80
  • docs/superpowers/notes/census-proposal-remote-instance-metrics.md +48 −0
  • docs/superpowers/notes/remote-instance-metrics.md +297 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-remote-instance-metrics-branch-r1.md +56 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-remote-instance-metrics-branch-r2.md +20 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-remote-instance-metrics-note-r1.md +14 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-remote-instance-metrics-note-r2.md +17 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-remote-instance-metrics-branch.md +114 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-remote-instance-metrics-census.md +32 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-remote-instance-metrics-note.md +111 −0
  • internal/activator/activator.go +14 −4
  • internal/activator/probewake.go +1 −1
  • internal/activator/recoveryprobe.go +1 −1
  • internal/activator/swaphold.go +1 −1
  • internal/activator/tenancies.go +80 −0
  • internal/activator/tenancies_test.go +184 −0
  • internal/cgroup/cgroup.go +26 −0
  • internal/cgroup/cgroup_test.go +70 −0
  • internal/console/apiinstances.go +40 −7
  • internal/console/metricsview.go +88 −14
  • internal/console/overview.go +11 −10
  • internal/console/remoteinstances.go +8 −3
  • internal/console/remoteinstances_round2_test.go +1 −1
  • internal/console/remoteinstances_round6_test.go +13 −8
  • internal/console/remotemetrics_test.go +461 −0
  • internal/console/runningtile_test.go +5 −2
  • internal/console/server.go +12 −8
  • internal/console/view.go +15 −10
  • internal/host/agent.go +9 −1
  • internal/host/agentalerts_test.go +3 −3
  • internal/host/metrics_loop.go +26 −6
  • internal/host/metrics_owner.go +43 −0
  • internal/host/metrics_owner_test.go +155 −0
  • internal/metrics/owner.go +99 −0
  • internal/metrics/owner_test.go +138 −0
  • internal/metrics/sample.go +4 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-remote-instance-metrics.tsv +36 −0

CI failed — run details

diff --git a/docs/superpowers/notes/census-proposal-remote-instance-metrics.md b/docs/superpowers/notes/census-proposal-remote-instance-metrics.md
new file mode 100644
index 000000000..bd2a8e85d
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-remote-instance-metrics.md
@@ -0,0 +1,48 @@
+# Census approval: remote-instance-metrics
+
+Ruling `census-ruling-remote-instance-metrics`. 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/activator/activator.go` `Service.WakeWorker` | body | unchanged (5) | the entries-map insertion goes through putEntryLocked (which also notes the route's tenant in memory for the metrics sampler); no read added |
+| `internal/activator/activator.go` `Service.begin` | body | unchanged (6) | the entries-map insertion goes through putEntryLocked (which also notes the route's tenant in memory for the metrics sampler); no read added |
+| `internal/activator/activator.go` `Service.sweepOnce` | body | unchanged (38) | its two entries-map insertions go through putEntryLocked (which also notes the route's tenant in memory for the metrics sampler); no read added |
+| `internal/activator/activator.go` `type Service` | body | unchanged (0) | gains tenancySeq, hostTenants and hostMixed, in-memory fields for Tenancies; no read added |
+| `internal/activator/probewake.go` `Service.ProbeWake` | body | unchanged (4) | the entries-map insertion goes through putEntryLocked; no read added |
+| `internal/activator/recoveryprobe.go` `Service.RecoveryProbe` | body | unchanged (8) | the entries-map insertion goes through putEntryLocked (its nil-map make moves there); no read added |
+| `internal/activator/swaphold.go` `Service.holdWakeLocked` | body | unchanged (2) | the entries-map insertion goes through putEntryLocked; no read added |
+| `internal/cgroup/cgroup.go` `Manager.sweepStale` | body | unchanged (2) | records the host of a per-host dir it could not remove in an in-memory leftover set (Manager.Leftover) for the metrics sampler, and marks the whole sweep incomplete (every host a leftover) when it cannot list the root; logs that; no read added, nothing removed differently |
+| `internal/cgroup/cgroup.go` `setupAt` | body | unchanged (1) | a retaining setup also marks every host a leftover for the metrics sampler (an in-memory flag); no read added |
+| `internal/host/agent.go` `runAgent` | body | unchanged (5) | 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 |
+| `internal/host/metrics_loop.go` `sampler.tick` | body | unchanged (1) | calls the owners probe before and after the unit read and tags readings with metrics.TagUnits and metrics.CarryTags; no read added |
+| `internal/metrics/sample.go` `type UnitSample` | body | unchanged (1) | one more field, Owner (omitempty), the tenant tag; schema only |
+
+Envelopes re-pinned: `internal/activator`, `internal/cgroup`, `internal/host`, `internal/metrics`.
+
+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/activator/activator.go` `Service.WakeWorker`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-carlos-run;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body; the stop now carries its reason for a run it interrupts (beginStopLocked's why argument); read sites unchanged, offsets moved
+- `internal/activator/activator.go` `Service.begin`: 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; the stop now carries its reason for a run it interrupts (beginStopLocked's why argument); read sites unchanged, offsets moved;rev3=census-ruling-edge-request-records;basis=gains a req *http.Request parameter and one edge.MarkWoke(req) call on the path that starts a wake, so the edge's request record can say which request woke the app; no read added
+- `internal/activator/activator.go` `Service.sweepOnce`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=PROPOSED-seed;basis=census-ruling-FS-R6; registry remains legacy; PROPOSED-plans-2-box-limits: the sweep also narrows an entry's idle window to its account's plan idle through the SetIdleFor hook (never lengthens it; always-on workers and held probe entries are untouched; the hibernate, inflight and held-for-tick guards are unchanged).;rev3=census-ruling-plans-4c-box-throttle;basis=after the worker max_run branch, stops a non-worker entry past the plans continuous-awake ceiling (maxRunFor, passed the row), busy or not, never mid-command (plans 4c). One more whole-row read: the row handed to the hook, as idleFor already is. This bypasses the inflight and held-for-tick protections the idle stop keeps, on purpose: escalated by Astra and ACCEPTED by Paul (census owner), 2026-10-25.;rev3=census-ruling-plans-4d-lapse;basis=stops a live entry the turned-off hook names (never mid-command, never a move's active probe), stands down an exited worker it names instead of restarting it (Astra finding 4), and skips such rows in the due loop and the always-on arm so they are not woken (plans 4d). Four more whole-row reads: the row handed to the hook (a.disabled), as idleFor and maxRunFor already are. Only stops or skips.
+- `internal/activator/activator.go` `type Service`: authority, task B,C,D,F,J4. Basis: rev3=PROPOSED-seed; existing activator lifecycle and due-wake state plus owned seed exclusion and incarnation-keyed diagnostics; normal refusal and preparation ordering remain authoritative; PROPOSED-plans-2-box-limits adds the idleFor hook field, which only narrows idle windows;rev3=census-ruling-plans-4c-box-throttle;basis=gains the maxRunFor hook field beside idleFor (plans 4c). No read added.;rev3=census-ruling-plans-4d-lapse;basis=gains the disabledFor hook field beside maxRunFor (plans 4d). No read added.
+- `internal/activator/probewake.go` `Service.ProbeWake`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route
+- `internal/activator/recoveryprobe.go` `Service.RecoveryProbe`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route
+- `internal/activator/swaphold.go` `Service.holdWakeLocked`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route
+- `internal/cgroup/cgroup.go` `Manager.sweepStale`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input
+- `internal/cgroup/cgroup.go` `setupAt`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 (final review F2): the supervise leaf's name now comes from the new exported constant SuperviseLeaf (the same value, supervise), which root's egress rail (internal/host/egress_rail_linux.go) also uses to tell the agent's own leaf from other cgroups in its delegated subtree. It is still the agent's own delegation dance, run by the agent (cgroup.Setup from runAgent, user carlos) in its own subtree; the same one site, the O_WRONLY OpenFile probe of cgroup.procs and cgroup.subtree_control; no read added.
+- `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.
+- `internal/host/metrics_loop.go` `sampler.tick`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input
+- `internal/metrics/sample.go` `type UnitSample`: diagnostic, task H3. Basis: schema-only
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `internal/activator/tenancies.go:Service.Tenancies`: reads +registry:Account, +registry:App, +whole:Route ×2; written legacy, accepted-legacy, frozen
+- new `internal/activator/tenancies.go:Service.putEntryLocked`: reads +registry:Account, +registry:App, +whole:Route ×2; written legacy, accepted-legacy, frozen
+- new `internal/host/metrics_owner.go:metricsOwners`: reads +whole:Route; written legacy, accepted-legacy, frozen
+- new `internal/metrics/owner.go:Vouched`: reads +registry:Account ×3, +registry:App ×3, +registry:Host ×3, +whole:Route; written legacy, accepted-legacy, frozen
+
+Seal: `0ef813eebfb1a2e2812d897c4f0b5fd7f75e3e39c7602cf64d1634e8374327af` → `ed0d770a827bdb37a87d21e5c8efb259ca0de88457b0cb3202ebb006fc0cd032`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-remote-instance-metrics.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
new file mode 100644
index 000000000..dda421d65
--- /dev/null
+++ b/docs/superpowers/notes/remote-instance-metrics.md
@@ -0,0 +1,297 @@
+# Remote instance metrics: samples tagged with their tenant
+
+Branch `remote-instance-metrics`, 2026-10-26. Box and console change: the
+console part does nothing until boxes run a release that tags samples.
+
+Fault family: **tenant identity of samples**. Every finding against this
+note or its branch names that family when it is about whose process a
+sample measured.
+
+## The problem
+
+Main 93425891 (console-remote-instances) cut CPU and memory for instances
+on other boxes. The console joined box metrics samples to a row by unit
+name, and a unit name is the hostname (`carlos-exec@<host>`,
+`carlos-app@<host>.service`). Hostnames change hands, so a predecessor's
+samples, or a successor's, could reach the wrong account. Six Astra rounds
+bounded the join by time and by box and each round found the next
+interleaving; round 6 found a predecessor's sample taken after the new
+record was created but before the box had reconciled. So an app whose
+instances all run on another box shows RESOURCES "no data right now".
+
+The agreed fix: the box says whose process each sample measured, and the
+console shows a sample on a remote row only when that matches the record
+it is showing.
+
+## Which identity
+
+What main has:
+
+- A record carries `account`, `app`, `created_at` and, under the lifetimes
+ cutover, `incarnation` (`provision.Record`). The incarnation is the
+ hostname's lifetime counter from `control/host-incarnations/<host>.json`.
+ It is 0 on every record on a deployment that has not run the cutover.
+- A registry row carries `Account`, `App` and its own `Incarnation`. The
+ row's incarnation is not a process identity: when the same account and
+ app recreate a hostname, reconcile installs the new lifetime on the
+ existing row in place (`installRowLifetime`, `ownsRowLifetime`), while
+ the old process may still be running.
+- A hostname moves to another tenant on a box only by its row being
+ deleted and a new row minted (`TestCrossOwnerRecreationWithdrawsThePredecessorRow`),
+ or by a full-row `Upsert` that names another account or app.
+
+So the identity is the **tenant: account and app**. It changes every time a
+hostname changes hands, on every deployment, cut over or not. Account sqids
+are never reused (accounts are never deleted). The incarnation adds nothing
+across tenants and would blank readings for a running process whenever a
+lifetime is installed in place, so it is not part of the tag.
+
+A hostname recreated by the same account and app is the same tenant's data.
+The console keeps today's lower bound for it: no sample older than the
+record's `created_at` is shown.
+
+## The box: tag only what the agent started for that tenant
+
+The tag lives on each unit's reading, additive and omitted when unset:
+
+```go
+type Owner struct {
+ Account string `json:"account"`
+ App string `json:"app"`
+}
+// metrics.UnitSample gains:
+Owner *Owner `json:"owner,omitempty"`
+```
+
+**Invariant.** The box tags `carlos-exec@<host>` with tenant T only when
+everything that reading measured was T's: every process that can be in
+the cgroup during the reading, and everything the cgroup's counters and
+charged memory carry over from before it. The per-host cgroup outlives
+its processes for the agent's whole life (`Manager.hostDir`: only
+generation and seed children are removed, and a killed cgroup is
+remade before its next spawn), so its CPU counter and the
+page cache charged to it can carry an earlier occupant's use. The rule is
+therefore about the cgroup, not the current process: **in this agent's
+life, the host's cgroup has only ever held tenant T**. It is enforced in
+one place, `metricsOwners` and the sampler's tick
+(`internal/host/metrics_loop.go`), from `metrics.Vouched`,
+`metrics.TagUnits` and `metrics.CarryTags`.
+
+Where the cgroup's contents come from, and how each is covered:
+
+1. **This agent's activator.** Every spawn into `carlos-exec@<host>` is an
+ activator entry's (instance, legacy sidecar, seed, generations). A
+ `carlos run` command runs in its own systemd unit, not in this cgroup.
+ Every entry enters `a.entries` through one helper, `putEntryLocked`,
+ which records the tenant its route names (a guard test parses the
+ package and fails on any other insertion). A host whose entries have
+ named two tenants is **mixed** and never vouched again in this agent's
+ life. A wake re-reads the row before it spawns and refuses one that now
+ names another account or app (`wakeRouteChanged`), so an entry's
+ processes are its route's tenant's; an entry inserted for a stale row
+ whose wake is refused still marks the host, which errs toward vouching
+ less. An entry whose route later names another tenant in place marks
+ the host mixed too. A new method, `activator.Service.Tenancies()`,
+ returns the tenant of each live entry on an unmixed host and a number
+ that is new for every new entry.
+2. **A previous agent.** In ordinary mode the agent's shutdown stops every
+ child, and a restart kills the delegated subtree. The cgroup setup
+ removes the per-host directories left behind (with their charges); one
+ it cannot remove may still hold a process or a child, so that host is
+ recorded as a leftover (`Manager.Leftover`) and never tagged in this
+ agent's life. A setup that could not list the root at all swept
+ nothing, so every host is a leftover for this agent's life (branch
+ review round 1).
+3. **Claim mode** retains processes and cgroups across restarts
+ (`SetupRetaining`). `Tenancies` returns nothing in claim mode, and a
+ retaining setup reports every host as a leftover, so nothing is tagged
+ there.
+
+The tick:
+
+```
+before := owners() // activator tenancies joined to registry rows
+units := read cgroups // as today
+after := owners()
+tag unit u with T iff before[u] and after[u] both exist and are equal
+ (same tenant, same entry number) TagUnits
+untag u iff the previous tick read u and did not
+ tag it T CarryTags
+```
+
+`owners()` maps `cgroup.ExecName(host)` to the tenant only when the
+activator vouches for the host, the registry row names the same non-empty
+account and app, and the host is not a leftover. The read after the
+cgroup read catches a host that became mixed, or got a new entry, during
+the reading. The CPU fraction is a delta from the previous tick's counter
+of the same cgroup, so the previous tick must also have tagged the unit
+for T, or not read it at all (then there is no previous counter and no
+delta). The row check keeps a stopping entry from being vouched once its
+host's row names someone else.
+
+Consequence: a hostname that changes tenant on a box shows no remote
+readings for the new tenant until that box's agent restarts (a release
+roll restarts it). The console's local rows are unaffected.
+
+Not tagged at all: `carlos-app@<host>.service` units (systemd runs them,
+and they can outlive the agent), nested (isolated exec) instances and
+`carlos run` units, stamped units, platform units, instances that never
+sleep, and anything on a box without a delegated subtree. Those remote
+rows keep showing no readings.
+
+## The console: show a remote sample only with its tenant's tag
+
+One place: `ownerAppMetricsFrom` (`internal/console/metricsview.go`).
+Callers pass, for each remote row, the tenant the record names
+(`metrics.Owner{rec.Account, rec.App}`) and the record's `created_at`.
+For such a host:
+
+- a box's reading counts only when the unit's **latest** sample carries
+ that tenant and is no older than `created_at`;
+- its graphs are drawn only from samples that carry that tenant and are no
+ older than `created_at` (the memory graph scaled to the peak of those);
+- no tag, another tenant's tag, or no `created_at` means nothing from that
+ box. When two boxes qualify (a move in flight), the fresher wins.
+
+The sweep keeps each unit's tag per sample (an index into a small
+per-box table), beside the CPU and memory series it already keeps.
+
+Callers:
+
+- `appResourceMetrics` (Overview, Running tab, instance page) stops
+ skipping remote rows and passes the record's tenant and `created_at`.
+ Remote rows carry them from `remoteRoute`.
+- `instanceHealth` (`carlos instances list`): a remote record with an
+ accepted rollout entry reads Running when the entry says awake **or** it
+ has a tagged reading, the same rule the Running tab applies. Unknown,
+ transient and held-down records are unchanged.
+
+Local rows keep today's behaviour exactly: the tag is ignored for them, and
+their history is bounded by the record's `created_at` as now.
+
+## Mixed fleet
+
+- **Old box, new console:** samples carry no tag, so remote rows show no
+ readings, as on main today. Local rows are unaffected.
+- **New box, old console:** the field is additive and ignored.
+- Day rollups are unchanged and carry no tag; the owner views read raw
+ chunks only.
+
+## Request budget
+
+Boxes: no new request. They write the same chunk keys on the same
+five-minute flush; bodies grow by about 40 bytes per tagged unit per
+sample, about 2.4 KB per awake instance-hour in the raw chunk. Steady
+state, nothing changing: 0 new requests per box per day.
+
+Console: no new kind of read and no new loop. The sweep's cost per run is
+unchanged (a LIST of `metrics/boxes/`, 48 hourly GETs per box, a LIST
+and the GETs of `alerts/boxes/`), and it still runs only when a page asks
+and its 60-second cache is stale, shared by every page and account. What
+changes is who can ask: an app whose instances all live on other boxes
+used to skip the sweep (`ownerAppMetricsFrom` returns before
+`LoadMetrics` with no hosts), and now its views read it like any app
+with a local instance. On a quiet console, one such view can start a
+sweep that would not otherwise have run; every view within the cache's
+minute pays nothing. Idle, with nobody browsing: 0 requests.
+`TestRemoteMetricsRequestBudget` pins it (Astra round 2, P2).
+
+## Tests
+
+Production-wired where the code allows:
+
+- **activator:** `Tenancies` over real wakes with the package's test
+ backend: an awake entry is vouched; a new wake gets a new number; a host
+ woken for one tenant and then another is never vouched again, nor is
+ one whose wake for another tenant was refused; a route changed in place
+ marks its host; claim mode returns nothing; every insertion into
+ `a.entries` goes through `putEntryLocked` (a parse of the package).
+- **cgroup:** a per-host dir setup could not remove is a leftover.
+- **host:** the sampler's tick and flush over a real registry and a
+ tenancy source: an agreeing row tags; a disagreeing or missing row does
+ not; an entry replaced between the two reads does not; a leftover host
+ does not; a unit-backed tenant never is; the flushed chunk carries the
+ tag; a delta whose previous counter was another tenant's is untagged
+ (round 1's scenario, two ticks).
+- **console, two boxes** (the `remoteinstances_test.go` fixture: real
+ create door, real reconcile on each box, real reports). Box B's chunk is
+ built by the box's own tagging code over B's real registry and written
+ with `metrics.WriteRaw`:
+ - reused hostname: another account held the hostname on B; its samples,
+ including ones timestamped after the new record's creation, are tagged
+ with it and never show on the new owner's pages, graphs or
+ `instances list`;
+ - successor: the old owner's view never shows samples tagged with the
+ account that holds the hostname now;
+ - untagged samples never show on a remote row
+ (`TestRemoteRowsNeverCarrySamples`, kept);
+ - another account's samples of the same hostname on another box never
+ show;
+ - the owner's own tagged samples show: reading, graphs, Running, the
+ Overview's Resources tile.
+- **Mutations** on the console filter (accept untagged, check only the
+ account, test any sample's tag instead of the latest, graph without the
+ per-sample check, drop the `created_at` bound) and on the box rule (one
+ read instead of two, skip the row check, vouch a leftover, vouch a mixed
+ host, skip `CarryTags`).
+
+## Not in this change
+
+- Same-owner recreation: a sample of the earlier instance taken after the
+ new record's `created_at` can show on the new record. Same account and
+ app, so not a tenant leak.
+- Readings for unit-backed, stamped and never-sleeping instances on other
+ boxes, and for a hostname that changed tenant on its box until that
+ box's agent restarts.
+- Local rows could adopt the tag once every box writes it; that would
+ close round 6's interleaving for the console's own box too. Follow-up.
+
+## Review rounds
+
+Round 1 (Astra, 98caa5f4): NOT READY, one P1 in the fault family.
+
+- P1: the CPU fraction is a delta from the previous tick's counter, read
+ by unit name; a successor's fresh cgroup whose counter exceeded the
+ predecessor's would be tagged with a delta that includes the
+ predecessor's. Fixed by `CarryTags` (the previous tick must have tagged
+ the unit for the same tenant). Looking at the same cause found a wider
+ one: the per-host cgroup itself outlives its processes, so counters and
+ charged memory can carry an earlier tenant's use without any two-tick
+ race. Round 2's rule is therefore about the cgroup's whole history in
+ this agent's life (a host is vouched only if it has only ever had one
+ tenant), which also replaced round 1's per-process checks (unproven
+ wakes, stray sidecars, incomplete stops): with one tenant ever, those
+ leftovers are the same tenant's.
+
+Round 2 (Astra, 0a90c4c3): READY AFTER FIXES. Round 1's P1 resolved.
+One P2 (request-budget accounting): remote-only views can now start the
+existing sweep. Fixed above, with `TestRemoteMetricsRequestBudget`. The
+note's review stops here (AGENTS.md stopping rule 1).
+
+## Branch review rounds
+
+Round 1 (Astra, e1233c74): NOT READY, one P1 in the fault family.
+
+- P1: `sweepStale` returned quietly when it could not list the delegated
+ root, so `Leftover` reported every host clean and a reused host's
+ retained charges could be tagged with its new tenant. Fixed as a gate
+ up front: a setup that cannot list the root, or a retaining one, makes
+ every host a leftover for the agent's life
+ (`TestLeftoverAfterAnUnreadableSweep`; three mutants killed).
+- Census: Astra approved all fourteen changed units and five envelopes,
+ and found the four decision rows' bases accurate.
+
+Round 2 (Astra, 88782257): READY. Round 1's P1 resolved; census
+verdicts for `Manager.sweepStale`, `setupAt` and `internal/cgroup`
+approved. One P3 (a stale test comment), fixed. The branch review stops
+here (AGENTS.md stopping rule 1).
+
+Merge of origin/main (C2 census re-base, label-case-running-tile): the
+console left the census's scope, and under C2 `census-propose` writes the
+four new units itself, so the hand-written decisions overlay was dropped
+and the overlay re-proposed. Main's `TestRunningTileCountsInstancesOnOtherBoxes`
+asserted the Resources tile's "no data right now" for an app whose
+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.
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-remote-instance-metrics-branch-r1.md b/docs/superpowers/reviews/CODEX-FINDINGS-remote-instance-metrics-branch-r1.md
new file mode 100644
index 000000000..345d3c70d
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-remote-instance-metrics-branch-r1.md
@@ -0,0 +1,56 @@
+Reviewed `e1233c74eaade1b0c8f0829ad1bf2c1be9d9c07b` against merge base `563453808bdd4ff0ac7f7c47f5a6e4a3293987f0`. Branch round **1 of 3**; the note’s two completed rounds remain recorded separately.
+
+1. **P1 — A failed startup sweep permits tagging cgroups whose previous tenant is unknown.**
+
+ **Section:** Box ownership proof, `Manager.sweepStale` / `Leftover`.
+ **Fault family:** **tenant identity of samples**.
+
+ **Evidence:** [`sweepStale` returns immediately when the root directory listing fails](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/cgroup/cgroup.go:367), without recording that the sweep was incomplete. The new [`Leftover` method](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/cgroup/cgroup.go:403) consequently returns false for every host. [`Vouched`](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/metrics/owner.go:52) accepts that answer as sufficient to tag the reading.
+
+ **Failure scenario:** Tenant A leaves a per-host cgroup containing charged memory across an agent restart. The startup `ReadDir` fails temporarily, so the cgroup is neither removed nor marked leftover. Once filesystem access recovers, tenant B acquires that hostname and wakes. [`startIn` uses `MkdirAll`, which accepts the existing directory](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/cgroup/cgroup.go:585); the new agent’s tenancy history contains only B. Both ownership probes therefore agree on B, and B receives a tagged memory reading that includes A’s retained charges. `CarryTags` cannot protect this case: it concerns previous sampler observations, and this sampler started after the restart.
+
+ **Fix:** Preserve an explicit “startup sweep incomplete” state and refuse all ownership tags while it holds. Do not interpret an unreadable inventory as an empty inventory. Add a regression test that fails the initial directory listing, restores access, and verifies that a reused host remains untagged.
+
+No additional P2 or P3 findings.
+
+The targeted tests could not start because the read-only filesystem prevented Go from creating its build directory. Test coverage and mutation sensitivity were inspected in source; mutations and full suites were not run. No files were edited.
+
+**Census verdicts**
+
+These approvals concern root-read authority and the recorded dispositions; they do not clear the P1 above.
+
+| Changed unit | Verdict and evidence |
+|---|---|
+| `Service.WakeWorker` | **Approve.** Existing wake and shutdown gates remain; insertion adds only tenant bookkeeping. [activator.go:3282](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/activator/activator.go:3282) |
+| `Service.begin` | **Approve.** Fence, shutdown and single-entry ordering remain. [activator.go:1527](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/activator/activator.go:1527) |
+| `Service.sweepOnce` | **Approve.** Both insertions retain their existing eligibility checks. [activator.go:5042](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/activator/activator.go:5042), [activator.go:5103](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/activator/activator.go:5103) |
+| `type Service` | **Approve.** Additional fields hold in-memory tenancy history under the existing mutex. [activator.go:1214](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/activator/activator.go:1214) |
+| `Service.ProbeWake` | **Approve.** Claim, held-row, fence and existing-entry refusals remain. [probewake.go:185](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/activator/probewake.go:185) |
+| `Service.RecoveryProbe` | **Approve.** Readiness, policy, shutdown and fence checks remain. [recoveryprobe.go:55](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/activator/recoveryprobe.go:55) |
+| `Service.holdWakeLocked` | **Approve.** The pinned-wake check and deletion on refusal remain. [swaphold.go:323](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/activator/swaphold.go:323) |
+| `Manager.sweepStale` | **Approve for census.** Directory reads and removal targets are unchanged; added bookkeeping grants no root authority. Its incomplete-sweep handling causes the separate P1. [cgroup.go:366](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/cgroup/cgroup.go:366) |
+| `Server.healthByHost` | **Approve.** Passing a nil tenant filter preserves local-row behavior and existing registry reads. [apiinstances.go:457](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/console/apiinstances.go:457) |
+| `Server.instanceHealth` | **Approve.** Remote metrics use each record’s account, app and creation time after the existing report checks. No registry authority is widened. [apiinstances.go:373](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/console/apiinstances.go:373) |
+| `type UnitRow` | **Approve.** Additional diagnostic sample-index field only. [metricsview.go:54](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/console/metricsview.go:54) |
+| `runAgent` | **Approve.** Wires the existing registry, activator and cgroup manager into the sampler; no new root-selected path. [agent.go:909](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/host/agent.go:909) |
+| `sampler.tick` | **Approve.** Ownership probes and tag bookkeeping surround existing sampling; no new filesystem target or write authority. [metrics_loop.go:76](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/host/metrics_loop.go:76) |
+| `type UnitSample` | **Approve.** Additive, optional diagnostic wire field. [sample.go:21](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/metrics/sample.go:21) |
+
+| Re-pinned envelope | Verdict and evidence |
+|---|---|
+| `internal/activator` | **Approve.** Changed insertion sites and tenancy helpers add in-memory tracking; lifecycle authority remains unchanged. [tenancies.go:21](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/activator/tenancies.go:21) |
+| `internal/cgroup` | **Approve for census.** Existing reads/removals remain; `Leftover` reads only the new map. P1 remains outstanding. [cgroup.go:366](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/cgroup/cgroup.go:366) |
+| `internal/console` | **Approve.** Changes carry and filter diagnostic ownership data through the existing sweep and views. [metricsview.go:614](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/console/metricsview.go:614), [metricsview.go:916](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/console/metricsview.go:916), [server.go:3848](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/console/server.go:3848) |
+| `internal/host` | **Approve.** Additional registry listings use the agent’s existing handle; sampling and flush destinations remain unchanged. [metrics_owner.go:25](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/host/metrics_owner.go:25), [metrics_loop.go:824](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/host/metrics_loop.go:824) |
+| `internal/metrics` | **Approve.** Ownership helpers operate on supplied data; the additive field does not change raw-chunk or rollup storage authority. [owner.go:42](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/metrics/owner.go:42), [owner.go:65](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/metrics/owner.go:65), [owner.go:85](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/metrics/owner.go:85) |
+
+The four decision-row bases are accurate regarding their read sources and execution identity:
+
+- **`Service.Tenancies`: accurate.** Reads existing entry routes, excludes mixed hosts and claim mode, and updates only in-memory bookkeeping. [tenancies.go:60](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/activator/tenancies.go:60)
+- **`Service.putEntryLocked`: accurate.** Replaces the seven existing insertions and records route identity in memory. [tenancies.go:21](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/activator/tenancies.go:21)
+- **`metricsOwners`: accurate.** Reads activator tenancies and the agent’s existing registry; makes no store request or tenant-selected file open. [metrics_owner.go:25](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/host/metrics_owner.go:25)
+- **`Vouched`: accurate.** Joins supplied rows, tenancies and the leftover predicate without opening resources. Its safety still depends on fixing P1’s predicate behavior. [owner.go:42](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/metrics/owner.go:42)
+
+Acceptance of those four new dispositions remains the census owner’s decision.
+
+**NOT READY**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-remote-instance-metrics-branch-r2.md b/docs/superpowers/reviews/CODEX-FINDINGS-remote-instance-metrics-branch-r2.md
new file mode 100644
index 000000000..18f04acf7
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-remote-instance-metrics-branch-r2.md
@@ -0,0 +1,20 @@
+Round 1 P1 — **resolved**. Fault family: **tenant identity of samples**. Failed root listings permanently set `unswept`; `Leftover` consequently rejects every host, including after access recovers ([cgroup.go:370](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/cgroup/cgroup.go:370), [cgroup.go:411](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/cgroup/cgroup.go:411)). The regression test covers recovery and retaining setups ([cgroup_test.go:607](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/cgroup/cgroup_test.go:607)).
+
+Reviewed `887822573655f294e0a5eccad8c94798cdb0ea5a` against merge base `563453808bdd4ff0ac7f7c47f5a6e4a3293987f0`, branch round **2 of 3**. No outstanding P1 or P2 findings.
+
+- **P3 — Stale test comment describes retaining setups incorrectly.**
+ **Section:** cgroup regression tests. **Evidence:** [cgroup_test.go:575](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/cgroup/cgroup_test.go:575) says retaining setups report no leftovers; they now report every host as a leftover. **Failure scenario:** a maintainer following this comment gets the opposite ownership contract; runtime behavior is correct. **Fix:** update the comment on the follow-up list. **Fault family:** documentation accuracy.
+
+**Census verdicts**
+
+| Unit or envelope | Verdict |
+|---|---|
+| `Manager.sweepStale` | **Approve.** Existing directory reads, removal targets and checks remain unchanged. The fix adds logging and an in-memory refusal flag. [cgroup.go:370](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/cgroup/cgroup.go:370) |
+| `setupAt` | **Approve.** Delegation probes, process placement and controller writes remain unchanged. Retaining setup additionally disables ownership vouching. [cgroup.go:324](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/cgroup/cgroup.go:324) |
+| `internal/cgroup` envelope | **Approve.** Reviewed the changed setup, sweep, manager fields and `Leftover`. No new filesystem authority or weakened validation; the added state only restricts tags. [cgroup.go:226](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/cgroup/cgroup.go:226), [cgroup.go:411](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/cgroup/cgroup.go:411) |
+
+Round one’s remaining census verdicts and decision-row basis assessments stand.
+
+Targeted tests could not start: Go could not create its build directory on the read-only filesystem. Coverage and mutation sensitivity were inspected in source; no full suites or mutations were run. No files were edited. Unrelated concurrent workspace changes were excluded from this commit-specific review.
+
+**READY**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-remote-instance-metrics-note-r1.md b/docs/superpowers/reviews/CODEX-FINDINGS-remote-instance-metrics-note-r1.md
new file mode 100644
index 000000000..70190a751
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-remote-instance-metrics-note-r1.md
@@ -0,0 +1,14 @@
+Round 1 of 3, reviewed at `98caa5f4ded08f0c5082311853275ae2633362e0`.
+
+1. **P1 — The box’s tag does not cover the previous CPU-counter reading.**
+ **Fault family: tenant identity of samples.**
+
+ The tick rule in [remote-instance-metrics.md:98](/home/paulca/amadan.net/carlos/platform-remote-metrics/docs/superpowers/notes/remote-instance-metrics.md:98) checks ownership only around the current cgroup read. However, [metrics_loop.go:94](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/host/metrics_loop.go:94) retrieves the previous counter by unit name alone and uses it to calculate `CPUFrac`. [parse.go:168](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/metrics/parse.go:168) rejects decreasing counters, but cannot detect a replacement cgroup whose counter already exceeds its predecessor’s.
+
+ **Failure scenario:** tick N records tenant A’s counter as 5 million microseconds. A stops completely; tenant B acquires the hostname and starts in a fresh cgroup. At tick N+1, 60 seconds later, B’s counter is 20 million. Both ownership checks now agree on B and its new entry number, so the proposed rule tags the calculated CPU fraction `(20−5)/60 = 0.25` as B’s. That value incorporates A’s counter. Its timestamp is after B’s creation, so the console accepts it into B’s reading and graph. No surviving predecessor process or race within the current tick is necessary.
+
+ **Fix:** retain the vouched tenant and entry number alongside each previous counter. Require matching proof for both counter observations before tagging a sample containing a CPU delta. Otherwise leave that sample untagged and establish a new baseline; this preserves local readings. Add a two-tick test with different tenants, stable ownership during each tick, and a replacement counter greater than its predecessor’s. Also cover an untagged previous observation.
+
+No additional P2 or P3 findings. No files edited or test suites run.
+
+**NOT READY**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-remote-instance-metrics-note-r2.md b/docs/superpowers/reviews/CODEX-FINDINGS-remote-instance-metrics-note-r2.md
new file mode 100644
index 000000000..bdaa4e827
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-remote-instance-metrics-note-r2.md
@@ -0,0 +1,17 @@
+Round 1 P1 — **resolved**: `CarryTags` checks the previous counter observation’s tenant before retaining the tag ([owner.go:85](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/metrics/owner.go:85)); mixed-host history provides the broader protection. Fault family: **tenant identity of samples**.
+
+1. **P2 — Request budget omits sweeps newly triggered by remote-only views.**
+
+ **Section:** [Request budget, line 179](/home/paulca/amadan.net/carlos/platform-remote-metrics/docs/superpowers/notes/remote-instance-metrics.md:179). “No new request anywhere” and “0 new console requests” are incorrect.
+
+ **Evidence:** Today, `appResourceMetrics` skips remote rows ([server.go:3860](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/console/server.go:3860)). With no local hosts, `ownerAppMetricsFrom` returns before calling `LoadMetrics` ([metricsview.go:828](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/console/metricsview.go:828)). Including remote hosts crosses that guard. A cold cache triggers `sweepAll` ([metricsview.go:343](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/console/metricsview.go:343)), including 48 raw-chunk GETs per discovered box ([metricsview.go:520](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/console/metricsview.go:520)).
+
+ **Failure scenario:** On a quiet console with a cold cache, opening an app whose instances are all remote previously made no metrics requests. Under the proposed design, that same visit triggers the fleet-wide sweep, including discovery and alert reads. Subsequent visits can trigger refreshes after cache expiry.
+
+ **Fix:** State that idle background traffic and requests per sweep remain unchanged, but remote-only views can now initiate the existing sweep. Document its cost and add a request-budget test covering cold and fresh-cache visits.
+
+ **Fault family:** request-budget accounting. The prohibition on new per-box polling remains satisfied.
+
+No outstanding P1 or P3 findings. Reviewed commit `0a90c4c3e15203654e17aae773dc9ca623f19829`; no files edited. Targeted tests could not start because the read-only filesystem prevented Go from creating its build directory. Fix the P2 without another review round.
+
+**READY AFTER FIXES**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-remote-instance-metrics-branch.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-remote-instance-metrics-branch.md
new file mode 100644
index 000000000..a5005b376
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-remote-instance-metrics-branch.md
@@ -0,0 +1,114 @@
+# Review brief: branch remote-instance-metrics, round 2 of 3
+
+Repo carlos/platform, branch `remote-instance-metrics`, commit named in the
+reviewer's prompt.
+Under review: the diff `origin/main..<commit>` (merge base 56345380).
+Authorities: the code on main at the merge base; the design note on this
+branch, `docs/superpowers/notes/remote-instance-metrics.md`, which had its
+own review (rounds 1 and 2, findings in
+`docs/superpowers/reviews/CODEX-FINDINGS-remote-instance-metrics-note-r1.md`
+and `-r2.md`; round 2 READY AFTER FIXES, fixed). 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, then the diff, and check
+the code against the note and the note's claims against the code.
+
+## Fixed: do not re-argue
+
+- Paul's rulings for this work (task brief, 2026-10-26): the boxes tag
+ every metrics sample with the instance's identity and the console
+ accepts a sample on a remote row only when the tag matches the record it
+ shows; untagged samples from old boxes are never shown remotely; local
+ rows keep today's behaviour; no new per-box polling.
+- The note's design choices reviewed in its rounds 1 and 2: the identity is
+ the tenant (account and app), not the incarnation; a host is vouched only
+ if every activator entry this agent made for it named one tenant; a
+ hostname that changes tenant on a box shows no remote readings until the
+ agent restarts; same-owner recreation is out of the fault family; a
+ remote-only view may start the existing sweep. Raise one again only with
+ new evidence that it lets a sample reach the wrong account.
+
+## What to check
+
+Fault family: **tenant identity of samples** (whose process or cgroup a
+sample measured, and whether any page, API answer or number can show it to
+the wrong account). Name it beside every finding in that family.
+
+1. Box: `internal/metrics/owner.go` (`Vouched`, `TagUnits`, `CarryTags`),
+ `internal/activator/tenancies.go` (`putEntryLocked`, `Tenancies`) and
+ the seven insertion sites it replaced, `internal/cgroup` `Leftover`,
+ `internal/host/metrics_owner.go` and `metrics_loop.go` (`sampler.tick`),
+ and the wiring in `agent.go`. Can any reading be tagged with a tenant
+ that is not the only tenant the host's exec cgroup ever held in this
+ agent's life?
+2. Console: `ownerAppMetricsFrom` (the tag filter, the newest-sample rule,
+ the per-sample graph filter, the `created_at` bound), `buildBoxView`'s
+ owner table, `remoteRoute`, `appResourceMetrics`, `instanceHealth`.
+ Can any remote row, page, `carlos instances list` answer or Overview
+ number carry a sample not tagged with the record's own account and app?
+ Do local rows behave exactly as before?
+3. Tests: are they production-wired where the note says, and do they cover
+ a reused hostname (including samples after the new record's creation),
+ a successor shown to the old owner, untagged samples, and another
+ account's report? Mutations were run (19 mutants, all killed): spot
+ check that the named tests would fail on the obvious breakages.
+4. Wire shape and consumers: the additive `owner` field; everything that
+ parses raw chunks or rollups.
+5. Request budget: no new box request; the console's sweep as the note
+ describes.
+6. **Census (cross-model approval).** The card is
+ `docs/superpowers/notes/census-proposal-remote-instance-metrics.md`.
+ Give a verdict, approve or escalate, for every changed unit and every
+ re-pinned envelope it lists, per AGENTS.md "The census: an approval,
+ not a decision", citing the lines you read. The four new units in
+ `internal/provision/testdata/plan14-root-reads-remote-instance-metrics-decisions.tsv`
+ are decisions for the census owner: say whether each row's basis is
+ accurate.
+
+## Round 2
+
+Earlier rounds of the branch: round 1,
+`docs/superpowers/reviews/CODEX-FINDINGS-remote-instance-metrics-branch-r1.md`
+(one P1, fault family tenant identity of samples: an unlistable root at
+setup read as "no leftovers"). The note's own two rounds are recorded
+separately (see Authorities).
+
+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, earlier rounds included. Give census verdicts again only for
+units the fix changed (`Manager.sweepStale`, `setupAt` and the
+`internal/cgroup` envelope); round 1's other verdicts stand.
+
+AGENTS.md stopping rule 2 applies: a P1 in the same fault family this
+round stops the work and goes to Paul with options, so report one only
+with a concrete failure scenario and evidence.
+
+## 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/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-remote-instance-metrics-census.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-remote-instance-metrics-census.md
new file mode 100644
index 000000000..4638f8c01
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-remote-instance-metrics-census.md
@@ -0,0 +1,32 @@
+# Review brief: census approval, branch remote-instance-metrics (after merging main's C2)
+
+Repo carlos/platform, branch `remote-instance-metrics`, commit named in the
+reviewer's prompt. This is the census check AGENTS.md ("The census: the
+reviewer decides") requires, not another review round of the branch:
+the branch review ended at round 2, READY
+(`docs/superpowers/reviews/CODEX-FINDINGS-remote-instance-metrics-branch-r1.md`, `-r2.md`).
+
+The branch merged origin/main's census re-base (C2) and re-ran
+`make census-propose NAME=remote-instance-metrics`. The card is
+`docs/superpowers/notes/census-proposal-remote-instance-metrics.md`.
+Rounds 1 and 2 of the branch review already approved, under the old rules,
+every changed unit and envelope that remains on the card; their code is
+unchanged by the merge (check: `git diff 887822573655f294e0a5eccad8c94798cdb0ea5a <commit> -- internal/activator internal/cgroup internal/host internal/metrics`
+should show only main's own changes, if any).
+
+Give a verdict, approve or reject with a finding, for:
+
+1. each of the four `new` units on the card (`Service.Tenancies`,
+ `Service.putEntryLocked`, `metricsOwners`, `metrics.Vouched`). Under
+ C2 the reviewer decides `new` units; nothing goes to Paul;
+2. each changed unit and re-pinned envelope on the card, confirming it
+ matches what rounds 1 and 2 approved, or reviewing it if it does not.
+
+Reject only with a concrete finding: root opening, running, querying or
+following something new from a path or input a tenant, an app or a box
+agent can create, write or name; or a weakened check, refusal,
+validation, argument or environment the basis relies on. Cite lines.
+End with APPROVE (all) or REJECT (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/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-remote-instance-metrics-note.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-remote-instance-metrics-note.md
new file mode 100644
index 000000000..58d2f29db
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-remote-instance-metrics-note.md
@@ -0,0 +1,111 @@
+# Review brief: remote instance metrics design note, round 2 of 3
+
+Repo carlos/platform, branch `remote-instance-metrics`, commit named in the
+reviewer's prompt.
+Under review: `docs/superpowers/notes/remote-instance-metrics.md`.
+Authorities: the code on main at the branch's base (origin/main 56345380),
+and `docs/superpowers/notes/console-remote-instances.md` on main (the
+history of the cut this note reverses). 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, then the code it names, and
+check every claim against that code. This is a short design note for a
+bounded change, not a spec: review the mechanism and its claims, not prose.
+
+## Fixed: do not re-argue
+
+- Paul's rulings for this work (task brief, 2026-10-26): the boxes tag every
+ metrics sample with the instance's identity and the console accepts a
+ sample on a remote row only when the tag matches the record it shows;
+ untagged samples from old boxes are never shown remotely; local rows
+ keep today's behaviour; no new per-box polling (ride the existing
+ metrics sweep). Report only mechanisms that fail to honour these.
+- Remote CPU and memory were cut on main because six rounds of time and
+ box bounds on a hostname join leaked. The note does not bring any of
+ those bounds back except the record's `created_at` lower bound.
+
+## What to check
+
+Fault family for this review: **tenant identity of samples** (whose
+process a sample measured, and whether the console can show it to the
+wrong account). Name it beside every finding in that family.
+
+1. The identity choice (account and app, not the incarnation). Check the
+ note's claims about `provision.Record`, `registry.Route.Incarnation`,
+ `installRowLifetime` / `ownsRowLifetime`, and how a hostname changes
+ tenant on a box. Is there a path where a hostname changes tenant on a
+ box without the row's account or app changing?
+2. The box invariant: "in this agent's life, the host's cgroup has only
+ ever held tenant T". Check the sources the note lists against
+ `internal/activator` (every insertion into `entries`,
+ `wakeRouteChanged`, `Shutdown`), `internal/cgroup` (`Setup`,
+ `sweepStale`, `freshen`, `SetupRetaining`) and
+ `internal/host/metrics_loop.go`. Is there a spawner into a host's exec
+ cgroup that is not an activator entry, a way for a second tenant's
+ process or charge to reach the cgroup without the host being marked
+ mixed, or a reading (CPU delta, memory) that still mixes tenants?
+3. The two reads around the cgroup read, the entry number and
+ `CarryTags`. Can a wake, stop or re-tenant during or between ticks
+ still produce a tag naming the wrong tenant?
+4. The console filter: latest sample's tag, per-sample graph filter,
+ `created_at` bound, freshest box. Can any remote row, page,
+ `carlos instances list` answer or Overview number show a sample not
+ tagged with the record's account and app? Check every caller of
+ `ownerAppMetricsFrom` and `appResourceMetrics`.
+5. Mixed fleet and wire shape: additive `owner` on `metrics.UnitSample`;
+ everything that parses raw chunks or rollups.
+6. Request budget: is any new request added?
+
+## Round 2
+
+Earlier rounds: round 1, `docs/superpowers/reviews/CODEX-FINDINGS-remote-instance-metrics-note-r1.md`
+(one P1, fault family tenant identity of samples). The round number
+counts every earlier review of this design or change, under any file
+name or reviewer.
+
+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, earlier rounds included.
+
+Round 2 changed the box rule from per-process checks to the cgroup's
+history: a host is vouched only if every activator entry this agent made
+for it named one tenant (`putEntryLocked`, `Tenancies`), plus
+`CarryTags` for the previous tick. The branch now carries the box-side
+code for this (`internal/metrics/owner.go`, `internal/activator/tenancies.go`,
+`internal/host/metrics_owner.go`, `internal/cgroup` `Leftover`) with its
+tests; check the note's claims against it. The console side is not built
+yet: review it as described in the note.
+
+AGENTS.md stopping rule 2 applies: a P1 in the same fault family this
+round stops the design and goes to Paul with options, so report one only
+with a concrete failure scenario and evidence.
+
+## 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). 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/activator/activator.go b/internal/activator/activator.go
index 196f8be8f..a6e24b244 100644
--- a/internal/activator/activator.go
+++ b/internal/activator/activator.go
@@ -492,6 +492,9 @@ type actEntry struct {
host string
route registry.Route
state actState
+ // tenancyNo is this entry's number in Tenancies (tenancies.go), 0 until
+ // it is first vouched. Under a.mu.
+ tenancyNo uint64
ready chan struct{} // waking: closed when the wake resolves; then check err
err error // waking: the wake's outcome
@@ -1210,6 +1213,13 @@ type Service struct {
mu sync.Mutex
entries map[string]*actEntry
+ // tenancySeq numbers the entries Tenancies vouches for; hostTenants is
+ // the first tenant each host's entries named in this agent's life, and
+ // hostMixed the hosts whose entries have named two (putEntryLocked).
+ // Under a.mu.
+ tenancySeq uint64
+ hostTenants map[string]tenantKey
+ hostMixed map[string]bool
// shuttingDown is set by Shutdown before it stops anything, and read by
// the supervised-respawn goroutines: the agent is going away, so nothing
// new may be spawned against a DB whose lease is about to be released.
@@ -1545,7 +1555,7 @@ func (a *Service) begin(ctx context.Context, rt registry.Route, stamp bool, req
// and two restore attempts per request (#184, seen only as a
// loaded-suite test flake because the window is that narrow).
e = &actEntry{host: rt.Host, route: rt, state: actWaking, ready: make(chan struct{})}
- a.entries[rt.Host] = e
+ a.putEntryLocked(rt.Host, e)
go a.wake(e)
edge.MarkWoke(req)
}
@@ -3281,7 +3291,7 @@ func (a *Service) WakeWorker(rt registry.Route) error {
// fails deletes its entry, so the initiator would find nothing and
// start a second one.
e = a.newWorkerEntry(rt)
- a.entries[rt.Host] = e
+ a.putEntryLocked(rt.Host, e)
go a.wake(e)
} else if !e.worker {
// A live entry for this host that is NOT a worker means the route
@@ -5072,7 +5082,7 @@ func (a *Service) sweepOnce() {
} else {
e = &actEntry{host: rt.Host, route: rt, state: actWaking, ready: make(chan struct{})}
}
- a.entries[rt.Host] = e
+ a.putEntryLocked(rt.Host, e)
go a.wake(e)
}
@@ -5105,7 +5115,7 @@ func (a *Service) sweepOnce() {
}
log.Printf("activator: always-on sidecar %s is not running — starting it", rt.Host)
e := a.newWorkerEntry(rt)
- a.entries[rt.Host] = e
+ a.putEntryLocked(rt.Host, e)
go a.wake(e)
started++
}
diff --git a/internal/activator/probewake.go b/internal/activator/probewake.go
index c5965f00b..654908375 100644
--- a/internal/activator/probewake.go
+++ b/internal/activator/probewake.go
@@ -213,7 +213,7 @@ func (a *Service) ProbeWake(ctx context.Context, cfg ProbeConfig) (ProbeResult,
a.mu.Unlock()
return ProbeResult{}, errors.Join(ErrProbeRefused, errProbeLive)
}
- a.entries[cfg.Host] = e
+ a.putEntryLocked(cfg.Host, e)
a.mu.Unlock()
if probeWakePublished != nil {
probeWakePublished()
diff --git a/internal/activator/recoveryprobe.go b/internal/activator/recoveryprobe.go
index 01ee80330..37d1f91d7 100644
--- a/internal/activator/recoveryprobe.go
+++ b/internal/activator/recoveryprobe.go
@@ -87,7 +87,7 @@ func (a *Service) RecoveryProbe(ctx context.Context, rt registry.Route, p StartP
if a.entries == nil {
a.entries = make(map[string]*actEntry)
}
- a.entries[rt.Host] = e
+ a.putEntryLocked(rt.Host, e)
fence := a.fences[rt.Host]
a.mu.Unlock()
if a.lifeCtx != nil {
diff --git a/internal/activator/swaphold.go b/internal/activator/swaphold.go
index 279606566..443004da4 100644
--- a/internal/activator/swaphold.go
+++ b/internal/activator/swaphold.go
@@ -327,7 +327,7 @@ func (a *Service) holdWakeLocked(e *actEntry, h *holdSpec) (*actEntry, error) {
// The same gate here, at the stop's end, and again at the pinned wake's
// exec (spec §6.3, §7.4): the lease and the restore come between.
next.pinCheck = func() error { return a.attemptCurrentLocked(next, h.at, h.newest, true) }
- a.entries[e.host] = next
+ a.putEntryLocked(e.host, next)
if err := next.pinCheck(); err != nil {
delete(a.entries, e.host)
return nil, err
diff --git a/internal/activator/tenancies.go b/internal/activator/tenancies.go
new file mode 100644
index 000000000..7231d7405
--- /dev/null
+++ b/internal/activator/tenancies.go
@@ -0,0 +1,80 @@
+package activator
+
+// Tenancy is the tenant whose route a live entry's processes were started
+// for, and the entry's number: a new entry is a new number, so a reader
+// that sees the same number twice knows no wake or stop came between.
+type Tenancy struct {
+ Account, App string
+ Entry uint64
+}
+
+// tenantKey is a route's tenant: its account and app as the row names them.
+type tenantKey struct{ acct, app string }
+
+// putEntryLocked is the one way an entry enters a.entries. Every process the
+// activator starts into a host's cgroup is an entry's, so recording each
+// entry's tenant here records every tenant whose processes the host's
+// cgroup has held in this agent's life: a host whose entries have named two
+// tenants is mixed for good (Tenancies). An entry whose wake is later
+// refused still counts; that errs toward vouching less. The caller holds
+// a.mu. TestEntriesEnterThroughPutEntryLocked keeps every insertion here.
+func (a *Service) putEntryLocked(host string, e *actEntry) {
+ if a.entries == nil {
+ a.entries = make(map[string]*actEntry)
+ }
+ a.entries[host] = e
+ a.noteTenantLocked(host, e.route.Account, e.route.App)
+}
+
+// noteTenantLocked records that host's cgroup has held, or may hold, a
+// process of tenant (acct, app). A second tenant makes the host mixed.
+func (a *Service) noteTenantLocked(host, acct, app string) {
+ k := tenantKey{acct, app}
+ if a.hostTenants == nil {
+ a.hostTenants = make(map[string]tenantKey)
+ }
+ first, ok := a.hostTenants[host]
+ if !ok {
+ a.hostTenants[host] = k
+ return
+ }
+ if first != k {
+ if a.hostMixed == nil {
+ a.hostMixed = make(map[string]bool)
+ }
+ a.hostMixed[host] = true
+ }
+}
+
+// Tenancies is the metrics sampler's word from the activator on whose
+// processes each host's exec cgroup holds (remote instance metrics note,
+// docs/superpowers/notes/remote-instance-metrics.md). A host is vouched
+// for tenant T only while it has a live entry and every entry this agent
+// has made for it named T: its cgroup persists between entries, so CPU
+// counters and charged memory can carry an earlier tenant's use, and a
+// host that ever had two tenants is never vouched again in this agent's
+// life. A route with no account or app vouches nothing, and an entry whose
+// route names another tenant than its host's first makes the host mixed
+// too. Claim mode retains processes across agent restarts, so it vouches
+// nothing. Entry numbers are given the first time an entry is vouched.
+func (a *Service) Tenancies() map[string]Tenancy {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ if a.cfg.HostWrites.Enabled {
+ return nil
+ }
+ out := make(map[string]Tenancy, len(a.entries))
+ for host, e := range a.entries {
+ acct, app := e.route.Account, e.route.App
+ a.noteTenantLocked(host, acct, app) // a route changed in place
+ if a.hostMixed[host] || acct == "" || app == "" {
+ continue
+ }
+ if e.tenancyNo == 0 {
+ a.tenancySeq++
+ e.tenancyNo = a.tenancySeq
+ }
+ out[host] = Tenancy{Account: acct, App: app, Entry: e.tenancyNo}
+ }
+ return out
+}
diff --git a/internal/activator/tenancies_test.go b/internal/activator/tenancies_test.go
new file mode 100644
index 000000000..217edd0c6
--- /dev/null
+++ b/internal/activator/tenancies_test.go
@@ -0,0 +1,184 @@
+package activator
+
+import (
+ "context"
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "io/fs"
+ "strings"
+ "testing"
+ "time"
+)
+
+// TestTenanciesVouchForLiveEntries drives real wakes and stops through the
+// fake backend: an awake entry is vouched with its route's tenant, a new
+// wake of the same host is a new entry number, and a host the activator
+// cannot vouch for is left out.
+func TestTenanciesVouchForLiveEntries(t *testing.T) {
+ a, _, _, _ := testActivator(t, time.Hour)
+ rt := testRoute("eu.shop.example.com")
+ rt.Account, rt.App = "bdn", "shop"
+ if got := a.Tenancies(); len(got) != 0 {
+ t.Fatalf("asleep host vouched: %+v", got)
+ }
+ arrangeAwake(t, a, rt)
+ first := a.Tenancies()[rt.Host]
+ if first.Account != "bdn" || first.App != "shop" || first.Entry == 0 {
+ t.Fatalf("awake entry = %+v", first)
+ }
+ if again := a.Tenancies()[rt.Host]; again != first {
+ t.Fatalf("the same entry changed number: %+v then %+v", first, again)
+ }
+
+ a.RetireExcept(map[string]bool{})
+ waitFor(t, "the stop", func() bool { return a.entryCount() == 0 })
+ if got := a.Tenancies(); len(got) != 0 {
+ t.Fatalf("stopped host still vouched: %+v", got)
+ }
+ arrangeAwake(t, a, rt)
+ second := a.Tenancies()[rt.Host]
+ if second.Entry == 0 || second.Entry == first.Entry {
+ t.Fatalf("a new wake kept the entry number: %+v then %+v", first, second)
+ }
+
+ // An unstamped route vouches nothing.
+ bare := testRoute("bare.example.com")
+ arrangeAwake(t, a, bare)
+ if _, ok := a.Tenancies()[bare.Host]; ok {
+ t.Fatal("a route with no account or app was vouched")
+ }
+}
+
+// TestTenanciesHostThatHadTwoTenants: a host's exec cgroup outlives its
+// entries, so its counters and charged memory can carry an earlier
+// tenant's use. Once two tenants' entries have been made for one host, it
+// is never vouched again in this agent's life, whoever is live there now.
+func TestTenanciesHostThatHadTwoTenants(t *testing.T) {
+ t.Run("woken for one tenant, then another", func(t *testing.T) {
+ a, _, _, _ := testActivator(t, time.Hour)
+ rt := testRoute("eu.shop.example.com")
+ rt.Account, rt.App = "rival", "shop"
+ arrangeAwake(t, a, rt)
+ a.RetireExcept(map[string]bool{})
+ waitFor(t, "the stop", func() bool { return a.entryCount() == 0 })
+ rt.Account = "bdn"
+ arrangeAwake(t, a, rt)
+ if got, ok := a.Tenancies()[rt.Host]; ok {
+ t.Fatalf("the successor on a host that had another tenant was vouched: %+v", got)
+ }
+ other := testRoute("other.example.com")
+ other.Account, other.App = "bdn", "shop"
+ arrangeAwake(t, a, other)
+ if _, ok := a.Tenancies()[other.Host]; !ok {
+ t.Fatal("a host with one tenant lost its vouch")
+ }
+ })
+ t.Run("a refused wake for another tenant counts", func(t *testing.T) {
+ a, _, _, reg := testActivator(t, time.Hour)
+ a.Routes = reg
+ rt := testRoute("eu.shop.example.com")
+ rt.Account, rt.App, rt.Status = "bdn", "shop", "ready"
+ if err := reg.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ // The edge's cached row still names the predecessor: the wake
+ // refreshes against the registry and refuses (wakeRouteChanged).
+ stale := rt
+ stale.Account = "rival"
+ if _, err := a.beginRequest(context.Background(), stale); err == nil {
+ t.Fatal("fixture: a wake for a re-tenanted row went ahead")
+ }
+ arrangeAwake(t, a, rt)
+ if got, ok := a.Tenancies()[rt.Host]; ok {
+ t.Fatalf("vouched %+v after another tenant's entry was made for the host", got)
+ }
+ })
+}
+
+// TestTenanciesRouteChangedInPlace: an entry whose route names another
+// tenant than when it was first vouched is never vouched again.
+func TestTenanciesRouteChangedInPlace(t *testing.T) {
+ a, _, _, _ := testActivator(t, time.Hour)
+ rt := testRoute("eu.shop.example.com")
+ rt.Account, rt.App = "bdn", "shop"
+ arrangeAwake(t, a, rt)
+ if _, ok := a.Tenancies()[rt.Host]; !ok {
+ t.Fatal("fixture: not vouched")
+ }
+ a.mu.Lock()
+ a.entries[rt.Host].route.Account = "rival"
+ a.mu.Unlock()
+ if got, ok := a.Tenancies()[rt.Host]; ok {
+ t.Fatalf("an entry re-tenanted in place was vouched: %+v", got)
+ }
+ a.mu.Lock()
+ a.entries[rt.Host].route.Account = "bdn"
+ a.mu.Unlock()
+ if got, ok := a.Tenancies()[rt.Host]; ok {
+ t.Fatalf("an entry that changed tenant once was vouched again: %+v", got)
+ }
+}
+
+// TestEntriesEnterThroughPutEntryLocked: putEntryLocked is how the host's
+// tenants are recorded, so an entry inserted any other way would be a
+// tenant Tenancies never saw. Fails on any other assignment into
+// a.entries in the package's production code.
+func TestEntriesEnterThroughPutEntryLocked(t *testing.T) {
+ fset := token.NewFileSet()
+ pkgs, err := parser.ParseDir(fset, ".", func(fi fs.FileInfo) bool {
+ return !strings.HasSuffix(fi.Name(), "_test.go")
+ }, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ found := 0
+ for _, pkg := range pkgs {
+ for _, f := range pkg.Files {
+ for _, d := range f.Decls {
+ fn, ok := d.(*ast.FuncDecl)
+ if !ok || fn.Body == nil {
+ continue
+ }
+ ast.Inspect(fn.Body, func(n ast.Node) bool {
+ as, ok := n.(*ast.AssignStmt)
+ if !ok {
+ return true
+ }
+ for _, lhs := range as.Lhs {
+ ix, ok := lhs.(*ast.IndexExpr)
+ if !ok {
+ continue
+ }
+ sel, ok := ix.X.(*ast.SelectorExpr)
+ if !ok || sel.Sel.Name != "entries" {
+ continue
+ }
+ if fn.Name.Name == "putEntryLocked" {
+ found++
+ continue
+ }
+ t.Errorf("%s: %s assigns into entries directly; use putEntryLocked", fset.Position(as.Pos()), fn.Name.Name)
+ }
+ return true
+ })
+ }
+ }
+ }
+ if found != 1 {
+ t.Fatalf("putEntryLocked's own insertion found %d times, want 1", found)
+ }
+}
+
+// TestTenanciesClaimModeVouchesNothing: claim mode retains processes across
+// agent restarts, so nothing is vouched there.
+func TestTenanciesClaimModeVouchesNothing(t *testing.T) {
+ a, _, _, _ := testActivator(t, time.Hour)
+ rt := testRoute("eu.shop.example.com")
+ rt.Account, rt.App = "bdn", "shop"
+ arrangeAwake(t, a, rt)
+ a.cfg.HostWrites.Enabled = true
+ if got := a.Tenancies(); len(got) != 0 {
+ t.Fatalf("claim mode vouched %+v", got)
+ }
+}
diff --git a/internal/cgroup/cgroup.go b/internal/cgroup/cgroup.go
index fcea822d3..c924b28e9 100644
--- a/internal/cgroup/cgroup.go
+++ b/internal/cgroup/cgroup.go
@@ -223,6 +223,14 @@ type Manager struct {
// and in tests, where the window exposes no exempt leaf and the fallback
// keeps its Ruling 2 behaviour.
fencedSpawn bool
+ // leftover is the hosts whose per-host dir sweepStale could not remove
+ // at setup: something a previous agent started may still be alive in
+ // it. unswept says setup did not sweep at all (a retaining setup) or
+ // could not list the root, so no host's dir is known clean. Both are
+ // written once, during setup, before the manager is shared; read only
+ // after (Leftover).
+ leftover map[string]bool
+ unswept bool
// locks holds each host's start lock (hostLock), made on first use.
locksMu sync.Mutex
locks map[string]*sync.Mutex
@@ -351,6 +359,7 @@ func setupAt(root string, logf func(string, ...any), retain bool) (*Manager, err
m.sweepStale()
} else {
m.seedKilled()
+ m.unswept = true // kept dirs may hold an earlier agent's processes
}
return m, nil
}
@@ -361,6 +370,9 @@ func setupAt(root string, logf func(string, ...any), retain bool) (*Manager, err
func (m *Manager) sweepStale() {
entries, err := os.ReadDir(m.root)
if err != nil {
+ // Nothing was swept, so nothing is known clean (Leftover).
+ m.logf("cgroup: stale exec dirs not swept: %v", err)
+ m.unswept = true
return
}
for _, e := range entries {
@@ -382,10 +394,24 @@ func (m *Manager) sweepStale() {
}
if err := os.Remove(dir); err != nil {
m.logf("cgroup: stale %s not removed: %v", e.Name(), err)
+ if m.leftover == nil {
+ m.leftover = map[string]bool{}
+ }
+ m.leftover[strings.TrimPrefix(e.Name(), execPrefix)] = true
}
}
}
+// Leftover reports whether host's dir may hold what a previous agent left:
+// setup's sweep could not remove it, or setup swept nothing (a retaining
+// setup, or a root it could not list), so no dir is known clean. The
+// metrics sampler never vouches for such a host's tenant in this agent's
+// life (docs/superpowers/notes/remote-instance-metrics.md). Nil-safe: no
+// manager, no exec cgroups, no leftovers.
+func (m *Manager) Leftover(host string) bool {
+ return m != nil && (m.unswept || m.leftover[host])
+}
+
// ErrKilledCgroupKept is a start refused because the cgroup it would spawn
// into took cgroup.kill and could not be removed and made fresh first
// (amadan #272). Spawning into it anyway would have the kernel SIGKILL the
diff --git a/internal/cgroup/cgroup_test.go b/internal/cgroup/cgroup_test.go
index 6b815097f..dd107eabe 100644
--- a/internal/cgroup/cgroup_test.go
+++ b/internal/cgroup/cgroup_test.go
@@ -567,3 +567,73 @@ func TestPlansTierMemoryAgrees(t *testing.T) {
t.Errorf("plans.TierMemoryMB[default] = %d, cgroup TierDefault = %d MB", got, want)
}
}
+
+// TestLeftoverNamesHostsTheSweepCouldNotRemove: a host whose dir a previous
+// agent left populated may still hold that agent's processes, so the
+// metrics sampler never vouches for it in this agent's life (remote
+// instance metrics note). Swept and never-seen hosts are not leftovers,
+// and a nil manager reports none. (A retaining setup reports every host:
+// TestLeftoverAfterAnUnreadableSweep.)
+func TestLeftoverNamesHostsTheSweepCouldNotRemove(t *testing.T) {
+ root := newDelegatedRoot(t)
+ if err := os.Mkdir(filepath.Join(root, "carlos-exec@old.example.com"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.MkdirAll(filepath.Join(root, "carlos-exec@busy.example.com", "child"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ m, err := SetupAt(root, t.Logf)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !m.Leftover("busy.example.com") {
+ t.Error("a dir the sweep could not remove is not a leftover")
+ }
+ for _, h := range []string{"old.example.com", "new.example.com"} {
+ if m.Leftover(h) {
+ t.Errorf("%s reported as a leftover", h)
+ }
+ }
+ var none *Manager
+ if none.Leftover("busy.example.com") {
+ t.Error("a nil manager reported a leftover")
+ }
+}
+
+// TestLeftoverAfterAnUnreadableSweep (Astra, branch round 1, P1): when
+// setup cannot list the delegated root, it cannot know which per-host dirs
+// a previous agent left, so every host is a leftover for this agent's
+// life, even after the root reads again. A retaining setup removes
+// nothing, so the same holds there.
+func TestLeftoverAfterAnUnreadableSweep(t *testing.T) {
+ root := newDelegatedRoot(t)
+ if err := os.MkdirAll(filepath.Join(root, "carlos-exec@busy.example.com"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chmod(root, 0o300); err != nil { // writable, not listable
+ t.Fatal(err)
+ }
+ if _, err := os.ReadDir(root); err == nil {
+ t.Skip("the root is listable without read permission here (running as root?)")
+ }
+ m, err := SetupAt(root, t.Logf)
+ if err := os.Chmod(root, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, h := range []string{"busy.example.com", "new.example.com"} {
+ if !m.Leftover(h) {
+ t.Errorf("%s is not a leftover after a sweep that could not list the root", h)
+ }
+ }
+
+ retained, err := SetupAtRetaining(newDelegatedRoot(t), t.Logf)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !retained.Leftover("new.example.com") {
+ t.Error("a retaining setup reported a host as known clean")
+ }
+}
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go
index ab11b4593..1dd1b037e 100644
--- a/internal/console/apiinstances.go
+++ b/internal/console/apiinstances.go
@@ -40,6 +40,7 @@ import (
"github.com/carlosframework/platform/internal/gate"
"github.com/carlosframework/platform/internal/hostops"
+ "github.com/carlosframework/platform/internal/metrics"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/ratelimit"
"github.com/carlosframework/platform/internal/regionlabel"
@@ -352,14 +353,23 @@ func (s *Server) instanceHealth(ctx context.Context, recs []provision.Record) ma
// A record whose route is on another box has no row here. Its health
// comes from the box that reports it, the same join the app pages make
// (remoteinstances.go): only a report whose rollout names this record's
- // own account and app. It takes no metrics readings at all: the word
- // comes from the rollout's awake, down and transient alone. A record no
- // box reports stays "Setting up" when every box was read; when the read
- // was incomplete, the record is placed on a customer fleet, or the only
- // report names no tenant, its state is unknown and says so.
+ // own account and app. Its word comes from the rollout's awake, down
+ // and transient, and, as on the Running tab, a reading its box tagged
+ // with this record's own account and app counts as awake
+ // (ownerAppMetricsFrom's tenant rule). A record no box reports stays
+ // "Setting up" when every box was read; when the read was incomplete,
+ // the record is placed on a customer fleet, or the only report names no
+ // tenant, its state is unknown and says so.
if s.cfg.Releases != nil {
var facts appFacts
loaded := false
+ type remoteWord struct {
+ rec provision.Record
+ kind string
+ status string
+ awake bool
+ }
+ var pending []remoteWord
for _, rec := range recs {
if _, local := byHost[rec.Host]; local {
continue
@@ -389,7 +399,30 @@ func (s *Server) instanceHealth(ctx context.Context, recs []provision.Record) ma
// page says.
status = "failed"
}
- out[rec.Host] = healthWord(kind, status, rec.HibernateOrDefault(), rep.awake, true)
+ pending = append(pending, remoteWord{rec: rec, kind: kind, status: status, awake: rep.awake})
+ }
+ if len(pending) > 0 {
+ hosts := make([]string, 0, len(pending))
+ since := make(map[string]time.Time, len(pending))
+ tenants := make(map[string]metrics.Owner, len(pending))
+ for _, p := range pending {
+ hosts = append(hosts, p.rec.Host)
+ since[p.rec.Host] = p.rec.CreatedAt
+ tenants[p.rec.Host] = metrics.Owner{Account: p.rec.Account, App: p.rec.App}
+ }
+ reporting := map[string]bool{}
+ am, err := s.ownerAppMetricsFrom(ctx, hosts, nil, since, tenants)
+ if err != nil {
+ log.Printf("console: api instances health: remote metrics: %v", err)
+ }
+ for _, m := range am {
+ if m.Reporting() {
+ reporting[m.Host] = true
+ }
+ }
+ for _, p := range pending {
+ out[p.rec.Host] = healthWord(p.kind, p.status, p.rec.HibernateOrDefault(), p.awake || reporting[p.rec.Host], true)
+ }
}
}
// Readings start with each record's created_at, as on the app pages: a
@@ -431,7 +464,7 @@ func (s *Server) healthByHost(ctx context.Context, routeFor map[string]registry.
unitByHost[h] = rt.Unit
}
}
- am, err := s.ownerAppMetricsFrom(ctx, hosts, unitByHost, sinceByHost)
+ am, err := s.ownerAppMetricsFrom(ctx, hosts, unitByHost, sinceByHost, nil)
if err != nil {
// An unreadable sweep is not knowledge that these instances are
// down: every host reads as not-reporting below, which healthWord
diff --git a/internal/console/metricsview.go b/internal/console/metricsview.go
index 70587ba37..5e6142844 100644
--- a/internal/console/metricsview.go
+++ b/internal/console/metricsview.go
@@ -51,6 +51,11 @@ type UnitRow struct {
// float32 and one int64 per sample per running unit.
cpu []float32
mem []int64
+ // owner is the tenant the box tagged the unit's reading with at each
+ // swept sample, as an index into BoxMetricsView.owners, -1 where it
+ // tagged none (metrics.UnitSample.Owner). A remote row reads only the
+ // samples tagged with its record's tenant (ownerAppMetricsFrom).
+ owner []int32
}
// BoxMetricsView is one box's assembled dashboard row: latest host readings
@@ -65,6 +70,19 @@ type BoxMetricsView struct {
// times is each swept sample's time, oldest first: the x axis of every
// unit's cpu and mem series.
times []time.Time
+ // owners is the distinct tenants the box's samples were tagged with,
+ // indexed by UnitRow.owner.
+ owners []metrics.Owner
+}
+
+// ownerIndex is tenant's index in v.owners, -1 when no sample carries it.
+func (v BoxMetricsView) ownerIndex(tenant metrics.Owner) int32 {
+ for i, o := range v.owners {
+ if o == tenant {
+ return int32(i)
+ }
+ }
+ return -1
}
// AlertRow is one currently-firing rule on one box. LoadMetrics only ever
@@ -593,6 +611,26 @@ func buildBoxView(box string, samples []metrics.Sample) BoxMetricsView {
for i, sm := range samples {
view.times[i] = sm.At
}
+ index := map[metrics.Owner]int32{}
+ for r := range view.Units {
+ name := view.Units[r].Unit
+ series := make([]int32, len(samples))
+ for i, sm := range samples {
+ series[i] = -1
+ u, ok := sm.Units[name]
+ if !ok || u.Owner == nil {
+ continue
+ }
+ k, seen := index[*u.Owner]
+ if !seen {
+ k = int32(len(view.owners))
+ index[*u.Owner] = k
+ view.owners = append(view.owners, *u.Owner)
+ }
+ series[i] = k
+ }
+ view.Units[r].owner = series
+ }
return view
}
@@ -666,20 +704,33 @@ func unitRawMem(samples []metrics.Sample, unit string) []int64 {
// since, the memory one scaled to the peak within them. ok is false when
// the unit has no sample there at all.
func sparksSince(times []time.Time, u UnitRow, since time.Time) (cpu, mem string, ok bool) {
+ return sparksWhere(times, u, since, nil)
+}
+
+// sparksWhere is sparksSince drawn from only the samples keep accepts (all
+// of them when keep is nil): a remote row's graph is redrawn from the
+// samples tagged with its tenant alone, the memory one scaled to the peak
+// within those. ok is false when no sample qualifies.
+func sparksWhere(times []time.Time, u UnitRow, since time.Time, keep func(i int) bool) (cpu, mem string, ok bool) {
if len(times) != len(u.cpu) || len(times) != len(u.mem) {
return "", "", false
}
k := sort.Search(len(times), func(i int) bool { return !times[i].Before(since) })
- if k >= len(times) {
+ var idx []int
+ for i := k; i < len(times); i++ {
+ if keep == nil || keep(i) {
+ idx = append(idx, i)
+ }
+ }
+ if len(idx) == 0 {
return "", "", false
}
- n := len(times) - k
- cs := make([]*float64, n)
+ cs := make([]*float64, len(idx))
var peak int64
- for i := k; i < len(times); i++ {
+ for j, i := range idx {
if c := u.cpu[i]; !math.IsNaN(float64(c)) {
f := float64(c)
- cs[i-k] = &f
+ cs[j] = &f
}
if u.mem[i] > peak {
peak = u.mem[i]
@@ -687,11 +738,11 @@ func sparksSince(times []time.Time, u UnitRow, since time.Time) (cpu, mem string
}
var ms []*float64
if peak > 0 {
- ms = make([]*float64, n)
- for i := k; i < len(times); i++ {
+ ms = make([]*float64, len(idx))
+ for j, i := range idx {
if u.mem[i] >= 0 {
f := float64(u.mem[i]) / float64(peak)
- ms[i-k] = &f
+ ms[j] = &f
}
}
}
@@ -791,16 +842,23 @@ func (m InstanceMetrics) Reporting() bool { return m.Box != "" }
// readings, Reporting false), never zeros and never silently dropped — an
// owner whose instance is asleep must still see it listed.
func (s *Server) OwnerAppMetrics(ctx context.Context, hosts []string, unitByHost map[string]string) ([]InstanceMetrics, error) {
- return s.ownerAppMetricsFrom(ctx, hosts, unitByHost, nil)
+ return s.ownerAppMetricsFrom(ctx, hosts, unitByHost, nil, nil)
}
// ownerAppMetricsFrom is OwnerAppMetrics where sinceByHost bounds a host's
// readings by when its current owner's route or record came to exist
// (graphs redrawn from later samples only; a zero time is no readings). A
-// host not named there reads as before: the freshest box's sample. Only
-// instances on the console's own box are ever asked for: an instance on
-// another box takes no readings (remoteinstances.go).
-func (s *Server) ownerAppMetricsFrom(ctx context.Context, hosts []string, unitByHost map[string]string, sinceByHost map[string]time.Time) ([]InstanceMetrics, error) {
+// host not named there reads as before: the freshest box's sample.
+//
+// tenantByHost names the hosts that live on another box (remote rows) and
+// the tenant their record names. Such a host reads ONLY samples the box
+// tagged with exactly that tenant (docs/superpowers/notes/remote-instance-metrics.md):
+// a box counts only when the unit's newest sample carries the tag, and the
+// graphs are drawn from tagged samples alone. No tag (a box built before
+// tagging, or a reading the box would not vouch for), another tenant's tag
+// or no start in sinceByHost means nothing from that box. The hostname is
+// never enough: it changes hands. This is the one place the rule lives.
+func (s *Server) ownerAppMetricsFrom(ctx context.Context, hosts []string, unitByHost map[string]string, sinceByHost map[string]time.Time, tenantByHost map[string]metrics.Owner) ([]InstanceMetrics, error) {
// The allowlist, keyed by the unit names each host can legally match.
// Matching is exact-string on this map: a unit the caller did not ask
// for cannot be reached by any path below.
@@ -856,9 +914,22 @@ func (s *Server) ownerAppMetricsFrom(ctx context.Context, hosts []string, unitBy
// readings at all; with a newest sample older than the start,
// not even the current one.
since, bounded := sinceByHost[host]
+ tenant, strict := tenantByHost[host]
+ if strict && !bounded {
+ continue // a remote row with no known start reads nothing
+ }
if bounded && (since.IsZero() || box.At.Before(since)) {
continue
}
+ var tagged func(i int) bool
+ if strict {
+ k := box.ownerIndex(tenant)
+ n := len(u.owner)
+ if k < 0 || n == 0 || n != len(box.times) || u.owner[n-1] != k {
+ continue // the newest reading is not this tenant's
+ }
+ tagged = func(i int) bool { return u.owner[i] == k }
+ }
// A host that reports on two boxes at once (a move in flight)
// shows the freshest box's reading, not whichever sorted first.
if prev, taken := at[host]; taken && !box.At.After(prev) {
@@ -874,7 +945,10 @@ func (s *Server) ownerAppMetricsFrom(ctx context.Context, hosts []string, unitBy
SparkCPU: u.SparkCPU,
SparkMem: u.SparkMem,
}
- if bounded && (len(box.times) == 0 || box.times[0].Before(since)) {
+ if strict {
+ // Only this tenant's tagged samples since its record.
+ row.SparkCPU, row.SparkMem, _ = sparksWhere(box.times, u, since, tagged)
+ } else if bounded && (len(box.times) == 0 || box.times[0].Before(since)) {
// Part of the window predates the owner: redraw from only
// their samples, or draw nothing when that cannot be done.
row.SparkCPU, row.SparkMem, _ = sparksSince(box.times, u, since)
diff --git a/internal/console/overview.go b/internal/console/overview.go
index 0f6a5cc69..2d0c7eb9a 100644
--- a/internal/console/overview.go
+++ b/internal/console/overview.go
@@ -56,14 +56,15 @@ type OverviewStats struct {
// MetricsUnavailable: the sweep itself failed (nil metrics) while an
// instance on the console's own box needed it, which is "readings
// unavailable", not "zero instances reporting". The Running tile and
- // the verdict read it. An instance on another box takes no readings
- // (appResourceMetrics), so an app with none on this box has nothing the
- // sweep could fail at: its tile counts the box reports' awake state.
+ // the verdict read it. An instance on another box has its state from
+ // its box report even when the sweep fails, so an app with none on
+ // this box keeps counting the reports' awake state; its readings, only
+ // samples tagged with its own tenant (remote-instance-metrics), are
+ // extra evidence it is running.
MetricsUnavailable bool
- // ResourcesUnavailable: no readings were taken at all (nil metrics),
- // whether the sweep failed or every instance is on another box. The
- // Resources tile's "no data right now" reads it; remote CPU and memory
- // are not shown.
+ // ResourcesUnavailable: no readings were taken at all (nil metrics):
+ // the sweep failed, or the app has no instance. The Resources tile's
+ // "no data right now" reads it.
ResourcesUnavailable bool
// InstanceExpected is how many of this account's routes are lifecycle-
@@ -122,9 +123,9 @@ type OverviewStats struct {
func assembleOverview(view *AppView, acct string, metrics []InstanceMetrics, versions []VersionView, dbJoin boxJoin) OverviewStats {
st := OverviewStats{ResourcesUnavailable: metrics == nil}
unknownInstances := 0
- // localInstances is how many of the account's instances the sweep was
- // asked for: only those on the console's own box (appResourceMetrics).
- // With none, a nil read is no sweep, not a failed one.
+ // localInstances is how many of the account's instances are on the
+ // console's own box, whose state rests on the sweep alone. With none,
+ // a failed sweep leaves every state to the box reports.
localInstances := 0
st.Deployment = observedDeployment(view.Routes, acct)
reporting := make(map[string]bool, len(metrics))
diff --git a/internal/console/remoteinstances.go b/internal/console/remoteinstances.go
index 60bf9f849..d7096fdf0 100644
--- a/internal/console/remoteinstances.go
+++ b/internal/console/remoteinstances.go
@@ -36,6 +36,7 @@ import (
"sync"
"time"
+ "github.com/carlosframework/platform/internal/metrics"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/regionlabel"
"github.com/carlosframework/platform/internal/registry"
@@ -391,9 +392,10 @@ type remoteRows struct {
// Asleep, Not responding or Serving. That includes static sites and
// instances that never sleep, which the rollout report does not cover.
//
-// No metrics: a remote row takes no CPU or memory readings and no graphs
-// (appResourceMetrics skips it), since no sample on any box is proven to
-// be this owner's. Unit and Caps are deliberately empty. Restartable is false: the browser restart door acts on the console box's
+// Metrics: a remote row reads only samples its box tagged with the
+// record's own account and app, from the record's created_at on
+// (RouteView.tenant and since; ownerAppMetricsFrom). The hostname alone is
+// never enough. Unit and Caps are deliberately empty. Restartable is false: the browser restart door acts on the console box's
// registry only.
func remoteRoute(rec provision.Record, rep *hostReport, f appFacts, acct string, dns DNSTargets) (RouteView, DomainView) {
kind := rec.Kind
@@ -412,6 +414,9 @@ func remoteRoute(rec provision.Record, rep *hostReport, f appFacts, acct string,
Environment: rec.Environment,
Provisioned: true,
remote: true,
+ tenant: metrics.Owner{Account: rec.Account, App: rec.App},
+ since: rec.CreatedAt,
+ bounded: true,
}
typ := "custom"
if strings.HasPrefix(ch, "canary/") {
diff --git a/internal/console/remoteinstances_round2_test.go b/internal/console/remoteinstances_round2_test.go
index ae36f2a9c..afa015f08 100644
--- a/internal/console/remoteinstances_round2_test.go
+++ b/internal/console/remoteinstances_round2_test.go
@@ -75,7 +75,7 @@ func TestOwnerMetricsSinceRules(t *testing.T) {
twoSamples(t, fx.rel, "box-x", "carlos-exec@"+host, time.Now().Add(-3*time.Hour), time.Now().Add(-90*time.Second))
for name, since := range map[string]time.Time{"unknown start": {}, "start after the newest sample": time.Now().Add(-time.Minute)} {
fx.srv.metricsCache = metricsCache{}
- am, err := fx.srv.ownerAppMetricsFrom(context.Background(), []string{host}, nil, map[string]time.Time{host: since})
+ am, err := fx.srv.ownerAppMetricsFrom(context.Background(), []string{host}, nil, map[string]time.Time{host: since}, nil)
if err != nil {
t.Fatal(err)
}
diff --git a/internal/console/remoteinstances_round6_test.go b/internal/console/remoteinstances_round6_test.go
index ec0a917ee..6258057b2 100644
--- a/internal/console/remoteinstances_round6_test.go
+++ b/internal/console/remoteinstances_round6_test.go
@@ -12,12 +12,15 @@ import (
"github.com/carlosframework/platform/internal/status"
)
-// Astra round 6, P1 #1: remote rows take no metrics. Every box that could
-// hold a sample of the remote host's unit has a fresh one (its own box, the
-// console's box, a third box), and its own box's rollout says it is asleep.
-// No remote row on any page, nor `carlos instances list`, may carry a
-// reading, a graph or a Running word drawn from a sample. The local row on
-// the console's box keeps its readings.
+// Astra round 6, P1 #1: remote rows took no metrics. Since
+// remote-instance-metrics they take only samples their box tagged with the
+// record's tenant, so this is now the untagged case (a box built before
+// tagging): every box that could hold a sample of the remote host's unit
+// has a fresh, untagged one (its own box, the console's box, a third box),
+// and its own box's rollout says it is asleep. No remote row on any page,
+// nor `carlos instances list`, may carry a reading, a graph or a Running
+// word drawn from a sample. The local row on the console's box keeps its
+// readings.
func TestRemoteRowsNeverCarrySamples(t *testing.T) {
tb := newTwoBoxes(t)
tb.setUp(t, true)
@@ -47,8 +50,10 @@ func TestRemoteRowsNeverCarrySamples(t *testing.T) {
}
local := false
for _, m := range tb.fx.srv.appResourceMetrics(context.Background(), &views[0], tb.account(t)) {
- if remote[m.Host] {
- t.Fatalf("a remote row carries a metrics row: %+v", m)
+ // Since remote-instance-metrics a remote row has a metrics row, but
+ // an untagged sample is never its reading.
+ if remote[m.Host] && (m.Reporting() || m.CPUFrac != nil || m.MemBytes != nil || m.SparkCPU != "") {
+ t.Fatalf("a remote row carries an untagged reading: %+v", m)
}
if m.Host == localHost && m.Reporting() && m.CPUFrac != nil {
local = true
diff --git a/internal/console/remotemetrics_test.go b/internal/console/remotemetrics_test.go
new file mode 100644
index 000000000..ff2cdc166
--- /dev/null
+++ b/internal/console/remotemetrics_test.go
@@ -0,0 +1,461 @@
+package console
+
+// CPU and memory for instances on other boxes, with samples tagged by the
+// box with the tenant whose process they measured
+// (docs/superpowers/notes/remote-instance-metrics.md). The fixture is
+// remoteinstances_test.go's: two boxes and one bucket, instances created
+// through the console's create and delete doors, minted by each box's real
+// reconcile pass, reported by each box's real status snapshot. Each box's
+// samples are tagged by the box's own rule (metrics.Vouched over the box's
+// real registry rows, then metrics.TagUnits), with the box activator's
+// view of its live entries as the one stand-in, and written with
+// metrics.WriteRaw as the sampler's flush writes them.
+
+import (
+ "context"
+ "net/http"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/metrics"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/status"
+)
+
+// boxSample is one sampler tick on a box: units read at at, tagged by the
+// box's rule over its own registry rows and its activator's live entries.
+func boxSample(t *testing.T, reg *registry.Registry, live map[string]metrics.Live, at time.Time, units map[string]metrics.UnitSample) metrics.Sample {
+ t.Helper()
+ routes, err := reg.List()
+ if err != nil {
+ t.Fatal(err)
+ }
+ v := metrics.Vouched(routes, live, nil)
+ metrics.TagUnits(units, v, v)
+ return metrics.Sample{At: at, Units: units}
+}
+
+// writeSamples flushes a box's samples, one raw chunk per hour, replacing
+// what the hour held.
+func writeSamples(t *testing.T, rel release.Store, box string, samples ...metrics.Sample) {
+ t.Helper()
+ byHour := map[string][]metrics.Sample{}
+ var hours []string
+ for _, s := range samples {
+ h := metrics.HourOf(s.At)
+ if _, ok := byHour[h]; !ok {
+ hours = append(hours, h)
+ }
+ byHour[h] = append(byHour[h], s)
+ }
+ for _, h := range hours {
+ if err := metrics.WriteRaw(context.Background(), rel, metrics.RawChunk{V: 1, Box: box, Hour: h, Samples: byHour[h]}); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+// fresh drops the console's held reads, as a minute passing would.
+func (tb *twoBoxes) fresh() {
+ tb.fx.srv.boxReports.expire()
+ tb.fx.srv.metricsCache = metricsCache{}
+}
+
+func execUnit(host string) string { return "carlos-exec@" + host }
+
+// remoteMetricsRow is the remote row's metrics row from the app pages' own
+// reader (appResourceMetrics), or a zero row.
+func (tb *twoBoxes) remoteMetricsRow(t *testing.T, host string) InstanceMetrics {
+ t.Helper()
+ views, err := tb.fx.srv.assembleApps(context.Background(), tb.sqid, []string{"shop"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, m := range tb.fx.srv.appResourceMetrics(context.Background(), &views[0], tb.account(t)) {
+ if m.Host == host {
+ return m
+ }
+ }
+ return InstanceMetrics{}
+}
+
+// noRemoteReadings fails if any app page, the remote row's metrics or
+// `carlos instances list` carries one of bad, or calls the remote row
+// Running from a reading.
+func (tb *twoBoxes) noRemoteReadings(t *testing.T, bad ...string) {
+ t.Helper()
+ if m := tb.remoteMetricsRow(t, remoteHost); m.Reporting() || m.CPUFrac != nil || m.MemBytes != nil || m.SparkCPU != "" || m.SparkMem != "" {
+ t.Fatalf("the remote row carries a reading: %+v", m)
+ }
+ for _, path := range []string{"/apps/shop", "/apps/shop/instances", "/apps/shop/instances/" + remoteHost} {
+ body := tb.page(t, path)
+ for _, b := range bad {
+ if strings.Contains(body, b) {
+ t.Fatalf("%s shows %q:\n%s", path, b, body)
+ }
+ }
+ }
+ if row := instanceRow(t, tb.page(t, "/apps/shop/instances"), remoteHost); strings.Contains(row, "<polyline") {
+ t.Fatalf("the remote row drew a graph: %s", row)
+ }
+ if code, _, out := rawReq(t, http.MethodGet, instancesURL(tb.fx, tb.sqid, "shop"), tb.token, ""); code != http.StatusOK || strings.Contains(out, `"health":"Running"`) {
+ t.Fatalf("instances list = %d %s", code, out)
+ }
+}
+
+// TestRemoteMetricsShowTheOwnersTaggedSamples is the feature: B's samples
+// of this account's instance, tagged with this account and app, are its
+// readings, graphs and Running state on every page.
+func TestRemoteMetricsShowTheOwnersTaggedSamples(t *testing.T) {
+ tb := newTwoBoxes(t)
+ tb.setUp(t, false)
+ // Asleep by B's rollout report: Running comes from the reading alone.
+ report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096)
+ live := map[string]metrics.Live{remoteHost: {Account: tb.sqid, App: "shop", Entry: 1}}
+ now := time.Now().UTC()
+ var samples []metrics.Sample
+ for i, cpu := range []float64{0.10, 0.18, 0.27} {
+ samples = append(samples, boxSample(t, tb.regB, live, now.Add(time.Duration(i)*time.Second), map[string]metrics.UnitSample{
+ execUnit(remoteHost): {CPUFrac: p(cpu), MemBytes: pi64(int64(i+1) << 20)},
+ }))
+ }
+ if o := samples[2].Units[execUnit(remoteHost)].Owner; o == nil || o.Account != tb.sqid {
+ t.Fatalf("fixture: box B did not tag its own tenant's sample: %+v", o)
+ }
+ writeSamples(t, tb.fx.rel, status.Label("box-b"), samples...)
+ tb.fresh()
+
+ m := tb.remoteMetricsRow(t, remoteHost)
+ if !m.Reporting() || m.CPUFrac == nil || *m.CPUFrac != 0.27 || m.MemBytes == nil || *m.MemBytes != 3<<20 {
+ t.Fatalf("remote metrics row = %+v", m)
+ }
+ if n := len(strings.Fields(m.SparkCPU)); n != 3 {
+ t.Fatalf("CPU graph has %d points, want the 3 tagged samples: %q", n, m.SparkCPU)
+ }
+ ov := tb.page(t, "/apps/shop")
+ for _, want := range []string{"27%", "3.0 MB"} {
+ if !strings.Contains(ov, want) {
+ t.Fatalf("overview is missing %q:\n%s", want, ov)
+ }
+ }
+ if strings.Contains(ov, "no data right now") {
+ t.Fatalf("overview still says no data:\n%s", ov)
+ }
+ row := instanceRow(t, tb.page(t, "/apps/shop/instances"), remoteHost)
+ if !strings.Contains(row, "Running") || !strings.Contains(row, "27%") || !strings.Contains(row, "<polyline") {
+ t.Fatalf("Running row = %s", row)
+ }
+ if inst := tb.page(t, "/apps/shop/instances/"+remoteHost); !strings.Contains(inst, "27%") || !strings.Contains(inst, "3.0 MB") {
+ t.Fatalf("instance page lacks the readings:\n%s", inst)
+ }
+ if code, _, out := rawReq(t, http.MethodGet, instancesURL(tb.fx, tb.sqid, "shop"), tb.token, ""); code != http.StatusOK || !strings.Contains(out, `"health":"Running"`) {
+ t.Fatalf("instances list = %d %s", code, out)
+ }
+}
+
+// TestRemoteMetricsReusedHostname: another account held the hostname on B
+// and deleted it; this account created it again. Until B reconciles, B
+// still runs the predecessor's process under the predecessor's row, and
+// its samples, taken after this account's record was created, are tagged
+// with the predecessor. After B reconciles, the predecessor's entry may
+// still be stopping: B's row names this account and its activator the
+// predecessor, so B vouches nothing. Neither ever shows here.
+func TestRemoteMetricsReusedHostname(t *testing.T) {
+ tb := newTwoBoxes(t)
+ ctx := context.Background()
+ now := time.Now()
+ const rivalID int64 = 6363
+ rival := accountSqid(rivalID)
+ if err := tb.fx.st.CreateAccount(rivalID, rival, "Rival", "bob@keymail.dev", now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := tb.fx.st.CreateAppIn(rivalID, "shop", "bob@keymail.dev", now); err != nil {
+ t.Fatal(err)
+ }
+ if err := WriteAccountManifest(ctx, tb.fx.rel, rivalID, rival, "Rival", now); err != nil {
+ t.Fatal(err)
+ }
+ if err := provision.PutManifest(ctx, tb.fx.rel, rival, "shop", shopManifest("shop", "shop.example.com")); err != nil {
+ t.Fatal(err)
+ }
+ shipAndPromote(t, tb.fx, rival, "shop", "v3", "stable")
+ bob := cliToken(t, tb.fx, "bob@keymail.dev", "code-reuse-bob")
+ tb.fx.setUser("paul@keymail.dev")
+
+ // The predecessor: the rival's instance, minted on B.
+ tb.create(t, bob, rival, "shop", remoteHost, "uk", "")
+ tb.reconcile(t, "v3")
+ if rt, _ := tb.regB.Get(remoteHost); rt == nil || rt.Account != rival {
+ t.Fatalf("fixture: B's row = %+v, want the rival's", rt)
+ }
+ rivalLive := map[string]metrics.Live{remoteHost: {Account: rival, App: "shop", Entry: 1}}
+ before := boxSample(t, tb.regB, rivalLive, time.Now().UTC(), map[string]metrics.UnitSample{
+ execUnit(remoteHost): {CPUFrac: p(0.61), MemBytes: pi64(11 << 20)},
+ })
+
+ // The rival deletes it; this account creates the same hostname. B has
+ // not reconciled.
+ if code, _, out := rawReq(t, http.MethodDelete, instancesURL(tb.fx, rival, "shop")+"/"+remoteHost, bob, ""); code/100 != 2 {
+ t.Fatalf("rival delete = %d %s", code, out)
+ }
+ tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "")
+ recs, _, err := provision.ListRecords(ctx, tb.fx.rel, tb.sqid, "shop", 10)
+ if err != nil || len(recs) != 1 {
+ t.Fatalf("records = %+v %v", recs, err)
+ }
+ afterCreate := recs[0].CreatedAt.Add(2 * time.Second)
+ pending := boxSample(t, tb.regB, rivalLive, afterCreate, map[string]metrics.UnitSample{
+ execUnit(remoteHost): {CPUFrac: p(0.66), MemBytes: pi64(7 << 20)},
+ })
+ if o := pending.Units[execUnit(remoteHost)].Owner; o == nil || o.Account != rival {
+ t.Fatalf("fixture: B tagged its predecessor's sample %+v, want the rival", o)
+ }
+
+ // B reconciles. With no lifetime judge it leaves another tenant's row
+ // alone while this account's record exists, so it still runs the
+ // predecessor as the predecessor's.
+ tb.reconcile(t, "v3")
+ if rt, _ := tb.regB.Get(remoteHost); rt == nil || rt.Account != rival {
+ t.Fatalf("fixture: B's row = %+v, want the rival's still", rt)
+ }
+ stuck := boxSample(t, tb.regB, rivalLive, afterCreate.Add(30*time.Second), map[string]metrics.UnitSample{
+ execUnit(remoteHost): {CPUFrac: p(0.63), MemBytes: pi64(13 << 20)},
+ })
+ // A box with a lifetime judge withdraws the predecessor's row first
+ // (TestCrossOwnerRecreationWithdrawsThePredecessorRow), then mints this
+ // account's; the rival's entry is still stopping.
+ if err := tb.regB.Delete(remoteHost); err != nil {
+ t.Fatal(err)
+ }
+ tb.reconcile(t, "v3")
+ if rt, _ := tb.regB.Get(remoteHost); rt == nil || rt.Account != tb.sqid {
+ t.Fatalf("fixture: B's row after reconcile = %+v", rt)
+ }
+ stopping := boxSample(t, tb.regB, rivalLive, afterCreate.Add(time.Minute), map[string]metrics.UnitSample{
+ execUnit(remoteHost): {CPUFrac: p(0.55), MemBytes: pi64(9 << 20)},
+ })
+ if o := stopping.Units[execUnit(remoteHost)].Owner; o != nil {
+ t.Fatalf("fixture: B vouched %+v while its row and activator disagree", o)
+ }
+ writeSamples(t, tb.fx.rel, status.Label("box-b"), before, pending, stuck, stopping)
+ report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096)
+ tb.fresh()
+
+ tb.noRemoteReadings(t, "61%", "11 MB", "66%", "7.0 MB", "63%", "13 MB", "55%", "9.0 MB")
+}
+
+// TestRemoteMetricsSuccessorNotShownToOldOwner: this account's page still
+// shows its record while B already runs the hostname for another account
+// (B reconciled the successor; the console's read of the records is up to
+// a minute old). B's samples are tagged with the successor, and none show.
+func TestRemoteMetricsSuccessorNotShownToOldOwner(t *testing.T) {
+ tb := newTwoBoxes(t)
+ tb.setUp(t, false)
+ const successor = "rvl"
+ rt, err := tb.regB.Get(remoteHost)
+ if err != nil || rt == nil {
+ t.Fatalf("fixture: %+v %v", rt, err)
+ }
+ // B's row as B minted it for the successor's record.
+ if err := tb.regB.Delete(remoteHost); err != nil {
+ t.Fatal(err)
+ }
+ next := *rt
+ next.Account, next.CreatedAt = successor, 0
+ if err := tb.regB.Upsert(next); err != nil {
+ t.Fatal(err)
+ }
+ live := map[string]metrics.Live{remoteHost: {Account: successor, App: "shop", Entry: 2}}
+ s := boxSample(t, tb.regB, live, time.Now().UTC(), map[string]metrics.UnitSample{
+ execUnit(remoteHost): {CPUFrac: p(0.66), MemBytes: pi64(7 << 20)},
+ })
+ if o := s.Units[execUnit(remoteHost)].Owner; o == nil || o.Account != successor {
+ t.Fatalf("fixture: B tagged %+v, want the successor", o)
+ }
+ writeSamples(t, tb.fx.rel, status.Label("box-b"), s)
+ report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) // asleep
+ tb.fresh()
+ tb.noRemoteReadings(t, "66%", "7.0 MB")
+}
+
+// TestRemoteMetricsAnotherAccountsBox: another box, C, serves the same
+// hostname for another account (a stale copy, or that account's own
+// instance) and tags its samples with that account. B, this instance's box,
+// has no sample. Nothing of C's shows.
+func TestRemoteMetricsAnotherAccountsBox(t *testing.T) {
+ tb := newTwoBoxes(t)
+ tb.setUp(t, false)
+ regC, err := registry.Open(filepath.Join(t.TempDir(), "registry-c.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { regC.Close() })
+ if err := regC.Upsert(registry.Route{Host: remoteHost, Kind: "instance", Account: "rvl", App: "shop", Provisioned: true, Hibernate: true}); err != nil {
+ t.Fatal(err)
+ }
+ live := map[string]metrics.Live{remoteHost: {Account: "rvl", App: "shop", Entry: 1}}
+ s := boxSample(t, regC, live, time.Now().UTC(), map[string]metrics.UnitSample{
+ execUnit(remoteHost): {CPUFrac: p(0.66), MemBytes: pi64(7 << 20)},
+ })
+ writeSamples(t, tb.fx.rel, status.Label("box-b"), metrics.Sample{At: time.Now().UTC()})
+ writeSamples(t, tb.fx.rel, status.Label("box-c"), s)
+ report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) // asleep
+ tb.fresh()
+ tb.noRemoteReadings(t, "66%", "7.0 MB")
+}
+
+// TestRemoteMetricsGraphOnlyTheOwnersSamples: B's window for the unit
+// holds samples of three kinds: this account's before its record was
+// created (an earlier instance of the same hostname), another account's,
+// and this account's since. The graph is drawn from the last kind alone;
+// and once the newest sample is not this account's, there is no current
+// reading at all.
+func TestRemoteMetricsGraphOnlyTheOwnersSamples(t *testing.T) {
+ tb := newTwoBoxes(t)
+ tb.setUp(t, false)
+ recs, _, err := provision.ListRecords(context.Background(), tb.fx.rel, tb.sqid, "shop", 10)
+ if err != nil || len(recs) != 1 {
+ t.Fatalf("records = %+v %v", recs, err)
+ }
+ created := recs[0].CreatedAt
+ own := &metrics.Owner{Account: tb.sqid, App: "shop"}
+ other := &metrics.Owner{Account: "rvl", App: "shop"}
+ sample := func(at time.Time, cpu float64, o *metrics.Owner) metrics.Sample {
+ return metrics.Sample{At: at.UTC(), Units: map[string]metrics.UnitSample{
+ execUnit(remoteHost): {CPUFrac: p(cpu), MemBytes: pi64(1 << 20), Owner: o},
+ }}
+ }
+ window := []metrics.Sample{
+ sample(created.Add(-2*time.Minute), 0.91, own), // before the record
+ sample(created.Add(-time.Minute), 0.92, other), // another tenant
+ sample(created.Add(time.Second), 0.20, own), // this tenant
+ sample(created.Add(2*time.Second), 0.93, other), // another tenant
+ sample(created.Add(3*time.Second), 0.30, own), // this tenant, newest
+ }
+ writeSamples(t, tb.fx.rel, status.Label("box-b"), window...)
+ tb.fresh()
+ m := tb.remoteMetricsRow(t, remoteHost)
+ if !m.Reporting() || m.CPUFrac == nil || *m.CPUFrac != 0.30 {
+ t.Fatalf("current reading = %+v", m)
+ }
+ if n := len(strings.Fields(m.SparkCPU)); n != 2 {
+ t.Fatalf("graph drawn from %d samples, want this tenant's 2 since its record: %q", n, m.SparkCPU)
+ }
+ if n := len(strings.Fields(m.SparkMem)); n != 2 {
+ t.Fatalf("memory graph drawn from %d samples, want 2: %q", n, m.SparkMem)
+ }
+
+ // The newest sample is another tenant's: no current reading.
+ writeSamples(t, tb.fx.rel, status.Label("box-b"), append(window, sample(created.Add(4*time.Second), 0.94, other))...)
+ tb.fresh()
+ if m := tb.remoteMetricsRow(t, remoteHost); m.Reporting() || m.SparkCPU != "" {
+ t.Fatalf("a remote row read through another tenant's newest sample: %+v", m)
+ }
+ // The newest is untagged (an old box, or a reading the box would not
+ // vouch for): no current reading either.
+ writeSamples(t, tb.fx.rel, status.Label("box-b"), append(window, sample(created.Add(4*time.Second), 0.94, nil))...)
+ tb.fresh()
+ if m := tb.remoteMetricsRow(t, remoteHost); m.Reporting() {
+ t.Fatalf("a remote row read through an untagged newest sample: %+v", m)
+ }
+ // The newest is this account's but another app's.
+ otherApp := &metrics.Owner{Account: tb.sqid, App: "web"}
+ writeSamples(t, tb.fx.rel, status.Label("box-b"), append(window, sample(created.Add(4*time.Second), 0.94, otherApp))...)
+ tb.fresh()
+ if m := tb.remoteMetricsRow(t, remoteHost); m.Reporting() {
+ t.Fatalf("a remote row read another app's sample: %+v", m)
+ }
+ // Only another app of this account was ever sampled: nothing.
+ writeSamples(t, tb.fx.rel, status.Label("box-b"), sample(created.Add(time.Second), 0.95, otherApp), sample(created.Add(2*time.Second), 0.96, otherApp))
+ tb.fresh()
+ if m := tb.remoteMetricsRow(t, remoteHost); m.Reporting() || m.SparkCPU != "" {
+ t.Fatalf("a remote row read only another app's samples: %+v", m)
+ }
+ // Only this account's samples from before its record (an earlier
+ // instance of the hostname): nothing, not even as the current reading.
+ writeSamples(t, tb.fx.rel, status.Label("box-b"), sample(created.Add(-2*time.Minute), 0.97, own), sample(created.Add(-time.Minute), 0.98, own))
+ tb.fresh()
+ if m := tb.remoteMetricsRow(t, remoteHost); m.Reporting() || m.SparkCPU != "" {
+ t.Fatalf("a remote row read samples from before its record: %+v", m)
+ }
+}
+
+// metricsBudgetStore counts the metrics sweep's reads: LISTs and GETs under
+// metrics/ and alerts/.
+type metricsBudgetStore struct {
+ release.Store
+ mu sync.Mutex
+ lists, gets int
+}
+
+func (c *metricsBudgetStore) metricsKey(key string) bool {
+ return strings.HasPrefix(key, "metrics/") || strings.HasPrefix(key, "alerts/")
+}
+
+func (c *metricsBudgetStore) List(ctx context.Context, prefix string) ([]string, error) {
+ if c.metricsKey(prefix) {
+ c.mu.Lock()
+ c.lists++
+ c.mu.Unlock()
+ }
+ return c.Store.List(ctx, prefix)
+}
+
+func (c *metricsBudgetStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ if c.metricsKey(key) {
+ c.mu.Lock()
+ c.gets++
+ c.mu.Unlock()
+ }
+ return c.Store.Get(ctx, key)
+}
+
+func (c *metricsBudgetStore) take() (lists, gets int) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ lists, gets = c.lists, c.gets
+ c.lists, c.gets = 0, 0
+ return lists, gets
+}
+
+// TestRemoteMetricsRequestBudget (Astra round 2 on the note, P2): an app
+// whose instances all live on other boxes used to make no metrics reads.
+// Now its pages read the console's existing shared sweep: on a cold cache,
+// one view pays the sweep's usual cost (a LIST of metrics/boxes/, 48
+// hourly GETs per box, a LIST of alerts/boxes/), and every view, tab and
+// `carlos instances list` within the cache's minute pays nothing. Boxes
+// write nothing new: tags ride the chunks they already flush.
+func TestRemoteMetricsRequestBudget(t *testing.T) {
+ tb := newTwoBoxes(t)
+ tb.setUp(t, false)
+ cs := &metricsBudgetStore{Store: tb.fx.rel}
+ tb.fx.srv.cfg.Releases = cs
+ tb.fresh()
+ cs.take()
+
+ tb.page(t, "/apps/shop")
+ boxes, err := tb.fx.srv.discoverBoxes(context.Background())
+ if err != nil || len(boxes) != 1 {
+ t.Fatalf("fixture: metrics boxes = %v %v", boxes, err)
+ }
+ cs.take() // discoverBoxes' own LIST above
+ tb.fresh()
+ tb.page(t, "/apps/shop")
+ if lists, gets := cs.take(); lists != 2 || gets != metricsSweepHours*len(boxes) {
+ t.Fatalf("cold overview: metrics LISTs %d GETs %d, want 2 and %d", lists, gets, metricsSweepHours*len(boxes))
+ }
+ for _, path := range []string{"/apps/shop", "/apps/shop/instances", "/apps/shop/instances/" + remoteHost} {
+ tb.page(t, path)
+ }
+ if code, _, out := rawReq(t, http.MethodGet, instancesURL(tb.fx, tb.sqid, "shop"), tb.token, ""); code != http.StatusOK {
+ t.Fatalf("instances list = %d %s", code, out)
+ }
+ if lists, gets := cs.take(); lists != 0 || gets != 0 {
+ t.Fatalf("views within the cache's minute: metrics LISTs %d GETs %d, want none", lists, gets)
+ }
+}
diff --git a/internal/console/runningtile_test.go b/internal/console/runningtile_test.go
index 4bb4d02d0..27858f61a 100644
--- a/internal/console/runningtile_test.go
+++ b/internal/console/runningtile_test.go
@@ -81,7 +81,7 @@ func TestRunningTileCountsInstancesOnOtherBoxes(t *testing.T) {
if strings.Contains(ov, "Can&#39;t tell right now") {
t.Fatalf("overview says it can't tell with every remote state known:\n%s", ov)
}
- // Still no remote metrics: the Resources tile is as it was.
+ // The samples are untagged (remote-instance-metrics): no remote reading.
for _, bad := range []string{"27%", "3.0 MB", "v8", "70.0 MB"} {
if strings.Contains(ov, bad) {
t.Fatalf("overview shows %q, a remote reading or another account's report:\n%s", bad, ov)
@@ -91,7 +91,10 @@ func TestRunningTileCountsInstancesOnOtherBoxes(t *testing.T) {
if !strings.Contains(ov, "8.0 KB") {
t.Fatalf("Database tile is not B's two sizes:\n%s", ov)
}
- if i := strings.Index(ov, "<h2>Resources</h2>"); i < 0 || !strings.Contains(ov[i:], "— · —</p>\n <p class=\"tile-detail\">no data right now</p>") {
+ // The sweep was read (remote rows read it too since
+ // remote-instance-metrics) and none of its samples is tagged with this
+ // tenant: no readings, "no recent data", not a failed sweep.
+ if i := strings.Index(ov, "<h2>Resources</h2>"); i < 0 || !strings.Contains(ov[i:], "— · —</p>\n <p class=\"tile-detail\">no recent data</p>") {
t.Fatalf("Resources tile changed:\n%s", ov)
}
}
diff --git a/internal/console/server.go b/internal/console/server.go
index 93ce5ce98..d9884cc49 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -50,6 +50,7 @@ import (
"github.com/carlosframework/platform/internal/infraview"
"github.com/carlosframework/platform/internal/lease"
"github.com/carlosframework/platform/internal/mail"
+ "github.com/carlosframework/platform/internal/metrics"
"github.com/carlosframework/platform/internal/moves"
"github.com/carlosframework/platform/internal/objstore"
"github.com/carlosframework/platform/internal/perf"
@@ -3849,21 +3850,24 @@ func (s *Server) appResourceMetrics(ctx context.Context, view *AppView, acct *Ac
hib := make(map[string]bool, len(view.Routes))
unitByHost := make(map[string]string, len(view.Routes))
sinceByHost := map[string]time.Time{}
+ tenantByHost := map[string]metrics.Owner{}
for _, rt := range view.Routes {
if rt.Account != acct.Sqid {
continue
}
- // An instance on another box takes no readings at all: its host
- // name alone is not this tenant's, since another box may serve it
- // for someone else, and no sample on any box is proven theirs. Its
- // row shows the no-data state (remoteinstances.go).
+ // An instance on another box reads only samples its box tagged
+ // with this record's account and app: its host name alone is not
+ // this tenant's, since the name changes hands and another box may
+ // serve it for someone else (remoteinstances.go,
+ // docs/superpowers/notes/remote-instance-metrics.md).
if rt.remote {
- continue
+ tenantByHost[rt.Host] = rt.tenant
}
// History starts when this owner came to have the host: samples
// from a previous tenant of the same hostname are not theirs. A
- // local row that is provisioned or has a record is bounded
- // (RouteView.bounded); only a hand route with no record is not.
+ // remote row, and a local row that is provisioned or has a record,
+ // is bounded (RouteView.bounded); only a hand route with no record
+ // is not.
if rt.bounded {
sinceByHost[rt.Host] = rt.since
}
@@ -3873,7 +3877,7 @@ func (s *Server) appResourceMetrics(ctx context.Context, view *AppView, acct *Ac
unitByHost[rt.Host] = rt.Unit
}
}
- am, err := s.ownerAppMetricsFrom(ctx, hosts, unitByHost, sinceByHost)
+ am, err := s.ownerAppMetricsFrom(ctx, hosts, unitByHost, sinceByHost, tenantByHost)
if err != nil {
log.Printf("console: app metrics %s: %v", view.App, err)
return nil
diff --git a/internal/console/view.go b/internal/console/view.go
index 51ac01480..bb2d26eb2 100644
--- a/internal/console/view.go
+++ b/internal/console/view.go
@@ -19,6 +19,7 @@ import (
"golang.org/x/net/publicsuffix"
+ "github.com/carlosframework/platform/internal/metrics"
"github.com/carlosframework/platform/internal/perf"
"github.com/carlosframework/platform/internal/regionlabel"
"github.com/carlosframework/platform/internal/registry"
@@ -360,18 +361,22 @@ type RouteView struct {
aliases []string
boxAwake bool
// unknown says the row's process state is not known (remoteRoute):
- // its health reads "Can't tell right now". A remote row takes no
- // metrics readings at all (appResourceMetrics skips it).
+ // its health reads "Can't tell right now".
unknown bool
- // since is when this local row's owner came to have the host: its
- // instance record's created_at (addRemoteRows). Metrics samples before
- // it are not this owner's (ownerAppMetricsFrom).
+ // tenant is a remote row's record's account and app: the only tag its
+ // metrics samples may carry (ownerAppMetricsFrom,
+ // docs/superpowers/notes/remote-instance-metrics.md). Zero on a local
+ // row, whose readings are not filtered by tag.
+ tenant metrics.Owner
+ // since is when this row's owner came to have the host: its instance
+ // record's created_at (addRemoteRows, remoteRoute). Metrics samples
+ // before it are not this owner's (ownerAppMetricsFrom).
since time.Time
- // bounded says since applies to this local row's readings, zero
- // meaning no readings at all: every local row that is provisioned or
- // has a record. A provisioned local row whose record could not be read
- // has an unknown start, so it shows nothing rather than the whole
- // window. Only a hand route with no record is unbounded.
+ // bounded says since applies to this row's readings, zero meaning no
+ // readings at all: every remote row, and every local row that is
+ // provisioned or has a record. A provisioned local row whose record
+ // could not be read has an unknown start, so it shows nothing rather
+ // than the whole window. Only a hand route with no record is unbounded.
bounded bool
}
diff --git a/internal/host/agent.go b/internal/host/agent.go
index e28bf3c75..14a7a47f5 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -193,6 +193,7 @@ import (
"github.com/carlosframework/platform/internal/instancefs"
"github.com/carlosframework/platform/internal/layout"
"github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/metrics"
"github.com/carlosframework/platform/internal/moves"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
@@ -902,7 +903,14 @@ func runAgent(args []string, buildClaims ClaimFactory) {
go steeringLoop(boxJudge)
// The sweep reads the registry only through this closure — the stamped
// bespoke units to sample beside the carlos- ones, re-read each tick.
- go metricsLoop(cgm.Root(), func() []string { return stampedUnitNames(reg) }, alerts)
+ // owners is the sweep's word on whose processes each exec cgroup
+ // holds: the activator's live entries joined to the registry
+ // (metricsOwners). With no activator it tags nothing.
+ var owners func() map[string]metrics.Vouch
+ 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 configSyncLoop(reg, svc, dd, claims.Writes)
go configGenLoop(reg, svc, dd, claims.Writes)
go socketAdvisoryLoop(reg, svc)
diff --git a/internal/host/agentalerts_test.go b/internal/host/agentalerts_test.go
index 149f3a49b..d0debe5c2 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, sinks)
+ metricsLoop(t.TempDir(), nil, nil, sinks)
}
h := newRevertHarness(t)
@@ -130,8 +130,8 @@ func TestAgentArmsPagingBeforeMovesConsumers(t *testing.T) {
if _, ok := at[name]; !ok {
at[name] = n.Pos()
}
- if name == "metricsLoop" && len(n.Args) == 3 {
- metricsArg = n.Args[2]
+ if name == "metricsLoop" && len(n.Args) == 4 {
+ metricsArg = n.Args[3]
}
}
return true
diff --git a/internal/host/metrics_loop.go b/internal/host/metrics_loop.go
index 845876a0c..b963933f8 100644
--- a/internal/host/metrics_loop.go
+++ b/internal/host/metrics_loop.go
@@ -33,7 +33,11 @@ type sampleProbes struct {
memFrac func() *float64
diskFrac func() *float64
units func() map[string]unitRaw
- now func() time.Time
+ // owners is the box's word on whose processes each exec cgroup holds
+ // (metricsOwners), read before and after units so a reading is tagged
+ // only when nothing changed during it. nil tags nothing.
+ owners func() map[string]metrics.Vouch
+ now func() time.Time
}
// samplerMaxBuf hard-caps sm.buf at ~2h of 60s ticks. metricsFlush only
@@ -57,7 +61,8 @@ const samplerMaxBuf = 120
// process for the first time in the same call.
type sampler struct {
prevCPU *metrics.CPUCounters
- prevUnit map[string]*int64 // unit -> cpu usec at previous tick
+ prevUnit map[string]*int64 // unit -> cpu usec at previous tick
+ prevOwner map[string]*metrics.Owner // unit -> owner vouched at previous tick (nil: none)
prevAt time.Time
buf []metrics.Sample
writtenHours map[string]bool // hour -> this process has written/merged it at least once
@@ -74,7 +79,14 @@ func (sm *sampler) tick(p sampleProbes) {
l1, l5, l15 := p.loadavg()
mem := p.memFrac()
disk := p.diskFrac()
+ var before, after map[string]metrics.Vouch
+ if p.owners != nil {
+ before = p.owners()
+ }
units := p.units()
+ if p.owners != nil {
+ after = p.owners()
+ }
var elapsed time.Duration
if !sm.prevAt.IsZero() {
@@ -102,7 +114,11 @@ func (sm *sampler) tick(p sampleProbes) {
}
newPrevUnit[name] = u.cpuUsec
}
+ metrics.TagUnits(unitSamples, before, after)
}
+ // 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.
+ sm.prevOwner = metrics.CarryTags(unitSamples, sm.prevOwner)
sm.buf = append(sm.buf, metrics.Sample{
At: now,
@@ -603,7 +619,7 @@ 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) sampleProbes {
+func realSampleProbes(execRoot string, stampedUnits func() []string, owners func() map[string]metrics.Vouch) sampleProbes {
return sampleProbes{
procStat: readProcStat,
loadavg: readLoadAvg,
@@ -616,7 +632,8 @@ func realSampleProbes(execRoot string, stampedUnits func() []string) sampleProbe
}
return realUnitReadings(execRoot, stamped)
},
- now: time.Now,
+ owners: owners,
+ now: time.Now,
}
}
@@ -750,10 +767,13 @@ func BoxLabel() string { return metricsBoxLabel(os.Getenv, readMachineID()) }
// minute. It is a func, 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.
+//
// 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, sinks *alertSinks) {
+func metricsLoop(execRoot string, stampedUnits func() []string, 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
@@ -801,7 +821,7 @@ func metricsLoop(execRoot string, stampedUnits func() []string, sinks *alertSink
log.Printf("agent: metrics loop armed (60s ticks, 5min flush), publishing to %s", target)
sm := &sampler{}
- probes := realSampleProbes(execRoot, stampedUnits)
+ probes := realSampleProbes(execRoot, stampedUnits, 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.
diff --git a/internal/host/metrics_owner.go b/internal/host/metrics_owner.go
new file mode 100644
index 000000000..0e8e2ae46
--- /dev/null
+++ b/internal/host/metrics_owner.go
@@ -0,0 +1,43 @@
+package host
+
+import (
+ "log"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/metrics"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// tenancySource is the activator's half of metricsOwners
+// (activator.Service.Tenancies).
+type tenancySource interface {
+ Tenancies() map[string]activator.Tenancy
+}
+
+// metricsOwners is the sampler's one statement of whose processes the box's
+// exec cgroups hold (docs/superpowers/notes/remote-instance-metrics.md):
+// the activator's live entries joined to the registry's rows by
+// metrics.Vouched, leaving out hosts a previous agent left populated. The
+// sampler reads it before and after each cgroup read and tags a unit only
+// when both agree (metrics.TagUnits). The activator is read first, then the
+// registry; nil act (no activator on this box) or an unreadable registry
+// vouches nothing, which tags nothing.
+func metricsOwners(reg *registry.Registry, act tenancySource, leftover func(string) bool) map[string]metrics.Vouch {
+ if act == nil || reg == nil {
+ return nil
+ }
+ ten := act.Tenancies()
+ if len(ten) == 0 {
+ return nil
+ }
+ live := make(map[string]metrics.Live, len(ten))
+ for host, t := range ten {
+ live[host] = metrics.Live{Account: t.Account, App: t.App, Entry: t.Entry}
+ }
+ routes, err := reg.List()
+ if err != nil {
+ log.Printf("agent: metrics: read route owners: %v", err)
+ return nil
+ }
+ return metrics.Vouched(routes, live, leftover)
+}
diff --git a/internal/host/metrics_owner_test.go b/internal/host/metrics_owner_test.go
new file mode 100644
index 000000000..5354e62a1
--- /dev/null
+++ b/internal/host/metrics_owner_test.go
@@ -0,0 +1,155 @@
+package host
+
+import (
+ "context"
+ "encoding/json"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/metrics"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+type stubTenancies struct {
+ next []map[string]activator.Tenancy
+}
+
+// Tenancies answers its queued views in turn, the last one forever.
+func (s *stubTenancies) Tenancies() map[string]activator.Tenancy {
+ v := s.next[0]
+ if len(s.next) > 1 {
+ s.next = s.next[1:]
+ }
+ return v
+}
+
+// TestMetricsOwnersTagsWhatTheBoxVouches is the box half end to end: a
+// real registry, the activator's view, the sampler's tick and flush, and
+// the chunk the console reads. A unit is tagged only when the activator's
+// entry and the registry row name one tenant across the whole read.
+func TestMetricsOwnersTagsWhatTheBoxVouches(t *testing.T) {
+ const own, prev, moved, gone = "own.example.com", "prev.example.com", "moved.example.com", "gone.example.com"
+ reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { reg.Close() })
+ for _, rt := range []registry.Route{
+ {Host: own, Kind: "instance", Account: "bdn", App: "shop", Provisioned: true},
+ // The successor's row, while the predecessor's entry still stops.
+ {Host: prev, Kind: "instance", Account: "bdn", App: "shop", Provisioned: true},
+ {Host: moved, Kind: "instance", Account: "bdn", App: "shop", Provisioned: true},
+ {Host: gone, Kind: "instance", Account: "bdn", App: "shop", Provisioned: true},
+ } {
+ if err := reg.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ }
+ view := func(movedEntry uint64) map[string]activator.Tenancy {
+ return map[string]activator.Tenancy{
+ own: {Account: "bdn", App: "shop", Entry: 1},
+ prev: {Account: "rival", App: "shop", Entry: 2},
+ moved: {Account: "bdn", App: "shop", Entry: movedEntry},
+ gone: {Account: "bdn", App: "shop", Entry: 4},
+ }
+ }
+ // moved gets a new entry between the two reads (a stop and a wake
+ // during the cgroup read); gone is a leftover from a previous agent.
+ src := &stubTenancies{next: []map[string]activator.Tenancy{view(3), view(5)}}
+ owners := func() map[string]metrics.Vouch {
+ return metricsOwners(reg, src, func(h string) bool { return h == gone })
+ }
+
+ f := 0.4
+ at := time.Date(2026, 10, 26, 12, 0, 0, 0, time.UTC)
+ sm := &sampler{}
+ sm.tick(sampleProbes{
+ procStat: func() *metrics.CPUCounters { return nil },
+ loadavg: func() (*float64, *float64, *float64) { return nil, nil, nil },
+ memFrac: func() *float64 { return &f },
+ diskFrac: func() *float64 { return &f },
+ units: func() map[string]unitRaw {
+ out := map[string]unitRaw{}
+ for _, h := range []string{own, prev, moved, gone} {
+ out["carlos-exec@"+h] = unitRaw{}
+ }
+ // A unit-backed tenant is never vouched, whatever the activator says.
+ out["carlos-app@"+own+".service"] = unitRaw{}
+ return out
+ },
+ owners: owners,
+ now: func() time.Time { return at },
+ })
+ store := release.NewDirStore(t.TempDir())
+ if err := metricsFlush(context.Background(), store, "box-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 || len(chunk.Samples) != 1 {
+ t.Fatalf("chunk = %s (%v)", body, err)
+ }
+ units := chunk.Samples[0].Units
+ if o := units["carlos-exec@"+own].Owner; o == nil || *o != (metrics.Owner{Account: "bdn", App: "shop"}) {
+ t.Fatalf("own unit owner = %+v", o)
+ }
+ for _, u := range []string{"carlos-exec@" + prev, "carlos-exec@" + moved, "carlos-exec@" + gone, "carlos-app@" + own + ".service"} {
+ if o := units[u].Owner; o != nil {
+ t.Errorf("%s tagged %+v, want untagged", u, o)
+ }
+ }
+}
+
+// TestMetricsOwnersWithoutAnActivator: a box with no activator vouches
+// nothing.
+func TestMetricsOwnersWithoutAnActivator(t *testing.T) {
+ reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { reg.Close() })
+ if got := metricsOwners(reg, nil, nil); len(got) != 0 {
+ t.Fatalf("vouched %+v with no activator", got)
+ }
+}
+
+// TestSamplerDeltaNeedsBothTicksVouched is Astra's round 1 finding on the
+// note: tick N reads tenant A's counter, A stops, B starts in the same
+// cgroup with a larger counter, and both reads at tick N+1 agree on B. The
+// CPU fraction at N+1 is a delta from A's counter, so it is not B's: the
+// reading stays untagged. The tick after that is B's on both ends.
+func TestSamplerDeltaNeedsBothTicksVouched(t *testing.T) {
+ const unit = "carlos-exec@own.example.com"
+ a := map[string]metrics.Vouch{unit: {Owner: metrics.Owner{Account: "rival", App: "shop"}, Entry: 1}}
+ b := map[string]metrics.Vouch{unit: {Owner: metrics.Owner{Account: "bdn", App: "shop"}, Entry: 2}}
+ f := 0.4
+ at := time.Date(2026, 10, 26, 12, 0, 0, 0, time.UTC)
+ sm := &sampler{}
+ tick := func(usec int64, owners map[string]metrics.Vouch, now time.Time) metrics.UnitSample {
+ sm.tick(sampleProbes{
+ procStat: func() *metrics.CPUCounters { return nil },
+ loadavg: func() (*float64, *float64, *float64) { return nil, nil, nil },
+ memFrac: func() *float64 { return &f },
+ diskFrac: func() *float64 { return &f },
+ units: func() map[string]unitRaw { return map[string]unitRaw{unit: {cpuUsec: &usec}} },
+ owners: func() map[string]metrics.Vouch { return owners },
+ now: func() time.Time { return now },
+ })
+ return sm.buf[len(sm.buf)-1].Units[unit]
+ }
+ if u := tick(5_000_000, a, at); u.Owner == nil || u.Owner.Account != "rival" {
+ t.Fatalf("tick N = %+v, want A's", u.Owner)
+ }
+ if u := tick(20_000_000, b, at.Add(time.Minute)); u.Owner != nil || u.CPUFrac == nil {
+ t.Fatalf("tick N+1 = owner %+v cpu %v: a delta from A's counter was tagged as B's", u.Owner, u.CPUFrac)
+ }
+ if u := tick(23_000_000, b, at.Add(2*time.Minute)); u.Owner == nil || u.Owner.Account != "bdn" {
+ t.Fatalf("tick N+2 = %+v, want B's", u.Owner)
+ }
+}
diff --git a/internal/metrics/owner.go b/internal/metrics/owner.go
new file mode 100644
index 000000000..04951d0be
--- /dev/null
+++ b/internal/metrics/owner.go
@@ -0,0 +1,99 @@
+package metrics
+
+import (
+ "github.com/carlosframework/platform/internal/cgroup"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// Owner is the tenant whose process a unit's reading measured: the account
+// and app of the route the box's activator started it for. The console
+// shows a reading on an instance that lives on another box only when this
+// names the account and app of the record it is showing
+// (docs/superpowers/notes/remote-instance-metrics.md). A tenant, not a
+// lifetime: a hostname changes hands between tenants only through its
+// row's account or app changing.
+type Owner struct {
+ Account string `json:"account"`
+ App string `json:"app"`
+}
+
+// Live is the activator's word on one host: the tenant of the route its
+// live entry was started for, and that entry's number, which is new for
+// every new entry (activator.Service.Tenancies).
+type Live struct {
+ Account, App string
+ Entry uint64
+}
+
+// Vouch is one exec cgroup's tenant at one moment, with the entry that
+// started its processes.
+type Vouch struct {
+ Owner Owner
+ Entry uint64
+}
+
+// Vouched is the box's one statement of whose processes its exec cgroups
+// hold: carlos-exec@<host> is vouched for tenant T only while the
+// activator's live entry for host was started for T, the registry row for
+// host names T too, and host is not a cgroup a previous agent left
+// populated. Nothing else is ever vouched: not carlos-app@ units (systemd
+// runs them, and they can outlive the agent), not stamped or platform
+// units. An empty account or app vouches nothing.
+func Vouched(rows []registry.Route, live map[string]Live, leftover func(host string) bool) map[string]Vouch {
+ if len(live) == 0 {
+ return nil
+ }
+ out := make(map[string]Vouch, len(live))
+ for _, rt := range rows {
+ l, ok := live[rt.Host]
+ if !ok || rt.Account == "" || rt.App == "" || rt.Account != l.Account || rt.App != l.App {
+ continue
+ }
+ if leftover != nil && leftover(rt.Host) {
+ continue
+ }
+ out[cgroup.ExecName(rt.Host)] = Vouch{Owner: Owner{Account: rt.Account, App: rt.App}, Entry: l.Entry}
+ }
+ return out
+}
+
+// TagUnits stamps each unit's reading with its owner when the box vouched
+// for that unit both before and after the cgroup read, for the same tenant
+// and the same activator entry. A wake, a stop or a change of tenant
+// during the read leaves the reading untagged, which no console shows on
+// an instance that lives on another box.
+func TagUnits(units map[string]UnitSample, before, after map[string]Vouch) {
+ for name, u := range units {
+ b, okB := before[name]
+ a, okA := after[name]
+ if !okB || !okA || a != b {
+ continue
+ }
+ o := b.Owner
+ u.Owner = &o
+ units[name] = u
+ }
+}
+
+// CarryTags applies the second half of the tag rule: a unit's CPU fraction
+// is the delta from the previous tick's counter of the same cgroup, so its
+// reading stays tagged only when the previous tick read that unit for the
+// same tenant, or did not read it at all (then there is no delta). prev is
+// the previous tick's vouched owner per unit read (nil for one it did not
+// vouch); the result is this tick's, made before anything is untagged
+// here, for the next call.
+func CarryTags(units map[string]UnitSample, prev map[string]*Owner) map[string]*Owner {
+ next := make(map[string]*Owner, len(units))
+ for name, u := range units {
+ next[name] = u.Owner
+ if u.Owner == nil {
+ continue
+ }
+ p, read := prev[name]
+ if read && (p == nil || *p != *u.Owner) {
+ u.Owner = nil
+ units[name] = u
+ }
+ }
+ return next
+}
diff --git a/internal/metrics/owner_test.go b/internal/metrics/owner_test.go
new file mode 100644
index 000000000..9bfbc1db0
--- /dev/null
+++ b/internal/metrics/owner_test.go
@@ -0,0 +1,138 @@
+package metrics
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+const ownHost = "eu.shop.example.com"
+
+func execUnit(host string) string { return "carlos-exec@" + host }
+
+// TestVouchedJoinsLiveEntryToRow: a host is vouched only while the
+// activator's live entry and the registry row name the same tenant.
+func TestVouchedJoinsLiveEntryToRow(t *testing.T) {
+ shop := Owner{Account: "bdn", App: "shop"}
+ rows := []registry.Route{
+ {Host: ownHost, Account: "bdn", App: "shop"},
+ {Host: "b.example.com", Account: "bdn", App: "shop"},
+ {Host: "c.example.com", Account: "", App: "shop"},
+ {Host: "d.example.com", Account: "bdn", App: "shop"},
+ {Host: "e.example.com", Account: "bdn", App: "shop"},
+ }
+ live := map[string]Live{
+ ownHost: {Account: "bdn", App: "shop", Entry: 7},
+ "b.example.com": {Account: "rival", App: "shop", Entry: 8}, // predecessor still stopping
+ "c.example.com": {Account: "", App: "shop", Entry: 9}, // unstamped row
+ "d.example.com": {Account: "bdn", App: "shop", Entry: 10}, // a leftover cgroup
+ "x.example.com": {Account: "bdn", App: "shop", Entry: 11}, // no row
+ }
+ leftover := func(host string) bool { return host == "d.example.com" }
+ got := Vouched(rows, live, leftover)
+ want := map[string]Vouch{execUnit(ownHost): {Owner: shop, Entry: 7}}
+ if len(got) != len(want) || got[execUnit(ownHost)] != want[execUnit(ownHost)] {
+ t.Fatalf("Vouched = %+v, want %+v", got, want)
+ }
+ for unit := range got {
+ if !strings.HasPrefix(unit, "carlos-exec@") {
+ t.Fatalf("vouched a non-exec unit %q", unit)
+ }
+ }
+ if Vouched(rows, nil, nil) != nil && len(Vouched(rows, nil, nil)) != 0 {
+ t.Fatal("no live entries vouched something")
+ }
+}
+
+// TestTagUnitsNeedsBothReads: a unit is tagged only when the reads before
+// and after the cgroup read agree on the tenant and the entry.
+func TestTagUnitsNeedsBothReads(t *testing.T) {
+ shop := Owner{Account: "bdn", App: "shop"}
+ rival := Owner{Account: "rival", App: "shop"}
+ f := 0.5
+ units := func() map[string]UnitSample {
+ return map[string]UnitSample{execUnit(ownHost): {CPUFrac: &f}, "carlos-edge.service": {CPUFrac: &f}}
+ }
+ cases := []struct {
+ name string
+ before, after map[string]Vouch
+ want *Owner
+ }{
+ {"agree", map[string]Vouch{execUnit(ownHost): {shop, 1}}, map[string]Vouch{execUnit(ownHost): {shop, 1}}, &shop},
+ {"new entry during the read", map[string]Vouch{execUnit(ownHost): {shop, 1}}, map[string]Vouch{execUnit(ownHost): {shop, 2}}, nil},
+ {"tenant changed during the read", map[string]Vouch{execUnit(ownHost): {rival, 1}}, map[string]Vouch{execUnit(ownHost): {shop, 1}}, nil},
+ {"vouched only before", map[string]Vouch{execUnit(ownHost): {shop, 1}}, nil, nil},
+ {"vouched only after", nil, map[string]Vouch{execUnit(ownHost): {shop, 1}}, nil},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ u := units()
+ TagUnits(u, c.before, c.after)
+ got := u[execUnit(ownHost)].Owner
+ if (got == nil) != (c.want == nil) || (got != nil && *got != *c.want) {
+ t.Fatalf("owner = %+v, want %+v", got, c.want)
+ }
+ if u["carlos-edge.service"].Owner != nil {
+ t.Fatal("tagged a unit nothing vouched for")
+ }
+ })
+ }
+}
+
+// TestOwnerWireShape: the tag is additive and omitted when unset, so a
+// chunk without it reads as before and an old reader ignores it.
+func TestOwnerWireShape(t *testing.T) {
+ f := 0.25
+ b, _ := json.Marshal(UnitSample{CPUFrac: &f})
+ if strings.Contains(string(b), "owner") {
+ t.Fatalf("untagged sample carries an owner key: %s", b)
+ }
+ b, _ = json.Marshal(UnitSample{CPUFrac: &f, Owner: &Owner{Account: "bdn", App: "shop"}})
+ if !strings.Contains(string(b), `"owner":{"account":"bdn","app":"shop"}`) {
+ t.Fatalf("tagged sample = %s", b)
+ }
+ var old struct {
+ CPUFrac *float64 `json:"cpu"`
+ }
+ if err := json.Unmarshal(b, &old); err != nil || old.CPUFrac == nil {
+ t.Fatalf("an old reader cannot read a tagged sample: %v", err)
+ }
+}
+
+// TestCarryTagsAcrossTicks: a unit's CPU fraction is a delta from the
+// previous tick's counter, so a reading stays tagged only when the
+// previous tick read the unit for the same tenant, or did not read it at
+// all (no previous counter, no delta). Astra round 1 on the note.
+func TestCarryTagsAcrossTicks(t *testing.T) {
+ shop := &Owner{Account: "bdn", App: "shop"}
+ rival := &Owner{Account: "rival", App: "shop"}
+ f := 0.25
+ tagged := func(o *Owner) UnitSample { return UnitSample{CPUFrac: &f, Owner: o} }
+ cases := []struct {
+ name string
+ prev map[string]*Owner
+ now *Owner
+ want *Owner
+ }{
+ {"first reading of the unit", map[string]*Owner{}, shop, shop},
+ {"same tenant before", map[string]*Owner{"u": {Account: "bdn", App: "shop"}}, shop, shop},
+ {"another tenant before", map[string]*Owner{"u": rival}, shop, nil},
+ {"untagged before", map[string]*Owner{"u": nil}, shop, nil},
+ {"untagged now", map[string]*Owner{"u": shop}, nil, nil},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ units := map[string]UnitSample{"u": tagged(c.now)}
+ next := CarryTags(units, c.prev)
+ got := units["u"].Owner
+ if (got == nil) != (c.want == nil) || (got != nil && *got != *c.want) {
+ t.Fatalf("owner = %+v, want %+v", got, c.want)
+ }
+ if o, ok := next["u"]; !ok || (o == nil) != (c.now == nil) {
+ t.Fatalf("next tick's memory = %+v (present %v), want what the box vouched now (%+v)", o, ok, c.now)
+ }
+ })
+ }
+}
diff --git a/internal/metrics/sample.go b/internal/metrics/sample.go
index da14784a0..1dc4b90eb 100644
--- a/internal/metrics/sample.go
+++ b/internal/metrics/sample.go
@@ -24,6 +24,10 @@ type UnitSample struct {
MemPeakBytes *int64 `json:"mem_peak_bytes"`
ReadBytes *int64 `json:"read_bytes"` // cumulative
WriteBytes *int64 `json:"write_bytes"` // cumulative
+ // Owner is the tenant the box vouches this reading measured (owner.go),
+ // nil when it vouches none. Additive: omitted when unset, so a chunk
+ // from a box built before it reads exactly as it did.
+ Owner *Owner `json:"owner,omitempty"`
}
// Sample is one point-in-time reading of a box: the host as a whole plus
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 9bd705194..3943d3a67 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -2,3 +2,4 @@
# loaded in order onto census-base.tsv. census-propose appends to it.
plan14-root-reads-c2-root-exec-inputs.tsv 0ef813eebfb1a2e2812d897c4f0b5fd7f75e3e39c7602cf64d1634e8374327af
plan14-root-reads-label-case-running-tile.tsv 0ef813eebfb1a2e2812d897c4f0b5fd7f75e3e39c7602cf64d1634e8374327af
+plan14-root-reads-remote-instance-metrics.tsv ed0d770a827bdb37a87d21e5c8efb259ca0de88457b0cb3202ebb006fc0cd032
diff --git a/internal/provision/testdata/plan14-root-reads-remote-instance-metrics.tsv b/internal/provision/testdata/plan14-root-reads-remote-instance-metrics.tsv
new file mode 100644
index 000000000..8e01d9736
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-remote-instance-metrics.tsv
@@ -0,0 +1,36 @@
+# Census overlay remote-instance-metrics, written by census-propose (#369). census-ruling-remote-instance-metrics, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-remote-instance-metrics.md.
+# 12 body, 0 sites, 4 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 a6eb3e02e5814f935d9388a84d59ab4b707ff4013a285b392c9490ac54eedbc9 internal/activator/activator.go Service.WakeWorker legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body; the stop now carries its reason for a run it interrupts (beginStopLocked's why argument); read sites unchanged, offsets moved;rev3=census-ruling-remote-instance-metrics;basis=the entries-map insertion goes through putEntryLocked (which also notes the route's tenant in memory for the metrics sampler); no read added registry:Host@1249,registry:Host@1658,registry:Host@834,registry:Host@864,whole:Route@1225 dab4506e9f7a8b802d2c930222b4775a4b1626c31c4e39ce2f39ca51c3ce37de
+@legacy 0f486d4a3e0c57b860cf6a7966366d9baf83b7b69543f83def56eae800828258 internal/activator/activator.go Service.begin 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; the stop now carries its reason for a run it interrupts (beginStopLocked's why argument); read sites unchanged, offsets moved;rev3=census-ruling-edge-request-records;basis=gains a req *http.Request parameter and one edge.MarkWoke(req) call on the path that starts a wake, so the edge's request record can say which request woke the app; no read added;rev3=census-ruling-remote-instance-metrics;basis=the entries-map insertion goes through putEntryLocked (which also notes the route's tenant in memory for the metrics sampler); no read added registry:Host@1721,registry:Host@1807,registry:Host@345,registry:Host@929,whole:Route@1730,whole:Route@1737 2a6b1e1412a88632293b4bf767f6daf9376d2a00a87d1c27c91eaf02f82da468
+@legacy 59675b94e0210da250a611e302a33102209d5cb39ec40054b743ef9a795ad896 internal/activator/activator.go Service.sweepOnce legacy accepted-legacy accepted-legacy;rev3=PROPOSED-seed;basis=census-ruling-FS-R6; registry remains legacy; PROPOSED-plans-2-box-limits: the sweep also narrows an entry's idle window to its account's plan idle through the SetIdleFor hook (never lengthens it; always-on workers and held probe entries are untouched; the hibernate, inflight and held-for-tick guards are unchanged).;rev3=census-ruling-plans-4c-box-throttle;basis=after the worker max_run branch, stops a non-worker entry past the plans continuous-awake ceiling (maxRunFor, passed the row), busy or not, never mid-command (plans 4c). One more whole-row read: the row handed to the hook, as idleFor already is. This bypasses the inflight and held-for-tick protections the idle stop keeps, on purpose: escalated by Astra and ACCEPTED by Paul (census owner), 2026-10-25.;rev3=census-ruling-plans-4d-lapse;basis=stops a live entry the turned-off hook names (never mid-command, never a move's active probe), stands down an exited worker it names instead of restarting it (Astra finding 4), and skips such rows in the due loop and the always-on arm so they are not woken (plans 4d). Four more whole-row reads: the row handed to the hook (a.disabled), as idleFor and maxRunFor already are. Only stops or skips.;rev3=census-ruling-remote-instance-metrics;basis=its two entries-map insertions go through putEntryLocked (which also notes the route's tenant in memory for the metrics sampler); no read added registry:Hibernate@10051,registry:Hibernate@13703,registry:Hibernate@22874,registry:Hibernate@5522,registry:Hibernate@7526,registry:Host@22943,registry:Host@23001,registry:Host@23468,registry:Host@23561,registry:Host@24296,registry:Host@24385,registry:Host@25449,registry:Host@25736,registry:Host@25792,registry:NextDue@24251,registry:Status@22890,whole:Route@10053,whole:Route@10806,whole:Route@13705,whole:Route@15638,whole:Route@17348,whole:Route@17538,whole:Route@17831,whole:Route@18003,whole:Route@18150,whole:Route@22361,whole:Route@23050,whole:Route@23965,whole:Route@24305,whole:Route@24312,whole:Route@25264,whole:Route@25565,whole:Route@25769,whole:Route@5333,whole:Route@5524,whole:Route@7359,whole:Route@7528,whole:Route@7962 48ad35e412fd9bd7569fd3d8c8369c951caeff2a9ce153f8ed99038420b22b67
+@legacy 953938d6308026adf92bfd2e38d303c3a92a0d2e9b985153fbcf56510f135b44 internal/activator/probewake.go Service.ProbeWake legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-remote-instance-metrics;basis=the entries-map insertion goes through putEntryLocked; no read added whole:Route@673,whole:Route@698,whole:Route@817,whole:Route@825 2781783e5f445b0bb4d191a7598388da2a6d6f544ad42c6fe35c4b2117950e4c
+@legacy d66d9f5d97e996bd8ab21e4456de1e5771d038ebcbe5e763bc4f0e0459000246 internal/activator/recoveryprobe.go Service.RecoveryProbe legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-remote-instance-metrics;basis=the entries-map insertion goes through putEntryLocked (its nil-map make moves there); no read added registry:Host@1103,registry:Host@1134,registry:Host@317,registry:Host@489,registry:Host@597,registry:Host@890,whole:Route@899,whole:Route@906 ddcaf70cc9a2701e9efb6dd042188febd3c48b586b78ca361341ecf32781ca6b
+@legacy 8dc5d5765e58fd34d2ef176a9aac6cc4e68d7b209a970fa52ce3c403ed35cc83 internal/activator/swaphold.go Service.holdWakeLocked legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-remote-instance-metrics;basis=the entries-map insertion goes through putEntryLocked; no read added whole:Route@127,whole:Route@136 f670fc50a38c73000d04a59d2f4d5145c6bdbf08929a60f9257034dcf87e718e
+@legacy 255a2f8002c3dd5271f633ee70236aa83985ec9618d56b09a7d93ad4c29345e1 internal/cgroup/cgroup.go Manager.sweepStale legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-remote-instance-metrics;basis=records the host of a per-host dir it could not remove in an in-memory leftover set (Manager.Leftover) for the metrics sampler, and marks the whole sweep incomplete (every host a leftover) when it cannot list the root; logs that; no read added, nothing removed differently file:ReadDir@50,file:ReadDir@520 7f2c44b07bba53901fd727fb9c523074ec6591e19355f2e3b6d3a17352642ac3
+@legacy 27dabc018aed7ce9bc1b99677ce678e9cbe194bc6747158c069fa6c297d543a5 internal/cgroup/cgroup.go setupAt legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 (final review F2): the supervise leaf's name now comes from the new exported constant SuperviseLeaf (the same value, supervise), which root's egress rail (internal/host/egress_rail_linux.go) also uses to tell the agent's own leaf from other cgroups in its delegated subtree. It is still the agent's own delegation dance, run by the agent (cgroup.Setup from runAgent, user carlos) in its own subtree; the same one site, the O_WRONLY OpenFile probe of cgroup.procs and cgroup.subtree_control; no read added.;rev3=census-ruling-remote-instance-metrics;basis=a retaining setup also marks every host a leftover for the metrics sampler (an in-memory flag); no read added file:OpenFile@423 65e910820bf75d058cc723b386549fe2bbb918d084535b22290a6464e0b698a8
+@legacy f0980583e1668d9bab93b81f49f6c80095da2d603e7ada5d5aadf641e45268a2 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 file:ReadBytes@963 74d913ac5a0b8a71822519a2a5e81235e4ec2d79793bbd4685e08d5e6e832533
+@legacy 9cd35b7cb1183b76ac21f6b20bfaefaa5f743733b5de6260a6088c694369169d internal/activator/tenancies.go Service.Tenancies legacy accepted-legacy accepted-legacy;rev3=census-ruling-remote-instance-metrics;basis=new (remote instance metrics): reads the Account and App of each live activator entry's route, already in memory, and returns them with an entry number for the metrics sampler's tenant tags; skips hosts whose entries named two tenants; nothing in claim mode; no file, no store, no registry open, nothing written; root never calls it registry:Account@230,registry:App@247,whole:Route@232,whole:Route@249 3ca1083d0c885bc42444aabd1d19956462c16b8dad624b7fc9cec05a5dfe49d1
+@legacy ae612d404ac266f4c262c90de918c688952f5d2ce4b3e8b4b022acbbff811189 internal/activator/tenancies.go Service.putEntryLocked legacy accepted-legacy accepted-legacy;rev3=census-ruling-remote-instance-metrics;basis=new: the one insertion into the activator's entries map, replacing the same write at seven sites; notes the entry route's Account and App (in memory) in a per-host tenant set; no file, no store, no registry open; root never calls it registry:Account@175,registry:App@192,whole:Route@177,whole:Route@194 fa3029b4758ce42209bb828d6e3c54a2b47444f01cf340ff8f5816e9d9407180
+@legacy 84f20a9cb1044f5ce7705a60ed3cdb677c2036579e84757a082b9e135aa4030b internal/host/metrics_owner.go metricsOwners legacy accepted-legacy accepted-legacy;rev3=census-ruling-remote-instance-metrics;basis=new: the agent's metrics loop asks the activator for its tenancies and lists the agent's own registry (as the stamped-units read already does each tick), twice a tick, joined by metrics.Vouched; no path a tenant names, no store request, nothing written; root never calls it whole:Route@523 224f7b50fd18bebec1b089b76d082ef122084e8d53d27690f0393032cd4ff12d
+@legacy 1e6ff6236cad300aad0292f604fe960ebaf0b8a006cdd2dcecd4aa11d3140163 internal/metrics/owner.go Vouched legacy accepted-legacy accepted-legacy;rev3=census-ruling-remote-instance-metrics;basis=new: a pure join of registry rows already in hand (Host, Account, App) with the activator's tenancies and a leftover predicate; no I/O registry:Account@253,registry:Account@289,registry:Account@472,registry:App@273,registry:App@316,registry:App@489,registry:Host@232,registry:Host@383,registry:Host@432,whole:Route@209 8a8e77aaa4aa0ca6077aa39310cb129247ab676099cfb494e6763e7fc4675794
+internal/activator/activator.go Service.WakeWorker legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body; the stop now carries its reason for a run it interrupts (beginStopLocked's why argument); read sites unchanged, offsets moved;rev3=census-ruling-remote-instance-metrics;basis=the entries-map insertion goes through putEntryLocked (which also notes the route's tenant in memory for the metrics sampler); no read added registry:Host@1249,registry:Host@1658,registry:Host@834,registry:Host@864,whole:Route@1225 dab4506e9f7a8b802d2c930222b4775a4b1626c31c4e39ce2f39ca51c3ce37de
+internal/activator/activator.go Service.begin 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; the stop now carries its reason for a run it interrupts (beginStopLocked's why argument); read sites unchanged, offsets moved;rev3=census-ruling-edge-request-records;basis=gains a req *http.Request parameter and one edge.MarkWoke(req) call on the path that starts a wake, so the edge's request record can say which request woke the app; no read added;rev3=census-ruling-remote-instance-metrics;basis=the entries-map insertion goes through putEntryLocked (which also notes the route's tenant in memory for the metrics sampler); no read added registry:Host@1721,registry:Host@1807,registry:Host@345,registry:Host@929,whole:Route@1730,whole:Route@1737 2a6b1e1412a88632293b4bf767f6daf9376d2a00a87d1c27c91eaf02f82da468
+internal/activator/activator.go Service.sweepOnce legacy accepted-legacy accepted-legacy;rev3=PROPOSED-seed;basis=census-ruling-FS-R6; registry remains legacy; PROPOSED-plans-2-box-limits: the sweep also narrows an entry's idle window to its account's plan idle through the SetIdleFor hook (never lengthens it; always-on workers and held probe entries are untouched; the hibernate, inflight and held-for-tick guards are unchanged).;rev3=census-ruling-plans-4c-box-throttle;basis=after the worker max_run branch, stops a non-worker entry past the plans continuous-awake ceiling (maxRunFor, passed the row), busy or not, never mid-command (plans 4c). One more whole-row read: the row handed to the hook, as idleFor already is. This bypasses the inflight and held-for-tick protections the idle stop keeps, on purpose: escalated by Astra and ACCEPTED by Paul (census owner), 2026-10-25.;rev3=census-ruling-plans-4d-lapse;basis=stops a live entry the turned-off hook names (never mid-command, never a move's active probe), stands down an exited worker it names instead of restarting it (Astra finding 4), and skips such rows in the due loop and the always-on arm so they are not woken (plans 4d). Four more whole-row reads: the row handed to the hook (a.disabled), as idleFor and maxRunFor already are. Only stops or skips.;rev3=census-ruling-remote-instance-metrics;basis=its two entries-map insertions go through putEntryLocked (which also notes the route's tenant in memory for the metrics sampler); no read added registry:Hibernate@10051,registry:Hibernate@13703,registry:Hibernate@22874,registry:Hibernate@5522,registry:Hibernate@7526,registry:Host@22943,registry:Host@23001,registry:Host@23468,registry:Host@23561,registry:Host@24296,registry:Host@24385,registry:Host@25449,registry:Host@25736,registry:Host@25792,registry:NextDue@24251,registry:Status@22890,whole:Route@10053,whole:Route@10806,whole:Route@13705,whole:Route@15638,whole:Route@17348,whole:Route@17538,whole:Route@17831,whole:Route@18003,whole:Route@18150,whole:Route@22361,whole:Route@23050,whole:Route@23965,whole:Route@24305,whole:Route@24312,whole:Route@25264,whole:Route@25565,whole:Route@25769,whole:Route@5333,whole:Route@5524,whole:Route@7359,whole:Route@7528,whole:Route@7962 48ad35e412fd9bd7569fd3d8c8369c951caeff2a9ce153f8ed99038420b22b67
+internal/activator/activator.go type Service authority B,C,D,F,J4 rev3=PROPOSED-seed; existing activator lifecycle and due-wake state plus owned seed exclusion and incarnation-keyed diagnostics; normal refusal and preparation ordering remain authoritative; PROPOSED-plans-2-box-limits adds the idleFor hook field, which only narrows idle windows;rev3=census-ruling-plans-4c-box-throttle;basis=gains the maxRunFor hook field beside idleFor (plans 4c). No read added.;rev3=census-ruling-plans-4d-lapse;basis=gains the disabledFor hook field beside maxRunFor (plans 4d). No read added.;rev3=census-ruling-remote-instance-metrics;basis=gains tenancySeq, hostTenants and hostMixed, in-memory fields for Tenancies; no read added b0884037418c076f20c9c7645bc63ff1b40323795af9554f2d35b99622a5c25f
+internal/activator/probewake.go Service.ProbeWake legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-remote-instance-metrics;basis=the entries-map insertion goes through putEntryLocked; no read added whole:Route@673,whole:Route@698,whole:Route@817,whole:Route@825 2781783e5f445b0bb4d191a7598388da2a6d6f544ad42c6fe35c4b2117950e4c
+internal/activator/recoveryprobe.go Service.RecoveryProbe legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-remote-instance-metrics;basis=the entries-map insertion goes through putEntryLocked (its nil-map make moves there); no read added registry:Host@1103,registry:Host@1134,registry:Host@317,registry:Host@489,registry:Host@597,registry:Host@890,whole:Route@899,whole:Route@906 ddcaf70cc9a2701e9efb6dd042188febd3c48b586b78ca361341ecf32781ca6b
+internal/activator/swaphold.go Service.holdWakeLocked legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-remote-instance-metrics;basis=the entries-map insertion goes through putEntryLocked; no read added whole:Route@127,whole:Route@136 f670fc50a38c73000d04a59d2f4d5145c6bdbf08929a60f9257034dcf87e718e
+internal/cgroup/cgroup.go Manager.sweepStale legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-remote-instance-metrics;basis=records the host of a per-host dir it could not remove in an in-memory leftover set (Manager.Leftover) for the metrics sampler, and marks the whole sweep incomplete (every host a leftover) when it cannot list the root; logs that; no read added, nothing removed differently file:ReadDir@50,file:ReadDir@520 7f2c44b07bba53901fd727fb9c523074ec6591e19355f2e3b6d3a17352642ac3
+internal/cgroup/cgroup.go setupAt legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 (final review F2): the supervise leaf's name now comes from the new exported constant SuperviseLeaf (the same value, supervise), which root's egress rail (internal/host/egress_rail_linux.go) also uses to tell the agent's own leaf from other cgroups in its delegated subtree. It is still the agent's own delegation dance, run by the agent (cgroup.Setup from runAgent, user carlos) in its own subtree; the same one site, the O_WRONLY OpenFile probe of cgroup.procs and cgroup.subtree_control; no read added.;rev3=census-ruling-remote-instance-metrics;basis=a retaining setup also marks every host a leftover for the metrics sampler (an in-memory flag); no read added file:OpenFile@423 65e910820bf75d058cc723b386549fe2bbb918d084535b22290a6464e0b698a8
+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 file:Exec@15382,file:Open@1150,registry:App@10663,whole:Route@10655,whole:Route@25558 86f6b56b31871b77d401220eaa81db6bbcd210828c410e474a7f5bbf1708905c
+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 file:ReadBytes@963 74d913ac5a0b8a71822519a2a5e81235e4ec2d79793bbd4685e08d5e6e832533
+internal/metrics/sample.go type UnitSample diagnostic H3 schema-only;rev3=census-ruling-remote-instance-metrics;basis=one more field, Owner (omitempty), the tenant tag; schema only file:ReadBytes@151 294c6d0be969498ccf499f72f9d0ba4f58544e3ae0038743954e2056a636adb7
+internal/activator/tenancies.go Service.Tenancies legacy accepted-legacy accepted-legacy;rev3=census-ruling-remote-instance-metrics;basis=new (remote instance metrics): reads the Account and App of each live activator entry's route, already in memory, and returns them with an entry number for the metrics sampler's tenant tags; skips hosts whose entries named two tenants; nothing in claim mode; no file, no store, no registry open, nothing written; root never calls it registry:Account@230,registry:App@247,whole:Route@232,whole:Route@249 3ca1083d0c885bc42444aabd1d19956462c16b8dad624b7fc9cec05a5dfe49d1
+internal/activator/tenancies.go Service.putEntryLocked legacy accepted-legacy accepted-legacy;rev3=census-ruling-remote-instance-metrics;basis=new: the one insertion into the activator's entries map, replacing the same write at seven sites; notes the entry route's Account and App (in memory) in a per-host tenant set; no file, no store, no registry open; root never calls it registry:Account@175,registry:App@192,whole:Route@177,whole:Route@194 fa3029b4758ce42209bb828d6e3c54a2b47444f01cf340ff8f5816e9d9407180
+internal/host/metrics_owner.go metricsOwners legacy accepted-legacy accepted-legacy;rev3=census-ruling-remote-instance-metrics;basis=new: the agent's metrics loop asks the activator for its tenancies and lists the agent's own registry (as the stamped-units read already does each tick), twice a tick, joined by metrics.Vouched; no path a tenant names, no store request, nothing written; root never calls it whole:Route@523 224f7b50fd18bebec1b089b76d082ef122084e8d53d27690f0393032cd4ff12d
+internal/metrics/owner.go Vouched legacy accepted-legacy accepted-legacy;rev3=census-ruling-remote-instance-metrics;basis=new: a pure join of registry rows already in hand (Host, Account, App) with the activator's tenancies and a leftover predicate; no I/O registry:Account@253,registry:Account@289,registry:Account@472,registry:App@273,registry:App@316,registry:App@489,registry:Host@232,registry:Host@383,registry:Host@432,whole:Route@209 8a8e77aaa4aa0ca6077aa39310cb129247ab676099cfb494e6763e7fc4675794
+@coverage internal/activator bad52a369f58e61a3b6b3bcb5835113ad70d04172789bc4387c36e81ab5a2e8f
+@coverage internal/cgroup 46d31c819724e4573b0f3004d5549722f671526fa5c926d4a63468d5ed44b2cf
+@coverage internal/host 18a8c501ac33fef4d3c72859105ca8132ef93a1cdcef0d29f5df877efbcbc1ff
+@coverage internal/metrics d7f3b57198083eb4e25ff6e3640e4f34b9f8235301182762c6883fa77ce12d76