carlos / platform Public

Merge remote-tracking branch 'origin/main' into alias-wake-338

# Conflicts:
#	internal/provision/testdata/plan14-root-reads-chain.tsv
claude agent, operated by paul@keymail.dev 4990ef730aa28e5769c7c1cbc4f9b8972564776d parent efbc834parent e92c22a
59 files changed, +3,212 −355
  • docs/site/cli.md +7 −5
  • docs/superpowers/notes/LUNA-COPY-BRIEF-USAGE-ATTRIBUTION-R2.md +64 −0
  • docs/superpowers/notes/LUNA-COPY-BRIEF-USAGE-ATTRIBUTION.md +67 −0
  • docs/superpowers/notes/LUNA-COPY-REVIEW-USAGE-ATTRIBUTION-R2.md +9 −0
  • docs/superpowers/notes/LUNA-COPY-REVIEW-USAGE-ATTRIBUTION.md +13 −0
  • docs/superpowers/notes/census-ha-p1a-433-claims.md +22 −0
  • docs/superpowers/notes/census-proposal-alias-wake-338.md +1 −1
  • docs/superpowers/notes/census-proposal-ha-p1a-433.md +34 −0
  • docs/superpowers/notes/census-proposal-rollup-tenant-tags.md +11 −0
  • docs/superpowers/notes/census-proposal-usage-attribution-390.md +11 −0
  • docs/superpowers/notes/remote-instance-metrics.md +41 −0
  • docs/superpowers/notes/reviews/ASTRA-FINDINGS-ha-p1a-433-r1.md +36 −0
  • docs/superpowers/notes/reviews/ASTRA-FINDINGS-ha-p1a-433-r2.md +21 −0
  • docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-ha-p1a-433-R1.md +30 −0
  • docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-ha-p1a-433-R2.md +30 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-rollup-tenant-tags-r1.md +18 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-usage-attribution-390-r1.md +47 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-usage-attribution-390-r2.md +23 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rollup-tenant-tags.md +82 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-usage-attribution-390-R2.md +103 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-usage-attribution-390.md +131 −0
  • internal/console/apistatusinstances.go +52 −26
  • internal/console/apistatusinstances_test.go +17 −11
  • internal/console/economicspage_test.go +17 −8
  • internal/console/economicspass.go +205 −96
  • internal/console/economicspass_test.go +29 −24
  • internal/console/economicsview.go +34 −30
  • internal/console/economicsview_test.go +13 −7
  • internal/console/metricsview.go +11 −0
  • internal/console/usageattrib.go +262 −0
  • internal/console/usageattrib_tags_test.go +167 −0
  • internal/console/usageattrib_test.go +513 −0
  • internal/host/agent.go +1 −6
  • internal/host/agent_layout_test.go +87 −4
  • internal/host/edgesfile_test.go +3 −0
  • internal/host/egress_source_test.go +30 −0
  • internal/host/host_test.go +12 −0
  • internal/host/layoutleg.go +43 −0
  • internal/host/rootfsplacement.go +10 −7
  • internal/instancectl/peer_edge.go +115 −0
  • internal/instancectl/peer_edge_test.go +120 −0
  • internal/instancectl/peer_linux.go +20 −50
  • internal/metrics/rollup.go +75 −1
  • internal/metrics/rollup_test.go +45 −0
  • internal/provision/boxpools_test.go +53 −0
  • internal/provision/plan9_b8_census_test.go +1 −1
  • internal/provision/reconcile.go +41 −0
  • internal/provision/reconcile_eligibility_test.go +2 −0
  • internal/provision/testdata/plan14-root-reads-alias-wake-338.tsv +1 −1
  • internal/provision/testdata/plan14-root-reads-chain.tsv +4 −1
  • internal/provision/testdata/plan14-root-reads-ha-p1a-433.tsv +28 −0
  • internal/provision/testdata/plan14-root-reads-rollup-tenant-tags.tsv +3 −0
  • internal/provision/testdata/plan14-root-reads-usage-attribution-390.tsv +3 −0
  • internal/provision/usage_attribution_390_census_test.go +31 −0
  • internal/registry/claimrows.go +5 −2
  • internal/registry/ha_test.go +157 −0
  • internal/registry/registry.go +155 −59
  • status_instances.go +27 −8
  • status_instances_test.go +19 −7

CI passed — run details

diff --git a/docs/site/cli.md b/docs/site/cli.md
index 42cf3ac0a..8d5ffd699 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -2305,11 +2305,13 @@ not a secret — a wrong-method request gets a 405 from the router, like every
other route here — but the answer is, because it names other people's
accounts.
-Two things it cannot see, both printed under the table. A sleeping instance
-has no process and so no reading, so it does not appear. And the readings are
-fleet-wide while the account each one is attributed to comes from the
-console's own box's route registry, so on a multi-box deployment an instance
-running elsewhere can show up under `(platform)` rather than under its tenant.
+A sleeping instance has no process or reading, so it does not appear. A note
+under the table explains this. Each reading belongs to the account whose own
+platform domain the instance's hostname is under
+(`<name>.<account>.<apps domain>`), wherever the instance runs, or to the
+owner its box recorded with the reading. An instance with neither, such as one
+on a custom domain, appears as `(unattributed)`. Its usage counts against no
+account, including the platform.
`--layout` shows which layout each instance is on, box by box. `flat` is the
shared `/data` every instance used to live in. `nested` is the instance's own
diff --git a/docs/superpowers/notes/LUNA-COPY-BRIEF-USAGE-ATTRIBUTION-R2.md b/docs/superpowers/notes/LUNA-COPY-BRIEF-USAGE-ATTRIBUTION-R2.md
new file mode 100644
index 000000000..d19c08bfa
--- /dev/null
+++ b/docs/superpowers/notes/LUNA-COPY-BRIEF-USAGE-ATTRIBUTION-R2.md
@@ -0,0 +1,64 @@
+# Copy review brief: usage attribution across boxes (#390), second pass
+
+Paul delegates copy review for platform CLI, console and docs copy to you. You
+are the copy editor; your edits will be applied as approved copy. Your first
+pass is `docs/superpowers/notes/LUNA-COPY-REVIEW-USAGE-ATTRIBUTION.md`. A code
+review then changed the facts, so two of those strings changed and one is new.
+UA-1 `(unattributed)` stands. UA-3 and UA-4 were dropped.
+
+## The new facts
+
+A box's CPU and memory reading of an instance now belongs to an account only
+on evidence that holds for the whole time the reading covers:
+
+- the instance's hostname is under that account's own platform domain
+ (`<name>.<account>.<apps domain>`, for example `shop.bdx.oncarlos.com`;
+ only that account can ever hold such a name), or
+- the box recorded the owner with the reading itself (live readings only).
+
+Instance records and box reports no longer decide it: they say who holds a
+hostname now, not who ran it last week. An instance with neither, such as an
+instance an operator put on a custom domain, is unattributed and its usage
+counts against no account, the platform's included.
+
+## The strings (draft text is yours to change; ids are fixed)
+
+- UA-2, a muted note printed under the `carlos status --instances` table,
+ only when at least one row's APP reads `(unattributed)`. Draft:
+ `(unattributed: neither its box nor its hostname shows whose instance this
+ is, so its usage counts against no account)`
+- UA-5, the docs paragraph in docs/site/cli.md, `--instances` section (your
+ first-pass text, with the facts corrected). Draft:
+
+ > A sleeping instance has no process or reading, so it does not appear. A
+ > note under the table explains this. Each reading belongs to the account
+ > whose platform domain the instance's hostname is under
+ > (`<name>.<account>.<apps domain>`), wherever the instance runs, or to the
+ > owner its box recorded with the reading. An instance with neither, such as
+ > one on a custom domain, appears as `(unattributed)`. Its usage counts
+ > against no account, including the platform.
+
+- UA-6, new, docs/site/plans.md, a sentence after "The figures come from what
+ the console already records: its own app list, the monthly usage
+ statements, the daily storage sweep and the mail counts. A cap whose limit
+ is 0 is skipped." Readers: account owners and operators. Draft:
+ `Awake hours count the instances on the account's own platform domain, on
+ every server. An instance on a custom domain is not counted, because nothing
+ records whose it was in each hour.`
+
+## House rules (Paul's, all binding)
+
+- No em dashes, ever. Use a full stop and a new sentence; in CLI strings the
+ new sentence continues in lower case.
+- Plain words. No jargon a reader would not know. Short.
+- Neutral names only (shop, example.com). Never a tenant's name. (The `bdx`
+ above is an example sqid and must not appear in your output.)
+- Keep UA-2's parentheses and the literal `(unattributed)` and
+ `<name>.<account>.<apps domain>`.
+- Do not change the facts. If a fact looks wrong or two rows disagree, flag it.
+
+## Output
+
+1. A table of changes only: `id | current | new | why`.
+2. A list of flagged rows: `id | problem`.
+3. One line of counts: changed, flagged, left alone.
diff --git a/docs/superpowers/notes/LUNA-COPY-BRIEF-USAGE-ATTRIBUTION.md b/docs/superpowers/notes/LUNA-COPY-BRIEF-USAGE-ATTRIBUTION.md
new file mode 100644
index 000000000..281ba1596
--- /dev/null
+++ b/docs/superpowers/notes/LUNA-COPY-BRIEF-USAGE-ATTRIBUTION.md
@@ -0,0 +1,67 @@
+# Copy review brief: usage attribution across boxes (#390)
+
+Paul delegates copy review for platform CLI, console and docs copy to you. You
+are the copy editor; your edits will be applied as approved copy.
+
+## What changed
+
+Until now `carlos status --instances` and the console's usage statements
+decided whose a box's CPU and memory readings were by looking only at the
+console's own box. An instance on any other box was filed under the
+platform. Now each reading belongs to the account and app its instance
+record names, on any box. A reading that nothing can be shown to belong to
+(no instance record, no box report naming its owner) is shown as
+unattributed and is counted against no account, the platform's included.
+
+## The strings (draft text is yours to change; ids are fixed)
+
+Readers: platform operators. `carlos status --instances` is operator-only
+and lists every awake instance on every box, one row per instance, columns
+BOX REGION HOST ACCOUNT APP CPU MEM.
+
+- UA-1, the APP cell of an instance whose owner cannot be established (the
+ ACCOUNT cell prints `-`). It sits beside the existing `(platform)` cell,
+ which marks the platform's own services. Draft: `(unattributed)`
+- UA-2, a note printed in muted text under the table, only when at least one
+ UA-1 row is present. The existing note above it reads `(awake instances
+ only — a hibernating instance has no process to measure)` (older copy, not
+ in scope). Draft: `(unattributed: no record or box report says whose this
+ instance is, so its usage counts against no account)`
+- UA-3, the console's refusal to `carlos status --instances` when it could not
+ read the instance records (transient; retrying usually works). The CLI
+ prints it after `status --instances: `. Draft: `could not read the instance
+ records. Try again.`
+- UA-4, a warning banner on the operator-only economics page when the
+ instance records could not be read; `%v` is a Go error string. Draft:
+ `instance records: %v; no instance's usage is attributed to an account this
+ sweep`
+- UA-5, a docs paragraph in docs/site/cli.md, `--instances` section, after a
+ paragraph about who may call it. Draft:
+
+ > A sleeping instance has no process and so no reading, so it does not
+ > appear, and a note under the table says so. Each reading belongs to the
+ > account and app its instance record names, on whichever box the instance
+ > runs. An instance that no record or box report accounts for shows as
+ > `(unattributed)`, and its usage counts against no account, the
+ > platform's included.
+
+## House rules (Paul's, all binding)
+
+- No em dashes, ever. Use a full stop and a new sentence; in CLI and API
+ error strings the new sentence continues in lower case (`could not provision
+ the store. re-run ...`).
+- Plain words. No jargon a reader would not know. Short.
+- Human text only. If a string is not human text, flag it rather than edit it.
+- Neutral names only (shop, example.com). Never a tenant's name.
+- Keep every placeholder exactly (`%v`) and keep UA-1's parentheses (it sits
+ beside `(platform)`).
+- Do not change the facts a string states. If a fact looks wrong or two rows
+ disagree, flag it.
+
+## Output
+
+Markdown, in this shape:
+
+1. A table of changes only: `id | current | new | why` (a few words in why).
+2. A list of flagged rows: `id | problem`.
+3. One line of counts: changed, flagged, left alone.
diff --git a/docs/superpowers/notes/LUNA-COPY-REVIEW-USAGE-ATTRIBUTION-R2.md b/docs/superpowers/notes/LUNA-COPY-REVIEW-USAGE-ATTRIBUTION-R2.md
new file mode 100644
index 000000000..86fcba1ad
--- /dev/null
+++ b/docs/superpowers/notes/LUNA-COPY-REVIEW-USAGE-ATTRIBUTION-R2.md
@@ -0,0 +1,9 @@
+| id | current | new | why |
+|---|---|---|---|
+| UA-2 | `(unattributed: no instance record or box report identifies its owner, so its usage counts against no account)` | `(unattributed: neither its box nor its hostname identifies its account, so its usage counts against no account)` | Matches the two valid attribution sources. |
+| UA-5 | Existing paragraph using the instance record and box report as attribution evidence. | A sleeping instance has no process or reading, so it does not appear. A note under the table explains this. Each reading belongs to the account whose own platform domain the instance's hostname is under (`<name>.<account>.<apps domain>`), wherever the instance runs, or to the owner its box recorded with the reading. An instance with neither, such as one on a custom domain, appears as `(unattributed)`. Its usage counts against no account, including the platform. | Uses the corrected attribution rules. |
+| UA-6 | `Awake hours count the instances on the account's own platform domain, on every server. An instance on a custom domain is not counted, because nothing records whose it was in each hour.` | Awake hours count readings for instances on the account's own platform domain, on every server, or readings whose box recorded the owner. An instance with neither is not counted, because nothing shows whose it was during that hour. | Includes live box ownership and avoids excluding every custom-domain instance. |
+
+- UA-6 | The draft incorrectly says custom-domain instances are never counted. A box can record their owner with a live reading.
+
+changed: 3, flagged: 1, left alone: 1
\ No newline at end of file
diff --git a/docs/superpowers/notes/LUNA-COPY-REVIEW-USAGE-ATTRIBUTION.md b/docs/superpowers/notes/LUNA-COPY-REVIEW-USAGE-ATTRIBUTION.md
new file mode 100644
index 000000000..d55f2c82f
--- /dev/null
+++ b/docs/superpowers/notes/LUNA-COPY-REVIEW-USAGE-ATTRIBUTION.md
@@ -0,0 +1,13 @@
+| id | current | new | why |
+|---|---|---|---|
+| UA-1 | `(platform)` | `(unattributed)` | Distinguishes unknown ownership from platform services. |
+| UA-2 | `(accounts are joined against the console's own box's route registry; an instance on another box in a fleet can land under (platform))` | `(unattributed: no instance record or box report identifies its owner, so its usage counts against no account)` | Explains the actual condition briefly. |
+| UA-3 | `could not read the route registry — try again` | `could not read the instance records. try again.` | Names the failed read and follows CLI sentence style. |
+| UA-4 | None | `instance records: %v. No instance's usage is attributed to an account this sweep.` | States the warning and its effect clearly. |
+| UA-5 | Existing paragraph about sleeping instances and the console box's route registry | A sleeping instance has no process or reading, so it does not appear. A note under the table explains this. Each reading belongs to the account and app named by its instance record, wherever the instance runs. An instance with no record or box report showing its owner appears as `(unattributed)`. Its usage counts against no account, including the platform. | Removes obsolete behavior and uses shorter, clearer sentences. |
+
+Flagged rows:
+
+None.
+
+changed: 5, flagged: 0, left alone: 0
\ No newline at end of file
diff --git a/docs/superpowers/notes/census-ha-p1a-433-claims.md b/docs/superpowers/notes/census-ha-p1a-433-claims.md
new file mode 100644
index 000000000..d2a5dacf4
--- /dev/null
+++ b/docs/superpowers/notes/census-ha-p1a-433-claims.md
@@ -0,0 +1,22 @@
+# CLAIMS for the root-read census, branch ha-p1a-dev-pair-433 (amadan #433: P1a follow-up fixes and the shared-pool token).
+# Format (AGENTS.md "The census"): <file>:<unit><TAB><what changed>. Lines starting with # are ignored.
+# Base: fc30b421 (origin/main, carries region HA P1a fd93024a).
+
+# Fix 1: root peer check (instance-control, uid 0)
+internal/instancectl/peer_linux.go:productionPeerOK root (carlos-instance-control.service): reads nothing now. The systemctl MainPID read moved verbatim to systemdEdgeMainPID, and the decision and its one-second cache moved to edgePeer.check (internal/instancectl/peer_edge.go, envelope re-pinned). Acceptance is unchanged: SO_PEERCRED uid carlos AND pid equal to the MainPID systemd reports for carlos-edge.service. New in edgePeer.check: a peer the cached answer refuses (a stale pid or a cached failure, #433) is checked once against a fresh read before the refusal, at most one forced read per 100 ms; the peer is accepted only if the fresh MainPID equals it, so nothing wider is accepted.
+internal/instancectl/peer_linux.go:systemdEdgeMainPID root (carlos-instance-control.service): the same exec productionPeerOK's closure ran before, moved out unchanged: systemctl show -p MainPID --value carlos-edge.service, fixed argv, 3 s timeout; output that does not parse is 0 (no MainPID), which edgePeer refuses. No input from a peer, tenant or agent reaches the argv.
+
+# Fix 2: root reads routes before the agent migrates (registry, read-only child as carlos; read-write in the agent)
+internal/registry/registry.go:Registry.List the registry's SQLite side as carlos (agent, registry child, and root's read-only registry child via openServiceRegistryReadOnly): calls readCols on the same connection before the same SELECT ... FROM routes ORDER BY host. A read-write registry gets routeCols unchanged; a read-only one gets routeCols with any column routeAddedColumns adds that the table lacks read as its migration default ("0 AS ha"), so root's egress naming and source work before the new agent migrates (#433). Decides nothing; no read added.
+internal/registry/registry.go:Registry.Get same identities as List: +registry:sql is r.sql handed to readCols, the same connection the SELECT already used; same SELECT ... WHERE host = ? with the select list readCols returns (routeCols for a read-write registry). Root's instanceRegistryHostApp and instanceRegistryHostRuntime read Get through the read-only child and now work before the migration too.
+internal/registry/registry.go:Registry.migrate the registry's SQLite side as carlos (agent, registry child; a box CLI verb that opens the registry directly runs it as whoever runs it), on every registry open: the ALTER TABLE routes statements are now built from the one migration definition routeAddedColumns (addedColumn name, type, default; review r1 P2): for each entry without the Claim mark, "ALTER TABLE routes ADD COLUMN " + spec(), byte for byte the statements main runs, in main's order, under the same duplicate-column rule. +registry:Claim is that mark, +whole:addedColumn the struct. Every name, type and default is an in-binary literal; no statement added, removed or changed; no read added.
+internal/registry/registry.go:Registry.readCols new; the registry's SQLite side as carlos. For a read-write registry returns routeCols and reads nothing. For a read-only one (registry:readOnly), one SELECT name FROM pragma_table_info('routes') over the registry's own mode=ro, query_only connection. The names read are only compared with the in-binary routeCols and routeAddedColumns lists, never put into SQL: the select list is built from routeCols and the in-binary defaults (the empty string literal or 0, parsed from routeAddedColumns by a fixed regexp). An agent-written table can only make a known added column read as its default, which is what the migration gives it; a missing CREATE column is not stood in for and the read fails as before.
+
+# Fix 3: CARLOS_POOLS token (agent, carlos)
+internal/host/agent.go:provisionTickConfig the agent (carlos-edge.service, user carlos) and the edges file loop's eligibility: the same CARLOS_POOLS read, now parsed by provision.ParseBoxPools (internal/provision, envelope re-pinned), the one parser boxPools also uses. "@shared" (provision.SharedPoolToken, never a valid pool name) is the shared "" pool; other tokens are literal as before; empty elements and repeats dropped. No read added.
+
+# Review r1 P2 (Astra): every migration-added column from one definition
+internal/registry/claimrows.go:Registry.migrateClaimOwnership the registry's SQLite side as carlos, on every registry open (called from migrate): the four claim ownership ALTERs for routes and timers come from routeAddedColumns' Claim-marked entries (claim_incarnation TEXT, claim_stamp INTEGER, claim_owner TEXT, claim_row_id TEXT, each NOT NULL DEFAULT the empty string or 0), as "ALTER TABLE " + table + " ADD COLUMN " + spec(): the same statements as main's inline list, same order, same tables, same duplicate-column rule. +registry:Claim is the mark, +whole:addedColumn the struct; in-binary literals only; no read added.
+internal/registry/registry.go:addedColumn.spec new; pure: joins the entry's in-binary Name, Type and Default into "<name> <type> NOT NULL DEFAULT <default>". +registry:Name/Type/Default are the struct's own fields; it reads nothing from the database, a file or an input.
+internal/registry/registry.go:addedRouteColumnDefaults new as a census unit (it replaces the regexp parse of the ALTER texts): pure, maps each routeAddedColumns entry's in-binary Name to its in-binary Default, now including the four claim ownership columns, so readCols stands their defaults in for a read-only registry that predates migrateClaimOwnership. Reads nothing from the database, a file or an input.
+# changed registry schema: the registry struct field set gains addedColumn's Name, Type, Default and Claim (an in-binary migration definition, not a table column); no route, timer or archive field changed. Re-pinned by census-propose.
diff --git a/docs/superpowers/notes/census-proposal-alias-wake-338.md b/docs/superpowers/notes/census-proposal-alias-wake-338.md
index dc1b245e2..88a04fc52 100644
--- a/docs/superpowers/notes/census-proposal-alias-wake-338.md
+++ b/docs/superpowers/notes/census-proposal-alias-wake-338.md
@@ -26,6 +26,6 @@ New dispositions, which census-propose wrote and the reviewer checks against the
- new `internal/edge/platformalias.go:PlatformAliasFold`: reads +registry:Account ×2, +registry:App ×4, +registry:Host ×3, +registry:Platform ×2, +registry:Socket ×6, +registry:Status ×2, +whole:Route ×10; written legacy, accepted-legacy, frozen
-Seal: `5192052a23d2fdd6f5d48b5617fe28a9bb03458e1e931c060fbdc42c3d627927` → `2f20bae6cb9da96cf1f247231d7b529a23828f2b0a74fa2c3bcbe4a7888e0f28`.
+Seal: `f8acbc0dd8828636e3f73d9afd0e539d3dfd1346e0232d91903c33d6eb27d820` → `deeddee1bf22a18562acda97cc34c6d73ee0dff1825100c73fa0be4c6a3f3e7b`.
Overlay: `internal/provision/testdata/plan14-root-reads-alias-wake-338.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/census-proposal-ha-p1a-433.md b/docs/superpowers/notes/census-proposal-ha-p1a-433.md
new file mode 100644
index 000000000..d39629b4a
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-ha-p1a-433.md
@@ -0,0 +1,34 @@
+# Census approval: ha-p1a-433
+
+Ruling `census-ruling-ha-p1a-433`. The independent reviewer approves or rejects every change below, 8 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/host/agent.go` `provisionTickConfig` | body | unchanged (2) | the agent (carlos-edge.service, user carlos) and the edges file loop's eligibility: the same CARLOS_POOLS read, now parsed by provision.ParseBoxPools (internal/provision, envelope re-pinned), the one parser boxPools also uses. "@shared" (provision.SharedPoolToken, never a valid pool name) is the shared "" pool; other tokens are literal as before; empty elements and repeats dropped. No read added. |
+| `internal/registry/registry.go` `Registry.List` | body | unchanged (16) | the registry's SQLite side as carlos (agent, registry child, and root's read-only registry child via openServiceRegistryReadOnly): calls readCols on the same connection before the same SELECT ... FROM routes ORDER BY host. A read-write registry gets routeCols unchanged; a read-only one gets routeCols with any column routeAddedColumns adds that the table lacks read as its migration default ("0 AS ha"), so root's egress naming and source work before the new agent migrates (#433). Decides nothing; no read added. |
+| `internal/registry/registry.go` `Registry.Get` | sites | +registry:sql | same identities as List: +registry:sql is r.sql handed to readCols, the same connection the SELECT already used; same SELECT ... WHERE host = ? with the select list readCols returns (routeCols for a read-write registry). Root's instanceRegistryHostApp and instanceRegistryHostRuntime read Get through the read-only child and now work before the migration too. |
+
+Envelopes re-pinned: `internal/host`, `internal/instancectl`, `internal/provision`, `internal/registry`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Escalate if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. An escalation goes to the census owner as a decision.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `internal/host/agent.go` `provisionTickConfig`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input
+- `internal/registry/registry.go` `Registry.List`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1,J4;basis=route-and-input;rev3=census-ruling-instance-egress-sizes-328-329;identity=the registry's SQLite side, as carlos: in the agent (/opt/carlos/carlos agent, carlos-edge.service) and in the registry child (carlos __registry-child, which a root pass forks as the service user), and now also in the read-only registry child (carlos __registry-child read-only, which root's instance control forks as the service user through openServiceRegistryReadOnly);basis=#328 plan 2 Task 13 fix (4e7bbc4b): a read-only registry (OpenReadOnly sets readOnly) lists over its own mode=ro, query_only connection (registry:sql, one site, r.sql) instead of a fresh sql.Open on its path, which opens read-write; registry:readOnly (one site) is the branch on that flag. A read-write registry keeps main's fresh connection. The same SELECT of routeCols from routes; it serves root's egress source (listRegistryReadOnly) every row; it decides nothing
+- `internal/registry/registry.go` `Registry.Get`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1,J4;basis=route-and-input
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `internal/instancectl/peer_linux.go:systemdEdgeMainPID`: reads +file:CommandContext; written legacy, accepted-legacy, frozen
+- new `internal/registry/registry.go:Registry.readCols`: reads +file:Query, +registry:readOnly; written legacy, accepted-legacy, frozen
+- new `internal/registry/registry.go:addedColumn.spec`: reads +registry:Default, +registry:Name, +registry:Type; written legacy, accepted-legacy, frozen
+- new `internal/registry/registry.go:addedRouteColumnDefaults`: reads +registry:Default, +registry:Name, +whole:addedColumn; written legacy, accepted-legacy, frozen
+- other `changed registry schema`: closed only if it is the registry schema (re-pinned)
+- quiet `internal/instancectl/peer_linux.go:productionPeerOK`: reads nothing now; retired while it reads nothing (or its row keeps no sites)
+- reads `internal/registry/claimrows.go:Registry.migrateClaimOwnership`: +registry:Claim, +whole:addedColumn; keeps legacy, task accepted-legacy
+- reads `internal/registry/registry.go:Registry.migrate`: +registry:Claim, +whole:addedColumn; keeps legacy, task accepted-legacy
+
+Seal: `5192052a23d2fdd6f5d48b5617fe28a9bb03458e1e931c060fbdc42c3d627927` → `f8acbc0dd8828636e3f73d9afd0e539d3dfd1346e0232d91903c33d6eb27d820`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-ha-p1a-433.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/census-proposal-rollup-tenant-tags.md b/docs/superpowers/notes/census-proposal-rollup-tenant-tags.md
new file mode 100644
index 000000000..f50ea83f9
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-rollup-tenant-tags.md
@@ -0,0 +1,11 @@
+# Census approval: rollup-tenant-tags
+
+Ruling `census-ruling-rollup-tenant-tags`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+Envelopes re-pinned: `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.
+
+Seal: `f8acbc0dd8828636e3f73d9afd0e539d3dfd1346e0232d91903c33d6eb27d820` → `f8acbc0dd8828636e3f73d9afd0e539d3dfd1346e0232d91903c33d6eb27d820`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-rollup-tenant-tags.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/census-proposal-usage-attribution-390.md b/docs/superpowers/notes/census-proposal-usage-attribution-390.md
new file mode 100644
index 000000000..d8a02fdb0
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-usage-attribution-390.md
@@ -0,0 +1,11 @@
+# Census approval: usage-attribution-390
+
+Ruling `census-ruling-usage-attribution-390`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+Envelopes re-pinned: `.`.
+
+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.
+
+Seal: `5192052a23d2fdd6f5d48b5617fe28a9bb03458e1e931c060fbdc42c3d627927` → `5192052a23d2fdd6f5d48b5617fe28a9bb03458e1e931c060fbdc42c3d627927`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-usage-attribution-390.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/remote-instance-metrics.md b/docs/superpowers/notes/remote-instance-metrics.md
index 52859a9ec..cf8c43813 100644
--- a/docs/superpowers/notes/remote-instance-metrics.md
+++ b/docs/superpowers/notes/remote-instance-metrics.md
@@ -378,3 +378,44 @@ continuity family, so under stopping rule 2 the overlap summing was cut
rather than patched again: a host read in both layouts in one tick has no
reading that tick (`TestMergeNestedCutsAnOverlap`). Census: the changed
units and envelope approved. The branch review stops here.
+
+## Follow-up: tags in the hourly rollups (branch rollup-tenant-tags)
+
+Usage attribution (#390, 70930b64) counts a reading for an account by
+the box's tag (live readings) or by a host in that account's namespace.
+The statements read hourly rollups, which carried no tag, so instances
+on custom domains counted against no account.
+
+Each rolled-up hour now carries, per unit, `owned`: one entry per tenant
+the box tagged any of that unit's samples with, holding the same `cpu`
+and `mem_bytes` aggregates over exactly those samples
+(`metrics.HourAgg.Owned`, `rollupOwned`). Untagged samples join no
+owner and stay only in the whole-unit aggregate. The tag rule is the
+sample's, unchanged: the rollup only groups what the box already
+vouched, sample by sample. Additive and omitted when empty.
+
+The usage sweep (`sweepUsage`, so the statements) charges a unit whose
+hostname names its account, or a platform unit, as before. A unit no
+hostname attributes is charged to each owner for its owned aggregate
+only (through the same `attribute` rule as a live tagged reading), and
+the rest of its hour is counted against no account and logged.
+
+No new request: the same day objects, a little larger. Old boxes'
+rollups have no `owned`; their custom-domain hours count nowhere, as
+now. Rides the next box release.
+
+Tests (`internal/console/usageattrib_tags_test.go`, samples tagged by the
+box's rule over box B's real registry, rolled up and stored by the box's
+own functions, the real sweep and statements pass): a custom-domain
+instance on box B counted for its owner for exactly its tagged samples
+(whole, part and untagged hours); a reused custom hostname charged to
+the predecessor for the hours its tag is on and never to the new owner,
+and to no one while B's row and activator disagree. `TestRollupHourOwned`
+in `internal/metrics`. Mutations: 6, all killed.
+
+Review (Astra, billing, 5fe6b58b): READY AFTER FIXES. One P2: the
+uncounted remainder subtracted CPU-else-memory counts, so a tagged
+memory-only sample could cancel an untagged CPU one in the log. Fixed:
+`unchargedSamples` subtracts CPU and memory counts separately and then
+applies the CPU-else-memory rule. Census: `internal/metrics` envelope
+approved. The review stops here.
diff --git a/docs/superpowers/notes/reviews/ASTRA-FINDINGS-ha-p1a-433-r1.md b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-ha-p1a-433-r1.md
new file mode 100644
index 000000000..e9428b8ac
--- /dev/null
+++ b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-ha-p1a-433-r1.md
@@ -0,0 +1,36 @@
+Reviewed `fc30b421..a3650c4c2eca917c2c2cce2c2ffc217114d37f32`, round 1.
+
+**P1: none found.**
+
+**P2 — Registry: fallback omits four migration-added columns.**
+`readCols` gets defaults only from `routeAddedColumns` ([registry.go:1135](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/ha-p1a-dev-pair-433/internal/registry/registry.go:1135)). That list excludes `claim_incarnation`, `claim_stamp`, `claim_owner`, and `claim_row_id`, added separately by [claimrows.go:39](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/ha-p1a-dev-pair-433/internal/registry/claimrows.go:39). All four remain in `routeCols`.
+
+A registry predating that migration still makes both `List` and `Get` fail with `no such column`, contrary to check 3’s requirement to tolerate every migration-added column. An in-memory SQLite probe using the source’s SQL reproduced this for each omitted column. The specific missing-`ha` case succeeds.
+
+Fix: include all four defaults through a shared migration definition and extend the compatibility test to remove each migration-added column independently. The current test checks the fallback list against itself, so it misses these omissions.
+
+**Fault family:** read-only registry compatibility before migration.
+
+**P3: none found.**
+
+Census decisions below approve the trust boundaries and dispositions at this commit; the P2 concerns compatibility completeness.
+
+| Unit or envelope | Class | Verdict | Lines read and basis |
+|---|---|---|---|
+| `provisionTickConfig` | body | APPROVE | `internal/host/agent.go:3490–3519`; same environment inputs, shared parser. |
+| `Registry.List` | body | APPROVE | `internal/registry/registry.go:1065–1102`; read-only connection retained; fixed select identifiers. |
+| `Registry.migrate` | body | APPROVE | `internal/registry/registry.go:646–830`; all 52 extracted statements retain their text and order. |
+| `Registry.Get` | sites | APPROVE | `internal/registry/registry.go:1153–1171`; same connection and parameterized host predicate. |
+| `systemdEdgeMainPID` | new, accepted-legacy | APPROVE | `internal/instancectl/peer_linux.go:74–85`; fixed command and arguments, three-second timeout; invalid answers refused by `readLocked`. |
+| `Registry.readCols` | new, accepted-legacy | APPROVE | `internal/registry/registry.go:703–715,1112–1150`; schema names only control membership checks; SQL comes from binary literals. |
+| `productionPeerOK` | quiet | APPROVE | `internal/instancectl/peer_linux.go:47–70`; scanned command read moved to the separately recorded unit; UID and PID checks remain. |
+| `internal/host` | envelope | APPROVE | `agent.go:635–725,3490–3519`; `layoutleg.go:355–469`; `rootfsplacement.go:149–169,309–321`. Retries precede recovery and startup; unswept fallback and ownership refusal remain. |
+| `internal/instancectl` | envelope | APPROVE | `peer_edge.go:27–115`; `peer_linux.go:22–85`; `server.go:315–365`. Fresh acceptance requires exact PID equality; forced reads are limited; production acceptance is serial. |
+| `internal/provision` | envelope | APPROVE | `reconcile.go:2894–2955`; `provision.go:875`. Only exact `@shared` maps to the shared pool; invalid nonempty tokens remain literal. |
+| `internal/registry` | envelope | APPROVE | `registry.go:607–624,646–830,1017–1171`; `readonly.go:11–25`; `claimrows.go:39–51`. Read-write migration behavior is unchanged; no database-supplied identifier enters generated SQL. |
+
+All four envelope hashes and six recorded function-body hashes match the proposal. `git diff --check` passed. Go tests could not start because the read-only sandbox denied build-directory creation; the SQLite probe is not a Go test result. Network restrictions prevented retrieving #433 or recording decisions on #280. No files changed.
+
+Apply the P2 without reopening the review, retaining the required census and changed-root-behavior checks within this round.
+
+**READY AFTER FIXES**
\ No newline at end of file
diff --git a/docs/superpowers/notes/reviews/ASTRA-FINDINGS-ha-p1a-433-r2.md b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-ha-p1a-433-r2.md
new file mode 100644
index 000000000..5f664b43b
--- /dev/null
+++ b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-ha-p1a-433-r2.md
@@ -0,0 +1,21 @@
+Reviewed `a3650c4c..3ffbf984a669778ea4fcb8e5d362e1f368787334`, scoped round 2. Earlier approvals remain unchanged.
+
+**P1: none found.**
+**P2: none found.** The four omitted claim columns now share the migration definition and receive their correct fallback defaults.
+
+**P3 — Census documentation:** [census-ha-p1a-433-claims.md:13](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/ha-p1a-dev-pair-433/docs/superpowers/notes/census-ha-p1a-433-claims.md:13) still describes defaults parsed by a regexp; the overlay repeats this description. Readers could mistake the removed parser for a validation boundary. Follow-up: describe the literal `addedColumn` definitions instead. **Fault family:** census explanation accuracy. No further review round needed.
+
+| Unit or envelope | Class | Verdict | Lines read and basis |
+|---|---|---|---|
+| `addedColumn.spec` | new, accepted-legacy | APPROVE | `internal/registry/registry.go:646–720`; joins binary literals only. |
+| `addedRouteColumnDefaults` | new, accepted-legacy | APPROVE | `internal/registry/registry.go:661–731,1130–1167`; all 56 added columns covered; database-provided names never enter SQL. |
+| `Registry.migrate` | reads | APPROVE | `internal/registry/registry.go:736–848`; same 52 statements, ordering and error handling. |
+| `Registry.migrateClaimOwnership` | reads | APPROVE | `internal/registry/claimrows.go:39–55`; same four definitions, both tables and duplicate-column handling. |
+| Registry schema | other | APPROVE | `internal/registry/registry.go:646–649`; field inventory adds only `Claim`, `Default`, `Type`; `Name` already existed. No stored schema change. |
+| `internal/registry` | envelope | APPROVE | Above ranges; `registry.go:1083–1189`, `readonly.go:11–25`, `ha_test.go:107–202`. Read-only restrictions remain; no new untrusted SQL or root authority. |
+
+Verified migration statement equivalence, all four changed function fingerprints, the registry envelope and cumulative census seals. An in-memory SQLite probe passed with each added column absent individually and all 56 absent together.
+
+Targeted Go tests could not start: the read-only sandbox blocked build-directory creation. Network restrictions prevented retrieving #433; review relied on the brief. No files changed.
+
+**READY**
\ No newline at end of file
diff --git a/docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-ha-p1a-433-R1.md b/docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-ha-p1a-433-R1.md
new file mode 100644
index 000000000..ca15574ae
--- /dev/null
+++ b/docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-ha-p1a-433-R1.md
@@ -0,0 +1,30 @@
+# Review brief: HA P1a #433 fixes and the shared-pool token (code + census), round 1 of 3
+
+Repo carlos/platform, branch `ha-p1a-dev-pair-433`, the commit named in the reviewer's prompt.
+Under review: the diff `fc30b421..<that commit>` (code, tests) AND its census proposal (`docs/superpowers/notes/census-proposal-ha-p1a-433.md`, overlay `internal/provision/testdata/plan14-root-reads-ha-p1a-433.tsv`, claims `docs/superpowers/notes/census-ha-p1a-433-claims.md`).
+Authorities: main's code; the approved spec `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md` (rev 6.1); AGENTS.md "The census: the reviewer decides". Problem statement: amadan discussion #433.
+
+You are the independent reviewer (Astra; the author is Claude) for both the code and the census. You decide every census class.
+
+## Fixed: do not re-argue
+- Paul's rulings: fix #433; add a reserved token so a box can serve the shared pool plus a named pool (dev HA pair "hapair" on two IE dev boxes, ordinary instances stay one-box).
+
+## What to check
+1. Root peer check (`internal/instancectl/peer_edge.go`, `peer_linux.go`): the re-read of systemd's MainPID on a mismatch accepts ONLY a peer whose pid equals the fresh MainPID; nothing wider; rate limit sound; no TOCTOU that lets another process in.
+2. Agent startup sweep retry (`internal/host/layoutleg.go` `startActivator`): bounded; strictly before recovery and any wake; never a sweep after wakes may start; unswept fallback unchanged.
+3. Registry read-only column tolerance (`Registry.readCols`, `List`, `Get`): root reads every migration-added column as its default when absent; the agent's read-write path unchanged; no SQL built from untrusted input.
+4. `provision.ParseBoxPools` and `@shared`: one parser for both call sites; `@shared` can never be a pool name; a typo can never widen a box to the shared pool; serves_shared_pool consistent.
+5. Census: for every unit and envelope on the card, a verdict citing the lines read; reject if root can now open, run, query or follow anything new from a path or input a tenant, an app or a box agent can create, write or name, or if a check root relies on is weakened.
+
+## Severity
+- **P1**: unsafe (for root, single writer, or tenancy), would not compile, a test fails, or it would not work. Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity. Follow-up list only.
+
+## Output
+Findings ranked P1, P2, P3 (area, problem, evidence file:line, failure scenario, fix, fault family), then the census table (unit, class, APPROVE/REJECT, lines read). End with exactly one verdict:
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1; listed P2s 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. Leave GOCACHE unset.
diff --git a/docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-ha-p1a-433-R2.md b/docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-ha-p1a-433-R2.md
new file mode 100644
index 000000000..bcb0d7ec4
--- /dev/null
+++ b/docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-ha-p1a-433-R2.md
@@ -0,0 +1,30 @@
+# Review brief: HA P1a #433 fixes and the shared-pool token (code + census), round 2 of 3 (scoped)
+
+Repo carlos/platform, branch `ha-p1a-dev-pair-433`, the commit named in the reviewer's prompt.
+Under review (SCOPED): the P2 fix and census update only, `85db2687` and `961f1e14` (diff `a3650c4c..<that commit>`). Round 1 (READY AFTER FIXES, P2: read-only fallback omitted four claim columns) approved every other unit; do not re-review those. Census units changed: new `addedColumn.spec`, `addedRouteColumnDefaults`; changed `Registry.migrate`, `Registry.migrateClaimOwnership`; other: registry schema re-pin; envelope `internal/registry`.
+Authorities: main's code; the approved spec `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md` (rev 6.1); AGENTS.md "The census: the reviewer decides". Problem statement: amadan discussion #433.
+
+You are the independent reviewer (Astra; the author is Claude) for both the code and the census. You decide every census class.
+
+## Fixed: do not re-argue
+- Paul's rulings: fix #433; add a reserved token so a box can serve the shared pool plus a named pool (dev HA pair "hapair" on two IE dev boxes, ordinary instances stay one-box).
+
+## What to check
+1. Root peer check (`internal/instancectl/peer_edge.go`, `peer_linux.go`): the re-read of systemd's MainPID on a mismatch accepts ONLY a peer whose pid equals the fresh MainPID; nothing wider; rate limit sound; no TOCTOU that lets another process in.
+2. Agent startup sweep retry (`internal/host/layoutleg.go` `startActivator`): bounded; strictly before recovery and any wake; never a sweep after wakes may start; unswept fallback unchanged.
+3. Registry read-only column tolerance (`Registry.readCols`, `List`, `Get`): root reads every migration-added column as its default when absent; the agent's read-write path unchanged; no SQL built from untrusted input.
+4. `provision.ParseBoxPools` and `@shared`: one parser for both call sites; `@shared` can never be a pool name; a typo can never widen a box to the shared pool; serves_shared_pool consistent.
+5. Census: for every unit and envelope on the card, a verdict citing the lines read; reject if root can now open, run, query or follow anything new from a path or input a tenant, an app or a box agent can create, write or name, or if a check root relies on is weakened.
+
+## Severity
+- **P1**: unsafe (for root, single writer, or tenancy), would not compile, a test fails, or it would not work. Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity. Follow-up list only.
+
+## Output
+Findings ranked P1, P2, P3 (area, problem, evidence file:line, failure scenario, fix, fault family), then the census table (unit, class, APPROVE/REJECT, lines read). End with exactly one verdict:
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1; listed P2s 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. Leave GOCACHE unset.
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-rollup-tenant-tags-r1.md b/docs/superpowers/reviews/CODEX-FINDINGS-rollup-tenant-tags-r1.md
new file mode 100644
index 000000000..94ee4c5d9
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-rollup-tenant-tags-r1.md
@@ -0,0 +1,18 @@
+Round 1 of 3: no P1 findings; one P2.
+
+1. **P2 — `sweepUsage`: subtract metric counts before selecting the unattributed remainder.**
+ At [economicspass.go:458](/home/paulca/amadan.net/carlos/platform-rollup-tags/internal/console/economicspass.go:458), the code subtracts independently selected instance counts. But [unitHourUsage:624](/home/paulca/amadan.net/carlos/platform-rollup-tags/internal/console/economicspass.go:624) selects CPU’s count when available, otherwise memory’s. Those counts can represent different samples.
+
+ **Failure scenario:** one tagged sample carries only memory; a later untagged sample carries CPU and memory. The whole aggregate selects CPU N=1; the owned aggregate selects memory N=1. Subtraction yields zero, so the untagged sample disappears from the log. A first reading without a CPU delta is supported by [parse.go:168](/home/paulca/amadan.net/carlos/platform-rollup-tags/internal/metrics/parse.go:168). Tenant charges remain isolated.
+
+ **Fix:** subtract accepted owners’ CPU and memory counts separately, then apply the CPU-else-memory rule to the residual counts. Add a regression test asserting the remaining `1/60` unattributed hour is logged.
+
+ **Fault family:** unattributed usage accounting — tagged samples must not cancel unrelated untagged samples in the remainder.
+
+Validation: reviewed both rollup production paths, replacement writes, statement reruns, live status, census and economics consumers, and fleet presence accounting. No new requests were introduced. `git diff --check` passed. Targeted Go tests could not start because the sandbox refused creation of Go’s build directory; the six reported mutation kills were not independently rerun.
+
+**Census verdict: APPROVE `internal/metrics` envelope re-pin.** The independently calculated fingerprint matches the overlay. [RollupHour:138](/home/paulca/amadan.net/carlos/platform-rollup-tags/internal/metrics/rollup.go:138) and [rollupOwned:145](/home/paulca/amadan.net/carlos/platform-rollup-tags/internal/metrics/rollup.go:145) add in-memory grouping over existing samples, calling the existing aggregator and sorting owners. They add no root reads, path resolution, execution, or weakened validation. No unit dispositions change.
+
+Fix the P2 without reopening the review, retaining the required checks on the resulting diff.
+
+**READY AFTER FIXES**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-usage-attribution-390-r1.md b/docs/superpowers/reviews/CODEX-FINDINGS-usage-attribution-390-r1.md
new file mode 100644
index 000000000..090095032
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-usage-attribution-390-r1.md
@@ -0,0 +1,47 @@
+1. **P1 — §1: `created_at` does not establish which tenant ran the process.**
+ **Evidence:** [usageattrib.go:219](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/console/usageattrib.go:219) accepts an untagged reading solely because the current record predates it. [remotemetrics_test.go:219](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/console/remotemetrics_test.go:219) establishes that, without a lifetime judge, reconcile can retain the predecessor’s running row after the successor’s record exists.
+ **Failure scenario:** A deletes a hostname; B recreates it at 10:59. A’s process continues into 11:00. The 11:00 rollup is charged to B. An untagged live reading is likewise assigned to B immediately after creation. The new reuse test manually deletes the predecessor’s row before checking attribution.
+ **Fix:** Require evidence binding the sampled process to its tenant for the measured interval. With the available inputs, leave unproven untagged readings unattributed; a longer creation-time delay cannot prove ownership. Add the retained-predecessor case to the billing test.
+ **Fault family:** Tenant identity of usage—record creation is not process ownership.
+
+2. **P1 — §2: Current reports and routes assign historical usage without any time bound.**
+ **Evidence:** [usageattrib.go:236](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/console/usageattrib.go:236) uses both fallbacks without consulting `at`; [remoteinstances.go:344](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/console/remoteinstances.go:344) checks only box and reported tenant.
+ **Failure scenario:** A used a hostname earlier this month. Its record is gone, and B now has a hand route on the same box. Today’s report assigns A’s earlier hours to B during the monthly re-sweep. The console-route fallback produces the same result.
+ **Fix:** Disable these fallbacks for historical attribution unless evidence establishes the tenant throughout the sampled interval. A report-generation timestamp or freshness threshold supplies no ownership start/end bound, so the existing reports cannot justify this retrospective join.
+ **Fault family:** Tenant identity of usage—present ownership cannot establish historical ownership.
+
+3. **P1 — §§1,3: Stamped units bypass the sampling-box boundary.**
+ **Evidence:** [usageattrib.go:201](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/console/usageattrib.go:201) matches the console registry’s stamped unit before checking `box`, records, or the live tag.
+ **Failure scenario:** The console box stamps `carlos-bespoke.service` for account A. Another box runs that unit name for B or as platform overhead. Every reading from that second box is assigned to A.
+ **Fix:** Apply stamped-route attribution only when the sampling box equals a known console-box label. An unknown label must not authorize every box; remove that permissive case from the local-route fallback too. Test identical stamped names on two boxes.
+ **Fault family:** Tenant identity of usage—a box-local unit name is not a fleet-wide identity.
+
+4. **P2 — §4: The create-only census discards malformed-record information.**
+ **Evidence:** [economicspass.go:123](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/console/economicspass.go:123) discards `unreadable`. The strict reader explicitly returns malformed records through that map with no error ([reconcile.go:2711](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/provision/reconcile.go:2711)). The census is then persisted at line 160.
+ **Failure scenario:** A remote app’s only instance record cannot decode. Its app and route disappear from the day’s census permanently, even after the record is repaired.
+ **Fix:** Refuse census creation when `unreadable` is nonempty. Test that no day object is written and that a subsequent clean read succeeds.
+ **Fault family:** Billing snapshot completeness—a permanent census must not treat an unreadable record as absent.
+
+5. **P2 — §4: Sidecar read failures still permit statement replacement.**
+ **Evidence:** [usageattrib.go:257](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/console/usageattrib.go:257) retains sidecar GET errors, but [usageattrib.go:215](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/console/usageattrib.go:215) converts them into ordinary unknown ownership. Statements subsequently reach [economicspass.go:864](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/console/economicspass.go:864).
+ **Failure scenario:** One sidecar GET fails transiently. All its monthly hours are omitted, and the pass overwrites an otherwise correct statement with the reduced total. The economics page receives no corresponding records warning.
+ **Fix:** Propagate attribution read failures separately from genuinely unknown ownership. Abort statement writes on those failures; expose a warning on the read path. Add a failing-sidecar-GET test that preserves the existing statement.
+ **Fault family:** Billing snapshot completeness—failed reads must not become zero usage.
+
+6. **P2 — §5: Route fallback reintroduces excluded records.**
+ **Evidence:** [economicspass.go:150](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/console/economicspass.go:150) skips trashed and customer-fleet records before marking their hosts covered; lines 156–157 then count every remaining local route.
+ **Failure scenario:** A trashed app still has a local route while withdrawal is pending. Its record is excluded, but its route restores the app to the permanent census. A placement change to a customer fleet has the same gap while the old local route remains.
+ **Fix:** Track all record-covered hosts separately from counted hosts. Apply exclusions before counting, and allow route fallback only for hosts no record covers.
+ **Fault family:** Census membership—route fallback must not override record exclusions.
+
+7. **P2 — §5: Remote sidecar-only apps remain absent from the census.**
+ **Evidence:** The reader used at [economicspass.go:123](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/console/economicspass.go:123) enumerates only `instances/` ([reconcile.go:2681](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/provision/reconcile.go:2681)); the remaining census source is the console’s local routes.
+ **Failure scenario:** An app with only a sidecar on another platform box contributes zero apps and routes. The same app counts when its sidecar runs on the console box. This undercounts `app_months`.
+ **Fix:** Include eligible sidecar records in the census, using the same exclusions and host deduplication. Test a remote sidecar-only app.
+ **Fault family:** Census membership—an app’s count must not depend on its platform box.
+
+**Census verdict for envelope `.`: APPROVE.** Read [status_instances.go:36](/home/paulca/amadan.net/carlos/platform-usage-attrib/status_instances.go:36), lines 102–159, and the formatting helpers at [color.go:137](/home/paulca/amadan.net/carlos/platform-usage-attrib/color.go:137), lines 210–237. The changes add a decoded boolean, select display text, and print a conditional note. They introduce no new root open, execution, query, path traversal, or weakened validation.
+
+Validation: `git diff --check` passed. Targeted tests could not start because the read-only sandbox prevented Go from creating its work directory. No files were edited.
+
+**NOT READY**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-usage-attribution-390-r2.md b/docs/superpowers/reviews/CODEX-FINDINGS-usage-attribution-390-r2.md
new file mode 100644
index 000000000..2cb1b45d0
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-usage-attribution-390-r2.md
@@ -0,0 +1,23 @@
+R1 finding 1 (P1) — **resolved**: `created_at` no longer establishes ownership; untagged custom-domain readings remain unattributed.
+R1 finding 2 (P1) — **resolved**: historical attribution no longer uses current records, reports, or routes.
+R1 finding 3 (P1) — **resolved**: tenant-stamped bespoke units are unattributed on every box.
+R1 finding 4 (P2) — **resolved**: a nonempty `unreadable` set refuses census creation.
+R1 finding 5 (P2) — **resolved**: billing no longer reads sidecar records for attribution, removing the failed-read-to-zero path.
+R1 finding 6 (P2) — **resolved**: excluded records’ hosts are marked covered before route fallback.
+R1 finding 7 (P2) — **resolved**: the census includes sidecar records from live and trashed apps, with placement exclusions.
+
+No outstanding P1 or P2 findings.
+
+1. **P3 — §§2–3: Comments still describe the removed attribution algorithm.**
+ **Problem and evidence:** [apistatusinstances.go:90](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/console/apistatusinstances.go:90) describes creation-time, report, and route fallbacks; [status_instances.go:141](/home/paulca/amadan.net/carlos/platform-usage-attrib/status_instances.go:141) says ownership comes from instance records. Neither matches [usageattrib.go:151](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/console/usageattrib.go:151).
+ **Failure scenario:** A maintainer investigating attribution follows an ownership rule deliberately removed after round 1. No current runtime failure.
+ **Fix:** Update these comments to describe live tags, account namespaces, and the stamped-unit exclusion. Keep this on the follow-up list.
+ **Fault family:** Attribution documentation must match the implemented evidence requirements.
+
+Validation: targeted tests could not start because the read-only sandbox prevented Go from creating its work directory. Mutation results were not independently rerun. Formatting checks on the inspected Go files passed. `git diff --check` reported only Markdown hard-break whitespace in the committed R1 findings. No files were edited.
+
+**Root census, envelope `.` — APPROVE.** Reviewed [status_instances.go:36](/home/paulca/amadan.net/carlos/platform-usage-attrib/status_instances.go:36), the printer at line 102, copy values at line 154, and their formatting helpers. The changes decode a boolean and select printed text. They introduce no new root open, execution, query, path traversal, or weakened validation.
+
+**Record-write census, `Server.handleAPIStatusInstances` — APPROVE.** Reviewed [apistatusinstances.go:98](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/console/apistatusinstances.go:98) through its response, including attribution and app-name reads. No record write is added, moved, or reclassified; the `key-site` / `lit:instances` disposition retained at [usage_attribution_390_census_test.go:17](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/provision/usage_attribution_390_census_test.go:17) remains appropriate.
+
+**READY**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rollup-tenant-tags.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rollup-tenant-tags.md
new file mode 100644
index 000000000..3a782cede
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rollup-tenant-tags.md
@@ -0,0 +1,82 @@
+# Review brief: branch rollup-tenant-tags (billing), round 1 of 3
+
+Repo carlos/platform, branch `rollup-tenant-tags`, commit named in the
+reviewer's prompt. Under review: the diff `origin/main..<commit>`.
+Authorities on main: `docs/superpowers/notes/remote-instance-metrics.md`
+(the box's per-sample tag rule, reviewed and merged in 4dc5902d and
+d7ae1d76) and `internal/console/usageattrib.go` (#390, 70930b64, its
+reviews in that branch's report). This branch adds the note's section
+"Follow-up: tags in the hourly rollups". 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 new note section, then the
+diff, and check every claim against the code.
+
+## Fixed: do not re-argue
+
+- Paul's rulings: a reading counts for an account only on evidence that
+ holds for the whole time it covers (#390); the box's per-sample tag is
+ such evidence (the merged tag rule); untagged usage of a custom-domain
+ instance counts against no account; local and namespace attribution
+ keep #390's behaviour.
+- The per-sample tag rule itself (merged). Raise it only with new
+ evidence that a rolled-up hour can carry a tag its samples did not.
+
+## What to check
+
+Fault family: **tenant identity of usage** (an hour, or part of one,
+charged to an account that did not run it, or a tenant's usage charged to
+the platform). Name it beside every finding in that family.
+
+1. `metrics.RollupHour`/`rollupOwned`: does each owner's aggregate cover
+ exactly the samples tagged with it, on every path the box rolls an
+ hour (metricsFlush's old-hour rollup over a merged chunk,
+ backfillPrevHourRollup)? Can a restart, a merged chunk or duplicate
+ timestamps make an owner's N or average include another tenant's or an
+ untagged sample?
+2. `sweepUsage` (`internal/console/economicspass.go`): namespace-owned and
+ platform units as before; an unknown unit charged to each owner only
+ for its owned aggregate, through `attribute`; the remainder counted for
+ no one. Double counting? Over-counting when an hour's rollup is
+ rewritten? Statements' re-runs over the month?
+3. Interaction with #390's other paths: status --instances (live), the
+ census, economics views. Anything still reading rollups as untagged?
+4. Wire shape: additive `owned`; every reader of day rollups (fleet
+ presence hours included).
+5. Tests: production-wired as described; a custom-domain instance on a
+ non-console box counted for its owner; a reused hostname not counted
+ for the wrong account; untagged hours counted nowhere. Mutations: 6,
+ all killed.
+6. Request budget: no new request.
+7. **Census (the reviewer decides every class).** Card
+ `docs/superpowers/notes/census-proposal-rollup-tenant-tags.md`: the
+ `internal/metrics` envelope re-pin. Approve or reject, citing lines.
+
+## 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 verdict. 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-usage-attribution-390-R2.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-usage-attribution-390-R2.md
new file mode 100644
index 000000000..1c0b8cbad
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-usage-attribution-390-R2.md
@@ -0,0 +1,103 @@
+# Review brief: branch usage-attribution-390 (#390), round 2 of 3
+
+Repo carlos/platform, branch `usage-attribution-390`, commit b84f7d476e876b4ebcb777db7a11bd88ee7134f6 (the code;
+this brief is committed on top).
+Under review: the diff `origin/main...usage-attribution-390` (main merged in at
+d3c5601b).
+Authorities, all on main: discussion #390, and
+`docs/superpowers/notes/remote-instance-metrics.md`. Do not review against
+unmerged branches.
+
+You are an independent reviewer. Read the diff, then the code it names, and
+check every claim against that code. This is billing code.
+
+## Fixed: do not re-argue
+
+- Paul, #390, 2026-10-26: "Build the fix; October self-corrects". No backfill.
+- A reading whose account cannot be established is counted against no
+ account and logged, never charged to ops.
+- Day rollups carry no tag; rolling tags into hours is a box change, out of
+ scope here (a follow-up).
+- Cap check done: plans are off on flagship (no CARLOS_PLAN_CATALOG, no
+ control/plans.json), so no cap can trip.
+- The consequence of the round 2 rule below is accepted: an instance on a
+ custom domain (5 of 202 instance records on flagship) is counted against no
+ account in statements until boxes roll tags into hours.
+
+## The change since round 1
+
+`internal/console/usageattrib.go` was rewritten. A reading is an account's
+only on evidence that holds for the whole time it covers: the box's tag on a
+live reading, or a host that names its account by construction
+(`<...>.<sqid>.<apps domain>` with at least one label before the sqid, or a
+sidecar's `<name>.<app>.<sqid>.sidecar.internal`), for a live console account.
+Billing reads no records, box reports or console-box routes for ownership any
+more. A unit stamped on a tenant's console-box route is counted nowhere on
+any box; one stamped on the platform's own route is platform overhead. The
+census (`censusPass`, `censusRecords` in `economicspass.go`) keeps records
+and adds sidecar records.
+
+## What to check
+
+1. **The namespace as identity (fault family: tenant identity of usage).**
+ Can any account other than <sqid> ever hold a host under
+ `<sqid>.<apps domain>`, through any door a tenant can reach (instance
+ create, domain attach, apex mints, sidecars, seeds, imports, moves,
+ adoption)? Operator store-mode writes are trusted. Is the sqid parse in
+ `namespaceOwner` right (case, trailing dot, the bare-domain exclusion,
+ an apps domain that is itself a suffix of another)?
+2. **Live tag** in `attribute`: used only on the live view.
+3. **Stamped units**: `tenantStamped` from the console box's registry.
+4. **Census**: unreadable records refuse; Trash and fleet hosts are covered
+ before console-box routes count; sidecars of live and trashed apps.
+5. **Request budget**: billing reads nothing new; the census adds one sidecar
+ listing per app per day through the record view when armed; the status
+ door reads records tolerantly for the APP column.
+6. **Tests** (`usageattrib_test.go` and the updated fixtures) and mutations
+ (12 run, 12 killed: live account not required, wrong sqid label, sidecar
+ not recognised, unknown charged to ops, tag ignored, tenant-stamped as
+ platform, unknown as platform, census ignores records, excluded host not
+ covered, undecodable accepted, sidecars skipped, bare domain accepted).
+7. **Census**: `docs/superpowers/notes/census-proposal-usage-attribution-390.md`,
+ root envelope `.` re-pinned (only `status_instances.go`, the CLI printer,
+ changed). Record-write census:
+ `internal/provision/usage_attribution_390_census_test.go` re-pins
+ `Server.handleAPIStatusInstances` (no write added). Verdict on both.
+
+## Round 2
+
+Earlier rounds: `docs/superpowers/reviews/CODEX-FINDINGS-usage-attribution-390-r1.md`.
+
+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.
+
+## 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-usage-attribution-390.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-usage-attribution-390.md
new file mode 100644
index 000000000..42aca29b7
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-usage-attribution-390.md
@@ -0,0 +1,131 @@
+# Review brief: branch usage-attribution-390 (#390), round 1 of 3
+
+Repo carlos/platform, branch `usage-attribution-390`, commit 902e12c9312e5cfbff3a5a0cf961defd6ce8ef11 (the code; this brief is committed on top).
+Under review: the diff `origin/main...usage-attribution-390` (merge base
+78c23655).
+Authorities, all on main: discussion #390 and its proposal reply
+(`AMADAN_HOME=~/.amadan-agent amadan discuss show carlos/platform 390` if you
+can reach it; otherwise this brief carries what matters), and
+`docs/superpowers/notes/remote-instance-metrics.md` (the box's tenant tag on
+live samples). Do not review against unmerged branches.
+
+You are an independent reviewer. Read the diff, then the code it names, and
+check every claim against that code. This is billing code: statements feed
+the economics page and the (dormant) plan caps.
+
+## The change in one paragraph
+
+Statements (`statementsPass`, hourly, create-or-replace for the month to
+date), the census (`censusPass`, daily, create-only), the economics page
+(`buildEconomicsView`) and `carlos status --instances` used to attribute
+every box's sampled units against the console box's own registry, so an
+instance on another box was charged to the ops account, and the month's
+re-sweep moved a moved instance's earlier hours to ops. Now
+`internal/console/usageattrib.go` attributes each reading: stamped
+console-box unit; non-instance unit = platform (ops); live reading tagged by
+its box = the tag; the host's instance or sidecar record if it existed when
+the hour began (a host some record names is decided by its records alone);
+for a host with no record, the sampling box's fresh report, then the console
+box's route (console's own box only); otherwise counted against no account
+and logged.
+
+## Fixed: do not re-argue
+
+- Paul, #390, 2026-10-26: "Build the fix; October self-corrects". No
+ backfill of stored statements or census days. The first statements pass
+ after release rewrites the open month.
+- Readings whose tenant cannot be established are counted nowhere and
+ logged, never charged to ops (the brief that started this branch).
+- Day rollups carry no tenant tag (remote-instance-metrics note, "Mixed
+ fleet"), and changing the box to roll tags into hours is out of scope (it
+ would need a box release). The tag is used only on the live view.
+- Cap check done before the switch: on flagship the console has no
+ `CARLOS_PLAN_CATALOG` or `CARLOS_BILLING` set and no `control/plans.json`
+ marker exists, so plans are off and no awake-hours cap can trip.
+
+## What to check
+
+1. **Attribution key (fault family: tenant identity of usage).** In
+ `usageAttribution.attribute` and `recordsFor`: can any reading reach an
+ account that did not run it? Walk: a hostname reused across accounts in
+ the month (predecessor's record deleted, successor's created); the hour
+ containing the successor's creation; same-account recreation; a move
+ (record keeps `created_at`, region changes, the source box drops the
+ route); a deleted instance; a sidecar's synthetic host
+ (`provision.SidecarHost`); a record with zero `created_at`; two records
+ naming one host.
+2. **Fallbacks for hosts with no record**: `appFacts.tenantOn`
+ (`remoteinstances.go`) and the console-box route. They carry no time
+ bound. Is that an attribution of a sample whose tenant cannot be
+ established? Say what a bound would need, if anything is possible.
+3. **Platform versus instance**: `instanceHost` treats only
+ `carlos-exec@<host>` and `carlos-app@<host>.service` as instances.
+ Anything else (including stamped units on other boxes) is platform
+ overhead, as on main. Is any tenant unit that main attributed correctly
+ now lost?
+4. **Write-pass failure behaviour**: `passAttribution` refuses on a missing
+ registry or unreadable records; `censusPass` refuses too (create-only).
+ Unreadable record hosts (`unreadable`) attribute nothing. Is there a
+ path that writes a statement or census day from a partial read?
+5. **Census**: records (minus Trash and customer-fleet placements) plus
+ console-box routes no record covers, one per host. Does this over- or
+ under-count `apps` (feeds `app_months`) against what main intended?
+6. **Read path**: `loadAttributionForEconomics` warnings and the fleet
+ meters' one-banner rule in `buildEconomicsView`.
+7. **Live view**: `handleAPIStatusInstances` with `latestOwner`
+ (`metricsview.go`) and the new `Unattributed` row; the CLI printer in
+ `status_instances.go`.
+8. **Request budget** (memory: S3 requests cost money; no new per-box
+ polling): records come through `recordWalkStore` (the change-index view
+ when armed); box reports only when a host has no record, through the
+ 60 s cache; one sidecar record GET per sidecar host per pass. Unarmed
+ deployments walk the records once per statements pass, census pass,
+ economics build and status request. Is that acceptable or a P2?
+9. **Tests** (`usageattrib_test.go`): production-wired through the real
+ create/delete doors, both boxes' real reconcile and reports, and the box's
+ own `metrics.RollupHour`/`UpsertRollup`. The move test re-homes the record
+ with `provision.SetRecordRegion` rather than the box-driven move protocol.
+ Mutations run (all killed): no created_at bound; bound on hour end;
+ records keyed wrong; box reports before records; console-box route for
+ any box; unknown charged to ops; live tag ignored; census ignores records;
+ unknown host treated as platform. Is a material behaviour untested?
+10. **Census**: `docs/superpowers/notes/census-proposal-usage-attribution-390.md`.
+ No unit changed; the root package's envelope (`.`) is re-pinned because
+ `status_instances.go` (the CLI printer) changed. Give a verdict on the
+ envelope: does anything in the root package's change let root open, run,
+ query or follow something it did not before, from a path or input a
+ tenant, an app or a box agent can create, write or name?
+
+## 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 verdict for envelope `.` (approve or reject, citing
+lines read). 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.
+
+In round 3, a NOT READY also says whether the P1s share one cause, and
+whether refusing the case up front or cutting the feature would remove
+them.
+
+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/console/apistatusinstances.go b/internal/console/apistatusinstances.go
index 5577e207c..0e2b845c8 100644
--- a/internal/console/apistatusinstances.go
+++ b/internal/console/apistatusinstances.go
@@ -31,23 +31,18 @@
// outright: this is an operator's view of the whole fleet, and no app-scoped
// machine token has any business holding it.
//
-// SCOPE: the two halves of the join do not reach equally far, and the answer
-// is only as fleet-wide as the shorter one. The READINGS are fleet-wide —
-// every box writes metrics/boxes/<box>/ and LoadMetrics sweeps all of it —
-// but the ROUTES they are attributed against come from openPassRegistry,
-// which opens this console's OWN box-local registry file. On a multi-box
-// deployment a unit sampled on any other box therefore matches no route
-// here, falls through routeForUnit's unmatched case, and lands in the answer
-// as platform overhead charged to the ops account: a whole box's tenants
-// read as the platform's own, which is the opposite of what an operator
-// asking "who is using what" would take from it. sweepUsage
-// (economicspass.go) carries this same trap and the same reasoning — both
-// production deployments are single-box today, so it is inert, and the
-// structural fix is routes-as-bucket-records (PR #137, unmerged), which
-// would give every pass a registry view spanning boxes instead of one box's
-// local file. Until that lands the CLI prints the limit beside the answer,
-// the way `carlos routes` does, rather than letting a short list read as the
-// whole fleet.
+// SCOPE: the readings are fleet-wide — every box writes metrics/boxes/<box>/
+// and LoadMetrics sweeps all of it — and so is the join (#390). Each reading
+// is attributed the way the economics passes attribute it
+// (usageattrib.go): a reading its box tagged with a tenant is that tenant's;
+// otherwise an instance's unit goes to the account its hostname names by
+// construction (the account's platform namespace, or a sidecar's synthetic
+// host), wherever the box is. An instance's unit neither can place (a custom
+// domain with no tag) is shown as unattributed, never as the platform's:
+// until #390
+// a whole remote box's tenants read as platform overhead charged to the ops
+// account, the opposite of what an operator asking "who is using what"
+// would take from it.
//
// The other limit is by design rather than a defect: an instance that is
// ASLEEP has no cgroup and therefore no sample, so it is not here at all.
@@ -61,12 +56,13 @@ import (
"net/http"
"sort"
+ "github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
)
-// apiStatusInstance is one awake instance. Account and app are joined on from
-// the registry through routeForUnit — the same matching rule the economics
-// pass attributes cost with, deliberately shared rather than reimplemented.
+// apiStatusInstance is one awake instance. Account and app are joined on
+// through usageAttribution — the same rule the economics passes attribute
+// cost with, deliberately shared rather than reimplemented.
type apiStatusInstance struct {
Box string `json:"box"`
Unit string `json:"unit"`
@@ -91,6 +87,13 @@ type apiStatusInstance struct {
// operator asking what is on the box wants the box's own overhead in the
// picture, clearly labelled rather than silently dropped.
Platform bool `json:"platform,omitempty"`
+ // Unattributed marks a tenant's unit whose account cannot be
+ // established (usageattrib.go): no tag from its box, and a host in no
+ // live account's namespace, or a unit stamped on a tenant's console-box
+ // route. Account and App are empty; Host is the unit's host (the unit
+ // itself for a stamped unit). The economics passes count such a reading
+ // against no account.
+ Unattributed bool `json:"unattributed,omitempty"`
}
func (s *Server) handleAPIStatusInstances(w http.ResponseWriter, r *http.Request) {
@@ -125,6 +128,17 @@ func (s *Server) handleAPIStatusInstances(w http.ResponseWriter, r *http.Request
jsonError(w, http.StatusBadGateway, "could not read the route registry — try again")
return
}
+ attrib, err := s.newUsageAttribution(routes)
+ if err != nil {
+ log.Printf("console: api status instances: %v", err)
+ jsonError(w, http.StatusBadGateway, "could not read the route registry — try again")
+ return
+ }
+ apps := s.appNames(r.Context())
+ localApps := map[string]registry.Route{}
+ for _, rt := range routes {
+ localApps[rt.Host] = rt
+ }
boxes, _, err := s.LoadMetrics(r.Context())
if err != nil {
log.Printf("console: api status instances: metrics: %v", err)
@@ -138,13 +152,25 @@ func (s *Server) handleAPIStatusInstances(w http.ResponseWriter, r *http.Request
for _, u := range b.Units {
row := apiStatusInstance{Box: b.Box, Unit: u.Unit, CPU: u.CPUFrac, Mem: u.MemBytes}
row.Region, row.RegionName = s.boxRegion(b.Box)
- // unitOwner's two cases, taken off the match already in hand
- // rather than by walking the whole route list a second time —
- // same rule, same answers, one pass.
- if rt, ok := routeForUnit(routes, u.Unit); ok {
- row.Host, row.App, row.Account = rt.Host, rt.App, release.RouteAccount(rt)
- } else {
+ who := attrib.attribute(u.Unit, b.latestOwner(u))
+ switch who.class {
+ case unitTenant:
+ row.Host, row.Account, row.App = who.host, who.owner.Account, who.owner.App
+ // The app, for display only: the host's record, else the
+ // console box's route, when it names the same account.
+ if rec, ok := apps[who.host]; ok && row.App == "" && rec.Account == row.Account {
+ row.App = rec.App
+ }
+ if rt, ok := localApps[who.host]; ok && row.App == "" && release.RouteAccount(rt) == row.Account {
+ row.App = rt.App
+ }
+ case unitPlatform:
row.Platform, row.Account = true, release.OpsAccount
+ default:
+ row.Unattributed, row.Host = true, who.host
+ if row.Host == "" {
+ row.Host = u.Unit
+ }
}
if want != "" && row.Account != want {
continue
diff --git a/internal/console/apistatusinstances_test.go b/internal/console/apistatusinstances_test.go
index 489bf37c8..745b42528 100644
--- a/internal/console/apistatusinstances_test.go
+++ b/internal/console/apistatusinstances_test.go
@@ -100,10 +100,16 @@ func tenancyFixture(t *testing.T, fx *consoleFixture) {
t.Helper()
// fx.sqid is the built-in ops account; "cdef" is somebody else. Two
// tenants on one box is the whole point: a filter can only be shown to
- // narrow if there is something for it to leave behind.
- fx.addRoute(t, registry.Route{Host: "ours.example.com", Kind: "instance", Status: "ready",
+ // narrow if there is something for it to leave behind. Each host is in
+ // its account's platform namespace, which is what establishes the
+ // account (#390); the routes name the apps.
+ fx.srv.cfg.AppsDomain = "oncarlos.test"
+ if err := fx.st.CreateAccount(7777, "cdef", "Widgets", "w@example.com", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ fx.addRoute(t, registry.Route{Host: "ours." + fx.sqid + ".oncarlos.test", Kind: "instance", Status: "ready",
App: "kass", Account: fx.sqid, Channel: "stable"})
- fx.addRoute(t, registry.Route{Host: "theirs.example.com", Kind: "instance", Status: "ready",
+ fx.addRoute(t, registry.Route{Host: "theirs.cdef.oncarlos.test", Kind: "instance", Status: "ready",
App: "widgets", Account: "cdef", Channel: "stable"})
at := time.Now().UTC().Add(-time.Minute)
cpu, mem := 0.25, int64(1<<20)
@@ -113,9 +119,9 @@ func tenancyFixture(t *testing.T, fx *consoleFixture) {
// A full reading, a partial one (CPU but no memory — the reason
// those fields are pointers), and a unit matching no route at
// all: the console's own, which is platform overhead.
- activator.UnitName("ours.example.com"): {CPUFrac: &cpu, MemBytes: &mem},
- activator.UnitName("theirs.example.com"): {CPUFrac: &cpu},
- "console.service": {},
+ activator.UnitName("ours." + fx.sqid + ".oncarlos.test"): {CPUFrac: &cpu, MemBytes: &mem},
+ activator.UnitName("theirs.cdef.oncarlos.test"): {CPUFrac: &cpu},
+ "console.service": {},
}}},
}); err != nil {
t.Fatal(err)
@@ -162,16 +168,16 @@ func TestAPIStatusInstancesAttributesUnitsToAccounts(t *testing.T) {
t.Fatalf("unfiltered = %d rows %+v, want one per sampled unit", len(rows), rows)
}
- ours := byUnit[activator.UnitName("ours.example.com")]
- if ours.Account != fx.sqid || ours.App != "kass" || ours.Host != "ours.example.com" || ours.Platform {
+ ours := byUnit[activator.UnitName("ours."+fx.sqid+".oncarlos.test")]
+ if ours.Account != fx.sqid || ours.App != "kass" || ours.Host != "ours."+fx.sqid+".oncarlos.test" || ours.Platform {
t.Errorf("ours = %+v, want the ops account's kass route rather than platform", ours)
}
if ours.Box != "box-tenancy" || ours.CPU == nil || *ours.CPU != 0.25 || ours.Mem == nil || *ours.Mem != 1<<20 {
t.Errorf("ours = %+v, want box-tenancy carrying its own readings", ours)
}
- theirs := byUnit[activator.UnitName("theirs.example.com")]
- if theirs.Account != "cdef" || theirs.App != "widgets" || theirs.Host != "theirs.example.com" || theirs.Platform {
+ theirs := byUnit[activator.UnitName("theirs.cdef.oncarlos.test")]
+ if theirs.Account != "cdef" || theirs.App != "widgets" || theirs.Host != "theirs.cdef.oncarlos.test" || theirs.Platform {
t.Errorf("theirs = %+v, want cdef's widgets route", theirs)
}
// A sampled unit with no memory reading must arrive as nil rather than 0:
@@ -213,7 +219,7 @@ func TestAPIStatusInstancesAccountFilterNarrows(t *testing.T) {
if len(only) != 1 {
t.Fatalf("?account=cdef = %d rows %+v, want just the one", len(only), only)
}
- if got, want := only[0].Unit, activator.UnitName("theirs.example.com"); got != want {
+ if got, want := only[0].Unit, activator.UnitName("theirs.cdef.oncarlos.test"); got != want {
t.Errorf("?account=cdef returned %q, want %q", got, want)
}
diff --git a/internal/console/economicspage_test.go b/internal/console/economicspage_test.go
index 520990836..a655e5ed2 100644
--- a/internal/console/economicspage_test.go
+++ b/internal/console/economicspage_test.go
@@ -67,7 +67,10 @@ func seedEconomicsGolden(t *testing.T, fx *consoleFixture) {
if err != nil {
t.Fatal(err)
}
- if err := reg.Upsert(registry.Route{Host: "a.example.com", Kind: "instance",
+ // In the ops account's platform namespace, which attributes its
+ // unit (#390).
+ fx.srv.cfg.AppsDomain = "oncarlos.test"
+ if err := reg.Upsert(registry.Route{Host: "a.bab.oncarlos.test", Kind: "instance",
Status: "ready", App: fixtureApp, Version: "v1"}); err != nil {
t.Fatal(err)
}
@@ -75,7 +78,7 @@ func seedEconomicsGolden(t *testing.T, fx *consoleFixture) {
date := usage.DayOf(time.Now())
roll := metrics.DayRollup{V: 1, Box: "box1", Date: date, Hours: map[string]metrics.HourAgg{
"09": {Units: map[string]map[string]metrics.Agg{
- "carlos-app@a.example.com.service": {
+ "carlos-app@a.bab.oncarlos.test.service": {
"cpu": {Avg: 0.5, N: 60},
"mem_bytes": {Avg: 1e9, N: 60},
},
@@ -86,7 +89,7 @@ func seedEconomicsGolden(t *testing.T, fx *consoleFixture) {
putStoreJSON(t, fx.rel, usage.EdgeDayKey("box1", date), usage.EdgeDay{
V: 1, Box: "box1", Date: date,
Hours: map[string]map[string]usage.EdgeRow{"09": {
- "a.example.com": {Account: fixtureAcct, App: fixtureApp, Requests: 4000, BytesOut: 2e9},
+ "a.bab.oncarlos.test": {Account: fixtureAcct, App: fixtureApp, Requests: 4000, BytesOut: 2e9},
}},
})
}
@@ -211,7 +214,10 @@ func TestEconomicsPageHonestUnmetered(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- if err := reg.Upsert(registry.Route{Host: "a.example.com", Kind: "instance",
+ // In the ops account's platform namespace, which attributes its
+ // unit (#390).
+ fx.srv.cfg.AppsDomain = "oncarlos.test"
+ if err := reg.Upsert(registry.Route{Host: "a.bab.oncarlos.test", Kind: "instance",
Status: "ready", App: fixtureApp, Version: "v1"}); err != nil {
t.Fatal(err)
}
@@ -219,7 +225,7 @@ func TestEconomicsPageHonestUnmetered(t *testing.T) {
date := usage.DayOf(time.Now())
roll := metrics.DayRollup{V: 1, Box: "darkbox", Date: date, Hours: map[string]metrics.HourAgg{
"09": {Units: map[string]map[string]metrics.Agg{
- "carlos-app@a.example.com.service": {
+ "carlos-app@a.bab.oncarlos.test.service": {
"cpu": {Avg: 0.5, N: 60},
"mem_bytes": {Avg: 1e9, N: 60},
},
@@ -450,7 +456,10 @@ func TestEconomicsAccountsPageThreadsPeriod(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- if err := reg.Upsert(registry.Route{Host: "a.example.com", Kind: "instance",
+ // In the ops account's platform namespace, which attributes its
+ // unit (#390).
+ fx.srv.cfg.AppsDomain = "oncarlos.test"
+ if err := reg.Upsert(registry.Route{Host: "a.bab.oncarlos.test", Kind: "instance",
Status: "ready", App: fixtureApp, Version: "v1"}); err != nil {
t.Fatal(err)
}
@@ -461,7 +470,7 @@ func TestEconomicsAccountsPageThreadsPeriod(t *testing.T) {
date := usage.DayOf(lastMonth)
roll := metrics.DayRollup{V: 1, Box: "box1", Date: date, Hours: map[string]metrics.HourAgg{
"09": {Units: map[string]map[string]metrics.Agg{
- "carlos-app@a.example.com.service": {
+ "carlos-app@a.bab.oncarlos.test.service": {
"cpu": {Avg: 0.5, N: 60},
"mem_bytes": {Avg: 1e9, N: 60},
},
@@ -471,7 +480,7 @@ func TestEconomicsAccountsPageThreadsPeriod(t *testing.T) {
putStoreJSON(t, fx.rel, usage.EdgeDayKey("box1", date), usage.EdgeDay{
V: 1, Box: "box1", Date: date,
Hours: map[string]map[string]usage.EdgeRow{"09": {
- "a.example.com": {Account: fixtureAcct, App: fixtureApp, Requests: 4000, BytesOut: 2e9},
+ "a.bab.oncarlos.test": {Account: fixtureAcct, App: fixtureApp, Requests: 4000, BytesOut: 2e9},
}},
})
diff --git a/internal/console/economicspass.go b/internal/console/economicspass.go
index db4dd18ca..29668a523 100644
--- a/internal/console/economicspass.go
+++ b/internal/console/economicspass.go
@@ -18,10 +18,10 @@ import (
"github.com/aws/aws-sdk-go-v2/aws"
awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
- "github.com/carlosframework/platform/internal/activator"
"github.com/carlosframework/platform/internal/economics"
"github.com/carlosframework/platform/internal/metrics"
"github.com/carlosframework/platform/internal/objstore"
+ "github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
"github.com/carlosframework/platform/internal/usage"
@@ -96,6 +96,18 @@ func (s *Server) openPassRegistry() (consoleRegistry, error) {
// a route with no account (Route.Account == "") to release.OpsAccount, the
// deployment operator's built-in account — so pre-accounts routes land in
// one place instead of scattering under "".
+//
+// What it counts (#390): every instance and sidecar record, wherever its box
+// is, plus every console-box route no record covers (a hand route, an apex
+// mint), one per host. Until #390 it counted the console box's routes
+// alone, so an account whose instances all ran on other boxes dropped out of
+// the census. Left out, though their hosts still count as covered so their
+// console-box routes are not counted either: records of an app in the Trash
+// (its routes are withdrawn while the record waits out the restore window),
+// and records placed on a customer fleet (fleet boxes are metered by
+// fleetMeters, and their routes were never counted here). Every read must
+// succeed, a record that does not decode included: the day is create-only,
+// so a partial read would be permanent.
func (s *Server) censusPass(ctx context.Context, date string) error {
key := usage.CensusDayKey(date)
if _, _, err := s.cfg.Releases.Get(ctx, key); err == nil {
@@ -109,26 +121,108 @@ func (s *Server) censusPass(ctx context.Context, date string) error {
if err != nil {
return err
}
+ held, err := s.censusRecords(ctx)
+ if err != nil {
+ return fmt.Errorf("console: census pass: %w", err)
+ }
accounts := map[string]usage.CensusAccount{}
apps := map[string]map[string]bool{}
- for _, rt := range routes {
- acct := release.RouteAccount(rt)
+ covered := map[string]bool{}
+ count := func(acct, app string) {
c := accounts[acct]
c.Routes++
if apps[acct] == nil {
apps[acct] = map[string]bool{}
}
- if rt.App != "" && !apps[acct][rt.App] {
- apps[acct][rt.App] = true
+ if app != "" && !apps[acct][app] {
+ apps[acct][app] = true
c.Apps++
}
accounts[acct] = c
}
+ for _, h := range held {
+ if covered[h.host] {
+ continue
+ }
+ covered[h.host] = true
+ if h.counts {
+ count(h.acct, h.app)
+ }
+ }
+ for _, rt := range routes {
+ if covered[rt.Host] {
+ continue
+ }
+ covered[rt.Host] = true
+ count(release.RouteAccount(rt), rt.App)
+ }
day := usage.CensusDay{V: 1, Date: date, Accounts: accounts}
_, err = usage.CreateDayObject(ctx, s.cfg.Releases, key, day)
return err
}
+// censusTenancy is one record's host and tenant for the census; counts is
+// false for a record the census covers but does not count (an app in the
+// Trash, a customer-fleet placement).
+type censusTenancy struct {
+ host, acct, app string
+ counts bool
+}
+
+// censusRecords is every instance and sidecar record for the census, read
+// through the record view when it is armed. Any read that fails, and any
+// record that does not decode, is an error: the census day is create-only.
+func (s *Server) censusRecords(ctx context.Context) ([]censusTenancy, error) {
+ src, _ := s.recordWalkStore(ctx, s.cfg.Releases)
+ recs, unreadable, err := provision.ListAllRecordsStrictJudged(ctx, src, provision.JudgeFrom(ctx))
+ if err != nil {
+ return nil, fmt.Errorf("instance records: %w", err)
+ }
+ if len(unreadable) > 0 {
+ return nil, fmt.Errorf("instance records: %d could not be decoded", len(unreadable))
+ }
+ accts, err := s.store.Accounts()
+ if err != nil {
+ return nil, err
+ }
+ trashed := map[string]bool{}
+ var out []censusTenancy
+ for _, a := range accts {
+ live, err := s.store.AppsIn(a.ID)
+ if err != nil {
+ return nil, err
+ }
+ gone, err := s.store.TrashedAppsIn(a.ID)
+ if err != nil {
+ return nil, err
+ }
+ // Trashed apps' sidecars are listed too, so their hosts are covered
+ // and a console-box route of theirs is not counted in their place.
+ inTrash := map[string]bool{}
+ names := append([]string(nil), live...)
+ for _, t := range gone {
+ trashed[a.Sqid+"/"+t.App] = true
+ inTrash[t.App] = true
+ names = append(names, t.App)
+ }
+ for _, app := range names {
+ scs, err := provision.ListSidecarRecordsStrict(ctx, src, a.Sqid, app)
+ if err != nil {
+ return nil, fmt.Errorf("sidecar records %s/%s: %w", a.Sqid, app, err)
+ }
+ for _, sc := range scs {
+ _, fleet := registry.FleetPlacement(sc.Region)
+ out = append(out, censusTenancy{host: sc.Host, acct: sc.Account, app: sc.App, counts: !fleet && !inTrash[app]})
+ }
+ }
+ }
+ for _, rec := range recs {
+ _, fleet := registry.FleetPlacement(rec.Region)
+ out = append(out, censusTenancy{host: rec.Host, acct: rec.Account, app: rec.App, counts: !fleet && !trashed[rec.Account+"/"+rec.App]})
+ }
+ return out, nil
+}
+
// storagePass sizes every app's deployment-bucket prefix, plus its tenant
// object store when one is provisioned, create-only per day. Requires the
// bucket to support sized listings (release.SizeLister); a store that
@@ -214,45 +308,6 @@ func (s *Server) storagePass(ctx context.Context, date string) error {
return err
}
-// unitOwner attributes a sampled systemd unit (or exec-child cgroup name) to
-// its route's account/app. Matching mirrors OwnerAppMetrics (metricsview.go
-// ~698-730): rather than parse a host back out of the unit string, it builds
-// each route's OWN expected unit names — activator.UnitName/ExecName for a
-// unit-backed or exec-backed instance route, plus the route's stamped Unit
-// column (#110's bespoke unit) — and compares those forward against the
-// sampled name. (Read first per the brief: neither UnitName nor ExecName
-// systemd-escapes the host — activator.UnitName is a bare string
-// concatenation and cgroup.ExecName likewise — so there is no unescaping
-// helper to reuse; building the expected name forward, the same direction
-// OwnerAppMetrics does it, is what keeps a hyphenated or dotted host correct
-// with no separate escaping step.) A unit matching no route — the console's
-// own unit, system units — attributes to release.OpsAccount, app "": platform
-// overhead.
-func unitOwner(routes []registry.Route, unit string) (acct, app string, ok bool) {
- rt, ok := routeForUnit(routes, unit)
- if !ok {
- return release.OpsAccount, "", false
- }
- return release.RouteAccount(rt), rt.App, true
-}
-
-// routeForUnit is the matching rule itself, split out of unitOwner so that a
-// second reader of the same sampled units — `carlos status --instances`,
-// which needs the route's HOST and not only its owner — cannot end up with a
-// private second notion of which route a cgroup belongs to. The comment above
-// unitOwner is the rationale for the rule; this is the rule.
-func routeForUnit(routes []registry.Route, unit string) (registry.Route, bool) {
- for _, rt := range routes {
- if rt.Unit != "" && rt.Unit == unit {
- return rt, true
- }
- if rt.Host != "" && (unit == activator.UnitName(rt.Host) || unit == activator.ExecName(rt.Host)) {
- return rt, true
- }
- }
- return registry.Route{}, false
-}
-
// usageSweep is sweepUsage's result: the box- and account-shaped meters
// accumulated by reading metrics and edge days over [from, to], plus enough
// coverage bookkeeping for callers to label a total honestly. It deliberately
@@ -284,16 +339,17 @@ type usageSweep struct {
// by statementsPass (whole month to date, create-or-replace statements) and
// Task 11's LoadEconomics (arbitrary period, priced live under a scenario).
//
-// routes is the registry snapshot unitOwner attributes sampled units
-// against — the CALLER resolves it, deliberately not sweepUsage itself,
-// because the two callers need opposite failure behaviour on a
-// missing/unmounted registry: statementsPass (a WRITE pass) must refuse
-// outright rather than write a permanent all-zero day off an empty
-// registry.Open (openPassRegistry's own doc comment), while LoadEconomics
-// (a READ path) degrades instead — see loadRoutesForEconomics
-// (economicsview.go). A nil/empty routes therefore isn't an error here:
-// every sampled unit simply falls through unitOwner's unmatched-unit case
-// to release.OpsAccount, same as any other unmatched unit.
+// attrib says whose each sampled unit's hour is (usageattrib.go, #390): an
+// instance's hour goes to the account its hostname names by construction
+// (its account's platform namespace, or a sidecar's synthetic host),
+// wherever the box was; a platform unit's to release.OpsAccount; and a
+// tenant's hour whose account cannot be established to no account at all,
+// tallied and logged once per sweep. The CALLER builds it, deliberately not
+// sweepUsage itself, because the two callers need opposite failure
+// behaviour: statementsPass (a WRITE pass) refuses outright when the console
+// box's registry is missing (passAttribution), while LoadEconomics (a READ
+// path) degrades with a warning (loadAttributionForEconomics,
+// economicsview.go).
//
// Storage and census are deliberately NOT accumulated here: storage's
// account attribution needs a ValidAccount guard with pass-scoped dedup
@@ -304,18 +360,7 @@ type usageSweep struct {
// sweep and nothing else is still a covered day, exactly as before this
// function existed, even though the bytes themselves are read again by
// foldStorageAndCensus.
-//
-// unitOwner attributes a sampled unit against routes, which — for both
-// current callers — is this CONSOLE's own box-local registry, while this
-// sweep iterates units published by every box under metrics/boxes/. On a
-// multi-box deployment a unit sampled on a box other than this console's own
-// can fail to match any route in this registry and silently fall to
-// release.OpsAccount, indistinguishable from the intended platform-overhead
-// fallback. Both production deployments are single-box today, so this is
-// currently inert; the structural fix is routes-as-bucket-records (PR #137,
-// unmerged), which would give every pass a registry view that spans boxes
-// instead of one box's local file.
-func (s *Server) sweepUsage(ctx context.Context, from, to time.Time, routes []registry.Route) (*usageSweep, error) {
+func (s *Server) sweepUsage(ctx context.Context, from, to time.Time, attrib *usageAttribution) (*usageSweep, error) {
metricsBoxes, err := s.cfg.Releases.ListDirs(ctx, metricsBoxesPrefix)
if err != nil {
return nil, fmt.Errorf("console: sweep usage: %w", err)
@@ -355,6 +400,9 @@ func (s *Server) sweepUsage(ctx context.Context, from, to time.Time, routes []re
return bl
}
+ unattributed := unattributedUsage{}
+ defer unattributed.log(from, to)
+
fromDay := from.UTC().Truncate(24 * time.Hour)
toDay := to.UTC().Truncate(24 * time.Hour)
for d := fromDay; !d.After(toDay); d = d.AddDate(0, 0, 1) {
@@ -376,29 +424,49 @@ func (s *Server) sweepUsage(ctx context.Context, from, to time.Time, routes []re
sweep.BoxDays[box]++
bl := boxLoad(box)
bl.Hours += float64(len(roll.Hours))
+ // charge adds one unit's aggregates for an hour to acct.
+ charge := func(acct string, um map[string]metrics.Agg) {
+ cpuCoreHours, memGBHours, instN, hasCPU, hasMem := unitHourUsage(um)
+ mm := touch(acct)
+ if hasCPU {
+ mm[usage.MeterCPUCoreHours] += cpuCoreHours
+ }
+ if hasMem {
+ mm[usage.MeterMemGBHours] += memGBHours
+ }
+ mm[usage.MeterInstanceHours] += float64(instN) / 60
+ al := bl.ByAccount[acct]
+ al.CPUCoreHours += cpuCoreHours
+ al.MemGBHours += memGBHours
+ bl.ByAccount[acct] = al
+ }
for _, hour := range roll.Hours {
for unit, um := range hour.Units {
- acct, _, _ := unitOwner(routes, unit)
- mm := touch(acct)
- var instN int
- var cpuCoreHours, memGBHours float64
- if cpu, ok := um["cpu"]; ok {
- cpuCoreHours = cpu.Avg * float64(cpu.N) / 60
- mm[usage.MeterCPUCoreHours] += cpuCoreHours
- instN = cpu.N
- }
- if mem, ok := um["mem_bytes"]; ok {
- memGBHours = mem.Avg * float64(mem.N) / 60 / 1e9
- mm[usage.MeterMemGBHours] += memGBHours
- if instN == 0 {
- instN = mem.N
+ who := attrib.attribute(unit, nil)
+ switch who.class {
+ case unitTenant:
+ charge(who.owner.Account, um)
+ case unitPlatform:
+ charge(release.OpsAccount, um)
+ default:
+ // No hostname names this unit's account. The part
+ // of the hour its box tagged with a tenant is that
+ // tenant's, as a live tagged reading is (the box's
+ // rollup aggregates each tenant's tagged samples
+ // alone, metrics.HourAgg.Owned); the rest counts
+ // against no account.
+ var charged []map[string]metrics.Agg
+ for _, oa := range hour.Owned[unit] {
+ tag := oa.Owner
+ if w := attrib.attribute(unit, &tag); w.class == unitTenant {
+ charge(w.owner.Account, oa.Metrics)
+ charged = append(charged, oa.Metrics)
+ }
+ }
+ if n := unchargedSamples(um, charged); n > 0 {
+ unattributed.add(box, unit, float64(n)/60)
}
}
- mm[usage.MeterInstanceHours] += float64(instN) / 60
- al := bl.ByAccount[acct]
- al.CPUCoreHours += cpuCoreHours
- al.MemGBHours += memGBHours
- bl.ByAccount[acct] = al
}
}
sweep.PerBox[box] = bl
@@ -549,6 +617,43 @@ func (s *Server) foldStorageAndCensus(ctx context.Context, from, to time.Time, d
return nil
}
+// unitHourUsage is one unit's hour of usage from its "cpu" and "mem_bytes"
+// aggregates: core-hours, GB-hours and the sample count that makes its
+// instance-minutes (the CPU count, else the memory count).
+func unitHourUsage(um map[string]metrics.Agg) (cpuCoreHours, memGBHours float64, instN int, hasCPU, hasMem bool) {
+ cpu, hasCPU := um["cpu"]
+ if hasCPU {
+ cpuCoreHours = cpu.Avg * float64(cpu.N) / 60
+ instN = cpu.N
+ }
+ mem, hasMem := um["mem_bytes"]
+ if hasMem {
+ memGBHours = mem.Avg * float64(mem.N) / 60 / 1e9
+ if instN == 0 {
+ instN = mem.N
+ }
+ }
+ return cpuCoreHours, memGBHours, instN, hasCPU, hasMem
+}
+
+// unchargedSamples is the instance-minutes of a unit's hour left over once
+// the charged owners' parts are taken out: CPU and memory counts are
+// subtracted separately, then the hour's own rule (the CPU count, else the
+// memory count) applies to what remains, so a tagged sample that carried
+// only memory never cancels an untagged one that carried CPU (Astra,
+// rollup-tenant-tags round 1).
+func unchargedSamples(um map[string]metrics.Agg, charged []map[string]metrics.Agg) int {
+ cpuN, memN := um["cpu"].N, um["mem_bytes"].N
+ for _, m := range charged {
+ cpuN -= m["cpu"].N
+ memN -= m["mem_bytes"].N
+ }
+ if cpuN > 0 {
+ return cpuN
+ }
+ return max(memN, 0)
+}
+
// rollupPresenceHours converts one box's day rollup into billable box-hours
// under the fleet-hours presence rule (task-3 brief): fleet-box rollups may
// carry only the host-level aggregate (no per-unit CPU sampling — the box
@@ -614,7 +719,7 @@ func hasDeviceTag(tags string) bool {
//
// Deliberately a SECOND bounded read over metrics day objects, not an
// extension of sweepUsage's single pass: sweepUsage iterates every box under
-// metrics/boxes/ once and attributes by UNIT (unitOwner), which has no
+// metrics/boxes/ once and attributes by UNIT (usageAttribution), which has no
// concept of a fleet box at all — a fleet box's day rollup carries no units
// most of the time (see rollupPresenceHours's doc comment), only a host
// aggregate, so folding this in there would mean threading a
@@ -652,9 +757,9 @@ func hasDeviceTag(tags string) bool {
// bucket-backed box publishing straight to the platform root, or one an
// operator hand-configured with CARLOS_STATUS_PREFIX="" — is invisible to
// this meter: its rollups never appear under fleets/<fleet>/, so it
-// contributes zero fleet box-hours, and its sampled units (if any) fall
-// through unitOwner's unmatched case to release.OpsAccount like any other
-// unrecognized unit, same as a platform box's stray unit would. This
+// contributes zero fleet box-hours, and its sampled units (if any) are
+// attributed like any platform box's (usageAttribution): an instance's
+// to the tenant its record names, anything else to release.OpsAccount. This
// closes itself once the box (re)publishes under its fleet prefix — no
// separate migration is needed.
// - fleetMeters failing makes statementsPass itself fail (see
@@ -731,7 +836,8 @@ func (s *Server) fleetMeters(ctx context.Context, from, to time.Time) (map[strin
// census, for app_months, and fleet box-hours, for fleet_box_hours_server/
// device) into one usage.Statement per account, create-or-replace via
// usage.UpsertStatement — safe to run repeatedly as new days' objects
-// appear. It is a thin caller: open the registry (refusing early — see
+// appear. It is a thin caller: build the attribution (passAttribution:
+// refusing early when the console box's registry is missing — see
// openPassRegistry — since this is the WRITE pass), sweep the whole month to
// date (sweepUsage), fold in storage/census meters (foldStorageAndCensus),
// fold in fleet meters (fleetMeters — a union merge, since an account with
@@ -744,6 +850,13 @@ func (s *Server) fleetMeters(ctx context.Context, from, to time.Time) (map[strin
// deletion onward — the account's last statement object simply stops moving
// forward, rather than the month closing it out explicitly.
//
+// Every run re-attributes the whole month (#390), by evidence that does not
+// change with time: the account a hostname names by construction, not
+// whoever routes the host today. So a move, a delete or a recreate never
+// moves an hour between accounts. An instance on a hostname outside every
+// account's namespace (a custom domain) carries no such evidence, and its
+// hours are counted against no account and logged.
+//
// fleetMeters failing (a bad registry read, a bucket hiccup under a fleet
// prefix) makes this WHOLE pass return an error rather than upsert
// statements missing that account's fleet hours — deliberate (review, fix
@@ -756,11 +869,7 @@ func (s *Server) fleetMeters(ctx context.Context, from, to time.Time) (map[strin
// economics page over it is not, the same asymmetry sweepUsage's own doc
// comment draws between its two callers.
func (s *Server) statementsPass(ctx context.Context, now time.Time) error {
- reg, err := s.openPassRegistry()
- if err != nil {
- return fmt.Errorf("console: statements pass: %w", err)
- }
- routes, err := reg.List()
+ attrib, err := s.passAttribution()
if err != nil {
return fmt.Errorf("console: statements pass: %w", err)
}
@@ -771,7 +880,7 @@ func (s *Server) statementsPass(ctx context.Context, now time.Time) error {
month := usage.MonthOf(nowUTC)
monthStart := time.Date(y, mo, 1, 0, 0, 0, 0, time.UTC)
- sweep, err := s.sweepUsage(ctx, monthStart, nowUTC, routes)
+ sweep, err := s.sweepUsage(ctx, monthStart, nowUTC, attrib)
if err != nil {
return fmt.Errorf("console: statements pass: %w", err)
}
diff --git a/internal/console/economicspass_test.go b/internal/console/economicspass_test.go
index 4a6819b99..7d768eacf 100644
--- a/internal/console/economicspass_test.go
+++ b/internal/console/economicspass_test.go
@@ -334,18 +334,21 @@ func TestStatementsPassGolden(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- if err := reg.Upsert(registry.Route{Host: "a.example.com", Kind: "instance",
+ // The host is in the ops account's platform namespace, which is what
+ // attributes its unit (#390).
+ fx.srv.cfg.AppsDomain = "oncarlos.test"
+ if err := reg.Upsert(registry.Route{Host: "a.bab.oncarlos.test", Kind: "instance",
Status: "ready", App: fixtureApp, Version: "v1"}); err != nil {
t.Fatal(err)
}
- // One box, one day of metrics: unit carlos-app@a.example.com with
+ // One box, one day of metrics: unit carlos-app@a.bab.oncarlos.test with
// cpu avg 0.5 for 60 samples in hour 09 (= 0.5 core-hours), mem avg
// 1e9 bytes (= 1 GB-hour, 1 instance-hour).
cpu, mem := 0.5, 1e9
roll := metrics.DayRollup{V: 1, Box: "box1", Date: "2026-08-10", Hours: map[string]metrics.HourAgg{
"09": {Units: map[string]map[string]metrics.Agg{
- "carlos-app@a.example.com.service": {
+ "carlos-app@a.bab.oncarlos.test.service": {
"cpu": {Avg: cpu, N: 60},
"mem_bytes": {Avg: mem, N: 60},
},
@@ -424,31 +427,33 @@ func TestStatementsPassZeroUsageAccountListed(t *testing.T) {
}
}
-// TestUnitOwnerUnmatchedFallsToOpsAccount pins the correction over the
-// brief's literal text: the fallback is release.OpsAccount ("bab"), never
-// the bare string "ops".
-func TestUnitOwnerUnmatchedFallsToOpsAccount(t *testing.T) {
- acct, app, ok := unitOwner(nil, "console.service")
- if ok {
- t.Fatalf("unitOwner matched an empty route list: acct=%q app=%q", acct, app)
- }
- if acct != release.OpsAccount {
- t.Fatalf("unmatched unit acct = %q, want release.OpsAccount (%q)", acct, release.OpsAccount)
- }
- if app != "" {
- t.Fatalf("unmatched unit app = %q, want empty", app)
+// TestAttributionPlatformUnitFallsToOpsAccount pins the correction over the
+// brief's literal text: a unit that is not a tenant's is platform overhead,
+// charged to release.OpsAccount ("bab"), never the bare string "ops".
+func TestAttributionPlatformUnitFallsToOpsAccount(t *testing.T) {
+ a := &usageAttribution{}
+ if who := a.attribute("console.service", nil); who.class != unitPlatform || who.owner != (metrics.Owner{}) {
+ t.Fatalf("console.service = %+v, want platform overhead", who)
}
}
-// TestUnitOwnerMatchesStampedUnitColumn: a route with a non-empty Unit
-// column matches that exact unit name, independent of Host.
-func TestUnitOwnerMatchesStampedUnitColumn(t *testing.T) {
- routes := []registry.Route{
- {Host: "bespoke.example.com", App: "bespoke", Unit: "carlos-bespoke.service"},
+// TestAttributionStampedUnits: a unit stamped on a tenant's console-box route
+// is that tenant's workload, but a stamped name is no identity on another
+// box or over time, so it is counted against no account (#390, Astra round
+// 1). A unit stamped on the platform's own route stays platform overhead.
+func TestAttributionStampedUnits(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fx.addRoute(t, registry.Route{Host: "bespoke.example.com", App: "bespoke", Account: "cdef", Unit: "carlos-bespoke.service"})
+ fx.addRoute(t, registry.Route{Host: "console.example.com", App: "console", Unit: "console.service"})
+ a, err := fx.srv.passAttribution()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if who := a.attribute("carlos-bespoke.service", nil); who.class != unitUnknown {
+ t.Fatalf("tenant-stamped unit = %+v, want counted against no account", who)
}
- acct, app, ok := unitOwner(routes, "carlos-bespoke.service")
- if !ok || app != "bespoke" || acct != release.OpsAccount {
- t.Fatalf("unitOwner(stamped unit) = %q %q %v", acct, app, ok)
+ if who := a.attribute("console.service", nil); who.class != unitPlatform {
+ t.Fatalf("platform-stamped unit = %+v, want platform overhead", who)
}
}
diff --git a/internal/console/economicsview.go b/internal/console/economicsview.go
index bb6c0ac25..24ff37471 100644
--- a/internal/console/economicsview.go
+++ b/internal/console/economicsview.go
@@ -46,10 +46,10 @@ type EconomicsView struct {
// not be loaded/parsed/validated — never set when active.json is simply
// absent (a fresh deployment, not a fault; see loadActiveScenario).
ScenarioWarning string
- // Warning is set when the SWEEP itself degraded — currently only "no
- // registry configured/reachable", which makes every sampled unit
- // attribute to release.OpsAccount instead of its real account (see
- // loadRoutesForEconomics). Distinct from ScenarioWarning: the two can
+ // Warning is set when the SWEEP itself degraded: no registry
+ // configured/reachable (a unit stamped on a tenant's console-box route
+ // reads as platform overhead), or fleet meters unavailable (see
+ // loadAttributionForEconomics). Distinct from ScenarioWarning: the two can
// both be set at once and Task 13 renders them as separate notices.
Warning string
Scenarios []string // names under economics/scenarios/
@@ -409,9 +409,12 @@ func (s *Server) buildEconomicsView(ctx context.Context, period string) (*Econom
// comment for why this must be the full month, not PeriodDays.
daysInMonth := time.Date(now.Year(), now.Month()+1, 0, 0, 0, 0, 0, time.UTC).Day()
- routes, warning := s.loadRoutesForEconomics(sweepCtx)
+ attrib, warning, err := s.loadAttributionForEconomics()
+ if err != nil {
+ return nil, fmt.Errorf("console: load economics: %w", err)
+ }
- sweep, err := s.sweepUsage(sweepCtx, from, to, routes)
+ sweep, err := s.sweepUsage(sweepCtx, from, to, attrib)
if err != nil {
return nil, fmt.Errorf("console: load economics: %w", err)
}
@@ -429,18 +432,18 @@ func (s *Server) buildEconomicsView(ctx context.Context, period string) (*Econom
// fleetMeters error — see that function's doc comment), THIS is a READ
// path: a bad registry read or a bucket hiccup under a fleet prefix
// degrades to "no fleet meters this render" plus a visible Warning,
- // never a failed dashboard — the same asymmetry loadRoutesForEconomics
+ // never a failed dashboard — the same asymmetry loadAttributionForEconomics
// already draws for the registry itself. Called once per
// buildEconomicsView call, which is already the unit the 60s
// stale-while-revalidate cache (economicsCacheTTL) bounds — no separate
// throttling needed here. A registry-less console would otherwise show
- // TWO banners for the SAME missing registry (loadRoutesForEconomics's
+ // TWO banners for the SAME missing registry (loadAttributionForEconomics's
// and this one, since fleetMeters opens that identical registry) — see
// the warning=="" guard below, which keeps it to one banner, one cause.
if fleetMM, ferr := s.fleetMeters(sweepCtx, from, to); ferr != nil {
log.Printf("console: load economics: fleet meters unavailable: %v", ferr)
// Suppress a second banner when routes are ALREADY degraded
- // (warning != "" here can only mean loadRoutesForEconomics found no
+ // (warning != "" here can only mean loadAttributionForEconomics found no
// usable registry, the one thing that precedes this call): fleetMeters
// opens that exact same registry, so its failure here is the same
// root cause restated, not a second independent fault. One banner,
@@ -714,28 +717,29 @@ func poolTopupAccrual(from, to time.Time, topupUSD float64) float64 {
return total
}
-// loadRoutesForEconomics resolves the routes sweepUsage needs to attribute
-// sampled units to accounts, DEGRADING rather than failing when the
-// registry is missing or unreadable — the opposite of openPassRegistry's
+// loadAttributionForEconomics builds the attribution sweepUsage needs
+// (usageattrib.go), DEGRADING rather than failing when the console box's
+// registry is missing or unreadable — the opposite of passAttribution's
// refusal, and deliberately so: that refusal protects a WRITE pass from
-// reading registry.Open's freshly-created empty sqlite as "zero routes" and
-// writing a permanent, uncorrectable all-zero day. This is a READ path —
-// there is nothing to protect by refusing. A nil routes list simply means
-// unitOwner falls every sampled unit through to release.OpsAccount
-// (indistinguishable from platform overhead, same as any other unmatched
-// unit), and the dashboard still renders with a visible warning rather than
-// a blank 500 — precedent: commit 0958fa3, instances health degrading on a
-// console with no registry rather than failing the page.
-func (s *Server) loadRoutesForEconomics(ctx context.Context) (routes []registry.Route, warning string) {
- reg, err := s.openPassRegistry()
- if err != nil {
- return nil, fmt.Sprintf("no registry available (%v); usage cannot be attributed to accounts by route this sweep", err)
- }
- routes, err = reg.List()
- if err != nil {
- return nil, fmt.Sprintf("registry: %v; usage cannot be attributed to accounts by route this sweep", err)
- }
- return routes, ""
+// reading registry.Open's freshly-created empty sqlite and writing numbers
+// it should not. This is a READ path — there is nothing to protect by
+// refusing. With no registry, a unit stamped on a tenant's console-box route
+// is not recognised, so it reads as platform overhead, and the dashboard
+// still renders with a visible warning rather than a blank 500 — precedent:
+// commit 0958fa3, instances health degrading on a console with no registry
+// rather than failing the page. err is the console's own account list
+// failing, which no page can do without.
+func (s *Server) loadAttributionForEconomics() (attrib *usageAttribution, warning string, err error) {
+ var routes []registry.Route
+ reg, rerr := s.openPassRegistry()
+ if rerr != nil {
+ warning = fmt.Sprintf("no registry available (%v); usage cannot be attributed to accounts by route this sweep", rerr)
+ } else if routes, rerr = reg.List(); rerr != nil {
+ routes = nil
+ warning = fmt.Sprintf("registry: %v; usage cannot be attributed to accounts by route this sweep", rerr)
+ }
+ attrib, err = s.newUsageAttribution(routes)
+ return attrib, warning, err
}
// loadActiveScenario resolves economics.ActiveKey -> named scenario ->
diff --git a/internal/console/economicsview_test.go b/internal/console/economicsview_test.go
index cd3f63dd7..33ed91651 100644
--- a/internal/console/economicsview_test.go
+++ b/internal/console/economicsview_test.go
@@ -34,7 +34,10 @@ func TestLoadEconomicsGolden(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- if err := reg.Upsert(registry.Route{Host: "a.example.com", Kind: "instance",
+ // In the ops account's platform namespace, which attributes its
+ // unit (#390).
+ fx.srv.cfg.AppsDomain = "oncarlos.test"
+ if err := reg.Upsert(registry.Route{Host: "a.bab.oncarlos.test", Kind: "instance",
Status: "ready", App: fixtureApp, Version: "v1"}); err != nil {
t.Fatal(err)
}
@@ -43,7 +46,7 @@ func TestLoadEconomicsGolden(t *testing.T) {
cpu, mem := 0.5, 1e9
roll := metrics.DayRollup{V: 1, Box: "box1", Date: date, Hours: map[string]metrics.HourAgg{
"09": {Units: map[string]map[string]metrics.Agg{
- "carlos-app@a.example.com.service": {
+ "carlos-app@a.bab.oncarlos.test.service": {
"cpu": {Avg: cpu, N: 60},
"mem_bytes": {Avg: mem, N: 60},
},
@@ -54,7 +57,7 @@ func TestLoadEconomicsGolden(t *testing.T) {
putStoreJSON(t, fx.rel, usage.EdgeDayKey("box1", date), usage.EdgeDay{
V: 1, Box: "box1", Date: date,
Hours: map[string]map[string]usage.EdgeRow{"09": {
- "a.example.com": {Account: fixtureAcct, App: fixtureApp, Requests: 4000, BytesOut: 2e9},
+ "a.bab.oncarlos.test": {Account: fixtureAcct, App: fixtureApp, Requests: 4000, BytesOut: 2e9},
}},
})
@@ -217,7 +220,10 @@ func TestLoadEconomicsTierRevenueAndPool(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- if err := reg.Upsert(registry.Route{Host: "a.example.com", Kind: "instance",
+ // In the ops account's platform namespace, which attributes its
+ // unit (#390).
+ fx.srv.cfg.AppsDomain = "oncarlos.test"
+ if err := reg.Upsert(registry.Route{Host: "a.bab.oncarlos.test", Kind: "instance",
Status: "ready", App: fixtureApp, Version: "v1"}); err != nil {
t.Fatal(err)
}
@@ -226,7 +232,7 @@ func TestLoadEconomicsTierRevenueAndPool(t *testing.T) {
cpu, mem := 0.5, 1e9
roll := metrics.DayRollup{V: 1, Box: "box1", Date: date, Hours: map[string]metrics.HourAgg{
"09": {Units: map[string]map[string]metrics.Agg{
- "carlos-app@a.example.com.service": {
+ "carlos-app@a.bab.oncarlos.test.service": {
"cpu": {Avg: cpu, N: 60},
"mem_bytes": {Avg: mem, N: 60},
},
@@ -250,8 +256,8 @@ func TestLoadEconomicsTierRevenueAndPool(t *testing.T) {
putStoreJSON(t, fx.rel, usage.EdgeDayKey("box1", date), usage.EdgeDay{
V: 1, Box: "box1", Date: date,
Hours: map[string]map[string]usage.EdgeRow{"09": {
- "a.example.com": {Account: fixtureAcct, App: fixtureApp, Requests: 4000, BytesOut: 2e9},
- "b.example.com": {Account: poolAcct, App: "poolapp", Requests: 1000, BytesOut: 1e9},
+ "a.bab.oncarlos.test": {Account: fixtureAcct, App: fixtureApp, Requests: 4000, BytesOut: 2e9},
+ "b.example.com": {Account: poolAcct, App: "poolapp", Requests: 1000, BytesOut: 1e9},
}},
})
diff --git a/internal/console/metricsview.go b/internal/console/metricsview.go
index 5e6142844..e9b2ca80c 100644
--- a/internal/console/metricsview.go
+++ b/internal/console/metricsview.go
@@ -85,6 +85,17 @@ func (v BoxMetricsView) ownerIndex(tenant metrics.Owner) int32 {
return -1
}
+// latestOwner is the tenant the box tagged u's latest reading with (the
+// reading UnitRow carries), nil when it tagged none.
+func (v BoxMetricsView) latestOwner(u UnitRow) *metrics.Owner {
+ n := len(u.owner)
+ if n == 0 || n != len(v.times) || u.owner[n-1] < 0 || int(u.owner[n-1]) >= len(v.owners) {
+ return nil
+ }
+ o := v.owners[u.owner[n-1]]
+ return &o
+}
+
// AlertRow is one currently-firing rule on one box. LoadMetrics only ever
// returns firing rules — a quiet rule has nothing to show.
type AlertRow struct {
diff --git a/internal/console/usageattrib.go b/internal/console/usageattrib.go
new file mode 100644
index 000000000..ea895756e
--- /dev/null
+++ b/internal/console/usageattrib.go
@@ -0,0 +1,262 @@
+package console
+
+// Usage attribution (#390): whose is a sampled unit's reading?
+//
+// The readings are fleet-wide: every box writes metrics/boxes/<box>/ and the
+// sweeps read all of it. Until #390 the owner of each reading came from the
+// console box's own registry, so an instance on any other box matched no
+// route and was charged to the ops account as platform overhead, and the
+// statements pass, which re-sweeps the whole month, moved an instance's
+// earlier hours to ops as soon as it left the console's box.
+//
+// The rule now: a reading is an account's only on evidence that holds for
+// the whole time the reading covers. Two things qualify.
+//
+// 1. The box's own tag on the reading (metrics.UnitSample.Owner,
+// docs/superpowers/notes/remote-instance-metrics.md): the box vouches
+// that everything the reading measured was that tenant's. A day
+// rollup's hour carries, per unit, each tenant's tagged samples
+// aggregated alone (metrics.HourAgg.Owned), so the statements count the
+// tagged part of an hour for its tenant and the untagged part for none.
+// 2. A hostname that names its account by construction: <...>.<sqid>.<apps
+// domain>, the account's own platform namespace (the console pins a
+// self-serve app's domain to it, handleAPIInstanceEnable), or a
+// sidecar's synthetic <name>.<app>.<sqid>.sidecar.internal
+// (provision.SidecarHost). No other account can ever hold such a host,
+// before, during or after any move, delete or recreate, and account
+// sqids are never reused. The sqid must be a live console account.
+//
+// What does not qualify, and why (Astra, round 1): a record's created_at says
+// when the record was written, not whose process the box was running (a box
+// can keep a predecessor's row and process after a successor's record
+// exists); a box's report and the console box's routes say who holds a host
+// now, not who held it during an earlier hour of the month; and a unit name
+// stamped on a console-box route is not an identity on any other box. So an
+// instance unit (carlos-exec@<host>, carlos-app@<host>.service) on a host
+// outside every account's namespace, with no tag, and a unit stamped on a
+// tenant's console-box route, are counted against no account, not even the
+// platform's, and the sweep logs them. Any other unit is the platform's own
+// overhead, charged to release.OpsAccount as before.
+//
+// Nothing here reads the bucket: the namespace needs only the console's
+// account list and apps domain. Records are read only for display, to name
+// an instance's app (appNames).
+
+import (
+ "context"
+ "fmt"
+ "log"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/metrics"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// unitClass is what a sampled unit is, for usage.
+type unitClass int
+
+const (
+ // unitPlatform is not a tenant's workload: the platform's own
+ // overhead, charged to release.OpsAccount.
+ unitPlatform unitClass = iota
+ // unitTenant is a reading whose account is established.
+ unitTenant
+ // unitUnknown is a tenant's workload whose account cannot be
+ // established. It is counted against no account.
+ unitUnknown
+)
+
+// unitOwnership is one reading's owner. owner.App is set only when the
+// evidence names it (a tag, a sidecar's host); the account is what
+// attribution establishes.
+type unitOwnership struct {
+ class unitClass
+ host string
+ owner metrics.Owner
+}
+
+// usageAttribution answers unitOwnership for every reading of one pass. It is
+// built once per pass (newUsageAttribution) and reads nothing after that.
+type usageAttribution struct {
+ // appsDomain is the console's platform apps domain; "" switches the
+ // namespace rule off, and then only tags attribute instances.
+ appsDomain string
+ // accounts is every live console account's sqid.
+ accounts map[string]bool
+ // tenantStamped is every unit stamped on a console-box route of a
+ // tenant (an account other than the platform's own).
+ tenantStamped map[string]bool
+}
+
+// newUsageAttribution builds the attribution: the console's accounts and
+// apps domain, and the units stamped on the console box's routes (routes
+// may be nil when it has no registry).
+func (s *Server) newUsageAttribution(routes []registry.Route) (*usageAttribution, error) {
+ accts, err := s.store.Accounts()
+ if err != nil {
+ return nil, fmt.Errorf("accounts: %w", err)
+ }
+ a := &usageAttribution{
+ appsDomain: strings.ToLower(strings.TrimSuffix(s.cfg.AppsDomain, ".")),
+ accounts: map[string]bool{},
+ tenantStamped: map[string]bool{},
+ }
+ for _, acct := range accts {
+ a.accounts[acct.Sqid] = true
+ }
+ for _, rt := range routes {
+ if rt.Unit != "" && release.RouteAccount(rt) != release.OpsAccount {
+ a.tenantStamped[rt.Unit] = true
+ }
+ }
+ return a, nil
+}
+
+// passAttribution is newUsageAttribution for a pass that writes: the console
+// box's registry must open (openPassRegistry: never an empty one created in
+// its place), or the pass writes nothing.
+func (s *Server) passAttribution() (*usageAttribution, error) {
+ reg, err := s.openPassRegistry()
+ if err != nil {
+ return nil, err
+ }
+ routes, err := reg.List()
+ if err != nil {
+ return nil, err
+ }
+ return s.newUsageAttribution(routes)
+}
+
+// instanceHost is the host of an instance's unit: carlos-exec@<host> (an
+// exec-backed or nested instance, or a sidecar) or carlos-app@<host>.service
+// (a unit-backed one). Anything else is not an instance's.
+func instanceHost(unit string) (string, bool) {
+ const app = "carlos-app@"
+ switch {
+ case strings.HasPrefix(unit, "carlos-exec@"):
+ host := strings.TrimPrefix(unit, "carlos-exec@")
+ return host, host != "" && activator.ExecName(host) == unit
+ case strings.HasPrefix(unit, app) && strings.HasSuffix(unit, ".service"):
+ host := strings.TrimSuffix(strings.TrimPrefix(unit, app), ".service")
+ return host, host != "" && activator.UnitName(host) == unit
+ }
+ return "", false
+}
+
+// attribute is the owner of a reading of unit. tag is the tenant the box
+// tagged the reading with, nil for none (a rollup hour's whole-unit
+// aggregate; its tagged parts come with their owner, HourAgg.Owned).
+func (a *usageAttribution) attribute(unit string, tag *metrics.Owner) unitOwnership {
+ host, ok := instanceHost(unit)
+ if !ok {
+ if a.tenantStamped[unit] {
+ return unitOwnership{class: unitUnknown}
+ }
+ return unitOwnership{class: unitPlatform}
+ }
+ if tag != nil && tag.Account != "" && tag.App != "" {
+ return unitOwnership{class: unitTenant, host: host, owner: *tag}
+ }
+ if o, ok := a.namespaceOwner(host); ok {
+ return unitOwnership{class: unitTenant, host: host, owner: o}
+ }
+ return unitOwnership{class: unitUnknown, host: host}
+}
+
+// namespaceOwner is the account a host names by construction: a sidecar's
+// <name>.<app>.<sqid>.sidecar.internal (with its app), or a host under
+// <sqid>.<apps domain> with at least one label before the sqid (a bare
+// <x>.<apps domain> may be a pre-accounts app's host whose name happens to
+// be a sqid). The sqid must be a live console account.
+func (a *usageAttribution) namespaceOwner(host string) (metrics.Owner, bool) {
+ host = strings.ToLower(host)
+ if rest, ok := strings.CutSuffix(host, provision.SidecarSuffix); ok {
+ parts := strings.Split(rest, ".")
+ if len(parts) == 3 && provision.ValidSidecarName(parts[0]) && release.ValidApp(parts[1]) && a.accounts[parts[2]] {
+ return metrics.Owner{Account: parts[2], App: parts[1]}, true
+ }
+ return metrics.Owner{}, false
+ }
+ if a.appsDomain == "" {
+ return metrics.Owner{}, false
+ }
+ rest, ok := strings.CutSuffix(host, "."+a.appsDomain)
+ if !ok {
+ return metrics.Owner{}, false
+ }
+ i := strings.LastIndexByte(rest, '.')
+ if i <= 0 {
+ return metrics.Owner{}, false
+ }
+ sqid := rest[i+1:]
+ if !a.accounts[sqid] {
+ return metrics.Owner{}, false
+ }
+ return metrics.Owner{Account: sqid}, true
+}
+
+// unattributedUsage tallies the instance-hours a sweep counted against no
+// account, by box and unit, for one log line per sweep.
+type unattributedUsage map[[2]string]float64
+
+func (u unattributedUsage) add(box, unit string, hours float64) { u[[2]string{box, unit}] += hours }
+
+// log writes the sweep's one line about readings it attributed to no
+// account, naming the ten largest.
+func (u unattributedUsage) log(from, to time.Time) {
+ if len(u) == 0 {
+ return
+ }
+ keys := make([][2]string, 0, len(u))
+ var total float64
+ for k, h := range u {
+ keys = append(keys, k)
+ total += h
+ }
+ sort.Slice(keys, func(i, j int) bool {
+ if u[keys[i]] != u[keys[j]] {
+ return u[keys[i]] > u[keys[j]]
+ }
+ return keys[i][0]+keys[i][1] < keys[j][0]+keys[j][1]
+ })
+ var b strings.Builder
+ for i, k := range keys {
+ if i == 10 {
+ fmt.Fprintf(&b, "; and %d more", len(keys)-10)
+ break
+ }
+ if i > 0 {
+ b.WriteString("; ")
+ }
+ fmt.Fprintf(&b, "%s on box %s %.2f h", k[1], k[0], u[k])
+ }
+ log.Printf("console: usage attribution %s..%s: %.2f instance-hours on %d units counted against no account (no box tag, and the host is in no account's namespace): %s",
+ usageDay(from), usageDay(to), total, len(keys), b.String())
+}
+
+func usageDay(t time.Time) string { return t.UTC().Format("2006-01-02") }
+
+// appNames is the app of every instance record by host, for display only
+// (the live view's APP column): read tolerantly, so a record that will not
+// read leaves its row's app blank and nothing else. ctx bounds the walk.
+func (s *Server) appNames(ctx context.Context) map[string]metrics.Owner {
+ out := map[string]metrics.Owner{}
+ if s.cfg.Releases == nil {
+ return out
+ }
+ src, _ := s.recordWalkStore(ctx, s.cfg.Releases)
+ recs, _, err := provision.ListAllRecordsTolerantJudged(ctx, src, provision.JudgeFrom(ctx))
+ if err != nil {
+ log.Printf("console: instance records for app names: %v", err)
+ return out
+ }
+ for _, rec := range recs {
+ out[rec.Host] = metrics.Owner{Account: rec.Account, App: rec.App}
+ }
+ return out
+}
diff --git a/internal/console/usageattrib_tags_test.go b/internal/console/usageattrib_tags_test.go
new file mode 100644
index 000000000..d025d349c
--- /dev/null
+++ b/internal/console/usageattrib_tags_test.go
@@ -0,0 +1,167 @@
+package console
+
+// Usage of instances on custom domains (#390 follow-up): no hostname names
+// their account, so only the box's tenant tag can, and the statements read
+// hourly rollups. The box rolls each tenant's tagged samples up on their own
+// (metrics.HourAgg.Owned). Two boxes as in usageattrib_test.go; each box's
+// samples are tagged by the box's own rule over its real registry
+// (boxSample: metrics.Vouched, metrics.TagUnits), rolled up by
+// metrics.RollupHour and stored by metrics.UpsertRollup; the passes are the
+// real sweepUsage and statementsPass.
+
+import (
+ "context"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/metrics"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/status"
+ "github.com/carlosframework/platform/internal/usage"
+)
+
+// rollTaggedHour writes one hour of box's rollup from 60 one-minute
+// samples of host's unit: the first tagged of them read while live names
+// the activator's entry, the rest with no live entry (so untagged), each
+// tagged by the box's rule over reg.
+func rollTaggedHour(t *testing.T, tb *twoBoxes, box string, hour time.Time, host string, live map[string]metrics.Live, tagged int) {
+ t.Helper()
+ var samples []metrics.Sample
+ for i := 0; i < 60; i++ {
+ l := live
+ if i >= tagged {
+ l = nil
+ }
+ samples = append(samples, boxSample(t, tb.regB, l, hour.Add(time.Duration(i)*time.Minute),
+ map[string]metrics.UnitSample{execUnit(host): busy()}))
+ }
+ if err := metrics.UpsertRollup(context.Background(), tb.fx.rel, box, hour, metrics.RollupHour(samples)); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// TestUsageTaggedCustomDomainCounted: an instance on a custom domain on
+// box B is counted for its owner for exactly the samples B tagged with it:
+// a whole tagged hour, two thirds of a part-tagged hour, nothing of an
+// untagged hour, and nothing charged to the platform.
+func TestUsageTaggedCustomDomainCounted(t *testing.T) {
+ tb := newTwoBoxes(t)
+ tb.fx.srv.cfg.AppsDomain = nsAppsDomain
+ tb.fx.srv.cfg.BoxLabel = status.Label("box-a")
+ tb.setUp(t, false) // remoteHost (shop.example.com, a custom domain) on B
+ boxB := status.Label("box-b")
+ live := map[string]metrics.Live{remoteHost: {Account: tb.sqid, App: "shop", Entry: 1}}
+ hours := hoursAfter(time.Now(), 4)
+ rollTaggedHour(t, tb, boxB, hours[0], remoteHost, live, 60)
+ rollTaggedHour(t, tb, boxB, hours[1], remoteHost, live, 40)
+ rollTaggedHour(t, tb, boxB, hours[2], remoteHost, live, 0)
+
+ logs := captureLog(t)
+ attrib, err := tb.fx.srv.passAttribution()
+ if err != nil {
+ t.Fatal(err)
+ }
+ sweep, err := tb.fx.srv.sweepUsage(context.Background(), hours[0], hours[3], attrib)
+ if err != nil {
+ t.Fatal(err)
+ }
+ near(t, "owner instance_hours", sweep.PerAccount[tb.sqid][usage.MeterInstanceHours], 1+40.0/60)
+ near(t, "owner cpu_core_hours", sweep.PerAccount[tb.sqid][usage.MeterCPUCoreHours], 0.5*(1+40.0/60))
+ near(t, "owner mem_gb_hours", sweep.PerAccount[tb.sqid][usage.MeterMemGBHours], 1+40.0/60)
+ near(t, "ops instance_hours", sweep.PerAccount[release.OpsAccount][usage.MeterInstanceHours], 0)
+ if !strings.Contains(logs.String(), execUnit(remoteHost)) || !strings.Contains(logs.String(), "counted against no account") {
+ t.Fatalf("the untagged part was not logged as counted against no account:\n%s", logs.String())
+ }
+ // The statement (the write pass) counts the same.
+ near(t, "statement instance_hours", statement(t, tb.fx, hours[3], tb.sqid)[usage.MeterInstanceHours], 1+40.0/60)
+}
+
+// TestUsageTaggedReusedHostname: the custom hostname was another
+// account's, which deleted it; this account created it again, and B (no
+// lifetime judge) kept the predecessor's row and process. B tags those
+// hours with the predecessor, and they are the predecessor's, never this
+// account's. When B's row names this account while the predecessor's
+// entry still stops, B vouches nothing: those hours count for no one.
+func TestUsageTaggedReusedHostname(t *testing.T) {
+ tb := newTwoBoxes(t)
+ fx := tb.fx
+ fx.srv.cfg.AppsDomain = nsAppsDomain
+ fx.srv.cfg.BoxLabel = status.Label("box-a")
+ ctx := context.Background()
+ now := time.Now()
+ const rivalID int64 = 6464
+ rival := accountSqid(rivalID)
+ if err := fx.st.CreateAccount(rivalID, rival, "Rival", "bob@keymail.dev", now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fx.st.CreateAppIn(rivalID, "shop", "bob@keymail.dev", now); err != nil {
+ t.Fatal(err)
+ }
+ if err := WriteAccountManifest(ctx, fx.rel, rivalID, rival, "Rival", now); err != nil {
+ t.Fatal(err)
+ }
+ if err := provision.PutManifest(ctx, fx.rel, rival, "shop", shopManifest("shop", "shop.example.com")); err != nil {
+ t.Fatal(err)
+ }
+ shipAndPromote(t, fx, rival, "shop", "v3", "stable")
+ bob := cliToken(t, fx, "bob@keymail.dev", "code-usage-tag-reuse-bob")
+ fx.setUser("paul@keymail.dev")
+ tb.create(t, bob, rival, "shop", remoteHost, "uk", "")
+ tb.reconcile(t, "v3")
+ if code, _, out := rawReq(t, http.MethodDelete, instancesURL(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", "")
+ 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)
+ }
+ boxB := status.Label("box-b")
+ rivalLive := map[string]metrics.Live{remoteHost: {Account: rival, App: "shop", Entry: 1}}
+ created := recordOf(t, fx, tb.sqid, "shop", remoteHost).CreatedAt.UTC().Truncate(time.Hour)
+ era := []time.Time{created, created.Add(time.Hour)}
+ rollTaggedHour(t, tb, boxB, era[0], remoteHost, rivalLive, 60)
+
+ // B withdraws the predecessor's row and mints this account's (a box
+ // with a lifetime judge); 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 = %+v, want this account's", rt)
+ }
+ rollTaggedHour(t, tb, boxB, era[1], remoteHost, rivalLive, 60)
+
+ attrib, err := fx.srv.passAttribution()
+ if err != nil {
+ t.Fatal(err)
+ }
+ sweep, err := fx.srv.sweepUsage(ctx, era[0], era[1].Add(time.Hour), attrib)
+ if err != nil {
+ t.Fatal(err)
+ }
+ near(t, "this account's instance_hours", sweep.PerAccount[tb.sqid][usage.MeterInstanceHours], 0)
+ near(t, "the predecessor's instance_hours (its own process, tagged)", sweep.PerAccount[rival][usage.MeterInstanceHours], 1)
+ near(t, "ops instance_hours", sweep.PerAccount[release.OpsAccount][usage.MeterInstanceHours], 0)
+}
+
+// TestUnchargedSamples (Astra, round 1, P2): a tagged sample with only a
+// memory reading and an untagged one with CPU and memory leave one
+// untagged minute, not zero.
+func TestUnchargedSamples(t *testing.T) {
+ whole := map[string]metrics.Agg{"cpu": {N: 1}, "mem_bytes": {N: 2}}
+ owned := map[string]metrics.Agg{"mem_bytes": {N: 1}}
+ if n := unchargedSamples(whole, []map[string]metrics.Agg{owned}); n != 1 {
+ t.Fatalf("uncharged = %d, want 1", n)
+ }
+ if n := unchargedSamples(map[string]metrics.Agg{"cpu": {N: 60}, "mem_bytes": {N: 60}}, []map[string]metrics.Agg{{"cpu": {N: 60}, "mem_bytes": {N: 60}}}); n != 0 {
+ t.Fatalf("a fully tagged hour leaves %d", n)
+ }
+ if n := unchargedSamples(map[string]metrics.Agg{"mem_bytes": {N: 5}}, nil); n != 5 {
+ t.Fatalf("an untagged memory-only hour = %d, want 5", n)
+ }
+}
diff --git a/internal/console/usageattrib_test.go b/internal/console/usageattrib_test.go
new file mode 100644
index 000000000..7838ffe91
--- /dev/null
+++ b/internal/console/usageattrib_test.go
@@ -0,0 +1,513 @@
+package console
+
+// Usage attribution across boxes (#390). The fixture is
+// remoteinstances_test.go's: two boxes and one bucket, instances created and
+// deleted through the console's doors, minted by each box's real reconcile
+// pass, reported by each box's real status snapshot. The app's domain is the
+// account's own platform namespace (<sqid>.<apps domain>), as the console's
+// enable door pins it. Each box's hourly rollups are written by the box's
+// own code (metrics.RollupHour over raw samples, then metrics.UpsertRollup),
+// and the passes under test are the console's real statementsPass,
+// censusPass and status door.
+
+import (
+ "context"
+ "encoding/json"
+ "math"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "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"
+ "github.com/carlosframework/platform/internal/usage"
+)
+
+// rollHour writes one hour of a box's day rollup the way the box's metrics
+// loop does: n one-minute samples of unit, rolled up by metrics.RollupHour
+// and stored by metrics.UpsertRollup. Units already in the hour are kept.
+func rollHour(t *testing.T, rel release.Store, box string, hour time.Time, units map[string]metrics.UnitSample, n int) {
+ t.Helper()
+ ctx := context.Background()
+ var samples []metrics.Sample
+ for i := 0; i < n; i++ {
+ us := map[string]metrics.UnitSample{}
+ for name, u := range units {
+ us[name] = u
+ }
+ samples = append(samples, metrics.Sample{At: hour.Add(time.Duration(i) * time.Minute), Units: us})
+ }
+ agg := metrics.RollupHour(samples)
+ raw, _, err := rel.Get(ctx, metrics.DayKey(box, hour.UTC().Format("2006-01-02")))
+ if err == nil {
+ var day metrics.DayRollup
+ if err := json.Unmarshal(raw, &day); err != nil {
+ t.Fatal(err)
+ }
+ if prev, ok := day.Hours[hour.UTC().Format("15")]; ok {
+ for name, u := range prev.Units {
+ if _, mine := agg.Units[name]; !mine {
+ agg.Units[name] = u
+ }
+ }
+ }
+ }
+ if err := metrics.UpsertRollup(ctx, rel, box, hour, agg); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// busy is one full minute of an instance: half a core and 1 GB, so an hour of
+// 60 samples is 1 instance-hour, 0.5 core-hours and 1 GB-hour.
+func busy() metrics.UnitSample {
+ return metrics.UnitSample{CPUFrac: p(0.5), MemBytes: pi64(1e9)}
+}
+
+// hoursAfter is n whole UTC hours, the first starting after t, all in one
+// calendar month: a statement covers one month, so a window that would
+// cross into the next starts at that month's first hour instead.
+func hoursAfter(t time.Time, n int) []time.Time {
+ first := t.UTC().Truncate(time.Hour).Add(time.Hour)
+ if last := first.Add(time.Duration(n) * time.Hour); last.Month() != first.Month() {
+ y, m, _ := last.Date()
+ first = time.Date(y, m, 1, 0, 0, 0, 0, time.UTC)
+ }
+ out := make([]time.Time, n)
+ for i := range out {
+ out[i] = first.Add(time.Duration(i) * time.Hour)
+ }
+ return out
+}
+
+// statement runs the real statements pass at now and reads acct's month.
+func statement(t *testing.T, fx *consoleFixture, now time.Time, acct string) map[string]float64 {
+ t.Helper()
+ if err := fx.srv.statementsPass(context.Background(), now); err != nil {
+ t.Fatal(err)
+ }
+ raw, _, err := fx.rel.Get(context.Background(), usage.StatementKey(acct, usage.MonthOf(now)))
+ if err != nil {
+ t.Fatalf("statement %s %s: %v", acct, usage.MonthOf(now), err)
+ }
+ var st usage.Statement
+ if err := json.Unmarshal(raw, &st); err != nil {
+ t.Fatal(err)
+ }
+ return st.Meters
+}
+
+func near(t *testing.T, what string, got, want float64) {
+ t.Helper()
+ if math.Abs(got-want) > 1e-9 {
+ t.Fatalf("%s = %v, want %v", what, got, want)
+ }
+}
+
+func recordOf(t *testing.T, fx *consoleFixture, acct, app, host string) provision.Record {
+ t.Helper()
+ recs, _, err := provision.ListRecords(context.Background(), fx.rel, acct, app, 50)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, r := range recs {
+ if r.Host == host {
+ return r
+ }
+ }
+ t.Fatalf("no record of %s in %s/%s", host, acct, app)
+ return provision.Record{}
+}
+
+// nsAppsDomain is the fixture console's platform apps domain.
+const nsAppsDomain = "oncarlos.test"
+
+// nsHost is a host in account sqid's platform namespace.
+func nsHost(label, sqid string) string { return label + "." + sqid + "." + nsAppsDomain }
+
+// inNamespace points the fixture's shop app at the account's own platform
+// namespace, the domain the console's enable door pins a self-serve app to.
+func (tb *twoBoxes) inNamespace(t *testing.T) {
+ t.Helper()
+ tb.fx.srv.cfg.AppsDomain = nsAppsDomain
+ tb.fx.srv.cfg.BoxLabel = status.Label("box-a")
+ if err := provision.PutManifest(context.Background(), tb.fx.rel, tb.sqid, "shop", shopManifest("shop", tb.sqid+"."+nsAppsDomain)); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// reportBoth writes both boxes' status snapshots from their registries.
+func (tb *twoBoxes) reportBoth(t *testing.T) {
+ t.Helper()
+ regA, err := registry.Open(tb.fx.regPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ report(t, tb.fx.rel, regA, "box-a", "ie", time.Now(), nil, 1024)
+ report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096)
+ tb.fresh()
+}
+
+// TestUsageTwoBoxTenant: one account with an instance on the console's box,
+// one on box B and a sidecar on B. All their hours are the account's, in the
+// statement, the census and `carlos status --instances`; the platform's own
+// unit stays with the ops account. On main the remote hours went to ops.
+func TestUsageTwoBoxTenant(t *testing.T) {
+ tb := newTwoBoxes(t)
+ fx := tb.fx
+ tb.inNamespace(t)
+ remote, local := nsHost("eu", tb.sqid), nsHost("ie", tb.sqid)
+ tb.create(t, tb.token, tb.sqid, "shop", remote, "uk", "")
+ tb.create(t, tb.token, tb.sqid, "shop", local, "ie", "")
+ tb.reconcile(t, "v3")
+ if rt, _ := tb.regB.Get(remote); rt == nil {
+ t.Fatal("fixture: box B did not mint the uk instance")
+ }
+ tb.reportBoth(t)
+ // A sidecar of a second app, which has no instance anywhere.
+ if _, err := fx.st.CreateAppIn(5151, "worker", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ side := provision.SidecarHost("bot", "worker", tb.sqid)
+ if err := provision.CreateSidecarRecord(context.Background(), fx.rel, provision.SidecarRecord{Schema: 1, Name: "bot",
+ Host: side, App: "worker", Account: tb.sqid, Region: "uk", Channel: "stable", CreatedAt: time.Now().UTC()}); err != nil {
+ t.Fatal(err)
+ }
+ boxA, boxB := status.Label("box-a"), status.Label("box-b")
+
+ hours := hoursAfter(time.Now(), 3)
+ rollHour(t, fx.rel, boxA, hours[0], map[string]metrics.UnitSample{execUnit(local): busy()}, 60)
+ rollHour(t, fx.rel, boxB, hours[0], map[string]metrics.UnitSample{execUnit(remote): busy(), "carlos-edge.service": busy()}, 60)
+ // A unit-backed instance is never tagged by its box; its host still
+ // names its account. And the sidecar.
+ rollHour(t, fx.rel, boxB, hours[1], map[string]metrics.UnitSample{activator.UnitName(remote): busy(), execUnit(side): busy()}, 60)
+
+ ours := statement(t, fx, hours[2], tb.sqid)
+ near(t, "instance_hours", ours[usage.MeterInstanceHours], 4)
+ near(t, "cpu_core_hours", ours[usage.MeterCPUCoreHours], 2)
+ near(t, "mem_gb_hours", ours[usage.MeterMemGBHours], 4)
+ ops := statement(t, fx, hours[2], release.OpsAccount)
+ near(t, "ops instance_hours (the edge on B)", ops[usage.MeterInstanceHours], 1)
+
+ date := usage.DayOf(hours[2])
+ if err := fx.srv.censusPass(context.Background(), date); err != nil {
+ t.Fatal(err)
+ }
+ raw, _, err := fx.rel.Get(context.Background(), usage.CensusDayKey(date))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var day usage.CensusDay
+ if err := json.Unmarshal(raw, &day); err != nil {
+ t.Fatal(err)
+ }
+ if got, want := day.Accounts[tb.sqid], (usage.CensusAccount{Apps: 2, Routes: 3}); got != want {
+ t.Fatalf("census %s = %+v, want %+v (an instance on each box and the sidecar-only app)", tb.sqid, got, want)
+ }
+
+ // The live view: B's unit is the account's shop, not the platform's.
+ if err := fx.st.SetOperator("paul@keymail.dev", true); err != nil {
+ t.Fatal(err)
+ }
+ writeSamples(t, fx.rel, boxB, metrics.Sample{At: time.Now().UTC(), Units: map[string]metrics.UnitSample{execUnit(remote): {CPUFrac: p(0.2)}}})
+ tb.fresh()
+ var found bool
+ for _, r := range statusInstanceRows(t, fx, tb.token, "?account="+tb.sqid) {
+ if r.Unit == execUnit(remote) {
+ found = true
+ if r.Box != boxB || r.Host != remote || r.App != "shop" || r.Platform || r.Unattributed {
+ t.Fatalf("status --instances row = %+v, want B's unit as the account's shop instance", r)
+ }
+ }
+ }
+ if !found {
+ t.Fatal("status --instances --account left out B's instance")
+ }
+}
+
+// TestUsageReusedHostname: a hostname reused across accounts. Outside every
+// account's namespace (a custom domain, here shop.example.com) nothing says
+// whose process a box ran in which hour: the record, B's row and B's report
+// all name the successor now, and B kept the predecessor's row after the
+// successor's record existed. So neither account is charged for any of it,
+// and the hours are logged. Inside a namespace the reuse cannot happen: the
+// rival cannot create a host in this account's namespace.
+func TestUsageReusedHostname(t *testing.T) {
+ tb := newTwoBoxes(t)
+ fx := tb.fx
+ fx.srv.cfg.AppsDomain = nsAppsDomain
+ fx.srv.cfg.BoxLabel = status.Label("box-a")
+ ctx := context.Background()
+ now := time.Now()
+ const rivalID int64 = 6363
+ rival := accountSqid(rivalID)
+ if err := fx.st.CreateAccount(rivalID, rival, "Rival", "bob@keymail.dev", now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fx.st.CreateAppIn(rivalID, "shop", "bob@keymail.dev", now); err != nil {
+ t.Fatal(err)
+ }
+ if err := WriteAccountManifest(ctx, fx.rel, rivalID, rival, "Rival", now); err != nil {
+ t.Fatal(err)
+ }
+ if err := provision.PutManifest(ctx, fx.rel, rival, "shop", shopManifest("shop", "shop.example.com")); err != nil {
+ t.Fatal(err)
+ }
+ shipAndPromote(t, fx, rival, "shop", "v3", "stable")
+ bob := cliToken(t, fx, "bob@keymail.dev", "code-usage-reuse-bob")
+ fx.setUser("paul@keymail.dev")
+
+ tb.create(t, bob, rival, "shop", remoteHost, "uk", "")
+ tb.reconcile(t, "v3")
+ if code, _, out := rawReq(t, http.MethodDelete, instancesURL(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", "")
+ // B keeps the rival's row (and process) after this account's record
+ // exists: reconcile with no lifetime judge leaves another tenant's row.
+ tb.reconcile(t, "v3")
+ if rt, _ := tb.regB.Get(remoteHost); rt == nil || rt.Account != tb.sqid && rt.Account != rival {
+ t.Fatalf("fixture: B's row = %+v", rt)
+ }
+ tb.reportBoth(t)
+
+ boxB := status.Label("box-b")
+ created := recordOf(t, fx, tb.sqid, "shop", remoteHost).CreatedAt.UTC().Truncate(time.Hour)
+ era := []time.Time{created.Add(-time.Hour), created, created.Add(time.Hour), created.Add(2 * time.Hour)}
+ for _, h := range era {
+ rollHour(t, fx.rel, boxB, h, map[string]metrics.UnitSample{execUnit(remoteHost): busy()}, 60)
+ }
+
+ logs := captureLog(t)
+ attrib, err := fx.srv.passAttribution()
+ if err != nil {
+ t.Fatal(err)
+ }
+ sweep, err := fx.srv.sweepUsage(ctx, era[0], era[3], attrib)
+ if err != nil {
+ t.Fatal(err)
+ }
+ near(t, "this account's instance_hours", sweep.PerAccount[tb.sqid][usage.MeterInstanceHours], 0)
+ near(t, "the rival's instance_hours", sweep.PerAccount[rival][usage.MeterInstanceHours], 0)
+ near(t, "ops instance_hours", sweep.PerAccount[release.OpsAccount][usage.MeterInstanceHours], 0)
+ if !strings.Contains(logs.String(), execUnit(remoteHost)) || !strings.Contains(logs.String(), "counted against no account") {
+ t.Fatalf("the unattributed hours were not logged:\n%s", logs.String())
+ }
+
+ // The rival cannot take a host in this account's namespace.
+ if code, _, out := rawReq(t, http.MethodPost, instancesURL(fx, rival, "shop"), bob, `{"host":"`+nsHost("eu", tb.sqid)+`","region":"uk"}`); code == http.StatusCreated {
+ t.Fatalf("the rival created a host in this account's namespace: %s", out)
+ }
+}
+
+// TestUsageSameAccountRecreate: inside its namespace an account's hostname
+// deleted and created again, on another box, is its own throughout, so the
+// re-run statement keeps every hour.
+func TestUsageSameAccountRecreate(t *testing.T) {
+ tb := newTwoBoxes(t)
+ fx := tb.fx
+ tb.inNamespace(t)
+ host := nsHost("eu", tb.sqid)
+ tb.create(t, tb.token, tb.sqid, "shop", host, "ie", "")
+ tb.reconcile(t, "v3")
+ hours := hoursAfter(time.Now(), 3)
+ rollHour(t, fx.rel, status.Label("box-a"), hours[0], map[string]metrics.UnitSample{execUnit(host): busy()}, 60)
+ if code, _, out := rawReq(t, http.MethodDelete, instancesURL(fx, tb.sqid, "shop")+"/"+host, tb.token, ""); code/100 != 2 {
+ t.Fatalf("delete = %d %s", code, out)
+ }
+ tb.reconcile(t, "v3")
+ tb.create(t, tb.token, tb.sqid, "shop", host, "uk", "")
+ tb.reconcile(t, "v3")
+ rollHour(t, fx.rel, status.Label("box-b"), hours[1], map[string]metrics.UnitSample{execUnit(host): busy()}, 60)
+ near(t, "instance_hours", statement(t, fx, hours[2], tb.sqid)[usage.MeterInstanceHours], 2)
+}
+
+// TestStatementRerunAcrossAMove: an instance runs on the console's box, its
+// record is re-homed to another region and box B mints it (the console's box
+// drops its route). The statement is re-run over the whole month after the
+// move, and keeps the hours from before it. On main the re-run moved them to
+// ops.
+func TestStatementRerunAcrossAMove(t *testing.T) {
+ tb := newTwoBoxes(t)
+ fx := tb.fx
+ tb.inNamespace(t)
+ ctx := context.Background()
+ host := nsHost("ie", tb.sqid)
+ tb.create(t, tb.token, tb.sqid, "shop", host, "ie", "")
+ tb.reconcile(t, "v3")
+ regA, err := registry.Open(fx.regPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if rt, _ := regA.Get(host); rt == nil {
+ t.Fatal("fixture: the console's box did not mint the ie instance")
+ }
+ boxA, boxB := status.Label("box-a"), status.Label("box-b")
+ hours := hoursAfter(time.Now(), 6)
+ for _, h := range hours[:3] {
+ rollHour(t, fx.rel, boxA, h, map[string]metrics.UnitSample{execUnit(host): busy()}, 60)
+ }
+ near(t, "before the move", statement(t, fx, hours[3], tb.sqid)[usage.MeterInstanceHours], 3)
+
+ if err := provision.SetRecordRegion(ctx, fx.rel, tb.sqid, "shop", host, "uk"); err != nil {
+ t.Fatal(err)
+ }
+ tb.reconcile(t, "v3")
+ if rt, _ := regA.Get(host); rt != nil {
+ t.Fatalf("fixture: the console's box still routes the moved instance: %+v", rt)
+ }
+ if rt, _ := tb.regB.Get(host); rt == nil {
+ t.Fatal("fixture: box B did not mint the moved instance")
+ }
+ for _, h := range hours[3:5] {
+ rollHour(t, fx.rel, boxB, h, map[string]metrics.UnitSample{execUnit(host): busy()}, 60)
+ }
+ ours := statement(t, fx, hours[5], tb.sqid)
+ near(t, "after the move, re-run", ours[usage.MeterInstanceHours], 5)
+ near(t, "cpu after the move", ours[usage.MeterCPUCoreHours], 2.5)
+ near(t, "ops after the move", statement(t, fx, hours[5], release.OpsAccount)[usage.MeterInstanceHours], 0)
+}
+
+// TestUsageUnknownInstanceCountsNowhere: a tenant's unit whose account
+// nothing establishes for the whole hour is nobody's: an untagged instance on
+// a custom domain (even one B's report and B's registry name now), a host
+// under the namespace of no live account, and a unit stamped on a tenant's
+// console-box route, on either box. It is not platform overhead, so ops is
+// not charged either; it is logged. A unit stamped on the platform's own
+// route stays the platform's.
+func TestUsageUnknownInstanceCountsNowhere(t *testing.T) {
+ tb := newTwoBoxes(t)
+ fx := tb.fx
+ tb.inNamespace(t)
+ boxA, boxB := status.Label("box-a"), status.Label("box-b")
+ if err := tb.regB.Upsert(registry.Route{Host: "hand.example.com", Kind: "instance", Status: "ready",
+ Account: "cdef", App: "widgets", Hibernate: true}); err != nil {
+ t.Fatal(err)
+ }
+ fx.addRoute(t, registry.Route{Host: "bespoke.example.com", Kind: "instance", Status: "ready", App: "bespoke", Account: "cdef", Unit: "carlos-bespoke.service"})
+ fx.addRoute(t, registry.Route{Host: "console.example.com", Kind: "instance", Status: "ready", App: "console", Unit: "console.service"})
+ tb.reportBoth(t)
+
+ hours := hoursAfter(time.Now(), 2)
+ rollHour(t, fx.rel, boxB, hours[0], map[string]metrics.UnitSample{
+ execUnit("stray.example.com"): busy(),
+ execUnit("hand.example.com"): busy(),
+ execUnit(nsHost("x", "zzzq")): busy(),
+ // The bare <sqid>.<apps domain>: a pre-accounts <app>.<apps domain>
+ // host could share its name with a sqid, so it names no account.
+ execUnit(tb.sqid + "." + nsAppsDomain): busy(),
+ "carlos-bespoke.service": busy(),
+ activator.UnitName("a.b.c.de"): busy(),
+ }, 60)
+ rollHour(t, fx.rel, boxA, hours[0], map[string]metrics.UnitSample{"carlos-bespoke.service": busy(), "console.service": busy()}, 60)
+ logs := captureLog(t)
+ near(t, "ops instance_hours (console.service only)", statement(t, fx, hours[1], release.OpsAccount)[usage.MeterInstanceHours], 1)
+ near(t, "the account whose bare domain was sampled", statement(t, fx, hours[1], tb.sqid)[usage.MeterInstanceHours], 0)
+ if raw, _, err := fx.rel.Get(context.Background(), usage.StatementKey("cdef", usage.MonthOf(hours[1]))); err == nil {
+ var st usage.Statement
+ if err := json.Unmarshal(raw, &st); err != nil {
+ t.Fatal(err)
+ }
+ near(t, "cdef instance_hours", st.Meters[usage.MeterInstanceHours], 0)
+ }
+ for _, u := range []string{execUnit("stray.example.com"), execUnit("hand.example.com"), execUnit(nsHost("x", "zzzq")), "carlos-bespoke.service on box " + boxA, "carlos-bespoke.service on box " + boxB} {
+ if !strings.Contains(logs.String(), u) {
+ t.Fatalf("%s was not logged as unattributed:\n%s", u, logs.String())
+ }
+ }
+}
+
+// TestStatusInstancesAcrossBoxes: the live view joins each sample to its
+// owner by the box's tag or the host's namespace. A sample its box tagged
+// names its tenant; an instance unit nothing establishes is marked
+// unattributed rather than charged to the platform.
+func TestStatusInstancesAcrossBoxes(t *testing.T) {
+ tb := newTwoBoxes(t)
+ fx := tb.fx
+ tb.inNamespace(t)
+ remote := nsHost("eu", tb.sqid)
+ tb.create(t, tb.token, tb.sqid, "shop", remote, "uk", "")
+ tb.reconcile(t, "v3")
+ tb.reportBoth(t)
+ if err := fx.st.SetOperator("paul@keymail.dev", true); err != nil {
+ t.Fatal(err)
+ }
+ boxB := status.Label("box-b")
+ writeSamples(t, fx.rel, boxB, metrics.Sample{At: time.Now().UTC(), Units: map[string]metrics.UnitSample{
+ execUnit(remote): {CPUFrac: p(0.2)},
+ execUnit("tagged.example.com"): {CPUFrac: p(0.3), Owner: &metrics.Owner{Account: "cdef", App: "widgets"}},
+ execUnit("nobodys.example.com"): {CPUFrac: p(0.4)},
+ "carlos-edge.service": {CPUFrac: p(0.1)},
+ }})
+ tb.fresh()
+ got := map[string]apiStatusInstance{}
+ for _, r := range statusInstanceRows(t, fx, tb.token, "") {
+ got[r.Unit] = r
+ }
+ if r := got[execUnit(remote)]; r.Account != tb.sqid || r.App != "shop" || r.Host != remote || r.Platform || r.Unattributed {
+ t.Errorf("remote instance = %+v, want this account's shop", r)
+ }
+ if r := got[execUnit("tagged.example.com")]; r.Account != "cdef" || r.App != "widgets" || r.Host != "tagged.example.com" || r.Unattributed {
+ t.Errorf("tagged sample = %+v, want the tenant its box vouched for", r)
+ }
+ if r := got[execUnit("nobodys.example.com")]; !r.Unattributed || r.Account != "" || r.Platform || r.Host != "nobodys.example.com" {
+ t.Errorf("unknown instance = %+v, want it unattributed, not the platform's", r)
+ }
+ if r := got["carlos-edge.service"]; !r.Platform || r.Account != release.OpsAccount {
+ t.Errorf("edge = %+v, want platform overhead", r)
+ }
+}
+
+// TestCensusRecordsAcrossBoxes: the census counts records wherever they run,
+// does not count an app in the Trash even while its console-box route is
+// still there, and refuses the day when a record will not decode (the day is
+// create-only).
+func TestCensusRecordsAcrossBoxes(t *testing.T) {
+ tb := newTwoBoxes(t)
+ fx := tb.fx
+ tb.inNamespace(t)
+ ctx := context.Background()
+ tb.create(t, tb.token, tb.sqid, "shop", nsHost("eu", tb.sqid), "uk", "")
+ tb.create(t, tb.token, tb.sqid, "shop", nsHost("ie", tb.sqid), "ie", "")
+ tb.reconcile(t, "v3")
+ // Trash the app; the console box's route is still there until its
+ // domains pass withdraws it.
+ if err := fx.st.TrashAppRow(5151, "shop", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ regA, _ := registry.Open(fx.regPath)
+ if rt, _ := regA.Get(nsHost("ie", tb.sqid)); rt == nil {
+ t.Fatal("fixture: the console box's route is gone")
+ }
+ date := usage.DayOf(time.Now())
+ if err := fx.srv.censusPass(ctx, date); err != nil {
+ t.Fatal(err)
+ }
+ raw, _, err := fx.rel.Get(ctx, usage.CensusDayKey(date))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var day usage.CensusDay
+ if err := json.Unmarshal(raw, &day); err != nil {
+ t.Fatal(err)
+ }
+ if got, ok := day.Accounts[tb.sqid]; ok {
+ t.Fatalf("census counts the trashed app: %+v", got)
+ }
+
+ // A record that does not decode: no day is written.
+ next := usage.DayOf(time.Now().Add(24 * time.Hour))
+ if _, err := fx.rel.Put(ctx, provision.RecordKey(tb.sqid, "shop", "bad."+tb.sqid+"."+nsAppsDomain), []byte(`{"schema":1,`), ""); err != nil {
+ t.Fatal(err)
+ }
+ if err := fx.srv.censusPass(ctx, next); err == nil {
+ t.Fatal("census with an undecodable record succeeded")
+ }
+ if _, _, err := fx.rel.Get(ctx, usage.CensusDayKey(next)); err == nil {
+ t.Fatal("census with an undecodable record wrote its day")
+ }
+}
diff --git a/internal/host/agent.go b/internal/host/agent.go
index 811b0ee89..cb6cb3528 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -3489,12 +3489,7 @@ func domainsTickConfig(getenv func(string) string, publicIP string) (domains.Con
// record's own "no-inbound" placement request — see ReconcileConfig.Inbound.
func provisionTickConfig(getenv func(string) string) provision.ReconcileConfig {
region := strings.TrimSpace(getenv("CARLOS_REGION"))
- var pools []string
- for _, p := range strings.Split(getenv("CARLOS_POOLS"), ",") {
- if p = strings.TrimSpace(p); p != "" {
- pools = append(pools, p)
- }
- }
+ pools := provision.ParseBoxPools(getenv("CARLOS_POOLS"))
dd := getenv("CARLOS_DATA_DIR")
if dd == "" {
dd = "/data"
diff --git a/internal/host/agent_layout_test.go b/internal/host/agent_layout_test.go
index 849a38bc0..b354e7861 100644
--- a/internal/host/agent_layout_test.go
+++ b/internal/host/agent_layout_test.go
@@ -3,6 +3,7 @@ package host
import (
"context"
"errors"
+ "fmt"
"os"
"path/filepath"
"reflect"
@@ -244,16 +245,33 @@ func TestLayoutLegNeverLosesAKick(t *testing.T) {
}
}
+// fastSweepRetries makes startActivator's retry waits a millisecond each
+// for one test, and puts them back after it.
+func fastSweepRetries(t *testing.T) {
+ t.Helper()
+ backoff, window := startupSweepBackoff, startupSweepWindow
+ startupSweepBackoff = []time.Duration{time.Millisecond, time.Millisecond, time.Millisecond, time.Millisecond}
+ startupSweepWindow = time.Minute
+ t.Cleanup(func() { startupSweepBackoff, startupSweepWindow = backoff, window })
+}
+
// Recovery runs after the startup unit sweep and before the activator
-// starts, and it runs even when the sweep failed, told so.
+// starts, and it runs even when the sweep failed, told so. A sweep that
+// keeps failing is tried once and retried len(startupSweepBackoff) times
+// first (#433).
func TestStartActivatorRecoversAfterTheSweepAndBeforeStart(t *testing.T) {
+ fastSweepRetries(t)
for _, tc := range []struct {
name string
sweepErr error
swept bool
+ sweeps int
}{
- {"sweep ok", nil, true},
- {"sweep failed", errors.New("channel down"), false},
+ {"sweep ok", nil, true, 1},
+ {"sweep failed", errors.New("channel down"), false, 5},
+ // No control socket at all: a box without the channel, not a
+ // refusal that may clear, so it is not retried.
+ {"no socket", fmt.Errorf("instance control socket /run/x.sock: %w", os.ErrNotExist), false, 1},
} {
t.Run(tc.name, func(t *testing.T) {
var events []string
@@ -262,7 +280,11 @@ func TestStartActivatorRecoversAfterTheSweepAndBeforeStart(t *testing.T) {
func(context.Context) error { events = append(events, "sweep"); return tc.sweepErr },
func(_ context.Context, swept bool) { events = append(events, "recover"); gotSwept = swept },
func() { events = append(events, "start") })
- if want := []string{"sweep", "recover", "start"}; !reflect.DeepEqual(events, want) {
+ var want []string
+ for range tc.sweeps {
+ want = append(want, "sweep")
+ }
+ if want = append(want, "recover", "start"); !reflect.DeepEqual(events, want) {
t.Fatalf("order = %v, want %v", events, want)
}
if gotSwept != tc.swept {
@@ -272,6 +294,67 @@ func TestStartActivatorRecoversAfterTheSweepAndBeforeStart(t *testing.T) {
}
}
+// #433: root refused the new agent's first call, the startup sweep,
+// because its view of the edge's main pid lagged the restart. The sweep is
+// retried before anything can wake, so the box counts as swept
+// (seedSweptAtStart, which same-box recovery of an HA host needs) and the
+// activator starts only after the sweep that succeeded.
+func TestStartupSweepRetriesARefusalBeforeAnyWake(t *testing.T) {
+ fastSweepRetries(t)
+ prev := seedSweptAtStart.Load()
+ t.Cleanup(func() { seedSweptAtStart.Store(prev) })
+ seedSweptAtStart.Store(false)
+ var events []string
+ sweeps := 0
+ done := activatorStart{
+ Sweep: func(context.Context) error {
+ sweeps++
+ events = append(events, "sweep")
+ if sweeps == 1 {
+ return errors.New("instance control socket /run/carlos/control.sock: EOF")
+ }
+ return nil
+ },
+ Recover: func(_ context.Context, swept bool) *layout.Pass {
+ seedSweptAtStart.Store(swept)
+ events = append(events, "recover")
+ return nil
+ },
+ Publish: func(*layout.Pass) {},
+ Start: func() {
+ if !seedSweptAtStart.Load() {
+ t.Error("the activator started with the box unswept")
+ }
+ events = append(events, "start")
+ },
+ Ready: func() { events = append(events, "ready") },
+ Routes: func() ([]registry.Route, error) { return nil, nil },
+ }.Run(t.Context())
+ <-done
+ if want := []string{"sweep", "sweep", "recover", "start", "ready"}; !reflect.DeepEqual(events, want) {
+ t.Fatalf("events = %v, want %v", events, want)
+ }
+ if !seedSweptAtStart.Load() {
+ t.Fatal("seedSweptAtStart false after the retried sweep succeeded")
+ }
+}
+
+// The retries stop at the window: a sweep that hangs to its own deadline
+// is not tried again, so the box never waits minutes before it serves.
+func TestStartupSweepRetriesStopAtTheWindow(t *testing.T) {
+ fastSweepRetries(t)
+ startupSweepWindow = 0
+ sweeps := 0
+ var gotSwept = true
+ startActivator(context.Background(),
+ func(context.Context) error { sweeps++; return errors.New("refused") },
+ func(_ context.Context, swept bool) { gotSwept = swept },
+ func() {})
+ if sweeps != 1 || gotSwept {
+ t.Fatalf("sweeps = %d, swept = %v; want one sweep, unswept", sweeps, gotSwept)
+ }
+}
+
// The intent recovery runs under at start: "" when none applies, the
// recorded mode when one does, and IntentUnreadable whenever the box
// cannot be sure, which holds a completed revert fenced.
diff --git a/internal/host/edgesfile_test.go b/internal/host/edgesfile_test.go
index 9d4ec950f..c16dfca27 100644
--- a/internal/host/edgesfile_test.go
+++ b/internal/host/edgesfile_test.go
@@ -1264,6 +1264,9 @@ func TestEdgesFileEligibilityFollowsTheReconcileConfig(t *testing.T) {
{"", "", true, true},
{"tito", "", false, true},
{",tito", "", false, true},
+ {"@shared,hapair", "", true, true},
+ {"@shared", "", true, true},
+ {"cohort1,hapair", "", false, true},
{"", "none", true, false},
{"tito", "NONE", false, false},
}
diff --git a/internal/host/egress_source_test.go b/internal/host/egress_source_test.go
index 6c21baeba..3772ec691 100644
--- a/internal/host/egress_source_test.go
+++ b/internal/host/egress_source_test.go
@@ -3,6 +3,7 @@ package host
import (
"context"
"crypto/ed25519"
+ "database/sql"
"encoding/json"
"errors"
"io/fs"
@@ -888,3 +889,32 @@ func TestRegistryEgressSourceCarriesTheRowTenant(t *testing.T) {
tenant("not nested", p, "abc", "shop")
tenant("under claims", readPolicy(t, claimsEgressSource(), "shop-a.example.com"), "", "")
}
+
+// #433: at the upgrade to region HA P1a root named slices from the
+// registry before the new agent's migration added routes.ha, and logged
+// "egress: naming slices: ... no such column: ha". Root's reads (the
+// slice names and the allow source) work on a registry the old agent
+// left, without the column.
+func TestRootEgressReadsARegistryWithoutTheHAColumn(t *testing.T) {
+ reg, dd := egressRegistry(t)
+ clock := &testClock{now: time.Date(2026, 10, 26, 21, 30, 0, 0, time.UTC)}
+ upsertRows(t, reg, nestedRow(dd, "shop-a.example.com"), nestedRow(dd, "shop-b.example.com"))
+ setAllow(t, reg, "shop-a.example.com", "10.0.5.20", unixText(clock.Now().Add(time.Hour)))
+ db, err := sql.Open("sqlite", reg.Path())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := db.Exec(`ALTER TABLE routes DROP COLUMN ha`); err != nil {
+ t.Fatal(err)
+ }
+ db.Close()
+
+ hosts, err := registryEgressHosts(dd)()
+ if err != nil {
+ t.Fatalf("naming slices without routes.ha: %v", err)
+ }
+ if want := []string{"shop-a.example.com", "shop-b.example.com"}; !reflect.DeepEqual(hosts, want) {
+ t.Fatalf("hosts = %v, want %v", hosts, want)
+ }
+ wantPolicy(t, readPolicy(t, testEgressSource(t, dd, clock.Now), "shop-a.example.com"), instancectl.EgressPolicy{Allow: []string{"10.0.5.20"}})
+}
diff --git a/internal/host/host_test.go b/internal/host/host_test.go
index 872e958ea..d96d2c955 100644
--- a/internal/host/host_test.go
+++ b/internal/host/host_test.go
@@ -896,6 +896,18 @@ func TestProvisionTickConfig(t *testing.T) {
t.Errorf("Pools = %v, want empties dropped and whitespace trimmed", got.Pools)
}
+ // The shared pool's token (provision.SharedPoolToken) is the "" pool,
+ // beside a named one: one parser for the tick and for boxPools.
+ got = provisionTickConfig(env(map[string]string{"CARLOS_POOLS": "@shared, hapair"}))
+ if !reflect.DeepEqual(got.Pools, []string{"", "hapair"}) {
+ t.Errorf("Pools = %#v, want the shared pool and hapair", got.Pools)
+ }
+ for raw, want := range map[string]string{"": "", "@shared": "", "@shared,hapair": "hapair", "cohort1, hapair": "cohort1,hapair"} {
+ if got := boxPools(env(map[string]string{"CARLOS_POOLS": raw})); got != want {
+ t.Errorf("boxPools(%q) = %q, want %q", raw, got, want)
+ }
+ }
+
got = provisionTickConfig(env(map[string]string{"CARLOS_DATA_DIR": "/custom"}))
if got.DataDir != "/custom" {
t.Errorf("DataDir = %q, want /custom", got.DataDir)
diff --git a/internal/host/layoutleg.go b/internal/host/layoutleg.go
index 71c8f9998..af6779d21 100644
--- a/internal/host/layoutleg.go
+++ b/internal/host/layoutleg.go
@@ -9,7 +9,9 @@ package host
import (
"context"
+ "errors"
"fmt"
+ "io/fs"
"log"
"os"
"os/user"
@@ -376,13 +378,54 @@ func newLayoutPass(reg *registry.Registry, svc *activator.Service, dd string, ne
return p
}
+// startupSweepBackoff is the wait before each retry of a failed startup
+// sweep: five tries over 15 s of waiting. startupSweepWindow bounds them
+// from the first try, so a sweep that hangs to its own deadline is not
+// tried again. Variables only so tests can shorten them.
+var (
+ startupSweepBackoff = []time.Duration{time.Second, 2 * time.Second, 4 * time.Second, 8 * time.Second}
+ startupSweepWindow = 20 * time.Second
+)
+
// startActivator is the order the activator comes up in. The startup unit
// sweep first, so nothing an earlier agent left is running. Then layout
// recovery, which runs even when the sweep failed (completing a journal
// is exact) and is told whether it succeeded. Then Start, so no host is
// woken while a journal says its files are between two directories.
+//
+// A failed sweep is retried (#433): root refused the new agent's first
+// call while its view of the edge's main pid lagged the restart, and a box
+// whose sweep failed can never retake an HA host on its own (same-box
+// recovery needs the sweep). The retries all run here, before Start, so
+// no wake can begin while one is pending: a sweep stops every instance
+// unit, and it must never run after wakes may have started. They wait
+// startupSweepBackoff between tries and stop once the next try would
+// begin past startupSweepWindow from the first, or when ctx ends; then
+// the box carries on unswept, as before, and same-box recovery stays
+// refused (and alarmed by the activator) until the agent restarts. A box
+// with no control socket at all is not retried: that is not a refusal
+// that can clear.
func startActivator(ctx context.Context, sweep func(context.Context) error, recoverLayout func(ctx context.Context, swept bool), start func()) {
+ deadline := time.Now().Add(startupSweepWindow)
err := sweep(ctx)
+ tries := 1
+retry:
+ for _, wait := range startupSweepBackoff {
+ if err == nil || ctx.Err() != nil || errors.Is(err, fs.ErrNotExist) || time.Now().Add(wait).After(deadline) {
+ break
+ }
+ log.Printf("agent: startup sweep try %d failed: %v; trying again in %s", tries, err, wait)
+ select {
+ case <-ctx.Done():
+ break retry
+ case <-time.After(wait):
+ }
+ err = sweep(ctx)
+ tries++
+ }
+ if err != nil && tries > 1 {
+ log.Printf("agent: startup sweep failed %d times, last: %v; serving unswept, so same-box recovery of HA hosts stays refused until the agent restarts", tries, err)
+ }
recoverLayout(ctx, err == nil)
start()
}
diff --git a/internal/host/rootfsplacement.go b/internal/host/rootfsplacement.go
index 66e47b851..b43c5b3cc 100644
--- a/internal/host/rootfsplacement.go
+++ b/internal/host/rootfsplacement.go
@@ -23,6 +23,7 @@ import (
"github.com/carlosframework/platform/internal/activator"
"github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
"github.com/carlosframework/platform/internal/status"
@@ -305,16 +306,18 @@ func singleTenant(getenv func(string) string) bool {
}
}
-// boxPools is CARLOS_POOLS as the provision tick reads it: the non-empty
-// trimmed names, joined by commas.
+// boxPools is the dedicated pools this box serves, as the provision tick
+// reads CARLOS_POOLS (provision.ParseBoxPools), joined by commas: "" when
+// it serves the shared pool alone. The shared pool is no dedicated pool,
+// so it is left out.
func boxPools(getenv func(string) string) string {
- var pools []string
- for _, p := range strings.Split(getenv("CARLOS_POOLS"), ",") {
- if p = strings.TrimSpace(p); p != "" {
- pools = append(pools, p)
+ var named []string
+ for _, p := range provision.ParseBoxPools(getenv("CARLOS_POOLS")) {
+ if p != "" {
+ named = append(named, p)
}
}
- return strings.Join(pools, ",")
+ return strings.Join(named, ",")
}
// rootfsReadiness is the control client's /ready/rootfs.
diff --git a/internal/instancectl/peer_edge.go b/internal/instancectl/peer_edge.go
new file mode 100644
index 000000000..7a48ac846
--- /dev/null
+++ b/internal/instancectl/peer_edge.go
@@ -0,0 +1,115 @@
+package instancectl
+
+import (
+ "fmt"
+ "sync"
+ "time"
+)
+
+// edgePeer decides whether a connecting peer is the edge's main process
+// (design §5.4): uid carlos AND the MainPID systemd reports for
+// carlos-edge.service. It is productionPeerOK's decision, apart from the
+// socket and from systemctl, so it can be tested on any platform.
+//
+// mainPID asks systemd. Its answer, a pid or a failure, is cached for
+// edgePIDCache: while the edge has no MainPID (a restart window) every
+// refused connect would otherwise re-exec systemctl, and the accept loop
+// waits on each check.
+//
+// A cached answer can predate an agent restart (#433): the old agent's
+// last calls cache its pid, and the new agent's first call, the startup
+// sweep, arrives within the second and was refused against it. So a peer
+// the cache refuses is checked once more against a fresh read before it is
+// refused, and accepted only if systemd names it now. That widens nothing:
+// the peer must still be the main pid systemd reports. Forced reads are
+// at most one per edgePIDForceEvery, so a refused peer connecting in a
+// loop cannot make every connect exec systemctl.
+type edgePeer struct {
+ carlosUID int
+ mainPID func() (int, error)
+ now func() time.Time
+
+ mu sync.Mutex
+ pid int
+ lastErr error
+ at time.Time
+ forced time.Time // the last forced read
+}
+
+// edgePIDCache is how long one systemd answer is reused.
+const edgePIDCache = time.Second
+
+// edgePIDForceEvery is the least time between two forced reads.
+const edgePIDForceEvery = 100 * time.Millisecond
+
+// cached is the edge's main pid, from the cache while it is fresh; read is
+// whether systemd was asked for it.
+func (p *edgePeer) cached() (pid int, read bool, err error) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if p.now().Sub(p.at) < edgePIDCache {
+ if p.pid > 0 {
+ return p.pid, false, nil
+ }
+ if p.lastErr != nil {
+ return 0, false, p.lastErr
+ }
+ }
+ pid, err = p.readLocked()
+ return pid, true, err
+}
+
+// fresh asks systemd again, past the cache, unless a forced read ran less
+// than edgePIDForceEvery ago; then it is the cached answer. read is
+// whether systemd was asked.
+func (p *edgePeer) fresh() (pid int, read bool, err error) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ now := p.now()
+ if !p.forced.IsZero() && now.Sub(p.forced) < edgePIDForceEvery {
+ return p.pid, false, p.lastErr
+ }
+ p.forced = now
+ pid, err = p.readLocked()
+ return pid, true, err
+}
+
+// readLocked asks systemd and caches the answer. p.mu is held.
+func (p *edgePeer) readLocked() (int, error) {
+ pid, err := p.mainPID()
+ if err == nil && pid <= 0 {
+ err = fmt.Errorf("carlos-edge.service has no MainPID")
+ }
+ if err != nil {
+ p.pid, p.lastErr, p.at = 0, err, p.now()
+ return 0, err
+ }
+ p.pid, p.lastErr, p.at = pid, nil, p.now()
+ return pid, nil
+}
+
+// check accepts the peer only when uid is carlos and pid is the edge's
+// main pid.
+func (p *edgePeer) check(uid uint32, pid int32) error {
+ if int(uid) != p.carlosUID {
+ return fmt.Errorf("peer uid %d is not carlos", uid)
+ }
+ main, read, err := p.cached()
+ if err == nil && int(pid) == main {
+ return nil
+ }
+ // A cached answer refuses: ask systemd now (#433), once. An answer
+ // cached() has just read is already fresh.
+ if !read {
+ if fmain, asked, ferr := p.fresh(); asked {
+ main, err = fmain, ferr
+ }
+ }
+ if err != nil {
+ return err
+ }
+ if int(pid) != main {
+ return fmt.Errorf("peer pid %d is not the edge's main pid %d", pid, main)
+ }
+ return nil
+}
diff --git a/internal/instancectl/peer_edge_test.go b/internal/instancectl/peer_edge_test.go
new file mode 100644
index 000000000..ae505d347
--- /dev/null
+++ b/internal/instancectl/peer_edge_test.go
@@ -0,0 +1,120 @@
+package instancectl
+
+import (
+ "errors"
+ "strings"
+ "testing"
+ "time"
+)
+
+// fakeSystemd answers MainPID from a value the test moves, and counts the
+// reads.
+type fakeSystemd struct {
+ pid int
+ err error
+ reads int
+}
+
+func (f *fakeSystemd) mainPID() (int, error) {
+ f.reads++
+ return f.pid, f.err
+}
+
+func newTestEdgePeer(sd *fakeSystemd, clock *time.Time) *edgePeer {
+ return &edgePeer{carlosUID: 990, mainPID: sd.mainPID, now: func() time.Time { return *clock }}
+}
+
+// #433: root's cached main pid lags an agent restart. The new agent's
+// first call is checked against a fresh read before it is refused, and
+// accepted only when systemd names it; a fresh read that still names
+// another pid refuses.
+func TestEdgePeerRereadsAStaleMainPID(t *testing.T) {
+ clock := time.Unix(1_700_000_000, 0)
+ sd := &fakeSystemd{pid: 100}
+ p := newTestEdgePeer(sd, &clock)
+ if err := p.check(990, 100); err != nil {
+ t.Fatalf("the edge's main pid refused: %v", err)
+ }
+ // The agent restarts inside the cache window: systemd now says 200.
+ sd.pid = 200
+ clock = clock.Add(300 * time.Millisecond)
+ if err := p.check(990, 200); err != nil {
+ t.Fatalf("the new main pid refused against a stale cache: %v", err)
+ }
+ // The refreshed answer is cached: the old pid is refused now.
+ if err := p.check(990, 100); err == nil || !strings.Contains(err.Error(), "is not the edge's main pid 200") {
+ t.Fatalf("the old main pid after the restart: %v", err)
+ }
+
+ // A peer systemd does not name is refused after the fresh read too.
+ clock = clock.Add(2 * time.Second)
+ sd.pid = 300
+ if err := p.check(990, 300); err != nil {
+ t.Fatalf("main pid 300: %v", err)
+ }
+ clock = clock.Add(300 * time.Millisecond)
+ before := sd.reads
+ if err := p.check(990, 301); err == nil || !strings.Contains(err.Error(), "peer pid 301 is not the edge's main pid 300") {
+ t.Fatalf("a child of the edge: %v", err)
+ }
+ if sd.reads != before+1 {
+ t.Fatalf("the mismatch made %d systemd reads, want one fresh read", sd.reads-before)
+ }
+}
+
+// A cached failure (the edge had no MainPID during its restart) does not
+// refuse the new main process either: systemd is asked again.
+func TestEdgePeerRereadsACachedFailure(t *testing.T) {
+ clock := time.Unix(1_700_000_000, 0)
+ sd := &fakeSystemd{pid: 0}
+ p := newTestEdgePeer(sd, &clock)
+ if err := p.check(990, 200); err == nil {
+ t.Fatal("a peer accepted while the edge has no MainPID")
+ }
+ sd.pid = 200
+ clock = clock.Add(200 * time.Millisecond)
+ if err := p.check(990, 200); err != nil {
+ t.Fatalf("the new main pid refused against a cached failure: %v", err)
+ }
+ sd.err = errors.New("systemctl: timeout")
+ clock = clock.Add(2 * time.Second)
+ if err := p.check(990, 200); err == nil {
+ t.Fatal("a peer accepted when systemd could not be read")
+ }
+}
+
+// Forced reads are rate-limited: a peer that keeps connecting with a pid
+// that is not the edge's does not exec systemctl on every connect.
+func TestEdgePeerForcedReadsAreRateLimited(t *testing.T) {
+ clock := time.Unix(1_700_000_000, 0)
+ sd := &fakeSystemd{pid: 100}
+ p := newTestEdgePeer(sd, &clock)
+ if err := p.check(990, 100); err != nil {
+ t.Fatal(err)
+ }
+ for i := 0; i < 50; i++ {
+ clock = clock.Add(time.Millisecond)
+ if err := p.check(990, 666); err == nil {
+ t.Fatal("a stranger accepted")
+ }
+ }
+ // 50 ms of a refused peer: the first mismatch forces a read, the rest
+ // fall inside edgePIDForceEvery.
+ if sd.reads != 2 {
+ t.Fatalf("systemd reads = %d, want 2 (the first check and one forced read)", sd.reads)
+ }
+}
+
+// The uid is checked first and never widened: a non-carlos peer is refused
+// without asking systemd, even when its pid is the main pid.
+func TestEdgePeerRefusesAnotherUID(t *testing.T) {
+ clock := time.Unix(1_700_000_000, 0)
+ sd := &fakeSystemd{pid: 100}
+ p := newTestEdgePeer(sd, &clock)
+ if err := p.check(0, 100); err == nil || !strings.Contains(err.Error(), "peer uid 0 is not carlos") {
+ t.Fatalf("uid 0: %v", err)
+ }
+ if sd.reads != 0 {
+ t.Fatalf("systemd asked %d times for a wrong uid", sd.reads)
+ }
+}
diff --git a/internal/instancectl/peer_linux.go b/internal/instancectl/peer_linux.go
index 11ee0e45f..6678a0218 100644
--- a/internal/instancectl/peer_linux.go
+++ b/internal/instancectl/peer_linux.go
@@ -13,7 +13,6 @@ import (
"os/user"
"strconv"
"strings"
- "sync"
"syscall"
"time"
@@ -43,8 +42,8 @@ func peerCred(conn net.Conn) (*unix.Ucred, error) {
// productionPeerOK requires the peer to be uid carlos AND the main process
// of carlos-edge.service as systemd reports it (design §5.4): a flat tenant
// is a child of that pid, never the pid itself, and a nested tenant cannot
-// reach the socket at all. MainPID is asked of systemctl and cached for one
-// second, because the agent restarts and the pid changes.
+// reach the socket at all. The decision is edgePeer's; MainPID is asked of
+// systemctl.
func productionPeerOK() func(net.Conn) error {
// A missing carlos user or an unparsable uid is fatal at startup, not a
// permanent refusal cached into the returned closure: socket activation
@@ -60,59 +59,30 @@ func productionPeerOK() func(net.Conn) error {
if err != nil {
log.Fatalf("instance-control: carlos uid %q: %v", u.Uid, err)
}
- var mu sync.Mutex
- var mainPID int
- var lastErr error
- var at time.Time
- edgePID := func() (int, error) {
- mu.Lock()
- defer mu.Unlock()
- // Cache both a success and a failure for one second: while the
- // edge has no MainPID yet (a restart window), every refused
- // connect would otherwise re-exec systemctl under this mutex —
- // the negative case needs the same cache the positive one always
- // had (codex review fix round 2 item 5).
- if time.Since(at) < time.Second {
- if mainPID > 0 {
- return mainPID, nil
- }
- if lastErr != nil {
- return 0, lastErr
- }
- }
- ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
- defer cancel()
- out, err := exec.CommandContext(ctx, "systemctl", "show", "-p", "MainPID", "--value", edgeUnit).Output()
- if err != nil {
- mainPID, lastErr, at = 0, err, time.Now()
- return 0, err
- }
- pid, err := strconv.Atoi(strings.TrimSpace(string(out)))
- if err != nil || pid <= 0 {
- err = fmt.Errorf("carlos-edge.service has no MainPID")
- mainPID, lastErr, at = 0, err, time.Now()
- return 0, err
- }
- mainPID, lastErr, at = pid, nil, time.Now()
- return pid, nil
- }
+ peer := &edgePeer{carlosUID: carlosUID, mainPID: systemdEdgeMainPID, now: time.Now}
return func(conn net.Conn) error {
cred, err := peerCred(conn)
if err != nil {
return err
}
- if int(cred.Uid) != carlosUID {
- return fmt.Errorf("peer uid %d is not carlos", cred.Uid)
- }
- pid, err := edgePID()
- if err != nil {
- return err
- }
- if int(cred.Pid) != pid {
- return fmt.Errorf("peer pid %d is not the edge's main pid %d", cred.Pid, pid)
- }
- return nil
+ return peer.check(cred.Uid, cred.Pid)
+ }
+}
+
+// systemdEdgeMainPID is carlos-edge.service's MainPID as systemd reports
+// it now; 0 when the unit has none.
+func systemdEdgeMainPID() (int, error) {
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ defer cancel()
+ out, err := exec.CommandContext(ctx, "systemctl", "show", "-p", "MainPID", "--value", edgeUnit).Output()
+ if err != nil {
+ return 0, err
+ }
+ pid, err := strconv.Atoi(strings.TrimSpace(string(out)))
+ if err != nil {
+ return 0, nil
}
+ return pid, nil
}
// activatedListener returns the socket-activated listener when systemd
diff --git a/internal/metrics/rollup.go b/internal/metrics/rollup.go
index 032562492..c206213cb 100644
--- a/internal/metrics/rollup.go
+++ b/internal/metrics/rollup.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"os"
+ "sort"
"time"
"github.com/carlosframework/platform/internal/release"
@@ -27,6 +28,21 @@ type Agg struct {
type HourAgg struct {
Host map[string]Agg `json:"host"` // "cpu","mem","disk","load1"
Units map[string]map[string]Agg `json:"units"` // unit -> "cpu","mem_bytes" -> Agg
+ // Owned is, per unit, the hour's readings the box tagged with a tenant
+ // (UnitSample.Owner, owner.go), aggregated per tenant over exactly the
+ // samples that carried that tag. Untagged samples are in Units only.
+ // Usage billing charges a reading no hostname attributes to these owners
+ // alone (docs/superpowers/notes/remote-instance-metrics.md). Additive:
+ // absent on every hour a box built before it rolled up.
+ Owned map[string][]OwnedAgg `json:"owned,omitempty"`
+}
+
+// OwnedAgg is the part of one unit's hour tagged with one tenant: the same
+// "cpu" and "mem_bytes" aggregates as HourAgg.Units, over only the samples
+// the box vouched were Owner's.
+type OwnedAgg struct {
+ Owner Owner `json:"owner"`
+ Metrics map[string]Agg `json:"metrics"`
}
// DayRollup is a box's rolled-up day, keyed by UTC hour ("00".."23") —
@@ -119,7 +135,65 @@ func RollupHour(samples []Sample) HourAgg {
}
}
- return HourAgg{Host: host, Units: units}
+ return HourAgg{Host: host, Units: units, Owned: rollupOwned(samples)}
+}
+
+// rollupOwned is RollupHour's Owned: per unit and per tenant, the
+// aggregates of the samples tagged with that tenant. A sample with no tag
+// joins none. Owners are listed in account then app order, so the same
+// samples always roll up to the same bytes; nil when no sample is tagged.
+func rollupOwned(samples []Sample) map[string][]OwnedAgg {
+ type key struct {
+ unit string
+ owner Owner
+ }
+ cpu := map[key][]float64{}
+ mem := map[key][]float64{}
+ seen := map[key]bool{}
+ for _, s := range samples {
+ for name, u := range s.Units {
+ if u.Owner == nil {
+ continue
+ }
+ k := key{name, *u.Owner}
+ seen[k] = true
+ if u.CPUFrac != nil {
+ cpu[k] = append(cpu[k], *u.CPUFrac)
+ }
+ if u.MemBytes != nil {
+ mem[k] = append(mem[k], float64(*u.MemBytes))
+ }
+ }
+ }
+ if len(seen) == 0 {
+ return nil
+ }
+ out := map[string][]OwnedAgg{}
+ for k := range seen {
+ m := map[string]Agg{}
+ if agg, ok := aggOf(cpu[k]); ok {
+ m["cpu"] = agg
+ }
+ if agg, ok := aggOf(mem[k]); ok {
+ m["mem_bytes"] = agg
+ }
+ if len(m) > 0 {
+ out[k.unit] = append(out[k.unit], OwnedAgg{Owner: k.owner, Metrics: m})
+ }
+ }
+ for unit := range out {
+ sort.Slice(out[unit], func(i, j int) bool {
+ a, b := out[unit][i].Owner, out[unit][j].Owner
+ if a.Account != b.Account {
+ return a.Account < b.Account
+ }
+ return a.App < b.App
+ })
+ }
+ if len(out) == 0 {
+ return nil
+ }
+ return out
}
// UpsertRollup reads box's day object for hour's UTC date (a missing
diff --git a/internal/metrics/rollup_test.go b/internal/metrics/rollup_test.go
index 9711ad3bf..660f3dd85 100644
--- a/internal/metrics/rollup_test.go
+++ b/internal/metrics/rollup_test.go
@@ -131,3 +131,48 @@ func TestUpsertRollupTwoHoursSameDay(t *testing.T) {
t.Fatalf("Hours[11] = %+v, want cpu avg 0.2", got.Hours["11"])
}
}
+
+// TestRollupHourOwned: an hour's tagged readings are aggregated per tenant
+// over exactly the samples carrying that tenant's tag; untagged samples
+// join no owner but stay in Units; a unit never tagged has no entry.
+func TestRollupHourOwned(t *testing.T) {
+ shop := &Owner{Account: "bdn", App: "shop"}
+ rival := &Owner{Account: "rvl", App: "shop"}
+ at := time.Date(2026, 10, 26, 10, 0, 0, 0, time.UTC)
+ f := func(v float64) *float64 { return &v }
+ i := func(v int64) *int64 { return &v }
+ var samples []Sample
+ add := func(o *Owner, cpu float64) {
+ samples = append(samples, Sample{At: at.Add(time.Duration(len(samples)) * time.Minute), Units: map[string]UnitSample{
+ "carlos-exec@a.example.com": {CPUFrac: f(cpu), MemBytes: i(100), Owner: o},
+ "carlos-exec@b.example.com": {CPUFrac: f(cpu)},
+ }})
+ }
+ add(shop, 0.2)
+ add(shop, 0.4)
+ add(nil, 0.9)
+ add(rival, 0.6)
+ agg := RollupHour(samples)
+ if n := agg.Units["carlos-exec@a.example.com"]["cpu"].N; n != 4 {
+ t.Fatalf("Units cpu N = %d, want every sample (4)", n)
+ }
+ owned := agg.Owned["carlos-exec@a.example.com"]
+ if len(owned) != 2 || owned[0].Owner != *shop || owned[1].Owner != *rival {
+ t.Fatalf("owned = %+v, want bdn/shop then rvl/shop", owned)
+ }
+ if c := owned[0].Metrics["cpu"]; c.N != 2 || c.Avg < 0.2999 || c.Avg > 0.3001 {
+ t.Fatalf("bdn/shop cpu = %+v, want N 2 avg 0.3", c)
+ }
+ if c := owned[1].Metrics["cpu"]; c.N != 1 || c.Avg != 0.6 {
+ t.Fatalf("rvl/shop cpu = %+v", c)
+ }
+ if m := owned[0].Metrics["mem_bytes"]; m.N != 2 {
+ t.Fatalf("bdn/shop mem = %+v", m)
+ }
+ if _, ok := agg.Owned["carlos-exec@b.example.com"]; ok {
+ t.Fatal("a unit never tagged has owned readings")
+ }
+ if RollupHour([]Sample{{At: at, Units: map[string]UnitSample{"u": {CPUFrac: f(1)}}}}).Owned != nil {
+ t.Fatal("an hour with no tag has an Owned map (it must stay absent on the wire)")
+ }
+}
diff --git a/internal/provision/boxpools_test.go b/internal/provision/boxpools_test.go
new file mode 100644
index 000000000..b18ea986c
--- /dev/null
+++ b/internal/provision/boxpools_test.go
@@ -0,0 +1,53 @@
+package provision
+
+import (
+ "reflect"
+ "testing"
+)
+
+// CARLOS_POOLS (#433 follow-up): SharedPoolToken names the shared "" pool,
+// so a box can serve it beside a named pool. Every other token is taken
+// literally, as before, and an empty element is dropped, never read as the
+// shared pool (",tito" serves tito alone, codex R3-3).
+func TestParseBoxPools(t *testing.T) {
+ for _, c := range []struct {
+ raw string
+ pools []string
+ serve []string // pools served
+ not []string // pools not served
+ }{
+ {"", nil, []string{""}, []string{"hapair"}},
+ {"@shared", []string{""}, []string{""}, []string{"hapair", "@shared"}},
+ {"@shared,hapair", []string{"", "hapair"}, []string{"", "hapair"}, []string{"cohort1", "@shared"}},
+ {" hapair , @shared ,, ", []string{"hapair", ""}, []string{"", "hapair"}, []string{"cohort1"}},
+ {"cohort1,hapair", []string{"cohort1", "hapair"}, []string{"cohort1", "hapair"}, []string{""}},
+ {",tito", []string{"tito"}, []string{"tito"}, []string{""}},
+ {"hapair,@shared,hapair,@shared", []string{"hapair", ""}, []string{"", "hapair"}, nil},
+ // Not the token and not a pool name: literal, so it serves no
+ // record a door mints, and never the shared pool.
+ {"@Shared", []string{"@Shared"}, nil, []string{"", "shared"}},
+ {"@other,hapair", []string{"@other", "hapair"}, []string{"hapair"}, []string{"", "other"}},
+ } {
+ got := ParseBoxPools(c.raw)
+ if !reflect.DeepEqual(got, c.pools) {
+ t.Errorf("ParseBoxPools(%q) = %#v, want %#v", c.raw, got, c.pools)
+ }
+ for _, p := range c.serve {
+ if !poolServed(got, p) {
+ t.Errorf("CARLOS_POOLS=%q does not serve pool %q", c.raw, p)
+ }
+ }
+ for _, p := range c.not {
+ if poolServed(got, p) {
+ t.Errorf("CARLOS_POOLS=%q serves pool %q", c.raw, p)
+ }
+ }
+ }
+}
+
+// The token can never be a pool's name: the record grammar refuses it.
+func TestSharedPoolTokenIsNoPoolName(t *testing.T) {
+ if ValidPool(SharedPoolToken) {
+ t.Fatalf("%q is a valid pool name", SharedPoolToken)
+ }
+}
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go
index 1efefd276..d95103afb 100644
--- a/internal/provision/plan9_b8_census_test.go
+++ b/internal/provision/plan9_b8_census_test.go
@@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) {
if len(got) < 100 {
t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root)
}
- inventory := nearestRegionBWriteCensusInventory()
+ inventory := usageAttribution390WriteCensusInventory()
problems := append(censusDiff(inventory, got), censusPolicy(inventory)...)
if len(problems) > 0 {
t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n "))
diff --git a/internal/provision/reconcile.go b/internal/provision/reconcile.go
index c47f75c7a..397d7e343 100644
--- a/internal/provision/reconcile.go
+++ b/internal/provision/reconcile.go
@@ -2891,6 +2891,47 @@ func forEach(items []string, f func(string)) {
wg.Wait()
}
+// SharedPoolToken is the CARLOS_POOLS token for the shared "" pool, so a
+// box can serve it beside a named pool ("@shared,hapair"). A pool name is
+// [a-z0-9-]{0,16} (ValidPool), so no pool can be called this.
+const SharedPoolToken = "@shared"
+
+// ParseBoxPools parses CARLOS_POOLS, the pools this box serves, into
+// ReconcileConfig.Pools. It is the one parser: the provision tick, the
+// edges file's serves_shared_pool (through the same config) and the rootfs
+// placement refusal all read the variable through it.
+//
+// Elements are comma-separated and trimmed; an empty one is dropped, never
+// read as the shared pool (",tito" serves tito alone). SharedPoolToken is
+// the shared pool, "" in the result. Every other token is taken literally,
+// as before this token existed: one that is not a pool name (another "@"
+// word, "@Shared", upper case) matches no record a door mints and never
+// the shared pool, and is logged once. A repeat is dropped. No element at
+// all is nil, which poolServed reads as the shared pool alone.
+func ParseBoxPools(raw string) []string {
+ var pools []string
+ for _, p := range strings.Split(raw, ",") {
+ p = strings.TrimSpace(p)
+ switch {
+ case p == "":
+ continue
+ case p == SharedPoolToken:
+ p = ""
+ case !ValidPool(p):
+ if _, seen := oddBoxPools.LoadOrStore(p, true); !seen {
+ log.Printf("provision: CARLOS_POOLS names %q, which is not a pool name (want [a-z0-9-]{0,16}, or %s for the shared pool); it serves no pool a door creates", p, SharedPoolToken)
+ }
+ }
+ if !slices.Contains(pools, p) {
+ pools = append(pools, p)
+ }
+ }
+ return pools
+}
+
+// oddBoxPools is the CARLOS_POOLS tokens ParseBoxPools has logged.
+var oddBoxPools sync.Map
+
// poolServed reports whether pool is one this box serves. An empty
// cfg.Pools means the shared "" pool ONLY, never "every pool" — the same
// convention domains.Config's AppsDomain=="" carries: unconfigured means the
diff --git a/internal/provision/reconcile_eligibility_test.go b/internal/provision/reconcile_eligibility_test.go
index 6f9ac5556..6c38cd5e2 100644
--- a/internal/provision/reconcile_eligibility_test.go
+++ b/internal/provision/reconcile_eligibility_test.go
@@ -13,6 +13,8 @@ func TestSharedInstanceEligibilityIsTheMintPredicate(t *testing.T) {
{nil, "", true, true},
{[]string{"tito"}, "", false, true},
{[]string{"", "tito"}, "", true, true},
+ {ParseBoxPools("@shared,hapair"), "", true, true},
+ {ParseBoxPools("cohort1,hapair"), "", false, true},
{nil, InboundNone, true, false},
{[]string{"tito"}, InboundNone, false, false},
}
diff --git a/internal/provision/testdata/plan14-root-reads-alias-wake-338.tsv b/internal/provision/testdata/plan14-root-reads-alias-wake-338.tsv
index 1bdff7061..9c40a8da0 100644
--- a/internal/provision/testdata/plan14-root-reads-alias-wake-338.tsv
+++ b/internal/provision/testdata/plan14-root-reads-alias-wake-338.tsv
@@ -13,4 +13,4 @@ internal/host/assetpolicy.go assetInputs.primary legacy accepted-legacy accepted
internal/host/assetpolicy.go newAssetInputs legacy accepted-legacy accepted-legacy;rev3=census-ruling-edge-asset-cache-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos), in the edges file loop (edgesFileLoop, edgesFileWriteClaims), only on a box armed with CARLOS_ASSET_CACHE=1 (armAssetPolicy answers nil otherwise): indexes rows already read (routes by host, exact aliases to their primary, hosts with path rows) and the owners (servedOwners when not handed them); reads nothing itself; no root pass calls it; no root decision;rev3=census-ruling-alias-wake-338;basis=#338 follow-up: records edge.PlatformAliasFold over the same routes (platformOf, platformRefused) registry:Alias@685,registry:Alias@720,registry:Alias@766,registry:Host@576,registry:Host@633,registry:Host@777,whole:Route@195,whole:Route@239,whole:Route@528,whole:Route@555,whole:Route@569,whole:Route@586,whole:Route@837,whole:RouteAlias@670,whole:RoutePath@610,whole:RoutePath@853 54c90ae15c22220b05121ba828a4a7c7be5c8a990d585bbe88900caaf319225d
internal/host/edgesfile.go edgesFileWriteClaims authority F,J1 rev3=census-ruling-self-serve-moves-1;basis=root-route;kept=F;scope=protected-decision-only; the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): region-ha-2a's body, which with the box's lifetimes switch on also publishes each served row's lifetime pair (registry:Incarnation and registry:ServingSeq, two new sites on the rows it already lists) and an alias's or served catch-all's primary's pair, and names that primary as target_host whatever the switch; a report the edge orders unstamped entries by, not a decision; no record, /data, release or claim read added; F,J1 authority retained; self-serve moves 1 Task 8;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Task 8: takes a localAddrs reader (instancectl.LocalAddresses in production, which reads /proc/net/fib_trie and /proc/net/if_inet6 in the agent) and publishes its non-loopback entries as the edges file's addrs before the write gate (boxAddrs, no read of its own), so an address change writes once. The same 44 sites, offsets moved; no record, /data, release or claim read added; a report the console's egress grant check reads, not a root decision; F,J1 authority retained.;rev3=census-ruling-edge-asset-cache-3;basis=starts with assets = assets.active(), so a policy whose box has not opened its asset store publishes no assets blocks and reads no manifests, and copies the decision's Primary (the route host the block was decided for, drift D4) into the published assets block; read sites unchanged (44); no read added. Merged onto main's #328 body, which takes the localAddrs reader: the assets.active() line sits after that signature and the loop passes pub and instancectl.LocalAddresses;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: the claims argument (*edgesClaims) becomes addrs (AddressSource) and the applyEdgesClaims(ctx, claims, routes, hosts) call is deleted with edgesclaims.go, which is the one whole:Route site removed: no host claim is read and every served row publishes as with region HA off; the box-address publication is the same code reading addrs.BoxAddresses() instead of claims.addrs; a report the edge reads, not a root decision; no read added; merge of origin/main d7ae1d76: main's edge asset cache plan 3 body is kept (census-ruling-edge-asset-cache-3): the first line is assets = assets.active(), so a policy whose store has not opened publishes no assets blocks and reads no manifests, and edgesFileLoop passes pub (assets.active() for that tick) in the assets argument; main's claims *edgesClaims argument is this branch's addrs AddressSource, and no edgesClaims, applyEdgesClaims or hostclaim reference remains;rev3=census-ruling-alias-wake-338;basis=#338 follow-up: skips publishing a platform alias edge.PlatformAliasFold refuses (and so anything attached to it); reads the same route listing registry:Account@12119,registry:Alias@6067,registry:Alias@6102,registry:Alias@6524,registry:Alias@6681,registry:Alias@6751,registry:Alias@6783,registry:Alias@7456,registry:Alias@9811,registry:App@12131,registry:DNSStatus@6199,registry:DNSStatus@6690,registry:Host@10039,registry:Host@1068,registry:Host@11549,registry:Host@3905,registry:Host@6159,registry:Host@7004,registry:Host@7440,registry:Host@7613,registry:Host@9858,registry:Host@9905,registry:Host@9955,registry:Host@9990,registry:Incarnation@3865,registry:Platform@3644,registry:Provisioned@3658,registry:Replica@3682,registry:ServingSeq@3880,registry:Status@1611,whole:Route@1012,whole:Route@1039,whole:Route@13214,whole:Route@13640,whole:Route@13815,whole:Route@4275,whole:Route@750,whole:RouteAlias@13236,whole:RouteAlias@13830,whole:RouteAlias@6052,whole:RouteAlias@9764,whole:RoutePath@13229,whole:RoutePath@13823,whole:RoutePath@4290,whole:WildcardDomain@9944 e75a5d7aacc51670ce9506f9301600c8a2bcfa3340825de0cc5b1b89ec8b5508
@coverage internal/edge eb3743f07bd5cd8394b4e9dfff5931bff9099e51362687f1e9c88baf716404de
-@coverage internal/host 25f86e4ab400612fe7948bb451a66c0e857c143d41a5fa261fa18661ea81d542
+@coverage internal/host e7130e3b04365ef971d16875c72b7b6e0d70706e5c8f663f74d64870081984ef
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 39d84d8a6..092af8496 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -8,4 +8,7 @@ plan14-root-reads-remote-metrics-nested.tsv e923841657499fc729713abdd750cbd2d601
plan14-root-reads-region-ha-p1a.tsv 125c5c411cd0a04000d9652800b51bc7c066081c00753fb1c7b6ee0b6e717dbd
plan14-root-reads-nearest-region-b.tsv f4e36134015ec6d09bada7be500c8faad22450afda12d033a8e3e24b1e8bb361
plan14-root-reads-alias-socket-follow-338.tsv 5192052a23d2fdd6f5d48b5617fe28a9bb03458e1e931c060fbdc42c3d627927
-plan14-root-reads-alias-wake-338.tsv 2f20bae6cb9da96cf1f247231d7b529a23828f2b0a74fa2c3bcbe4a7888e0f28
+plan14-root-reads-usage-attribution-390.tsv 5192052a23d2fdd6f5d48b5617fe28a9bb03458e1e931c060fbdc42c3d627927
+plan14-root-reads-ha-p1a-433.tsv f8acbc0dd8828636e3f73d9afd0e539d3dfd1346e0232d91903c33d6eb27d820
+plan14-root-reads-rollup-tenant-tags.tsv f8acbc0dd8828636e3f73d9afd0e539d3dfd1346e0232d91903c33d6eb27d820
+plan14-root-reads-alias-wake-338.tsv deeddee1bf22a18562acda97cc34c6d73ee0dff1825100c73fa0be4c6a3f3e7b
diff --git a/internal/provision/testdata/plan14-root-reads-ha-p1a-433.tsv b/internal/provision/testdata/plan14-root-reads-ha-p1a-433.tsv
new file mode 100644
index 000000000..9278afba2
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-ha-p1a-433.tsv
@@ -0,0 +1,28 @@
+# Census overlay ha-p1a-433, written by census-propose (#369). census-ruling-ha-p1a-433, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-ha-p1a-433.md.
+# 2 body, 1 sites, 4 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 8 new dispositions: 2 reads re-frozen at their disposition with the claim, 4 new units frozen accepted-legacy, 1 quiet units retired while they read nothing, 1 other.
+@legacy d5186710900d37c74a217ea1c872a06c8afd634093845b390830c888dc2e6988 internal/host/agent.go provisionTickConfig legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-ha-p1a-433;basis=the agent (carlos-edge.service, user carlos) and the edges file loop's eligibility: the same CARLOS_POOLS read, now parsed by provision.ParseBoxPools (internal/provision, envelope re-pinned), the one parser boxPools also uses. "@shared" (provision.SharedPoolToken, never a valid pool name) is the shared "" pool; other tokens are literal as before; empty elements and repeats dropped. No read added. data-literal@207,data-literal@248 0321619c2abad2a9431515f92e28465a6b40aa49332fdcddf939e7b3e2a6ebe7
+@legacy 4de6e4827c9e69619633552c8c373e9704097d986b8ab4ce2b07bb4952ceb460 internal/registry/registry.go Registry.List legacy accepted-legacy accepted-legacy;rev3=J1,J4;basis=route-and-input;rev3=census-ruling-instance-egress-sizes-328-329;identity=the registry's SQLite side, as carlos: in the agent (/opt/carlos/carlos agent, carlos-edge.service) and in the registry child (carlos __registry-child, which a root pass forks as the service user), and now also in the read-only registry child (carlos __registry-child read-only, which root's instance control forks as the service user through openServiceRegistryReadOnly);basis=#328 plan 2 Task 13 fix (4e7bbc4b): a read-only registry (OpenReadOnly sets readOnly) lists over its own mode=ro, query_only connection (registry:sql, one site, r.sql) instead of a fresh sql.Open on its path, which opens read-write; registry:readOnly (one site) is the branch on that flag. A read-write registry keeps main's fresh connection. The same SELECT of routeCols from routes; it serves root's egress source (listRegistryReadOnly) every row; it decides nothing;rev3=census-ruling-ha-p1a-433;basis=the registry's SQLite side as carlos (agent, registry child, and root's read-only registry child via openServiceRegistryReadOnly): calls readCols on the same connection before the same SELECT ... FROM routes ORDER BY host. A read-write registry gets routeCols unchanged; a read-only one gets routeCols with any column routeAddedColumns adds that the table lacks read as its migration default ("0 AS ha"), so root's egress naming and source work before the new agent migrates (#433). Decides nothing; no read added. file:Exec@396,file:Open@212,file:Query@569,registry:Routes@145,registry:path@231,registry:readOnly@183,registry:remote@49,registry:remote@81,registry:sql@172,whole:Route@149,whole:Route@797,whole:Route@810,whole:Route@815,whole:Route@829,whole:remoteClient@51,whole:remoteClient@83 4505dd81395a06055029d52b27debb90209fd3a8aac1af4d589bee8bc33a0ba5
+@legacy 182fbc52eb5bd221ef5f55b07e56d5dda2b09e1b3da28e47919c521b270062e9 internal/instancectl/peer_linux.go systemdEdgeMainPID legacy accepted-legacy accepted-legacy;rev3=census-ruling-ha-p1a-433;basis=root (carlos-instance-control.service): the same exec productionPeerOK's closure ran before, moved out unchanged: systemctl show -p MainPID --value carlos-edge.service, fixed argv, 3 s timeout; output that does not parse is 0 (no MainPID), which edgePeer refuses. No input from a peer, tenant or agent reaches the argv. file:CommandContext@143 f71136a6afa17f28657515e080c67d3391a21e7475b4eca3e5249f607b175a4e
+@legacy 5fc36e10630d095bb775ab528335634412a33d3aea9809af9403ad998fcb7d64 internal/registry/registry.go Registry.readCols legacy accepted-legacy accepted-legacy;rev3=census-ruling-ha-p1a-433;basis=new; the registry's SQLite side as carlos. For a read-write registry returns routeCols and reads nothing. For a read-only one (registry:readOnly), one SELECT name FROM pragma_table_info('routes') over the registry's own mode=ro, query_only connection. The names read are only compared with the in-binary routeCols and routeAddedColumns lists, never put into SQL: the select list is built from routeCols and the in-binary defaults (the empty string literal or 0, parsed from routeAddedColumns by a fixed regexp). An agent-written table can only make a known added column read as its default, which is what the migration gives it; a missing CREATE column is not stood in for and the read fails as before. file:Query@117,registry:readOnly@63 f4b586a0331bbf958a2b957f08ef779bf7ca16a99101891ee0007cf142fa7f1b
+@legacy 90b76b74a3a96404f981c217def2e8cf6d7aaf172b67aaa3714245d6438c3cde internal/registry/registry.go addedColumn.spec legacy accepted-legacy accepted-legacy;rev3=census-ruling-ha-p1a-433;basis=new; pure: joins the entry's in-binary Name, Type and Default into "<name> <type> NOT NULL DEFAULT <default>". +registry:Name/Type/Default are the struct's own fields; it reads nothing from the database, a file or an input. registry:Default@92,registry:Name@45,registry:Type@60 4a0c847a4c4afc8ef279b0cf45e1d77b9f48839337222b5b2d7f9bd0d9e18078
+@legacy 7f57f26c268c831d65e4dc8ff1610d684d067dc291115463dd0f7a18efc4d480 internal/registry/registry.go addedRouteColumnDefaults legacy accepted-legacy accepted-legacy;rev3=census-ruling-ha-p1a-433;basis=new as a census unit (it replaces the regexp parse of the ALTER texts): pure, maps each routeAddedColumns entry's in-binary Name to its in-binary Default, now including the four claim ownership columns, so readCols stands their defaults in for a read-only registry that predates migrateClaimOwnership. Reads nothing from the database, a file or an input. registry:Default@135,registry:Name@125,whole:addedColumn@99 c1764a9b1a6df43619e98a9efd2867b81f32441b63fe23e5520d8ca177e41e47
+@legacy 84032054f14612fedfe899360fec0296d3b3a2136db23fea9ab562a23da8cace internal/registry/claimrows.go Registry.migrateClaimOwnership legacy accepted-legacy accepted-legacy;rev3=J1,J4;basis=route-and-input;rev3=census-ruling-ha-p1a-433;basis=the registry's SQLite side as carlos, on every registry open (called from migrate): the four claim ownership ALTERs for routes and timers come from routeAddedColumns' Claim-marked entries (claim_incarnation TEXT, claim_stamp INTEGER, claim_owner TEXT, claim_row_id TEXT, each NOT NULL DEFAULT the empty string or 0), as "ALTER TABLE " + table + " ADD COLUMN " + spec(): the same statements as main's inline list, same order, same tables, same duplicate-column rule. +registry:Claim is the mark, +whole:addedColumn the struct; in-binary literals only; no read added. file:Exec@196,file:Exec@365,registry:Claim@152,registry:sql@196,registry:sql@365,whole:addedColumn@125 9c23e3ca20731e3eb1b11e8758ee562f121922fb024dae3b839c4e121ce924b3
+@legacy 3bbee2be2030884bb5d02ece03fd5767aa744deafebc0edffe6452901337338c internal/registry/registry.go Registry.migrate legacy accepted-legacy accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=the registry's SQLite side, as carlos: in the agent (/opt/carlos/carlos agent, carlos-edge.service) and in the registry child (carlos __registry-child, which a root pass forks as the service user), on every registry open; a box CLI verb that opens the registry directly runs it as whoever runs the verb: census-ruling-seeded-instances's body with two more columns added to routes (incarnation and serving_seq, INTEGER NOT NULL DEFAULT 0, idempotent through the duplicate-column rule); self-serve moves 1 Task 7;rev3=census-ruling-rootfs-apps-2;basis=one more ALTER TABLE, routes ADD COLUMN runtime TEXT NOT NULL DEFAULT '', beside main's rate_limit, assets_off, asset_gen, incarnation and serving_seq (the last four from the merges of origin/main 3c33f2eb and 953b9fda); the same sixteen sites, no read added;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328/#329 plan 1 Task 4: three more ALTER TABLE statements in the existing loop, routes ADD COLUMN egress_allow, size and policy_expires_at, each TEXT NOT NULL DEFAULT '' and idempotent through the duplicate-column rule; the same sixteen sites, no read added.;rev3=census-ruling-region-ha-p1a;basis=one more ALTER TABLE in the existing loop: routes ADD COLUMN ha INTEGER NOT NULL DEFAULT 0, idempotent through the duplicate-column rule; the same sixteen sites, no read added;rev3=census-ruling-ha-p1a-433;basis=the registry's SQLite side as carlos (agent, registry child; a box CLI verb that opens the registry directly runs it as whoever runs it), on every registry open: the ALTER TABLE routes statements are now built from the one migration definition routeAddedColumns (addedColumn name, type, default; review r1 P2): for each entry without the Claim mark, "ALTER TABLE routes ADD COLUMN " + spec(), byte for byte the statements main runs, in main's order, under the same duplicate-column rule. +registry:Claim is that mark, +whole:addedColumn the struct. Every name, type and default is an in-binary literal; no statement added, removed or changed; no read added. file:Exec@1694,file:Exec@2554,file:Exec@2833,file:Exec@3696,file:Exec@3872,file:Exec@51,file:Exec@600,file:Exec@963,registry:Claim@525,registry:sql@1694,registry:sql@2554,registry:sql@2833,registry:sql@3696,registry:sql@3872,registry:sql@51,registry:sql@600,registry:sql@963,whole:addedColumn@500 c1aa99249122d7976764fc6571eada4c1fbda98d52e96d493c64f3e39c31d5bd
+@legacy c4f52621ee9b897da8526befa1450902d86770d3f07954b1b297de96cb1181f5 internal/registry/registry.go Registry.Get legacy accepted-legacy accepted-legacy;rev3=J1,J4;basis=route-and-input;rev3=census-ruling-ha-p1a-433;basis=same identities as List: +registry:sql is r.sql handed to readCols, the same connection the SELECT already used; same SELECT ... WHERE host = ? with the select list readCols returns (routeCols for a read-write registry). Root's instanceRegistryHostApp and instanceRegistryHostRuntime read Get through the read-only child and now work before the migration too. file:QueryRow@262,registry:Route@165,registry:remote@58,registry:remote@90,registry:sql@209,registry:sql@262,whole:Route@169,whole:Route@455,whole:remoteClient@60,whole:remoteClient@92 736f4a42df871f765a124ea532a38ba1c8ab8bf16375eb0c480f855ddf5c3e82
+internal/host/agent.go provisionTickConfig legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-ha-p1a-433;basis=the agent (carlos-edge.service, user carlos) and the edges file loop's eligibility: the same CARLOS_POOLS read, now parsed by provision.ParseBoxPools (internal/provision, envelope re-pinned), the one parser boxPools also uses. "@shared" (provision.SharedPoolToken, never a valid pool name) is the shared "" pool; other tokens are literal as before; empty elements and repeats dropped. No read added. data-literal@207,data-literal@248 0321619c2abad2a9431515f92e28465a6b40aa49332fdcddf939e7b3e2a6ebe7
+internal/registry/registry.go Registry.List legacy accepted-legacy accepted-legacy;rev3=J1,J4;basis=route-and-input;rev3=census-ruling-instance-egress-sizes-328-329;identity=the registry's SQLite side, as carlos: in the agent (/opt/carlos/carlos agent, carlos-edge.service) and in the registry child (carlos __registry-child, which a root pass forks as the service user), and now also in the read-only registry child (carlos __registry-child read-only, which root's instance control forks as the service user through openServiceRegistryReadOnly);basis=#328 plan 2 Task 13 fix (4e7bbc4b): a read-only registry (OpenReadOnly sets readOnly) lists over its own mode=ro, query_only connection (registry:sql, one site, r.sql) instead of a fresh sql.Open on its path, which opens read-write; registry:readOnly (one site) is the branch on that flag. A read-write registry keeps main's fresh connection. The same SELECT of routeCols from routes; it serves root's egress source (listRegistryReadOnly) every row; it decides nothing;rev3=census-ruling-ha-p1a-433;basis=the registry's SQLite side as carlos (agent, registry child, and root's read-only registry child via openServiceRegistryReadOnly): calls readCols on the same connection before the same SELECT ... FROM routes ORDER BY host. A read-write registry gets routeCols unchanged; a read-only one gets routeCols with any column routeAddedColumns adds that the table lacks read as its migration default ("0 AS ha"), so root's egress naming and source work before the new agent migrates (#433). Decides nothing; no read added. file:Exec@396,file:Open@212,file:Query@569,registry:Routes@145,registry:path@231,registry:readOnly@183,registry:remote@49,registry:remote@81,registry:sql@172,whole:Route@149,whole:Route@797,whole:Route@810,whole:Route@815,whole:Route@829,whole:remoteClient@51,whole:remoteClient@83 4505dd81395a06055029d52b27debb90209fd3a8aac1af4d589bee8bc33a0ba5
+internal/instancectl/peer_linux.go systemdEdgeMainPID legacy accepted-legacy accepted-legacy;rev3=census-ruling-ha-p1a-433;basis=root (carlos-instance-control.service): the same exec productionPeerOK's closure ran before, moved out unchanged: systemctl show -p MainPID --value carlos-edge.service, fixed argv, 3 s timeout; output that does not parse is 0 (no MainPID), which edgePeer refuses. No input from a peer, tenant or agent reaches the argv. file:CommandContext@143 f71136a6afa17f28657515e080c67d3391a21e7475b4eca3e5249f607b175a4e
+internal/registry/registry.go Registry.readCols legacy accepted-legacy accepted-legacy;rev3=census-ruling-ha-p1a-433;basis=new; the registry's SQLite side as carlos. For a read-write registry returns routeCols and reads nothing. For a read-only one (registry:readOnly), one SELECT name FROM pragma_table_info('routes') over the registry's own mode=ro, query_only connection. The names read are only compared with the in-binary routeCols and routeAddedColumns lists, never put into SQL: the select list is built from routeCols and the in-binary defaults (the empty string literal or 0, parsed from routeAddedColumns by a fixed regexp). An agent-written table can only make a known added column read as its default, which is what the migration gives it; a missing CREATE column is not stood in for and the read fails as before. file:Query@117,registry:readOnly@63 f4b586a0331bbf958a2b957f08ef779bf7ca16a99101891ee0007cf142fa7f1b
+internal/registry/registry.go addedColumn.spec legacy accepted-legacy accepted-legacy;rev3=census-ruling-ha-p1a-433;basis=new; pure: joins the entry's in-binary Name, Type and Default into "<name> <type> NOT NULL DEFAULT <default>". +registry:Name/Type/Default are the struct's own fields; it reads nothing from the database, a file or an input. registry:Default@92,registry:Name@45,registry:Type@60 4a0c847a4c4afc8ef279b0cf45e1d77b9f48839337222b5b2d7f9bd0d9e18078
+internal/registry/registry.go addedRouteColumnDefaults legacy accepted-legacy accepted-legacy;rev3=census-ruling-ha-p1a-433;basis=new as a census unit (it replaces the regexp parse of the ALTER texts): pure, maps each routeAddedColumns entry's in-binary Name to its in-binary Default, now including the four claim ownership columns, so readCols stands their defaults in for a read-only registry that predates migrateClaimOwnership. Reads nothing from the database, a file or an input. registry:Default@135,registry:Name@125,whole:addedColumn@99 c1764a9b1a6df43619e98a9efd2867b81f32441b63fe23e5520d8ca177e41e47
+internal/registry/claimrows.go Registry.migrateClaimOwnership legacy accepted-legacy accepted-legacy;rev3=J1,J4;basis=route-and-input;rev3=census-ruling-ha-p1a-433;basis=the registry's SQLite side as carlos, on every registry open (called from migrate): the four claim ownership ALTERs for routes and timers come from routeAddedColumns' Claim-marked entries (claim_incarnation TEXT, claim_stamp INTEGER, claim_owner TEXT, claim_row_id TEXT, each NOT NULL DEFAULT the empty string or 0), as "ALTER TABLE " + table + " ADD COLUMN " + spec(): the same statements as main's inline list, same order, same tables, same duplicate-column rule. +registry:Claim is the mark, +whole:addedColumn the struct; in-binary literals only; no read added. file:Exec@196,file:Exec@365,registry:Claim@152,registry:sql@196,registry:sql@365,whole:addedColumn@125 9c23e3ca20731e3eb1b11e8758ee562f121922fb024dae3b839c4e121ce924b3
+internal/registry/registry.go Registry.migrate legacy accepted-legacy accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=the registry's SQLite side, as carlos: in the agent (/opt/carlos/carlos agent, carlos-edge.service) and in the registry child (carlos __registry-child, which a root pass forks as the service user), on every registry open; a box CLI verb that opens the registry directly runs it as whoever runs the verb: census-ruling-seeded-instances's body with two more columns added to routes (incarnation and serving_seq, INTEGER NOT NULL DEFAULT 0, idempotent through the duplicate-column rule); self-serve moves 1 Task 7;rev3=census-ruling-rootfs-apps-2;basis=one more ALTER TABLE, routes ADD COLUMN runtime TEXT NOT NULL DEFAULT '', beside main's rate_limit, assets_off, asset_gen, incarnation and serving_seq (the last four from the merges of origin/main 3c33f2eb and 953b9fda); the same sixteen sites, no read added;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328/#329 plan 1 Task 4: three more ALTER TABLE statements in the existing loop, routes ADD COLUMN egress_allow, size and policy_expires_at, each TEXT NOT NULL DEFAULT '' and idempotent through the duplicate-column rule; the same sixteen sites, no read added.;rev3=census-ruling-region-ha-p1a;basis=one more ALTER TABLE in the existing loop: routes ADD COLUMN ha INTEGER NOT NULL DEFAULT 0, idempotent through the duplicate-column rule; the same sixteen sites, no read added;rev3=census-ruling-ha-p1a-433;basis=the registry's SQLite side as carlos (agent, registry child; a box CLI verb that opens the registry directly runs it as whoever runs it), on every registry open: the ALTER TABLE routes statements are now built from the one migration definition routeAddedColumns (addedColumn name, type, default; review r1 P2): for each entry without the Claim mark, "ALTER TABLE routes ADD COLUMN " + spec(), byte for byte the statements main runs, in main's order, under the same duplicate-column rule. +registry:Claim is that mark, +whole:addedColumn the struct. Every name, type and default is an in-binary literal; no statement added, removed or changed; no read added. file:Exec@1694,file:Exec@2554,file:Exec@2833,file:Exec@3696,file:Exec@3872,file:Exec@51,file:Exec@600,file:Exec@963,registry:Claim@525,registry:sql@1694,registry:sql@2554,registry:sql@2833,registry:sql@3696,registry:sql@3872,registry:sql@51,registry:sql@600,registry:sql@963,whole:addedColumn@500 c1aa99249122d7976764fc6571eada4c1fbda98d52e96d493c64f3e39c31d5bd
+internal/registry/registry.go Registry.Get legacy accepted-legacy accepted-legacy;rev3=J1,J4;basis=route-and-input;rev3=census-ruling-ha-p1a-433;basis=same identities as List: +registry:sql is r.sql handed to readCols, the same connection the SELECT already used; same SELECT ... WHERE host = ? with the select list readCols returns (routeCols for a read-write registry). Root's instanceRegistryHostApp and instanceRegistryHostRuntime read Get through the read-only child and now work before the migration too. file:QueryRow@262,registry:Route@165,registry:remote@58,registry:remote@90,registry:sql@209,registry:sql@262,whole:Route@169,whole:Route@455,whole:remoteClient@60,whole:remoteClient@92 736f4a42df871f765a124ea532a38ba1c8ab8bf16375eb0c480f855ddf5c3e82
+@remove internal/instancectl/peer_linux.go productionPeerOK
+@removed internal/instancectl/peer_linux.go productionPeerOK H3 census-ruling-ha-p1a-433;basis=root (carlos-instance-control.service): reads nothing now. The systemctl MainPID read moved verbatim to systemdEdgeMainPID, and the decision and its one-second cache moved to edgePeer.check (internal/instancectl/peer_edge.go, envelope re-pinned). Acceptance is unchanged: SO_PEERCRED uid carlos AND pid equal to the MainPID systemd reports for carlos-edge.service. New in edgePeer.check: a peer the cached answer refuses (a stale pid or a cached failure, #433) is checked once against a fresh read before the refusal, at most one forced read per 100 ms; the peer is accepted only if the fresh MainPID equals it, so nothing wider is accepted.
+@coverage internal/host 797fbd93c1ef001e1a3cc2a21ab096695e919926e8eb3b2bf7d92c35722b2568
+@coverage internal/instancectl bd5c2dc71194fb61dd4dc3c34c0bc001b1f7ff3a605718161a3d68ff5e42be41
+@coverage internal/provision 97e8b635847f2d6808f21d7ae068f362993c69f547e02c5b311756da8f662c50
+@coverage internal/registry 40555af3a72b13fa691f023156257d3e8020fe26119edcbab940c6323978dffc
+@fields A,Account,Accounts,AddedAt,Addr,Addrs,Alias,Aliases,Alive,AllowAbsent,App,Archives,Args,AssetGen,AssetsOff,At,Attempts,B,Backing,Bucket,BuildState,Callback,CallbackError,CallbackFailed,Canary,Caps,CertExpiresAt,Changed,Channel,CheckedAt,Claim,ClaimIncarnation,ClaimOwner,ClaimOwnership,ClaimRowID,ClaimStamp,Class,Contents,CreatedAt,DBPath,DNSCheckedAt,DNSStatus,Deadline,Default,Demand,Digest,DoneBefore,Due,DueAt,EgressAllow,Env,EnvBefore,Environment,Error,ErrorKind,ExcludeHosts,ExpectGood,ExpectOp,ExpectPair,Expected,F,Failed,FenceGen,Fleet,FleetBox,FleetBoxes,Fleets,From,FromDB,FromOp,FromSock,Gate,GoodDemand,GoodDigest,GoodVersion,HA,Hash,Health,Held,Hibernate,HoldOp,Host,Hosts,ID,Id,IdValue,Idle,IdleSeconds,ImportGate,Incarnation,Journal,Keep,Kind,Label,LastAt,LastError,LastMs,LastStatus,Limit,MaxRun,MaxRunSeconds,Method,Ms,Name,Next,NextAt,NextDue,NextGood,NextValue,Now,Number,Number64,Observed,ObservedValue,Old,On,Op,Original,Owner,Ownership,P,Pair,Path,Paths,Platform,PolicyExpiresAt,Pool,Prefix,Prev,PrevVersion,Provisioned,RateLimit,RecordKey,Region,Registration,Replica,Replicas,Replication,Retirement,Route,Routes,Row,Rows,Runtime,Seed,SeedID,SeedSource,ServingSeq,ServingVersion,Size,Slug,Socket,Spec,Sqid,State,Status,StatusNamed,Steering,StringMap,T,TValue,Tags,Target,Targets,Text,Timer,Timers,Times,To,ToDB,ToOp,ToSock,TokenHash,Tunnel,Type,Unit,UpdateSettings,Ver,Version,W,WakeIncarnation,Wildcards,closed,conn,connect,ctx,d,dec,done,enc,full,input,mu,output,path,readOnly,remote,sql,wait
diff --git a/internal/provision/testdata/plan14-root-reads-rollup-tenant-tags.tsv b/internal/provision/testdata/plan14-root-reads-rollup-tenant-tags.tsv
new file mode 100644
index 000000000..360a9cdea
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-rollup-tenant-tags.tsv
@@ -0,0 +1,3 @@
+# Census overlay rollup-tenant-tags, written by census-propose (#369). census-ruling-rollup-tenant-tags, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-rollup-tenant-tags.md.
+# 0 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@coverage internal/metrics ccc6723430e0c436f01843706c3e11e42dadcf357f0848795983e20ed9c9a439
diff --git a/internal/provision/testdata/plan14-root-reads-usage-attribution-390.tsv b/internal/provision/testdata/plan14-root-reads-usage-attribution-390.tsv
new file mode 100644
index 000000000..088139390
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-usage-attribution-390.tsv
@@ -0,0 +1,3 @@
+# Census overlay usage-attribution-390, written by census-propose (#369). census-ruling-usage-attribution-390, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-usage-attribution-390.md.
+# 0 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@coverage . 9861a9ec86221ad5d3d3c541c01511488cbd169ddd105ecced9402d0490439b0
diff --git a/internal/provision/usage_attribution_390_census_test.go b/internal/provision/usage_attribution_390_census_test.go
new file mode 100644
index 000000000..719c322c0
--- /dev/null
+++ b/internal/provision/usage_attribution_390_census_test.go
@@ -0,0 +1,31 @@
+package provision
+
+// Record-write census entry for usage-attribution-390 (#390: console usage
+// and billing attribute every box's readings by the box's tag or the
+// hostname's account namespace, not the console box's registry), layered on
+// nearestRegionBWriteCensusInventory (main's newest at d3c5601b). Reviewed
+// by the branch author and the cross-model reviewer (Astra) with the branch.
+// No record write is added, moved or reclassified:
+// - Server.handleAPIStatusInstances keeps its one key site, the
+// "instances" JSON literal of its answer. Its body now attributes each
+// reading through usageAttribution, reads the instance records (read
+// only, for the APP column) and marks an unattributed row. It writes
+// nothing.
+func usageAttribution390WriteCensusInventory() []censusEntry {
+ entries := append([]censusEntry(nil), nearestRegionBWriteCensusInventory()...)
+ replacements := []censusEntry{
+ {"internal/console/apistatusinstances.go", "Server.handleAPIStatusInstances", "key-site", "lit:instances", "f6f97ed6ce5d68f2dd8a7254409b9d26c64cda6dde78460812ea7f7603bd386d"},
+ }
+ for _, r := range replacements {
+ found := false
+ for i, e := range entries {
+ if e.File == r.File && e.Unit == r.Unit {
+ entries[i], found = r, true
+ }
+ }
+ if !found {
+ panic("usage-attribution-390 replacement of an unlisted unit " + r.File + ":" + r.Unit)
+ }
+ }
+ return entries
+}
diff --git a/internal/registry/claimrows.go b/internal/registry/claimrows.go
index 4b164549c..237b2e91d 100644
--- a/internal/registry/claimrows.go
+++ b/internal/registry/claimrows.go
@@ -38,8 +38,11 @@ type ClaimRowArchive struct {
func (r *Registry) migrateClaimOwnership() error {
for _, table := range []string{"routes", "timers"} {
- for _, column := range []string{"claim_incarnation TEXT NOT NULL DEFAULT ''", "claim_stamp INTEGER NOT NULL DEFAULT 0", "claim_owner TEXT NOT NULL DEFAULT ''", "claim_row_id TEXT NOT NULL DEFAULT ''"} {
- if _, err := r.sql.Exec("ALTER TABLE " + table + " ADD COLUMN " + column); err != nil && !strings.Contains(err.Error(), "duplicate column") {
+ for _, c := range routeAddedColumns {
+ if !c.Claim {
+ continue
+ }
+ if _, err := r.sql.Exec("ALTER TABLE " + table + " ADD COLUMN " + c.spec()); err != nil && !strings.Contains(err.Error(), "duplicate column") {
return err
}
}
diff --git a/internal/registry/ha_test.go b/internal/registry/ha_test.go
index 9a8f53bd4..6ccdd97db 100644
--- a/internal/registry/ha_test.go
+++ b/internal/registry/ha_test.go
@@ -1,7 +1,10 @@
package registry
import (
+ "database/sql"
"path/filepath"
+ "reflect"
+ "strings"
"testing"
)
@@ -43,3 +46,157 @@ func TestHAMarkIsSticky(t *testing.T) {
t.Fatal("SetHA on an unknown host: want an error")
}
}
+
+// dropRouteColumns opens path read-write and drops cols from routes: the
+// registry an older agent left, before its successor's migration ran.
+func dropRouteColumns(t *testing.T, path string, cols ...string) {
+ t.Helper()
+ db, err := sql.Open("sqlite", path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ for _, c := range cols {
+ if _, err := db.Exec(`ALTER TABLE routes DROP COLUMN ` + c); err != nil {
+ t.Fatalf("drop %s: %v", c, err)
+ }
+ }
+}
+
+// #433: at the upgrade to P1a root read routes.ha before the new agent's
+// migration added it ("no such column: ha"), and egress slice naming
+// failed. A read-only registry, root's, reads a column the table lacks as
+// its migration default.
+func TestReadOnlyRegistryReadsBeforeTheAgentMigrates(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "registry.db")
+ w, err := Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ rt := Route{Host: "shop.example.com", Kind: "instance", Status: "ready", App: "shop", Channel: "stable", EgressAllow: "203.0.113.7/32"}
+ if err := w.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ w.Close()
+ dropRouteColumns(t, path, "ha", "policy_expires_at")
+
+ ro, err := OpenReadOnly(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer ro.Close()
+ rows, err := ro.List()
+ if err != nil {
+ t.Fatalf("List without the ha column: %v", err)
+ }
+ if len(rows) != 1 || rows[0].Host != rt.Host || rows[0].HA || rows[0].PolicyExpiresAt != "" || rows[0].EgressAllow != rt.EgressAllow {
+ t.Fatalf("List = %+v", rows)
+ }
+ got, err := ro.Get(rt.Host)
+ if err != nil {
+ t.Fatalf("Get without the ha column: %v", err)
+ }
+ if got == nil || got.HA || got.App != "shop" || got.EgressAllow != rt.EgressAllow {
+ t.Fatalf("Get = %+v", got)
+ }
+ if got, err := ro.Get("absent.example.com"); err != nil || got != nil {
+ t.Fatalf("Get of an absent host = %+v, %v", got, err)
+ }
+}
+
+// routeAddedColumns, the one migration definition, is exactly routeCols
+// less the first CREATE's columns (review r1 P2, #433): a column read by
+// routeCols that no definition adds, or a definition routeCols does not
+// read, fails here. Each default is one a TEXT or INTEGER column can take.
+func TestRouteAddedColumnsIsEveryMigrationAddedColumn(t *testing.T) {
+ defined := map[string]bool{}
+ for _, c := range routeAddedColumns {
+ if defined[c.Name] {
+ t.Errorf("%s is defined twice", c.Name)
+ }
+ defined[c.Name] = true
+ if !(c.Type == "TEXT" && c.Default == "''") && !(c.Type == "INTEGER" && c.Default == "0") {
+ t.Errorf("%s: %s DEFAULT %s", c.Name, c.Type, c.Default)
+ }
+ }
+ read := map[string]bool{}
+ for _, c := range migrationAddedRouteCols() {
+ read[c] = true
+ if !defined[c] {
+ t.Errorf("routeCols reads %s, which no migration definition adds", c)
+ }
+ }
+ for c := range defined {
+ if !read[c] {
+ t.Errorf("%s is defined but not in routeCols", c)
+ }
+ }
+ for _, c := range []string{"ha", "claim_incarnation", "claim_stamp", "claim_owner", "claim_row_id"} {
+ if !defined[c] {
+ t.Errorf("%s missing", c)
+ }
+ }
+}
+
+// routesCreateColumns is the first CREATE TABLE routes's columns; every
+// other routeCols column is added by a migration.
+var routesCreateColumns = map[string]bool{
+ "host": true, "kind": true, "socket": true, "status": true, "last_error": true,
+ "db_path": true, "version": true, "prev_version": true, "created_at": true,
+}
+
+// migrationAddedRouteCols is routeCols less the first CREATE's columns,
+// read from routeCols itself rather than from any migration list.
+func migrationAddedRouteCols() []string {
+ var out []string
+ for _, c := range strings.Split(routeCols, ",") {
+ if c = strings.TrimSpace(c); !routesCreateColumns[c] {
+ out = append(out, c)
+ }
+ }
+ return out
+}
+
+// Review r1 P2 (#433): root's read-only List and Get work on a registry
+// that lacks ANY one migration-added routes column, each read as its
+// migration default, the claim ownership columns included.
+func TestReadOnlyRegistryReadsWithoutEachAddedColumn(t *testing.T) {
+ for _, c := range routeAddedColumns {
+ col := c.Name
+ t.Run(col, func(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "registry.db")
+ w, err := Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // Only first-CREATE columns set: every added column holds its
+ // default, which is what the stand-in must read back.
+ rt := Route{Host: "shop.example.com", Kind: "instance", Status: "ready", Socket: "/run/shop.sock"}
+ if err := w.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ want, err := w.Get(rt.Host)
+ if err != nil || want == nil {
+ t.Fatalf("writer Get: %+v, %v", want, err)
+ }
+ w.Close()
+ dropRouteColumns(t, path, col)
+ ro, err := OpenReadOnly(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer ro.Close()
+ rows, err := ro.List()
+ if err != nil {
+ t.Fatalf("List without %s: %v", col, err)
+ }
+ got, err := ro.Get(rt.Host)
+ if err != nil {
+ t.Fatalf("Get without %s: %v", col, err)
+ }
+ if len(rows) != 1 || !reflect.DeepEqual(rows[0], *want) || got == nil || !reflect.DeepEqual(*got, *want) {
+ t.Fatalf("without %s: List %+v, Get %+v, want %+v", col, rows, got, want)
+ }
+ })
+ }
+}
diff --git a/internal/registry/registry.go b/internal/registry/registry.go
index cf6ee2c8e..2fb646e27 100644
--- a/internal/registry/registry.go
+++ b/internal/registry/registry.go
@@ -638,6 +638,98 @@ func (r *Registry) Close() error {
return r.sql.Close()
}
+// addedColumn is one column a migration adds to an existing table: a
+// name, a type (TEXT or INTEGER) and its NOT NULL DEFAULT as SQL (the
+// empty string literal or 0). Claim marks the claim ownership columns,
+// which migrateClaimOwnership adds to routes and timers; migrate adds the
+// rest to routes.
+type addedColumn struct {
+ Name, Type, Default string
+ Claim bool
+}
+
+// spec is the column's ADD COLUMN text: "<name> <type> NOT NULL DEFAULT <default>".
+func (c addedColumn) spec() string {
+ return c.Name + " " + c.Type + " NOT NULL DEFAULT " + c.Default
+}
+
+// routeAddedColumns is the one definition of every column a migration adds
+// to routes after the first CREATE, in the order each migration adds them:
+// migrate and migrateClaimOwnership both range over it, and a read-only
+// reader stands each one's default in for a column the agent has not
+// added yet (readCols, #433).
+var routeAddedColumns = []addedColumn{
+ {Name: "slug", Type: "TEXT", Default: "''"},
+ {Name: "addr", Type: "TEXT", Default: "''"},
+ {Name: "app", Type: "TEXT", Default: "''"},
+ {Name: "pool", Type: "TEXT", Default: "''"},
+ {Name: "region", Type: "TEXT", Default: "''"},
+ {Name: "channel", Type: "TEXT", Default: "''"},
+ {Name: "hibernate", Type: "INTEGER", Default: "0"},
+ {Name: "canary", Type: "INTEGER", Default: "0"},
+ {Name: "replication", Type: "TEXT", Default: "''"},
+ {Name: "next_due", Type: "INTEGER", Default: "0"},
+ {Name: "backing", Type: "TEXT", Default: "''"},
+ {Name: "status_named", Type: "INTEGER", Default: "0"},
+ {Name: "platform", Type: "INTEGER", Default: "0"},
+ {Name: "dns_status", Type: "TEXT", Default: "''"},
+ {Name: "dns_checked_at", Type: "INTEGER", Default: "0"},
+ {Name: "cert_expires_at", Type: "INTEGER", Default: "0"},
+ {Name: "account", Type: "TEXT", Default: "''"},
+ {Name: "environment", Type: "TEXT", Default: "''"},
+ {Name: "caps", Type: "TEXT", Default: "''"},
+ {Name: "tunnel", Type: "TEXT", Default: "''"},
+ {Name: "provisioned", Type: "INTEGER", Default: "0"},
+ {Name: "seed", Type: "TEXT", Default: "''"},
+ {Name: "unit", Type: "TEXT", Default: "''"},
+ {Name: "fleet_box", Type: "TEXT", Default: "''"},
+ {Name: "addrs", Type: "TEXT", Default: "''"},
+ {Name: "health", Type: "TEXT", Default: "''"},
+ {Name: "steering", Type: "TEXT", Default: "''"},
+ {Name: "gate", Type: "TEXT", Default: "''"},
+ {Name: "args", Type: "TEXT", Default: "''"},
+ {Name: "idle_seconds", Type: "INTEGER", Default: "0"},
+ {Name: "max_run_seconds", Type: "INTEGER", Default: "0"},
+ {Name: "replicas", Type: "TEXT", Default: "''"},
+ {Name: "replica", Type: "INTEGER", Default: "0"},
+ {Name: "hold_op", Type: "TEXT", Default: "''"},
+ {Name: "good_version", Type: "TEXT", Default: "''"},
+ {Name: "good_digest", Type: "TEXT", Default: "''"},
+ {Name: "good_demand", Type: "TEXT", Default: "''"},
+ {Name: "serving_version", Type: "TEXT", Default: "''"},
+ {Name: "update_settings", Type: "TEXT", Default: "''"},
+ {Name: "build_state", Type: "TEXT", Default: "''"},
+ {Name: "seed_source", Type: "TEXT", Default: "''"},
+ {Name: "import_gate", Type: "TEXT", Default: "''"},
+ {Name: "runtime", Type: "TEXT", Default: "''"},
+ {Name: "rate_limit", Type: "TEXT", Default: "''"},
+ {Name: "assets_off", Type: "INTEGER", Default: "0"},
+ {Name: "asset_gen", Type: "TEXT", Default: "''"},
+ {Name: "incarnation", Type: "INTEGER", Default: "0"},
+ {Name: "serving_seq", Type: "INTEGER", Default: "0"},
+ // The app policy's converge (#328, #329; Route.EgressAllow): '' = none.
+ {Name: "egress_allow", Type: "TEXT", Default: "''"},
+ {Name: "size", Type: "TEXT", Default: "''"},
+ {Name: "policy_expires_at", Type: "TEXT", Default: "''"},
+ // Region HA P1a: the born-HA mark (Route.HA), sticky.
+ {Name: "ha", Type: "INTEGER", Default: "0"},
+ // Host claims' ownership (migrateClaimOwnership, routes and timers).
+ {Name: "claim_incarnation", Type: "TEXT", Default: "''", Claim: true},
+ {Name: "claim_stamp", Type: "INTEGER", Default: "0", Claim: true},
+ {Name: "claim_owner", Type: "TEXT", Default: "''", Claim: true},
+ {Name: "claim_row_id", Type: "TEXT", Default: "''", Claim: true},
+}
+
+// addedRouteColumnDefaults maps each column routeAddedColumns adds to its
+// DEFAULT as SQL: the empty string literal or 0.
+func addedRouteColumnDefaults() map[string]string {
+ out := map[string]string{}
+ for _, c := range routeAddedColumns {
+ out[c.Name] = c.Default
+ }
+ return out
+}
+
// migrate is additive (CREATE TABLE IF NOT EXISTS), so deploying new code
// over an existing registry is always safe. New columns go in the ALTER list —
// the "duplicate column" error is swallowed so the list stays idempotent.
@@ -656,63 +748,11 @@ CREATE TABLE IF NOT EXISTS routes (
);`); err != nil {
return err
}
- for _, stmt := range []string{
- `ALTER TABLE routes ADD COLUMN slug TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN addr TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN app TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN pool TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN region TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN channel TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN hibernate INTEGER NOT NULL DEFAULT 0`,
- `ALTER TABLE routes ADD COLUMN canary INTEGER NOT NULL DEFAULT 0`,
- `ALTER TABLE routes ADD COLUMN replication TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN next_due INTEGER NOT NULL DEFAULT 0`,
- `ALTER TABLE routes ADD COLUMN backing TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN status_named INTEGER NOT NULL DEFAULT 0`,
- `ALTER TABLE routes ADD COLUMN platform INTEGER NOT NULL DEFAULT 0`,
- `ALTER TABLE routes ADD COLUMN dns_status TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN dns_checked_at INTEGER NOT NULL DEFAULT 0`,
- `ALTER TABLE routes ADD COLUMN cert_expires_at INTEGER NOT NULL DEFAULT 0`,
- `ALTER TABLE routes ADD COLUMN account TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN environment TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN caps TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN tunnel TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN provisioned INTEGER NOT NULL DEFAULT 0`,
- `ALTER TABLE routes ADD COLUMN seed TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN unit TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN fleet_box TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN addrs TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN health TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN steering TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN gate TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN args TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN idle_seconds INTEGER NOT NULL DEFAULT 0`,
- `ALTER TABLE routes ADD COLUMN max_run_seconds INTEGER NOT NULL DEFAULT 0`,
- `ALTER TABLE routes ADD COLUMN replicas TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN replica INTEGER NOT NULL DEFAULT 0`,
- `ALTER TABLE routes ADD COLUMN hold_op TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN good_version TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN good_digest TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN good_demand TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN serving_version TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN update_settings TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN build_state TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN seed_source TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN import_gate TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN runtime TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN rate_limit TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN assets_off INTEGER NOT NULL DEFAULT 0`,
- `ALTER TABLE routes ADD COLUMN asset_gen TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN incarnation INTEGER NOT NULL DEFAULT 0`,
- `ALTER TABLE routes ADD COLUMN serving_seq INTEGER NOT NULL DEFAULT 0`,
- // The app policy's converge (#328, #329; Route.EgressAllow): '' = none.
- `ALTER TABLE routes ADD COLUMN egress_allow TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN size TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE routes ADD COLUMN policy_expires_at TEXT NOT NULL DEFAULT ''`,
- // Region HA P1a: the born-HA mark (Route.HA), sticky.
- `ALTER TABLE routes ADD COLUMN ha INTEGER NOT NULL DEFAULT 0`,
- } {
- if _, err := r.sql.Exec(stmt); err != nil && !strings.Contains(err.Error(), "duplicate column") {
+ for _, c := range routeAddedColumns {
+ if c.Claim {
+ continue // migrateClaimOwnership's, below
+ }
+ if _, err := r.sql.Exec("ALTER TABLE routes ADD COLUMN " + c.spec()); err != nil && !strings.Contains(err.Error(), "duplicate column") {
return err
}
}
@@ -1059,7 +1099,11 @@ func (r *Registry) List() ([]Route, error) {
}
db = fresh
}
- rows, err := db.Query(`SELECT ` + routeCols + ` FROM routes ORDER BY host`)
+ cols, err := r.readCols(db)
+ if err != nil {
+ return nil, err
+ }
+ rows, err := db.Query(`SELECT ` + cols + ` FROM routes ORDER BY host`)
if err != nil {
return nil, err
}
@@ -1075,6 +1119,54 @@ func (r *Registry) List() ([]Route, error) {
return out, rows.Err()
}
+// readCols is the select list List and Get read routes with over db. A
+// read-write registry has migrated, so it is routeCols. A read-only one is
+// root's, which can open a table an older agent left before its
+// successor's migrate adds the newest columns (#433: "no such column: ha"
+// at the upgrade to region HA P1a). So each routeCols column the table
+// lacks that routeAddedColumns adds is read as the default the migration
+// will give it ("0 AS ha"). A column of the first CREATE is never stood
+// in for: without it the read fails, as it always has.
+func (r *Registry) readCols(db *sql.DB) (string, error) {
+ if !r.readOnly {
+ return routeCols, nil
+ }
+ rows, err := db.Query(`SELECT name FROM pragma_table_info('routes')`)
+ if err != nil {
+ return "", err
+ }
+ defer rows.Close()
+ have := map[string]bool{}
+ for rows.Next() {
+ var name string
+ if err := rows.Scan(&name); err != nil {
+ return "", err
+ }
+ have[name] = true
+ }
+ if err := rows.Err(); err != nil {
+ return "", err
+ }
+ if len(have) == 0 {
+ return routeCols, nil // no routes table: the read fails as before
+ }
+ defaults := addedRouteColumnDefaults()
+ cols := strings.Split(routeCols, ",")
+ stood := false
+ for i, c := range cols {
+ c = strings.TrimSpace(c)
+ cols[i] = c
+ if def, ok := defaults[c]; ok && !have[c] {
+ cols[i] = def + " AS " + c
+ stood = true
+ }
+ }
+ if !stood {
+ return routeCols, nil
+ }
+ return strings.Join(cols, ", "), nil
+}
+
// Get returns the route for host, or (nil, nil) if there is none.
func (r *Registry) Get(host string) (*Route, error) {
if r.remote != nil {
@@ -1082,7 +1174,11 @@ func (r *Registry) Get(host string) (*Route, error) {
return out.Route, err
}
- row := r.sql.QueryRow(`SELECT `+routeCols+` FROM routes WHERE host = ?`, host)
+ cols, err := r.readCols(r.sql)
+ if err != nil {
+ return nil, err
+ }
+ row := r.sql.QueryRow(`SELECT `+cols+` FROM routes WHERE host = ?`, host)
t, err := scanRoute(row.Scan)
if err == sql.ErrNoRows {
return nil, nil
diff --git a/status_instances.go b/status_instances.go
index b6b2b04d6..d61760fcc 100644
--- a/status_instances.go
+++ b/status_instances.go
@@ -42,6 +42,9 @@ type statusInstanceRow struct {
CPU *float64 `json:"cpu"`
Mem *int64 `json:"mem_bytes"`
Platform bool `json:"platform"`
+ // Unattributed is an instance whose owner the console cannot establish
+ // (#390); Account and App are empty. Absent from an older console.
+ Unattributed bool `json:"unattributed"`
// Region and RegionName are the box's placement code and label (region
// labels spec §4); "" from an older console or for a box it cannot name.
Region string `json:"region"`
@@ -117,6 +120,12 @@ func printStatusInstances(w io.Writer, rows []statusInstanceRow, account string)
// overhead in the picture.
host, app = r.Unit, "(platform)"
}
+ if r.Unattributed {
+ // An instance whose owner the console cannot establish: named
+ // by its host, with the reason under the table, rather than
+ // filed under the platform.
+ app = statusInstancesCopy.Unattributed
+ }
fmt.Fprintf(t, "%s\t%s\t%s\t%s\t%s\t%s\t%s\n",
r.Box, statusRegionCell(r.Region, r.RegionName), dashIfEmpty(host), dashIfEmpty(r.Account), dashIfEmpty(app),
cpuCell(r.CPU), memCell(r.Mem))
@@ -129,14 +138,24 @@ func printStatusInstances(w io.Writer, rows []statusInstanceRow, account string)
// it does not exist. The question this verb answers is "right now", and
// that limit belongs next to the answer.
mutedf(w, "(awake instances only — a hibernating instance has no process to measure)")
- // The readings are fleet-wide, but the console joins them against its own
- // box's route registry, so a unit on any other box matches nothing and
- // lands under (platform) rather than under its tenant. Inert on a
- // single-box deployment and fixed structurally by PR #137; until then an
- // operator reading this for "who is using what" has to be told, the same
- // way `carlos routes` says whose routes it is showing.
- mutedf(w, "(accounts are joined against the console's own box's route registry; "+
- "an instance on another box in a fleet can land under (platform))")
+ // Said only when it applies: since #390 the console joins every box's
+ // readings to the instance records, so an instance on another box is
+ // its tenant's. What is left is an instance nothing can be shown to own.
+ for _, r := range rows {
+ if r.Unattributed {
+ mutedf(w, "%s", statusInstancesCopy.UnattributedNote)
+ break
+ }
+ }
+}
+
+// statusInstancesCopy is `carlos status --instances`' new copy (#390; Luna
+// passes 2026-10-26, docs/superpowers/notes/LUNA-COPY-REVIEW-USAGE-ATTRIBUTION*.md).
+var statusInstancesCopy = struct {
+ Unattributed, UnattributedNote string
+}{
+ Unattributed: "(unattributed)",
+ UnattributedNote: "(unattributed: neither its box nor its hostname identifies its account, so its usage counts against no account)",
}
// statusLayoutRow is one host's layout, as the console answers it
diff --git a/status_instances_test.go b/status_instances_test.go
index d9dfea623..fa2a98c94 100644
--- a/status_instances_test.go
+++ b/status_instances_test.go
@@ -19,12 +19,12 @@ import (
// (platform) rather than as two blank cells a reader would take for missing
// data.
//
-// And the table is followed, every time, by the two ways it misleads: a
-// hibernating instance has no process and so no reading, and the readings are
-// fleet-wide while the account each is attributed to comes from the console's
-// own box's registry. Neither caveat is conditional, because both are ways a
-// SHORT list reads as a complete one, and short is exactly when nobody thinks
-// to ask.
+// And the table is followed, every time, by the way it misleads: a
+// hibernating instance has no process and so no reading. Not conditional,
+// because a SHORT list reads as a complete one, and short is exactly when
+// nobody thinks to ask. An instance whose owner cannot be established
+// (#390) prints by its host with (unattributed), and the note saying what
+// that means follows the table only when such a row is there.
func TestPrintStatusInstancesLabelsPlatformAndStatesItsLimits(t *testing.T) {
rows := []statusInstanceRow{
{Box: "box-a", Host: "app.example.com", Account: "cdef", App: "widgets",
@@ -39,12 +39,24 @@ func TestPrintStatusInstancesLabelsPlatformAndStatesItsLimits(t *testing.T) {
"app.example.com", "cdef", "widgets", "0.250", "1MB",
"console.service", "(platform)",
"awake instances only",
- "console's own box's route registry",
} {
if !strings.Contains(out, want) {
t.Errorf("missing %q in:\n%s", want, out)
}
}
+ if strings.Contains(out, statusInstancesCopy.UnattributedNote) {
+ t.Errorf("the unattributed note printed with no unattributed row:\n%s", out)
+ }
+
+ rows = append(rows, statusInstanceRow{Box: "box-b", Unit: "carlos-exec@stray.example.com", Host: "stray.example.com", Unattributed: true})
+ buf.Reset()
+ printStatusInstances(&buf, rows, "")
+ out = buf.String()
+ for _, want := range []string{"stray.example.com", statusInstancesCopy.Unattributed, statusInstancesCopy.UnattributedNote} {
+ if !strings.Contains(out, want) {
+ t.Errorf("missing %q in:\n%s", want, out)
+ }
+ }
}
// TestPrintStatusLayoutRendersSortedAndMarksStale pins the CLI table for