carlos / platform Public

remote-instance-metrics: design note and review brief

Samples tagged with their tenant (account and app) by the box, from the
activator's live entry joined to the registry row, read before and after
the cgroup read; the console shows a remote sample only with its
record's tag.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 98caa5f4ded08f0c5082311853275ae2633362e0 parent 5634538
2 files changed, +293 −0
  • docs/superpowers/notes/remote-instance-metrics.md +206 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-remote-instance-metrics-note.md +87 −0
diff --git a/docs/superpowers/notes/remote-instance-metrics.md b/docs/superpowers/notes/remote-instance-metrics.md
new file mode 100644
index 000000000..320f0034c
--- /dev/null
+++ b/docs/superpowers/notes/remote-instance-metrics.md
@@ -0,0 +1,206 @@
+# 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
+every process that can be in that cgroup during the reading was started by
+the activator for a route of tenant T. The rule is enforced in one place,
+the sampler's tick (`internal/host/metrics_loop.go`), from one function that
+lists the vouched owners (`metricsOwners`).
+
+Where processes in a host's exec cgroup come from, and how each is covered:
+
+1. **The activator's live entry for the host.** Every spawn into
+ `carlos-exec@<host>` goes through the activator (instance, legacy
+ sidecar, seed, generations). A `carlos run` command runs in its own
+ systemd unit, not in this cgroup. A wake re-reads the registry
+ row before it spawns and refuses a row that now names another account
+ or app (`wakeRouteChanged`). So an entry's processes belong to its
+ route's tenant. A new method, `activator.Service.Tenancies()`, returns
+ each live entry's tenant and a number that is new for every new entry.
+2. **Earlier entries of this agent.** A stop deletes the entry only after
+ the process is gone; what the activator cannot prove stopped it records.
+ `Tenancies` leaves out a host with an unproven failed wake, a stray
+ sidecar, or a recorded stop that is not complete (`stopObservation.complete`,
+ sticky for the agent's life).
+3. **A previous agent's processes.** 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; one it cannot remove
+ still holds a process, so that host is recorded as a leftover and never
+ tagged in this agent's life.
+4. **Claim mode** retains processes across restarts (`SetupRetaining`).
+ `Tenancies` returns nothing in claim mode, 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)
+```
+
+`owners()` maps `cgroup.ExecName(host)` to the tenant only when the
+activator's entry and the registry row name the same non-empty account and
+app, and the host is not a leftover. The two reads around the cgroup read
+mean a wake, a stop or a re-tenant during the reading leaves that sample
+untagged. The row check covers an entry whose host has since been given to
+another tenant: a predecessor still stopping while the successor's row
+exists.
+
+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
+
+No new request anywhere. Boxes write the same chunk keys on the same
+five-minute flush; the console sweeps the same 48 hourly keys per box on
+the same cache. Steady state, nothing changing: 0 new requests per box per
+day, 0 new console requests. Bodies grow by about 40 bytes per tagged unit
+per sample: about 2.4 KB per awake instance-hour in the raw chunk.
+
+## Tests (to write first)
+
+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; an
+ unproven wake, a stray sidecar or an incomplete stop leaves the host
+ out; claim mode returns nothing.
+- **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; the flushed chunk carries the tag.
+- **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).
+
+## 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.
+- 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.
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..7a5a5d1fa
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-remote-instance-metrics-note.md
@@ -0,0 +1,87 @@
+# Review brief: remote instance metrics design note, round 1 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: "`carlos-exec@<host>` is tagged with T only when
+ every process that can be in that cgroup during the reading was started
+ by the activator for a route of tenant T." Check the four sources the
+ note lists against `internal/activator` (entries, `wakeRouteChanged`,
+ `unprovenWakes`, `straySidecars`, `stopHistory`, `finishStop`,
+ `Shutdown`), `internal/cgroup` (`Setup`, `sweepStale`,
+ `SetupRetaining`) and `internal/host/metrics_loop.go`. Is there a
+ spawner into a host's exec cgroup the note misses, or a way for an
+ earlier tenant's process to remain in the cgroup while a later
+ tenant's entry is vouched?
+3. The two reads around the cgroup read, and the entry number. Can a
+ wake, stop or re-tenant during one tick 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?
+
+## 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.