Merge origin/main (cb23eb51, claims cleanup R1) into plans-6-checkout; census re-layered after Astra round 4: plans-6a-units re-sealed after main's lines (EndBillingDiscovery changed), census-propose re-run, record-write layer on claimsCleanupR1; ledger
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
48 files changed,
+2,327
−126
AGENTS.md+48 −5docs/superpowers/notes/census-proposal-claims-cleanup-r1.md+23 −0docs/superpowers/notes/census-proposal-offline-move-trim-t1.md+11 −0docs/superpowers/notes/census-proposal-plans-6-checkout.md+4 −2docs/superpowers/notes/plans-6a-ledger.md+2 −0docs/superpowers/plans/2026-10-25-claims-cleanup-r0.md+80 −0docs/superpowers/plans/2026-10-25-claims-cleanup-r1.md+68 −0docs/superpowers/plans/2026-10-25-offline-move-trim-t1.md+57 −0internal/activator/backend_exec.go+38 −1internal/activator/dropstaged_test.go+325 −0internal/console/apidbforward.go+1 −2internal/console/apiinstancemove.go+2 −1internal/console/apiinstancemove_offline.go+9 −6internal/console/apiinstancemove_offline_absence.go+74 −0internal/console/apiinstancemove_offline_absence_test.go+154 −0internal/console/apiruns.go+1 −2internal/dbreads/agent.go+1 −2internal/dbreads/fixture_test.go+1 −2internal/host/agent.go+7 −2internal/host/boxreference.go+16 −3internal/host/claimsoff_golden_test.go+34 −0internal/host/movesoffline.go+11 −11internal/host/movesoffline_seal.go+2 −2internal/host/movessources.go+2 −1internal/host/runexec.go+1 −2internal/hostclaim/claim.go+8 −11internal/instancectl/claimunit.go+3 −6internal/instancectl/names.go+10 −0internal/instancectl/rununit_golden_test.go+14 −0internal/park/region_names.go+3 −2internal/provision/census_propose_internal_test.go+1 −0internal/provision/census_propose_test.go+117 −19internal/provision/census_removal_fs_test.go+266 −0internal/provision/census_removal_test.go+408 −0internal/provision/claims_cleanup_r1_census_test.go+30 −0internal/provision/incarnation.go+32 −0internal/provision/incarnation_golden_test.go+66 −0internal/provision/plan14_input_inventory_test.go+156 −8internal/provision/plan14_root_reads_test.go+123 −27internal/provision/plans6a_census_test.go+2 −2internal/provision/testdata/plan14-root-reads-chain.tsv+4 −2internal/provision/testdata/plan14-root-reads-claims-cleanup-r1.tsv+16 −0internal/provision/testdata/plan14-root-reads-offline-move-trim-t1.tsv+3 −0internal/provision/testdata/plan14-root-reads-plans-6-checkout.tsv+1 −1internal/provision/testdata/plan14-root-reads-plans-6a-units.tsv+3 −3internal/regionname/region.go+8 −0internal/regionname/region_golden_test.go+80 −0internal/runs/runs.go+1 −1
CI passed — run details
diff --git a/AGENTS.md b/AGENTS.md| index a57f05a58..a05cc3c01 100644 |
| --- a/AGENTS.md |
| +++ b/AGENTS.md |
| @@ -237,15 +237,33 @@ approved like this: |
| - `body`: the digest moved and the reads did not; |
| - `sites`: more or fewer reads of kinds the unit already makes; |
| - `envelope`: a package was re-pinned; |
| + - `removed`: the scan finds neither the unit's declaration nor any of |
| + its sites, or an envelope's directory is gone. A path counts as gone |
| + only if it is absent by Lstat: no file, directory or symlink there, |
| + and no symlink above it; |
| - `reads` (a kind of read the unit did not make before), `new`, |
| - `removed` or `other` (any census discrepancy none of these explains, |
| - shown with the census's own message): a decision. |
| + `quiet` (a unit still declared that reads nothing now, a directory |
| + still there with no source the census scans, or a path replaced by a |
| + symlink) or `other` (any census |
| + discrepancy none of these explains, shown with the census's own |
| + message): a decision. |
| 2. Write a CLAIMS file with one line per changed unit: |
| `<file>:<unit><TAB><what changed, and that no read was added or which one was>`. |
| + A claim for a removed unit is optional. A branch that only deletes |
| + code can pass an empty file. |
| 3. `make census-propose NAME=<branch> CLAIMS=<file>` writes the rest: |
| - the overlay (`testdata/plan14-root-reads-<NAME>.tsv`), each unit |
| re-frozen at its existing disposition with the claim appended; |
| - - the `@legacy` fingerprints, the envelope re-pins and the new seal; |
| + - for each removed unit, `@remove` for its row and, if its declaration |
| + was frozen, `@removed` with the basis |
| + `census-ruling-<NAME>;absent;basis=<claim>`. That removal holds only |
| + while the declaration stays out of the tree, even one that reads |
| + nothing; |
| + - for each deleted directory, `@coverage <dir> -`, which retires its |
| + envelope. The census fails while anything is at that path, even a |
| + directory of tests or a symlink; |
| + - the `@legacy` fingerprints, the envelope re-pins and the new seal (a |
| + deletion alone leaves the seal as it was); |
| - its line in `testdata/plan14-root-reads-chain.tsv`; |
| - the approval card, `docs/superpowers/notes/census-proposal-<NAME>.md`. |
| @@ -263,7 +281,10 @@ approved like this: |
| the card lists; |
| - an envelope means every changed function in that package and what |
| it reaches, since an envelope re-pin is how the census sees reads its |
| - scanner cannot attribute to a unit. |
| + scanner cannot attribute to a unit; |
| + - a removed unit or a retired envelope means confirming the code is |
| + deleted, not moved, and that no check root relies on goes with it |
| + unless its callers' changes on the card account for that. |
| It escalates 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 |
| @@ -280,7 +301,29 @@ read, not where a read points, so a `body` change can aim an existing |
| `Open` at a tenant-writable path. Someone other than the author has to |
| read the diff, but it need not be the owner. |
| -The tool refuses decisions (`reads`, `new`, `removed`, `other`): a new |
| +A deletion is an approval, not a decision (Paul, 2026-10-25, ruling 1 on |
| +#280): a deletion cannot add a read, and the scan, not the claim, proves |
| +the unit absent. Code that moved is not a deletion. A unit moved whole |
| +shows as `new`, and a read that moved shows as a change to the unit that |
| +took it. |
| + |
| +J4 (`TestPlan14RootInputInventoryCoverage`) checks its own inventory, |
| +the 27 overlays up to `activation-tools`, and its caller check covers |
| +those rows only. A row a later overlay added is never caller-checked. A |
| +row of J4's inventory is retired when the full chain no longer carries |
| +it and the tree no longer declares its unit. J4 skips a retired row. A |
| +row the chain removed whose unit is still declared is still checked. A |
| +family's witness tests stay required while any authority row in the full |
| +chain names the family and its unit is still declared. That includes a |
| +row only a later overlay added. Rows outside J4's scope do not count: |
| +those tagged only E4 or J1 to J4, and the relocation and activator |
| +worker files. Once no such |
| +row names the family, its witnesses may go in the same change. A |
| +surviving row of J4's inventory with no production caller still fails, |
| +so a deleting branch removes the row or keeps the caller. An exemption |
| +for a retired unit fails until it is deleted with the unit. |
| + |
| +The tool refuses decisions (`reads`, `new`, `quiet`, `other`): a new |
| kind of read can make a unit's disposition wrong, so it is the owner's |
| call, not an approval. Write those rows by hand, following the overlays in the |
| chain, and ask on #280 with the card attached; the census owner decides |
diff --git a/docs/superpowers/notes/census-proposal-claims-cleanup-r1.md b/docs/superpowers/notes/census-proposal-claims-cleanup-r1.md| new file mode 100644 |
| index 000000000..d188f4665 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-claims-cleanup-r1.md |
| @@ -0,0 +1,23 @@ |
| +# Census approval: claims-cleanup-r1 |
| + |
| +Ruling `census-ruling-claims-cleanup-r1`. Every change below keeps the disposition it already has, so it needs an approval, not a decision. |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `internal/console/apiinstancemove_offline.go` `Server.offlineClaimEvidence` | body | unchanged (1) | claims cleanup R1: the admission and backfill reads use the console's own keys and a local copy of hostops.BackfillPlan (same store Gets, same refusals) instead of hostops.AdmissionKey and CheckCreateFreeze; the host claim is still read through hostclaim.Read; no read added, the one scanned read (hostclaim.Read) unchanged | |
| +| `internal/console/apiruns.go` `Server.handleAPIRunCreate` | body | unchanged (1) | claims cleanup R1: the request's incarnation comes from provision.Incarnation, hostclaim.Incarnation's body moved unchanged (golden vectors); no read added or changed | |
| +| `internal/host/agent.go` `runAdoptUnderRootRelease` | body | unchanged (4) | claims cleanup R1: the claims shutdown timeout is the host constant claimsShutdownLimit (120s) instead of hostbox.RequestLimit (120s); no read added or changed | |
| + |
| +Envelopes re-pinned: `internal/console`, `internal/dbreads`, `internal/host`, `internal/hostclaim`, `internal/instancectl`, `internal/park`, `internal/provision`, `internal/regionname`, `internal/runs`. |
| + |
| +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/console/apiinstancemove_offline.go` `Server.offlineClaimEvidence`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-moves-offline;basis=root-input (J4, as main's moves units); the console (cmd/console serve under console.service, user carlos-console): new, reads the host claim, the record's acquisition, a domains claim and the app's admission only to refuse an offline start (MV-O29, MV-O20); a failed read refuses with a 502, never reads as absence; deny-only |
| +- `internal/console/apiruns.go` `Server.handleAPIRunCreate`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=the console (cmd/console serve under console.service, user carlos-console): the run create door reads the record, and rereads it after an unknown admit, through readRecord, judged under a unit admitted on and unjudged before; read sites unchanged, offsets moved |
| +- `internal/host/agent.go` `runAdoptUnderRootRelease`: authority, task B3,E1,E2,E3. Basis: rev3=census-ruling-self-serve-moves-1;basis=root claim/adopt/update controller uid 0: builds root's lifetime judge once from the host-claim switch and hands it to both productionRestartRequestPass calls; read sites unchanged, offsets moved; the preceding B3,E1,E2,E3 classification retained |
| + |
| +Seal: `a864cf31b6bf2c30b5aa8c2647835efdc456f34f4945eea12751daab2457728e` → `9cef5e93a1e3520e02efe66455bf70c1170d380b6d6a72ede02036ce3dd41924`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-claims-cleanup-r1.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/notes/census-proposal-offline-move-trim-t1.md b/docs/superpowers/notes/census-proposal-offline-move-trim-t1.md| new file mode 100644 |
| index 000000000..802a73ac9 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-offline-move-trim-t1.md |
| @@ -0,0 +1,11 @@ |
| +# Census approval: offline-move-trim-t1 |
| + |
| +Ruling `census-ruling-offline-move-trim-t1`. Every change below keeps the disposition it already has, so it needs an approval, not a decision. |
| + |
| +Envelopes re-pinned: `internal/activator`. |
| + |
| +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: `a864cf31b6bf2c30b5aa8c2647835efdc456f34f4945eea12751daab2457728e` → `a864cf31b6bf2c30b5aa8c2647835efdc456f34f4945eea12751daab2457728e`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-offline-move-trim-t1.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/notes/census-proposal-plans-6-checkout.md b/docs/superpowers/notes/census-proposal-plans-6-checkout.md| index 898f4f4d6..c7a853a1d 100644 |
| --- a/docs/superpowers/notes/census-proposal-plans-6-checkout.md |
| +++ b/docs/superpowers/notes/census-proposal-plans-6-checkout.md |
| @@ -24,13 +24,13 @@ Recorded dispositions, which each change must still satisfy: |
| - `internal/console/server.go` `NewServer`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=console construction adds the lifetime judge, the cutover admission gate and its first marker read; claims-off app materialisation moves to the cutover watch; the existing logs/data route literal moves and is not a filesystem read;rev3=census-ruling-plans-4d-lapse;basis=registers GET and POST /a/{sqid}/plan/keep (the owner-only keep page, plans 4d) beside the account settings routes; no goroutine; read sites unchanged, offsets moved |
| - `internal/console/store.go` `Store.migrate`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=console.service user carlos-console, J4 root-input: adds the three account/app-scoped lifetime intent tables and apps.lifetime at unarmed store boot, then backfills missing lifetimes;rev3=census-ruling-plans-4d-lapse;basis=adds the additive account_plans.lapse_since and account_plans.disabled columns and calls migratePlanLapse last, which creates the console's own plan_lapse_items table (plans 4d). No read added; the new store units are the plans-4d-units decision. |
| -Seal: `61c5a2d77fa39607d7ce7224a8914c3bed2de78ad38819ef4ff1665bb6d8848f` → `ec611e77887f625ca08877e6f1457cbf904b9efac0964172f0e162ff49c8f824`. |
| +Seal: `9b27c8b855ca32a3f12119da92a7571542d2b0c4be4f3383e2ac482323b60ca8` → `c6a920b27d3206e85ac923b308bdf287931954776681732937f7445dd88ec11b`. |
| Overlay: `internal/provision/testdata/plan14-root-reads-plans-6-checkout.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
| ## Decision: census-ruling-plans-6a-units |
| -Twenty-three new units, written by hand in `internal/provision/testdata/plan14-root-reads-plans-6a-units.tsv` (chained before this proposal's overlay, after main's edge-protection-2 lines, seal `61c5a2d77fa39607d7ce7224a8914c3bed2de78ad38819ef4ff1665bb6d8848f`), regenerated after the Astra fix pass and the Plan 4d integration. Each is accepted legacy, mirroring its closest sibling: |
| +Twenty-three new units, written by hand in `internal/provision/testdata/plan14-root-reads-plans-6a-units.tsv` (chained before this proposal's overlay, after main's claims-cleanup-r1 lines, seal `9b27c8b855ca32a3f12119da92a7571542d2b0c4be4f3383e2ac482323b60ca8`), regenerated after the Astra fix pass and the Plan 4d integration. Each is accepted legacy, mirroring its closest sibling: |
| - console SQL on the console's own billing tables (`billing_price_books`, `billing_accounts`, `billing_problems`): `Store.NotePriceBook`, `Store.SetBillingCustomer`, `putBillingState`, `type sqlExecer` (an interface; not a read), `Store.LiveBillingAccounts`, `Store.DiscoverableBillingAccounts`, `Store.MarkBillingDiscovery` and `Store.EndBillingDiscovery` (discovery's outstanding-work marker, written before any candidate syncs, and its failure count), `Store.ResolveBillingProblem` (a sync resolving a missing-subscription problem), `Store.billingAccountWhere`, `Store.OpenBillingProblem`, `Store.BillingProblems`, `Store.BillingProblem`, `Store.CloseBillingProblem`, `Store.migrateBilling`, `Store.migrateBillingAccounts` (J4, as the plans-4a store units); |
| - `Store.SaveBillingSync`: one transaction holding the billing row, the guarded plan write and, for a fall, Plan 4d's own lapse-mark and grace-reset statements (`markLapseSQL`, `deleteCapStateSQL`); called only by `Server.applyBillingPlan`, which shares `applyAccountPlan`'s transition under the account's lapse lock (J4); |
| @@ -45,3 +45,5 @@ Since Astra's review at 7826d2e0 (which approved the seventeen units then listed |
| Since Astra's round 2 at 05b28473 (which approved the twenty then listed): `Store.DiscoverableBillingAccounts` and `Store.migrateBillingAccounts` changed (the `discover_retry` column and its use), and `Store.SetBillingDiscoveryRetry` and `Store.ResolveBillingProblem` are new. All four are parameterized console SQL on the console's own billing tables. |
| Since Astra's round 3 at 0a9b202a (which approved the four changed then): `Store.SetBillingDiscoveryRetry` is replaced by `Store.MarkBillingDiscovery` and `Store.EndBillingDiscovery`, and `Store.migrateBillingAccounts` changed (the `discover_failures` column). All parameterized console SQL on the console's own billing_accounts table. |
| + |
| +Since Astra's round 4 at af8cc0e1: `Store.EndBillingDiscovery` changed (its success branch clears the marker and resolves the account's `discovery_failing` problem in one transaction: one more Exec, on the console's own `billing_problems`). |
diff --git a/docs/superpowers/notes/plans-6a-ledger.md b/docs/superpowers/notes/plans-6a-ledger.md| index c945ba9df..c5b0e8ce2 100644 |
| --- a/docs/superpowers/notes/plans-6a-ledger.md |
| +++ b/docs/superpowers/notes/plans-6a-ledger.md |
| @@ -61,3 +61,5 @@ Round 2: census: plans-6a-units now 22 units (DiscoverableBillingAccounts, migra |
| Round 3: fixed finding 1 (discovery marker not durable before commits) — Store.MarkBillingDiscovery sets discover_retry before any candidate is synced and the customer is skipped for the pass if it fails; Store.EndBillingDiscovery clears it only when every candidate succeeds — TestDiscoveryMarkerIsDurableBeforeACandidateCommits, TestDiscoverySkipsACustomerWhoseMarkerCannotBeWritten RED→GREEN (TestDiscoveryKeepsAFailedCandidate still green). |
| Round 3: added discover_failures; after 24 consecutive failed passes a deduplicated discovery_failing problem opens (retries continue hourly) and a successful pass resolves it — TestPersistentDiscoveryFailureOpensAProblem RED→GREEN; plan request budget: up to 31 requests per discovery customer per pass, retained retries extend past the seven-day cohort; docs reason row. |
| Round 3: merged origin/main 96564cf3 (edge protection plan 2); census: plans-6a-units 23 units (migrateBillingAccounts changed; MarkBillingDiscovery, EndBillingDiscovery new; SetBillingDiscoveryRetry gone), seal 61c5a2d7; census-propose seal ec611e77; record-write: main.go main digest moved with main's merge (e639a4e3); census tests ok. |
| +Round 4: fixed Minor (discovery_failing could stay open) — EndBillingDiscovery clears the marker and resolves the account's discovery_failing problem in one transaction; a failed resolve keeps the marker so the next pass finishes — TestDiscoverySuccessResolvesItsProblemWithTheMarker RED→GREEN. |
| +Round 4: merged origin/main cb23eb51 (claims cleanup R1); census: plans-6a-units 23 units (EndBillingDiscovery changed), seal 9b27c8b8; census-propose seal c6a920b2; record-write layer on claimsCleanupR1, digests unchanged; census tests ok. |
diff --git a/docs/superpowers/plans/2026-10-25-claims-cleanup-r0.md b/docs/superpowers/plans/2026-10-25-claims-cleanup-r0.md| new file mode 100644 |
| index 000000000..489398cff |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-10-25-claims-cleanup-r0.md |
| @@ -0,0 +1,80 @@ |
| +# Claims cleanup R0: census removal plumbing |
| + |
| +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [x]`) syntax for tracking. |
| + |
| +**Goal:** A deleted unit, frozen declaration or package directory passes the census with an overlay `make census-propose` writes and a reviewer's approval; changed and new reads still fail. |
| + |
| +**Architecture:** Test code only, all in `internal/provision`. The scan records every directory it walks, the inventory learns a retired envelope (`@coverage <dir> -`), census-propose treats an absent unit or directory as the approval class `removed`, and J4 drops a row the full chain removed once its declaration is gone. |
| + |
| +**Tech Stack:** Go tests in `internal/provision`; the TSV census chain under `internal/provision/testdata`. |
| + |
| +**Spec:** Paul's ruling 1 on amadan #280 (2026-10-25); `docs/superpowers/plans/2026-10-25-claims-cleanup.md` row R0; `docs/superpowers/notes/claims-inventory.md` §4 R0 and §5 (on design-live-moves-ha). |
| + |
| +## Global Constraints |
| + |
| +- Production code unchanged. Only `*_test.go`, testdata and AGENTS.md. |
| +- The seal chain stays append-only: no existing overlay or seal is edited. |
| +- `new`, `reads` and `other` stay decisions census-propose refuses. |
| +- Run census tests under `nice -n 19`, serially, only `internal/provision`. |
| +- AGENTS.md prose: short sentences, no em dashes. |
| + |
| +## Review Focus |
| + |
| +- A unit still declared but reading nothing is not a deletion: it stays a decision (new class `quiet`), never `removed`. |
| +- A directory that lost its scanned files but still exists (tests or testdata left) is not retired: `quiet`, a decision. |
| +- A retired envelope whose directory comes back fails the census, even if the directory holds only test files. |
| +- A generated `@removed` row must not tolerate the declaration coming back without reads (the zddr3 H3 rule would): it requires absence. |
| +- J4 must not stop checking a row the chain removed while its declaration is still in the tree. |
| + |
| +--- |
| + |
| +### Task 1: Retired envelopes |
| + |
| +**Files:** Modify `internal/provision/plan14_root_reads_test.go` (`rootReadScan`, `rootReadProduction`, `rootReadInventory`, `loadRootReadInventory`, `compareRootReads`); `census_propose_test.go` (`cloneRootReadInventory`). Test: `plan14_root_reads_test.go`. |
| + |
| +**Interfaces:** |
| +- Produces: `rootReadScan.Dirs map[string]bool` (every walked directory, slash-relative, "." for the root); `rootReadInventory.Retired map[string]bool`; directive `@coverage<TAB><dir><TAB>-` (delta only; refused for an envelope not pinned); compare error `retired root source envelope still present <dir>` when `Dirs == nil || Dirs[dir]`. |
| + |
| +- [x] Test `TestPlan14RetiredEnvelope`: an overlay `@coverage internal/gone -` loaded on an inventory pinning `internal/gone` leaves no discrepancy for a scan without that directory; the same scan with `Dirs["internal/gone"]` fails with "retired root source envelope still present"; the directive in a base file, or for an unpinned directory, fails to load; a later `@coverage internal/gone <hash>` clears the retirement. |
| +- [x] Run it, see it fail; implement; run it, see it pass. |
| +- [x] Commit; advance the amadan task. |
| + |
| +### Task 2: `removed` as an approval in census-propose |
| + |
| +**Files:** Modify `internal/provision/census_propose_test.go`, `plan14_root_reads_test.go` (`checkRootReadDeclarations`). Test: `census_propose_internal_test.go`. |
| + |
| +**Interfaces:** |
| +- Consumes: Task 1's `Dirs`, `Retired`, the `-` directive. |
| +- Produces: class `censusQuiet = "quiet"` (a decision); `censusRemoved` approvable, used only when the scan proves the unit or directory absent; `rootReadAbsentRemoval(removal string) bool`, true for a removal whose basis is `census-ruling-<name>;absent;...`; such a removal fails while the declaration exists, unlike the H3 retire rule. |
| +- Overlay rows for a removed unit: `@remove<TAB>file<TAB>unit` when classified; for a frozen unit not already removed, `@removed<TAB>file<TAB>unit<TAB><owner><TAB>census-ruling-<NAME>;absent;basis=<claim or "deleted: declaration and sites absent from the tree">`, owner the row's task when it is a kept family, else `H3`. A retired directory: `@coverage<TAB>dir<TAB>-`. Claims for removed units are optional. |
| + |
| +- [x] Tests: `TestCensusClassifiesARemovedUnit` keeps `removed` and now also wants `Absent`; `TestCensusClassifiesAQuietUnit` (declared, no reads: `quiet`); `TestCensusProposalRetiresADeletedPackage` (fixture deletes a legacy frozen unit, an authority unit and their directory: the overlay loads, leaves the census clean, keeps the seal, and the card lists both units, their dispositions and the retired envelope); `TestCensusProposalRefusesADeletionWithAChangedRead` (same deletion plus a `reads` change or a new unit elsewhere: refused as a decision); `TestCensusAbsentRemovalNeedsAbsence` (after the generated overlay, the unit's declaration back without reads fails; back with reads fails; the directory back fails). |
| +- [x] Run, see them fail; implement; run, see them pass, with the existing census-propose tests. |
| +- [x] Commit; advance the amadan task. |
| + |
| +### Task 3: J4 retires a family's rows with its witnesses |
| + |
| +**Files:** Modify `internal/provision/plan14_input_inventory_test.go`. Test: same file. |
| + |
| +**Interfaces:** |
| +- Produces: `inputRetired(inv, full rootReadInventory, declared map[string]bool, key string) bool`: true when the full chain no longer carries the row and the tree declares no such unit. `TestPlan14RootInputInventoryCoverage` skips retired rows. `rootReadDeclared(root string) (map[string]bool, error)` names every declaration as the census does, without type-checking. |
| + |
| +- [x] Test `TestPlan14J4RetiresAFamily`: family A's every row retired and its witnesses gone: no failure; one surviving A row and a witness gone: fails "missing"; a surviving row with no production caller still fails; a row removed from the chain whose declaration is still in the tree is still checked. |
| +- [x] Run, see it fail; implement; run it and the J4 coverage test. |
| +- [x] Commit; advance the amadan task. |
| + |
| +### Task 4: AGENTS.md, the experiment, and the gate |
| + |
| +**Files:** Modify `AGENTS.md` ("The census"). |
| + |
| +- [x] Describe `removed` as an approval class, `quiet` as a decision, and the envelope retirement. |
| +- [x] Experiment (not committed): delete `internal/sim/hostlife`, run census-propose with an empty CLAIMS file, run `TestPlan14RootReadCensus`, restore with `git checkout -- internal/sim/hostlife` plus removing the generated files by exact path, confirm `git status` is clean. |
| +Result (2026-10-25): deleting `internal/sim/hostlife` gave a card with one removed unit (`mutate.sh`, frozen legacy) and one retired envelope, and an overlay of `@remove`, `@removed` (absent) and `@coverage internal/sim/hostlife -` with the seal unchanged. `TestPlan14RootReadCensus` and J4 both passed on the deleted tree. Restored; `git status` clean. J4's new retired-exemption check caught the roster-binding exemption for the deleted `servingPriorRevision`, which the retirement rule now covers, so that exemption was removed. |
| + |
| +- [x] `go vet ./internal/provision/`, the census and census-propose tests, `GOOS=darwin` and `GOOS=windows go build ./...`; push; `amadan ci status carlos/platform -branch claims-cleanup-r0`. |
| + |
| +## Review fixes (Astra, NOT READY at 4c85788e) |
| + |
| +- P1, J4: a family's witnesses stay required while any in-scope authority row of the full chain names it and its unit is still declared (`inputLiveFamilies`, `checkInputLiveWitnesses`), so a later-only row such as roster-binding's `servingPriorBinding` keeps them. J4's caller check still covers only its 27-overlay inventory. A retired row is not caller-checked. |
| +- P1, symlinks: a removed unit's file and a retired directory must be absent by Lstat with no symlinked ancestor (`rootReadPathAbsent`), when classifying and when re-checking a retired envelope. |
| +- P2: `census_removal_fs_test.go` runs `rootReadProduction` over a temp module for deletion, tests left behind, recreation, symlinks and a tagged declaration. |
diff --git a/docs/superpowers/plans/2026-10-25-claims-cleanup-r1.md b/docs/superpowers/plans/2026-10-25-claims-cleanup-r1.md| new file mode 100644 |
| index 000000000..9f713f0e6 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-10-25-claims-cleanup-r1.md |
| @@ -0,0 +1,68 @@ |
| +# Claims cleanup R1: move the live slices out of the claim packages |
| + |
| +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. |
| + |
| +**Goal:** No claims-off production caller imports a claim package (hostclaim, park, hostops, hostbox, hostactors) for live behaviour, with no behaviour change. One dependency stays on purpose: the offline door's host claim check keeps `hostclaim.Read`, because telling a malformed claim (502) from a valid one needs hostclaim's full decode and `Validate`. It goes when R6 removes the claim objects' writers. |
| + |
| +**Architecture:** Each live slice gets a neutral home (`provision`, `regionname`, `console`, `host`, `instancectl`). Claim packages that still use a symbol keep it as a thin delegate to the new home, or as a test-pinned twin where the import direction forbids delegation. Golden vectors land first and must pass unchanged after every move. |
| + |
| +**Tech Stack:** Go. |
| + |
| +**Spec:** `docs/superpowers/notes/claims-inventory.md` (on design-live-moves-ha) §2.4, §3, §4 row R1; `docs/superpowers/plans/2026-10-25-claims-cleanup.md` row R1. |
| + |
| +## Global Constraints |
| + |
| +- Claims-off behaviour byte-identical: Incarnation bytes (legacy and created forms), placement codes, offline-door statuses and messages. |
| +- Targeted tests only locally (`nice -n 19 go test ./internal/<pkg>/ -run <X>`); `go build ./...` plus `GOOS=darwin` and `GOOS=windows` before the push; `go vet` on touched packages. |
| +- Census: `make census-card`, CLAIMS file, `make census-propose NAME=claims-cleanup-r1`. A refused class (`removed`, `new`, `reads`, `other`) stops the branch for a report. |
| + |
| +## Review Focus |
| + |
| +- A present-but-malformed `control/hosts/<host>.json` stays a 502: the claim object is still read through `hostclaim.Read`, because only the claim schema can tell a malformed object from a claim. Pinned by `TestOfflineDoorAbsenceChecksRefuseAndFail`. The admission and backfill checks are console-local. |
| +- A backfill plan at phase `done` must still be allowed; the console-local verify must re-encode canonically, so the local plan type copies `hostops.BackfillPlan`'s shape exactly (pinned by a test that signs a `hostops.BackfillPlan` and reads it locally). |
| +- An invalid host or account shape must still give 502 on the claim and admission checks. |
| +- `hostclaim.Incarnation` must keep returning `hostclaim.ErrMalformed` for its claim callers. |
| + |
| +--- |
| + |
| +### Task 1: Golden vectors |
| + |
| +**Files:** Test: `internal/provision/incarnation_test.go`, `internal/regionname/region_golden_test.go`, `internal/host/boxreference_golden_test.go` |
| + |
| +- [ ] Pin `hostclaim.Incarnation` today for one legacy (zero time) and one created (`2026-10-01T12:34:56.789Z`) record, plus one malformed account, as literal hex strings (computed from main before any move). |
| +- [ ] Pin `HomePlacementCode`, `PlacementRegion`, `SameRegion`, `PlacementMatches` over a table (home "", "ie"; codes "", "ie", "uk", "@home", "Bad", 17 chars) through `park.*`. |
| +- [ ] Pin `hostactors.GroupBoxReference("123456789012", "i-0a61f580df1acfa65")` and `hostbox.RequestLimit == 120s`. |
| +- [ ] Run; commit. |
| + |
| +### Task 2: Incarnation into provision |
| + |
| +- [ ] `provision.Incarnation(account, app, host string, created time.Time) (string, error)` in `internal/provision/incarnation.go`; `provision.ErrIncarnation`. |
| +- [ ] Golden test runs against `provision.Incarnation` too; `hostclaim.Incarnation` delegates and maps errors to `ErrMalformed`. |
| +- [ ] Switch `dbreads/agent.go`, `host/runexec.go`, `console/apidbforward.go`, `console/apiruns.go`, the `runs/runs.go` comment. |
| +- [ ] Run dbreads, runs, host `-run Run`, console `-run 'DBRead|Run'`; commit. |
| + |
| +### Task 3: Placement helpers into regionname |
| + |
| +- [ ] `regionname.PlacementMatches(home, code, engine string) bool`; `park.PlacementMatches` delegates. |
| +- [ ] Golden table runs against `regionname.*` too. |
| +- [ ] Switch `console/apiinstancemove.go` `homePlacementCode`, `host/movesoffline.go`, `host/movesoffline_seal.go`, `host/movessources.go` `parkRegion`. |
| +- [ ] Run host `-run Offline`, console `-run 'Offline|Region|InstanceCreate'`; commit. |
| + |
| +### Task 4: The offline door's checks, console-local; dead sentinels |
| + |
| +- [ ] `offlineClaimEvidence` reads `apps/<acct>/<app>/admission.json` and `control/hosts-backfill.json` itself (`offlineAdmissionKey`, `offlineBackfillKey`, `offlineBackfillPlan` mirroring `hostops.BackfillPlan`). The host claim `control/hosts/<host>.json` stays on `hostclaim.Read` (see the goal). |
| +- [ ] Tests: keys equal hostops'; a signed `hostops.BackfillPlan` reads locally; a malformed host claim gives 502, as on main; an unreadable object gives 502. |
| +- [ ] ~~Delete the `hostops.ErrPending`/`ErrContract` comparisons at `domainattach.go`, `apidomains.go`, `apisystem.go`, `scandeliver.go`.~~ Not done: each never matches claims off (the sources are `domains`/`provision`/`objstore`/`appconfig` on an ungated store), but each does match claims on, and `TestClaimScanCallbackContentionAndSettlement` and `TestClaimScanMasterRotationSkipsBusyApp` pin two of them. Deleting them changes claims-on behaviour, so they go with R6, when their sources do. |
| +- [ ] Run console `-run 'Offline|Domain|Scan|System'`; commit. |
| + |
| +### Task 5: RequestLimit, GroupBoxReference, the unit control group |
| + |
| +- [ ] `host.claimsShutdownLimit = 120 * time.Second` replaces `hostbox.RequestLimit` in `agent.go`; `host.groupBoxReference` replaces `hostactors.GroupBoxReference` in `boxreference.go`; golden tests pin both against the claim twins. |
| +- [ ] `instancectl.RunUnitControlGroup` in `names.go`; the offline round calls it; `ClaimUnitControlGroup` stays as a delegate for its ~25 claim callers (renaming them all would edit census authority units for no live gain). Golden test pins the path. |
| +- [ ] Run host `-run 'BoxReference|Joining|Group'`, instancectl, activator `-run RoleLaunch`; commit. |
| + |
| +### Task 6: Census, builds, push |
| + |
| +- [ ] `make census-card`; CLAIMS; `make census-propose NAME=claims-cleanup-r1 CLAIMS=<file>`; `TestPlan14RootReadCensus`, `TestPlan14RootInputInventoryCoverage`. |
| +- [ ] `go build ./...`, darwin, windows; `go vet` touched packages; `gofmt -l`. |
| +- [ ] Commit, push, `amadan ci status carlos/platform -branch claims-cleanup-r1`. |
diff --git a/docs/superpowers/plans/2026-10-25-offline-move-trim-t1.md b/docs/superpowers/plans/2026-10-25-offline-move-trim-t1.md| new file mode 100644 |
| index 000000000..306cf5f52 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-10-25-offline-move-trim-t1.md |
| @@ -0,0 +1,57 @@ |
| +# Offline move trim T1: drop the staged replica in parallel |
| + |
| +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. |
| + |
| +**Goal:** The first wake after an offline move deletes the 270-305 staged keys under `moves/<host>/` with bounded parallelism instead of one `DeleteObject` at a time, still before the app starts. |
| + |
| +**Architecture:** Only `(*ExecBackend).dropStagedReplica` in `internal/activator/backend_exec.go` changes. It keeps its signature and its one caller (`Restore`, after a clean restore of a copy promoted on this call). The loop becomes a fixed pool of workers fed the same keys; the function returns only when every delete has returned, so the wake still does nothing more until the drop is over. |
| + |
| +**Tech Stack:** Go, `lease.MirrorStore`. |
| + |
| +**Spec:** `docs/superpowers/notes/offline-move-pause-trim.md` §4, item "T1a"; row T1 of `docs/superpowers/plans/2026-10-25-claims-cleanup.md`. |
| + |
| +## Global Constraints |
| + |
| +- Same keys: exactly the keys of the `staged` map `promoteStagedReplica` returned, each deleted once with `b.Mirror.Delete(ctx, b.Cfg.Bucket, key)`. Today's code deletes by key, not by version id; that stays. |
| +- Same failure semantics as the serial loop: best-effort. A failed delete is ignored, does not stop or cancel the other deletes, is not returned, and does not fail the wake. A leftover staged key is storage, not correctness (the existing comment), and the next landing or promotion owns it. |
| +- Order: none. The serial loop ranges over a Go map, whose order is unspecified and randomised per run, so no caller can depend on it. |
| +- Bound: the promotion's own worker count, `lease.DefaultMirrorWorkers` (8), or the store's `lease.MirrorConcurrency` answer (floored at 1), matching `lease.mirrorWorkers`. Never more workers than keys. |
| +- Do not edit `internal/lease/mirror.go` (changed on self-serve-moves-2 and -3). |
| +- No user-facing string changes. |
| + |
| +## Review Focus |
| + |
| +- A store whose `Delete` fails for one key: every other key is still deleted and the wake still succeeds (Task 1 test). |
| +- A store that answers `MirrorWorkers() == 1`: strictly serial, as before (Task 1 test, bound assertion). |
| +- The drop must finish before `Restore` returns, or the app could start with staging present and "staging wins" could put an old copy back after a crash (Task 1 test: no delete in flight once the call returns). |
| +- An empty or nil `staged` map: no goroutines, no calls (caller already guards `len(promoted) > 0`; the function handles it anyway). |
| +- A cancelled ctx: each key is still handed to `Delete` with that ctx, as the serial loop did. |
| + |
| +--- |
| + |
| +### Task 1: Parallel drop with the promotion's bound |
| + |
| +**Files:** |
| +- Modify: `internal/activator/backend_exec.go` (`dropStagedReplica`) |
| +- Test: `internal/activator/dropstaged_test.go` (new) |
| + |
| +**Interfaces:** |
| +- Consumes: `lease.MirrorStore`, `lease.MirrorConcurrency`, `lease.DefaultMirrorWorkers`. |
| +- Produces: `func (b *ExecBackend) dropStagedReplica(ctx context.Context, staged map[string]lease.MirrorObject)` (unchanged signature) and `func dropWorkers(m lease.MirrorStore, n int) int`. |
| + |
| +- [ ] **Step 1: Write the failing tests** in `dropstaged_test.go` with a counting store wrapping `fakeMirrorStore` (in-flight counter with max, a delay per delete, a key set that fails, a record of every key deleted): |
| + - `TestDropStagedReplicaDeletesEveryStagedKeyInParallel`: 300 staged keys plus one unrelated key under `instances/`; after the call every staged key is gone, each deleted exactly once, the unrelated key remains, max in flight is > 1 and <= `lease.DefaultMirrorWorkers`, and in-flight is 0 when the call returns. |
| + - `TestDropStagedReplicaHonoursTheStoresConcurrency`: a store answering `MirrorWorkers() == 1` sees max in flight 1; one answering 3 sees at most 3. |
| + - `TestDropStagedReplicaFailureIsBestEffort`: one key's delete fails; every other key is deleted, the failing key is attempted exactly once and stays, and the call returns normally. |
| +- [ ] **Step 2: Run** `nice -n 19 go test ./internal/activator/ -run TestDropStagedReplica -count=1`. Expected: FAIL on the in-flight > 1 assertion (serial loop). |
| +- [ ] **Step 3: Implement** `dropWorkers` (the `mirrorWorkers` rule, capped at n) and the worker pool in `dropStagedReplica`: collect keys, feed a channel, `sync.WaitGroup`, errors dropped, no cancellation. |
| +- [ ] **Step 4: Run** the Step 2 command plus `-run 'Staged|Promot|Boomerang'`. Expected: PASS. |
| +- [ ] **Step 5: Commit.** |
| + |
| +### Task 2: Gates, census, push |
| + |
| +**Files:** census overlay files only if `TestPlan14RootReadCensus` fails. |
| + |
| +- [ ] **Step 1:** `go build ./...`, `GOOS=darwin go build ./...`, `GOOS=windows go build ./...`, `go vet ./internal/activator/`, `gofmt -l internal/activator`, `nice -n 19 go test -race ./internal/activator/ -count=1`. Expected: all clean. |
| +- [ ] **Step 2:** `nice -n 19 go test ./internal/provision/ -run TestPlan14RootReadCensus -count=1`. If it fails: `make census-card`; a CLAIMS file; `make census-propose NAME=offline-move-trim-t1 CLAIMS=<file>`. If the card shows a decision class (`reads`, `new`, `removed`, `other`), stop and report. |
| +- [ ] **Step 3:** Commit, push to origin, `amadan ci status carlos/platform -branch offline-move-trim-t1`. No merge, no review request. |
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go| index ae034bcc0..de121e97f 100644 |
| --- a/internal/activator/backend_exec.go |
| +++ b/internal/activator/backend_exec.go |
| @@ -3533,8 +3533,45 @@ func (b *ExecBackend) promoteStagedReplica(ctx context.Context, host string) (ma |
| // third listing of a prefix this restore has already walked twice. |
| // Best-effort: a leftover staging copy is storage, not a correctness |
| // problem. |
| +// |
| +// The deletes run side by side (offline-move trim T1), on as many workers |
| +// as the promotion just before it used (dropWorkers): 270 to 305 staged |
| +// objects one DeleteObject at a time was 5 to 12 s of the move's pause. |
| +// What the serial loop did still holds. The same keys, each once, by key. |
| +// No order: the loop ranged over a map. A failed delete is dropped and |
| +// cancels nothing, so every other key is still tried, each with the |
| +// caller's ctx (an ended ctx is handed to every delete, as the loop did). |
| +// And the call returns only once every delete attempt has returned, so the |
| +// wake still spawns nothing while a delete is in flight. Best-effort as |
| +// before: a key whose delete failed stays staged. |
| func (b *ExecBackend) dropStagedReplica(ctx context.Context, staged map[string]lease.MirrorObject) { |
| + keys := make(chan string) |
| + var wg sync.WaitGroup |
| + for w := dropWorkers(b.Mirror, len(staged)); w > 0; w-- { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + for k := range keys { |
| + _ = b.Mirror.Delete(ctx, b.Cfg.Bucket, k) |
| + } |
| + }() |
| + } |
| for k := range staged { |
| - _ = b.Mirror.Delete(ctx, b.Cfg.Bucket, k) |
| + keys <- k |
| + } |
| + close(keys) |
| + wg.Wait() |
| +} |
| + |
| +// dropWorkers is how many deletes dropStagedReplica runs at once: the |
| +// mirror round's own rule (lease.DefaultMirrorWorkers, or the store's |
| +// lease.MirrorConcurrency answer floored at one), so the drop never puts |
| +// more requests in flight than the promotion it follows did. Never more |
| +// workers than keys. |
| +func dropWorkers(m lease.MirrorStore, n int) int { |
| + w := lease.DefaultMirrorWorkers |
| + if c, ok := m.(lease.MirrorConcurrency); ok { |
| + w = max(c.MirrorWorkers(), 1) |
| } |
| + return min(w, n) |
| } |
diff --git a/internal/activator/dropstaged_test.go b/internal/activator/dropstaged_test.go| new file mode 100644 |
| index 000000000..ea1bf7be4 |
| --- /dev/null |
| +++ b/internal/activator/dropstaged_test.go |
| @@ -0,0 +1,325 @@ |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/lease" |
| +) |
| + |
| +// countingDeleteStore wraps fakeMirrorStore to watch dropStagedReplica's |
| +// deletes: how many run at once, which keys were asked for, how often and |
| +// with which ctx, how many have returned, and which keys fail. |
| +// |
| +// The barrier: with release set, every delete announces itself on started |
| +// and then blocks until release is closed. A test can so hold a full batch |
| +// in flight and see that the drop has not returned, with no sleep. |
| +// respectCtx makes a delete whose ctx has ended refuse (and delete nothing), |
| +// the way an SDK call does. |
| +type countingDeleteStore struct { |
| + *fakeMirrorStore |
| + fail map[string]bool |
| + release chan struct{} |
| + started chan string |
| + respectCtx bool |
| + |
| + cmu sync.Mutex |
| + inFlight int |
| + maxSeen int |
| + finished int |
| + calls map[string]int |
| + ctxs map[string][]context.Context |
| +} |
| + |
| +func newCountingDeleteStore() *countingDeleteStore { |
| + return &countingDeleteStore{ |
| + fakeMirrorStore: newFakeMirrorStore(), |
| + fail: map[string]bool{}, |
| + calls: map[string]int{}, |
| + ctxs: map[string][]context.Context{}, |
| + } |
| +} |
| + |
| +// withBarrier arms the barrier for a drop of n keys. |
| +func (s *countingDeleteStore) withBarrier(n int) *countingDeleteStore { |
| + s.release = make(chan struct{}) |
| + s.started = make(chan string, n) |
| + return s |
| +} |
| + |
| +func (s *countingDeleteStore) Delete(ctx context.Context, bucket, key string) error { |
| + s.cmu.Lock() |
| + s.inFlight++ |
| + if s.inFlight > s.maxSeen { |
| + s.maxSeen = s.inFlight |
| + } |
| + s.calls[key]++ |
| + s.ctxs[key] = append(s.ctxs[key], ctx) |
| + s.cmu.Unlock() |
| + defer func() { |
| + s.cmu.Lock() |
| + s.inFlight-- |
| + s.finished++ |
| + s.cmu.Unlock() |
| + }() |
| + if s.release != nil { |
| + s.started <- key |
| + <-s.release |
| + } |
| + if s.respectCtx && ctx.Err() != nil { |
| + return ctx.Err() |
| + } |
| + if s.fail[key] { |
| + return errors.New("injected delete failure") |
| + } |
| + return s.fakeMirrorStore.Delete(ctx, bucket, key) |
| +} |
| + |
| +// workersStore is a countingDeleteStore that answers lease.MirrorConcurrency. |
| +type workersStore struct { |
| + *countingDeleteStore |
| + workers int |
| +} |
| + |
| +func (s *workersStore) MirrorWorkers() int { return s.workers } |
| + |
| +// stageKeys puts n staged objects for host and returns them in the shape |
| +// promoteStagedReplica hands to dropStagedReplica. |
| +func stageKeys(b *ExecBackend, s *countingDeleteStore, host string, n int) map[string]lease.MirrorObject { |
| + staged := map[string]lease.MirrorObject{} |
| + for i := 0; i < n; i++ { |
| + k := fmt.Sprintf("%sgenerations/0000/%08d.ltx", MovesPrefix(host), i) |
| + s.put(b.Cfg.Bucket, k, fmt.Sprintf("e%d", i)) |
| + staged[k] = lease.MirrorObject{ETag: fmt.Sprintf("e%d", i)} |
| + } |
| + return staged |
| +} |
| + |
| +// dropInBackground runs the drop and closes the returned channel when it |
| +// returns. |
| +func dropInBackground(b *ExecBackend, ctx context.Context, staged map[string]lease.MirrorObject) chan struct{} { |
| + done := make(chan struct{}) |
| + go func() { |
| + defer close(done) |
| + b.dropStagedReplica(ctx, staged) |
| + }() |
| + return done |
| +} |
| + |
| +// awaitStarted waits for n deletes to be held at the barrier. |
| +func awaitStarted(t *testing.T, s *countingDeleteStore, n int) { |
| + t.Helper() |
| + for i := 0; i < n; i++ { |
| + select { |
| + case <-s.started: |
| + case <-time.After(10 * time.Second): |
| + t.Fatalf("only %d of %d deletes reached the barrier", i, n) |
| + } |
| + } |
| +} |
| + |
| +// assertNotReturned fails if the drop returned while deletes are held. |
| +func assertNotReturned(t *testing.T, done chan struct{}) { |
| + t.Helper() |
| + select { |
| + case <-done: |
| + t.Fatal("the drop returned while deletes were still in flight") |
| + default: |
| + } |
| +} |
| + |
| +func awaitDone(t *testing.T, done chan struct{}) { |
| + t.Helper() |
| + select { |
| + case <-done: |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("the drop did not return once the deletes were released") |
| + } |
| +} |
| + |
| +// assertEachOnceWith checks every staged key was attempted exactly once, |
| +// with ctx, and that no attempt was still running when the drop returned. |
| +func assertEachOnceWith(t *testing.T, s *countingDeleteStore, staged map[string]lease.MirrorObject, ctx context.Context) { |
| + t.Helper() |
| + s.cmu.Lock() |
| + defer s.cmu.Unlock() |
| + if s.inFlight != 0 || s.finished != len(staged) { |
| + t.Fatalf("at return: %d in flight, %d of %d attempts finished", s.inFlight, s.finished, len(staged)) |
| + } |
| + if len(s.calls) != len(staged) { |
| + t.Fatalf("attempted %d distinct keys, want %d", len(s.calls), len(staged)) |
| + } |
| + for k := range staged { |
| + if s.calls[k] != 1 { |
| + t.Fatalf("key %s attempted %d times, want 1", k, s.calls[k]) |
| + } |
| + if got := s.ctxs[k]; len(got) != 1 || got[0] != ctx { |
| + t.Fatalf("key %s was not deleted with the caller's ctx", k) |
| + } |
| + } |
| +} |
| + |
| +// T1 (docs/superpowers/notes/offline-move-pause-trim.md, T1a): the drop |
| +// deletes exactly the staged keys, each once, a full batch at a time, and |
| +// does not return while any delete is still in flight (the wake spawns |
| +// only after it). |
| +func TestDropStagedReplicaDeletesEveryStagedKeyInParallel(t *testing.T) { |
| + b := testExecBackend(t) |
| + const n = 300 |
| + s := newCountingDeleteStore().withBarrier(n) |
| + b.Mirror = s |
| + host := "moved.example.com" |
| + staged := stageKeys(b, s, host, n) |
| + own := b.Cfg.hibernatePrefix(host) + "/generations/0000/00000000.ltx" |
| + s.put(b.Cfg.Bucket, own, "own") |
| + ctx := context.Background() |
| + |
| + done := dropInBackground(b, ctx, staged) |
| + awaitStarted(t, s, lease.DefaultMirrorWorkers) // a full batch held at once |
| + assertNotReturned(t, done) |
| + close(s.release) |
| + awaitDone(t, done) |
| + |
| + assertEachOnceWith(t, s, staged, ctx) |
| + s.cmu.Lock() |
| + defer s.cmu.Unlock() |
| + if s.maxSeen > lease.DefaultMirrorWorkers { |
| + t.Fatalf("max in flight %d exceeds the bound %d", s.maxSeen, lease.DefaultMirrorWorkers) |
| + } |
| + for k := range staged { |
| + if _, ok := s.buckets[b.Cfg.Bucket][k]; ok { |
| + t.Fatalf("staged key %s survived the drop", k) |
| + } |
| + } |
| + if _, ok := s.buckets[b.Cfg.Bucket][own]; !ok { |
| + t.Fatal("the drop deleted a key it was not handed") |
| + } |
| +} |
| + |
| +// The bound itself: the mirror round's rule, never more workers than keys. |
| +func TestDropWorkers(t *testing.T) { |
| + plain := newCountingDeleteStore() |
| + for _, c := range []struct { |
| + m lease.MirrorStore |
| + n int |
| + want int |
| + }{ |
| + {plain, 300, lease.DefaultMirrorWorkers}, |
| + {plain, 3, 3}, |
| + {plain, 0, 0}, |
| + {&workersStore{plain, 1}, 300, 1}, |
| + {&workersStore{plain, 3}, 300, 3}, |
| + {&workersStore{plain, 0}, 300, 1}, |
| + {&workersStore{plain, -2}, 300, 1}, |
| + } { |
| + if got := dropWorkers(c.m, c.n); got != c.want { |
| + t.Errorf("dropWorkers(%T, %d) = %d, want %d", c.m, c.n, got, c.want) |
| + } |
| + } |
| +} |
| + |
| +// A store that sets its own concurrency gets it, as a mirror round does: |
| +// one is strictly serial, as every drop was before T1. |
| +func TestDropStagedReplicaHonoursTheStoresConcurrency(t *testing.T) { |
| + for _, workers := range []int{1, 3} { |
| + b := testExecBackend(t) |
| + const n = 40 |
| + s := &workersStore{countingDeleteStore: newCountingDeleteStore().withBarrier(n), workers: workers} |
| + b.Mirror = s |
| + staged := stageKeys(b, s.countingDeleteStore, "moved.example.com", n) |
| + ctx := context.Background() |
| + |
| + done := dropInBackground(b, ctx, staged) |
| + awaitStarted(t, s.countingDeleteStore, workers) |
| + assertNotReturned(t, done) |
| + close(s.release) |
| + awaitDone(t, done) |
| + |
| + assertEachOnceWith(t, s.countingDeleteStore, staged, ctx) |
| + if s.maxSeen > workers { |
| + t.Fatalf("workers=%d: max in flight %d", workers, s.maxSeen) |
| + } |
| + } |
| +} |
| + |
| +// The drop stays best-effort, exactly as the serial loop was: a failed |
| +// delete neither stops nor cancels the others, is tried once, and leaves |
| +// only its own key behind. |
| +func TestDropStagedReplicaFailureIsBestEffort(t *testing.T) { |
| + b := testExecBackend(t) |
| + s := newCountingDeleteStore() |
| + b.Mirror = s |
| + staged := stageKeys(b, s, "moved.example.com", 100) |
| + var bad string |
| + for k := range staged { |
| + bad = k |
| + break |
| + } |
| + s.fail[bad] = true |
| + ctx := context.Background() |
| + |
| + b.dropStagedReplica(ctx, staged) |
| + |
| + assertEachOnceWith(t, s, staged, ctx) |
| + s.cmu.Lock() |
| + defer s.cmu.Unlock() |
| + for k := range staged { |
| + _, left := s.buckets[b.Cfg.Bucket][k] |
| + if k == bad && !left { |
| + t.Fatal("the failing key was removed") |
| + } |
| + if k != bad && left { |
| + t.Fatalf("key %s was not deleted after another key's delete failed", k) |
| + } |
| + } |
| +} |
| + |
| +// An already-ended ctx is handed to every delete, as the serial loop did: |
| +// each key is attempted once with it, and the drop still returns. |
| +func TestDropStagedReplicaWithAnEndedContext(t *testing.T) { |
| + b := testExecBackend(t) |
| + s := newCountingDeleteStore() |
| + s.respectCtx = true |
| + b.Mirror = s |
| + staged := stageKeys(b, s, "moved.example.com", 50) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + cancel() |
| + |
| + b.dropStagedReplica(ctx, staged) |
| + |
| + assertEachOnceWith(t, s, staged, ctx) |
| + s.cmu.Lock() |
| + defer s.cmu.Unlock() |
| + for k := range staged { |
| + if _, ok := s.buckets[b.Cfg.Bucket][k]; !ok { |
| + t.Fatalf("key %s deleted through an ended ctx", k) |
| + } |
| + } |
| +} |
| + |
| +// A ctx that ends while deletes are in flight: the drop does not return |
| +// until the held deletes have, and every remaining key is still attempted |
| +// once with the caller's ctx, as the serial loop would have. |
| +func TestDropStagedReplicaCancelledDuringTheDeletes(t *testing.T) { |
| + b := testExecBackend(t) |
| + const n = 60 |
| + s := newCountingDeleteStore().withBarrier(n) |
| + s.respectCtx = true |
| + b.Mirror = s |
| + staged := stageKeys(b, s, "moved.example.com", n) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + |
| + done := dropInBackground(b, ctx, staged) |
| + awaitStarted(t, s, lease.DefaultMirrorWorkers) |
| + cancel() |
| + assertNotReturned(t, done) |
| + close(s.release) |
| + awaitDone(t, done) |
| + |
| + assertEachOnceWith(t, s, staged, ctx) |
| +} |
diff --git a/internal/console/apidbforward.go b/internal/console/apidbforward.go| index 3b6a66777..2d4d9ccc8 100644 |
| --- a/internal/console/apidbforward.go |
| +++ b/internal/console/apidbforward.go |
| @@ -25,7 +25,6 @@ import ( |
| "github.com/carlosframework/platform/internal/dbdoor" |
| "github.com/carlosframework/platform/internal/dbquery" |
| "github.com/carlosframework/platform/internal/dbreads" |
| - "github.com/carlosframework/platform/internal/hostclaim" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| @@ -412,7 +411,7 @@ func (s *Server) admitDBRead(w http.ResponseWriter, r *http.Request) (dbReadAdmi |
| if err != nil { |
| return fail("mint id", err) |
| } |
| - inc, err := hostclaim.Incarnation(acct.Sqid, app, host, rec.CreatedAt) |
| + inc, err := provision.Incarnation(acct.Sqid, app, host, rec.CreatedAt) |
| if err != nil { |
| return fail("incarnation", err) |
| } |
diff --git a/internal/console/apiinstancemove.go b/internal/console/apiinstancemove.go| index 2ac1ca6b4..95fda4da5 100644 |
| --- a/internal/console/apiinstancemove.go |
| +++ b/internal/console/apiinstancemove.go |
| @@ -8,6 +8,7 @@ import ( |
| "errors" |
| "fmt" |
| "github.com/carlosframework/platform/internal/park" |
| + "github.com/carlosframework/platform/internal/regionname" |
| "log" |
| "net/http" |
| "os" |
| @@ -316,7 +317,7 @@ func (s *Server) homeRegionIn(region string) string { |
| // home named nothing is the home. claimMoveRosterPlaces reads roster |
| // regions through it too, so the door and the API translate home one way. |
| func homePlacementCode(home, region string) string { |
| - return park.HomePlacementCode(home, region) |
| + return regionname.HomePlacementCode(home, region) |
| } |
| func (s *Server) homeRegionOut(region string) string { |
diff --git a/internal/console/apiinstancemove_offline.go b/internal/console/apiinstancemove_offline.go| index 103ac3927..1739c1776 100644 |
| --- a/internal/console/apiinstancemove_offline.go |
| +++ b/internal/console/apiinstancemove_offline.go |
| @@ -18,7 +18,6 @@ import ( |
| "github.com/carlosframework/platform/internal/domains" |
| "github.com/carlosframework/platform/internal/hostclaim" |
| - "github.com/carlosframework/platform/internal/hostops" |
| "github.com/carlosframework/platform/internal/moves" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/release" |
| @@ -438,6 +437,10 @@ func (s *Server) offlineClaimEvidence(ctx context.Context, d offlineDoor) *offli |
| if d.rec.Acquisition != "" { |
| return has |
| } |
| + // The claim object is still read through hostclaim: an object that is |
| + // present but does not decode and validate as a claim is a 502, and |
| + // only the claim schema can say which it is (claims cleanup R1 keeps |
| + // this one read where it was). |
| obs, err := hostclaim.Read(ctx, s.cfg.Releases, d.host) |
| if err != nil { |
| log.Printf("console: offline move %s: claim read: %v", d.host, err) |
| @@ -452,9 +455,9 @@ func (s *Server) offlineClaimEvidence(ctx context.Context, d offlineDoor) *offli |
| log.Printf("console: offline move %s: domains claim read: %v", d.host, err) |
| return unreadable |
| } |
| - key, err := hostops.AdmissionKey(d.acct.Sqid, d.app) |
| - if err != nil { |
| - log.Printf("console: offline move %s: admission key: %v", d.host, err) |
| + key, ok := offlineAdmissionKey(d.acct.Sqid, d.app) |
| + if !ok { |
| + log.Printf("console: offline move %s: admission key: invalid account or app", d.host) |
| return unreadable |
| } |
| if _, _, err := s.cfg.Releases.Get(ctx, key); err == nil { |
| @@ -465,9 +468,9 @@ func (s *Server) offlineClaimEvidence(ctx context.Context, d offlineDoor) *offli |
| } |
| // A plan at done is allowed; one that has begun, or that cannot be |
| // verified, is not. |
| - switch err := hostops.CheckCreateFreeze(ctx, s.cfg.Releases, s.cfg.ReleasePub); { |
| + switch err := offlineBackfillFreeze(ctx, s.cfg.Releases, s.cfg.ReleasePub); { |
| case err == nil: |
| - case errors.Is(err, hostops.ErrPending), errors.Is(err, hostops.ErrIdentity): |
| + case errors.Is(err, errOfflineBackfillBegun): |
| return &offlineRefusal{status: http.StatusConflict, msg: "offline moves are not available while host claims or Phase 1 moves are on"} |
| default: |
| log.Printf("console: offline move %s: backfill plan read: %v", d.host, err) |
diff --git a/internal/console/apiinstancemove_offline_absence.go b/internal/console/apiinstancemove_offline_absence.go| new file mode 100644 |
| index 000000000..1338bf80a |
| --- /dev/null |
| +++ b/internal/console/apiinstancemove_offline_absence.go |
| @@ -0,0 +1,74 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "crypto/ed25519" |
| + "errors" |
| + "os" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/controlname" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// The offline move door's admission and backfill checks (MV-O20, MV-O29), |
| +// read here and not through hostops since claims cleanup R1: host claims |
| +// are off everywhere and hostops is going, but a deployment that ever wrote |
| +// one of these objects must still be refused. Each key is hostops' own |
| +// (TestOfflineAbsenceKeysAreTheClaimKeys). The claim object itself is still |
| +// read through hostclaim (offlineClaimEvidence). |
| + |
| +// offlineBackfillKey is the host-claim backfill plan (hostops.BackfillKey). |
| +const offlineBackfillKey = "control/hosts-backfill.json" |
| + |
| +// offlineAdmissionKey is an app's claim admission (hostops.AdmissionKey); |
| +// false for an account or app that is not well formed. |
| +func offlineAdmissionKey(account, app string) (string, bool) { |
| + if !controlname.ValidAccount(account) || !controlname.ValidApp(app) { |
| + return "", false |
| + } |
| + return "apps/" + account + "/" + app + "/admission.json", true |
| +} |
| + |
| +// offlineBackfillPlan and offlineBackfillHost are hostops.BackfillPlan and |
| +// hostops.BackfillHost field for field: the plan is a signed root envelope |
| +// whose payload must re-encode byte for byte, so the shapes cannot differ |
| +// (TestOfflineBackfillPlanReadsTheClaimPlan). |
| +type offlineBackfillHost struct { |
| + Key string `json:"key"` |
| + ETag string `json:"etag"` |
| + Acquisition string `json:"acq"` |
| + Region string `json:"region"` |
| + Box string `json:"box"` |
| +} |
| +type offlineBackfillPlan struct { |
| + V int `json:"v"` |
| + ID string `json:"id"` |
| + Phase string `json:"phase"` |
| + DirectoryRevision uint64 `json:"directory_revision"` |
| + CreatedAt time.Time `json:"created_at"` |
| + Reports map[string]string `json:"reports"` |
| + Hosts map[string]offlineBackfillHost `json:"hosts"` |
| +} |
| + |
| +// errOfflineBackfillBegun is a backfill plan that has begun, or that does |
| +// not verify under the release key (hostops.ErrPending, hostops.ErrIdentity). |
| +var errOfflineBackfillBegun = errors.New("console: the host-claim backfill has begun") |
| + |
| +// offlineBackfillFreeze is hostops.CheckCreateFreeze: nil with no plan or a |
| +// verified plan at done, errOfflineBackfillBegun for any other plan, and the |
| +// read's own error when the plan cannot be read. |
| +func offlineBackfillFreeze(ctx context.Context, s release.Store, pub ed25519.PublicKey) error { |
| + raw, _, err := s.Get(ctx, offlineBackfillKey) |
| + if errors.Is(err, os.ErrNotExist) { |
| + return nil |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + var plan offlineBackfillPlan |
| + if release.VerifyRootEnvelope(pub, raw, &plan) != nil || plan.V != 1 || plan.ID == "" || plan.Phase != "done" { |
| + return errOfflineBackfillBegun |
| + } |
| + return nil |
| +} |
diff --git a/internal/console/apiinstancemove_offline_absence_test.go b/internal/console/apiinstancemove_offline_absence_test.go| new file mode 100644 |
| index 000000000..a45536537 |
| --- /dev/null |
| +++ b/internal/console/apiinstancemove_offline_absence_test.go |
| @@ -0,0 +1,154 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + "reflect" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/hostclaim" |
| + "github.com/carlosframework/platform/internal/hostops" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// The console-local keys are the claim packages' keys, for well-formed and |
| +// malformed inputs alike. The hostclaim and hostops halves go when those |
| +// packages are deleted; the literals stay. |
| +func TestOfflineAbsenceKeysAreTheClaimKeys(t *testing.T) { |
| + for _, want := range []string{"control/hosts-backfill.json", hostops.BackfillKey} { |
| + if offlineBackfillKey != want { |
| + t.Fatalf("backfill key = %q, want %q", offlineBackfillKey, want) |
| + } |
| + } |
| + for _, c := range []struct{ acct, app string }{{"bab", "shop"}, {"BAB", "shop"}, {"bab", ""}, {"", "shop"}, {"bab", "../x"}} { |
| + got, ok := offlineAdmissionKey(c.acct, c.app) |
| + want, err := hostops.AdmissionKey(c.acct, c.app) |
| + if ok != (err == nil) || got != want { |
| + t.Errorf("admission key %q/%q = %q %v; hostops.AdmissionKey = %q %v", c.acct, c.app, got, ok, want, err) |
| + } |
| + if ok && got != "apps/"+c.acct+"/"+c.app+"/admission.json" { |
| + t.Errorf("admission key %q/%q = %q", c.acct, c.app, got) |
| + } |
| + } |
| +} |
| + |
| +// The local plan type is hostops.BackfillPlan field for field, and the |
| +// local freeze check classifies every plan as hostops.CheckCreateFreeze |
| +// does: nil, begun (ErrPending or ErrIdentity), or the read's own error. |
| +func TestOfflineBackfillPlanReadsTheClaimPlan(t *testing.T) { |
| + sameShape(t, reflect.TypeOf(offlineBackfillPlan{}), reflect.TypeOf(hostops.BackfillPlan{})) |
| + fx, _ := instanceFixture(t, "code-offline-backfill") |
| + signed := func(p hostops.BackfillPlan) []byte { |
| + t.Helper() |
| + raw, err := release.SignRootEnvelope(release.RootSigner(fx.priv), p) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return raw |
| + } |
| + full := hostops.BackfillPlan{V: 1, ID: "plan-1", Phase: "done", DirectoryRevision: 7, CreatedAt: time.Date(2026, 10, 1, 12, 0, 0, 5, time.UTC), |
| + Reports: map[string]string{"ie-box": "sha"}, Hosts: map[string]hostops.BackfillHost{offlineHost: {Key: "k", ETag: "e", Acquisition: "a", Region: "ie", Box: "ie-box"}}} |
| + variant := func(f func(*hostops.BackfillPlan)) []byte { p := full; f(&p); return signed(p) } |
| + cases := map[string][]byte{ |
| + "done, full": signed(full), |
| + "done, minimal": signed(hostops.BackfillPlan{V: 1, ID: "plan-1", Phase: "done"}), |
| + "collecting": variant(func(p *hostops.BackfillPlan) { p.Phase = "collecting" }), |
| + "adopting": variant(func(p *hostops.BackfillPlan) { p.Phase = "adopting" }), |
| + "version 2": variant(func(p *hostops.BackfillPlan) { p.V = 2 }), |
| + "no id": variant(func(p *hostops.BackfillPlan) { p.ID = "" }), |
| + "not an envelope": []byte("not an envelope"), |
| + } |
| + ctx := context.Background() |
| + for name, raw := range cases { |
| + offlinePut(t, fx.rel, offlineBackfillKey, raw) |
| + local := offlineBackfillFreeze(ctx, fx.rel, fx.srv.cfg.ReleasePub) |
| + claim := hostops.CheckCreateFreeze(ctx, fx.rel, fx.srv.cfg.ReleasePub) |
| + begun := errors.Is(claim, hostops.ErrPending) || errors.Is(claim, hostops.ErrIdentity) |
| + if (local == nil) != (claim == nil) || errors.Is(local, errOfflineBackfillBegun) != begun { |
| + t.Errorf("%s: local %v, hostops %v", name, local, claim) |
| + } |
| + } |
| + if err := fx.rel.Delete(ctx, offlineBackfillKey); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := offlineBackfillFreeze(ctx, fx.rel, fx.srv.cfg.ReleasePub); err != nil { |
| + t.Fatalf("no plan = %v", err) |
| + } |
| + boom := errors.New("boom") |
| + if err := offlineBackfillFreeze(ctx, offlineFaultStore{fx.rel, offlineBackfillKey, boom}, fx.srv.cfg.ReleasePub); !errors.Is(err, boom) || errors.Is(err, errOfflineBackfillBegun) { |
| + t.Fatalf("unreadable plan = %v", err) |
| + } |
| +} |
| + |
| +func sameShape(t *testing.T, a, b reflect.Type) { |
| + t.Helper() |
| + if a.Kind() != b.Kind() { |
| + t.Fatalf("%v is a %v, %v a %v", a, a.Kind(), b, b.Kind()) |
| + } |
| + switch a.Kind() { |
| + case reflect.Struct: |
| + if a.NumField() != b.NumField() { |
| + t.Fatalf("%v has %d fields, %v %d", a, a.NumField(), b, b.NumField()) |
| + } |
| + for i := 0; i < a.NumField(); i++ { |
| + fa, fb := a.Field(i), b.Field(i) |
| + if fa.Name != fb.Name || fa.Tag != fb.Tag { |
| + t.Fatalf("%v field %d = %s %q, %v's = %s %q", a, i, fa.Name, fa.Tag, b, fb.Name, fb.Tag) |
| + } |
| + sameShape(t, fa.Type, fb.Type) |
| + } |
| + case reflect.Map: |
| + sameShape(t, a.Key(), b.Key()) |
| + sameShape(t, a.Elem(), b.Elem()) |
| + default: |
| + if a != b { |
| + t.Fatalf("%v != %v", a, b) |
| + } |
| + } |
| +} |
| + |
| +// offlineFaultStore fails every Get of one key. |
| +type offlineFaultStore struct { |
| + release.Store |
| + key string |
| + err error |
| +} |
| + |
| +func (s offlineFaultStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + if key == s.key { |
| + return nil, "", s.err |
| + } |
| + return s.Store.Get(ctx, key) |
| +} |
| + |
| +// A claim object that is present but does not decode and validate as a |
| +// claim is a 502, as it was before claims cleanup R1 (a valid one is a 409: |
| +// TestOfflineStartRefusals); any failed read of the three objects is a 502 |
| +// and never an absence. Nothing is written either way. |
| +func TestOfflineDoorAbsenceChecksRefuseAndFail(t *testing.T) { |
| + const body = `{"region":"uk"}` |
| + claimKey, err := hostclaim.Key(offlineHost) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + w := newOfflineWorld(t, oneEach...) |
| + for _, raw := range []string{"not json", `{}`, `{"v":1,"host":"other.example.com"}`} { |
| + offlinePut(t, w.fx.rel, claimKey, []byte(raw)) |
| + w.refused(http.MethodPost, "", body, http.StatusBadGateway, "could not read the host claim") |
| + w.refused(http.MethodPost, "/stage", body, http.StatusBadGateway, "could not read the host claim") |
| + } |
| + if err := w.fx.rel.Delete(context.Background(), claimKey); err != nil { |
| + t.Fatal(err) |
| + } |
| + admission, _ := offlineAdmissionKey("bab", "shop") |
| + real := w.fx.srv.cfg.Releases |
| + for _, key := range []string{claimKey, admission, offlineBackfillKey} { |
| + w.fx.srv.cfg.Releases = offlineFaultStore{real, key, errors.New("boom")} |
| + w.refused(http.MethodPost, "", body, http.StatusBadGateway, "could not read the host claim") |
| + w.refused(http.MethodPost, "/stage", body, http.StatusBadGateway, "could not read the host claim") |
| + } |
| + w.fx.srv.cfg.Releases = real |
| + w.start() |
| +} |
diff --git a/internal/console/apiruns.go b/internal/console/apiruns.go| index b60d6a9a7..b9d61437c 100644 |
| --- a/internal/console/apiruns.go |
| +++ b/internal/console/apiruns.go |
| @@ -15,7 +15,6 @@ import ( |
| "os" |
| "time" |
| - "github.com/carlosframework/platform/internal/hostclaim" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| @@ -534,7 +533,7 @@ func (s *Server) handleAPIRunCreate(w http.ResponseWriter, r *http.Request) { |
| jsonErrorCode(w, http.StatusBadGateway, runCodeRecordFailed, runRecordFailedMsg) |
| return |
| } |
| - inc, err := hostclaim.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt) |
| + inc, err := provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt) |
| if err != nil { |
| jsonErrorCode(w, http.StatusBadGateway, runCodeRecordFailed, runRecordFailedMsg) |
| return |
diff --git a/internal/dbreads/agent.go b/internal/dbreads/agent.go| index 78ac62fee..6d7abe273 100644 |
| --- a/internal/dbreads/agent.go |
| +++ b/internal/dbreads/agent.go |
| @@ -17,7 +17,6 @@ import ( |
| mrand "math/rand/v2" |
| "github.com/carlosframework/platform/internal/dbdoor" |
| - "github.com/carlosframework/platform/internal/hostclaim" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| @@ -215,7 +214,7 @@ func (a *Agent) check(ctx context.Context, req Request) (provision.Record, strin |
| if err != nil { |
| return provision.Record{}, "", err |
| } |
| - inc, ierr := hostclaim.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt) |
| + inc, ierr := provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt) |
| _, fleet := registry.FleetPlacement(rec.Region) |
| switch { |
| case ierr != nil, inc != req.Incarnation, rec.Account != req.Account, rec.App != req.App, |
diff --git a/internal/dbreads/fixture_test.go b/internal/dbreads/fixture_test.go| index c4a481a30..b6388798e 100644 |
| --- a/internal/dbreads/fixture_test.go |
| +++ b/internal/dbreads/fixture_test.go |
| @@ -22,7 +22,6 @@ import ( |
| "github.com/carlosframework/platform/internal/dbdoor" |
| "github.com/carlosframework/platform/internal/dbdoor/dbdoortest" |
| - "github.com/carlosframework/platform/internal/hostclaim" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/release" |
| ) |
| @@ -182,7 +181,7 @@ func (fx *fixture) record() provision.Record { |
| func (fx *fixture) request(sqlText, at string) Request { |
| fx.t.Helper() |
| rec := fx.record() |
| - inc, err := hostclaim.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt) |
| + inc, err := provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt) |
| if err != nil { |
| fx.t.Fatal(err) |
| } |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index 42dbceabd..3245308c3 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -188,7 +188,6 @@ import ( |
| "github.com/carlosframework/platform/internal/edge" |
| "github.com/carlosframework/platform/internal/edgesfile" |
| "github.com/carlosframework/platform/internal/fleetapi" |
| - "github.com/carlosframework/platform/internal/hostbox" |
| "github.com/carlosframework/platform/internal/hostwrite" |
| "github.com/carlosframework/platform/internal/instancectl" |
| "github.com/carlosframework/platform/internal/instancefs" |
| @@ -4960,7 +4959,7 @@ func runAdoptUnderRootRelease(args []string, buildClaims ClaimFactory, ensureUni |
| } |
| } |
| defer func() { |
| - ctx, cancel := context.WithTimeout(context.Background(), hostbox.RequestLimit) |
| + ctx, cancel := context.WithTimeout(context.Background(), claimsShutdownLimit) |
| defer cancel() |
| if err := claims.close(ctx); err != nil { |
| log.Printf("adopt: host claims shutdown: %v", err) |
| @@ -5268,3 +5267,9 @@ func runAdoptUnderRootRelease(args []string, buildClaims ClaimFactory, ensureUni |
| } |
| return passErr |
| } |
| + |
| +// claimsShutdownLimit bounds the adopt pass's host-claim shutdown. It is |
| +// hostbox.RequestLimit's value (two minutes), kept here since claims |
| +// cleanup R1 so the agent no longer imports hostbox for it |
| +// (TestClaimsShutdownLimitGolden). |
| +const claimsShutdownLimit = 120 * time.Second |
diff --git a/internal/host/boxreference.go b/internal/host/boxreference.go| index 47bbf843f..7dce6ce52 100644 |
| --- a/internal/host/boxreference.go |
| +++ b/internal/host/boxreference.go |
| @@ -2,7 +2,9 @@ package host |
| import ( |
| "context" |
| + "crypto/sha256" |
| "encoding/base64" |
| + "encoding/hex" |
| "encoding/json" |
| "errors" |
| "fmt" |
| @@ -11,7 +13,6 @@ import ( |
| "sync" |
| "time" |
| - "github.com/carlosframework/platform/internal/hostactors" |
| "github.com/carlosframework/platform/internal/hostenv" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| @@ -19,7 +20,7 @@ import ( |
| ) |
| // A box its region's group launched is referenced by its group reference |
| -// (census ruling region-ha-2b): hostactors.GroupBoxReference of its account |
| +// (census ruling region-ha-2b): groupReferenceOf its account |
| // and instance, "g-" and 20 hex digits. Its host.env says so: |
| // carlos system host-env write adds CARLOS_BOX_REFERENCE=group. Status |
| // labels come from 1,600 values and identity records are never deleted, so |
| @@ -83,10 +84,22 @@ func resolveGroupBoxReference() (string, error) { |
| if err != nil { |
| return "", err |
| } |
| - groupRef.ref = hostactors.GroupBoxReference(account, instance) |
| + groupRef.ref = groupReferenceOf(account, instance) |
| return groupRef.ref, nil |
| } |
| +// groupReferenceOf is the reference of a box its region's group launched: |
| +// "g-" and the first 20 hex digits of |
| +// sha256("carlos-box-ref-v1|" + account + "|" + instance). It is |
| +// hostactors.GroupBoxReference, which the console's claim activation |
| +// derives again from the instance it proved; it moved here in claims |
| +// cleanup R1 so the agent no longer imports hostactors, and |
| +// TestGroupBoxReferenceGolden holds the two to one vector. |
| +func groupReferenceOf(account, instance string) string { |
| + sum := sha256.Sum256([]byte("carlos-box-ref-v1|" + account + "|" + instance)) |
| + return "g-" + hex.EncodeToString(sum[:])[:20] |
| +} |
| + |
| // errNoGroupReference is a tick of a group box whose reference has not |
| // resolved: it publishes nothing. |
| var errNoGroupReference = errors.New("this group box's reference could not be read, so it publishes no status report this tick") |
diff --git a/internal/host/claimsoff_golden_test.go b/internal/host/claimsoff_golden_test.go| new file mode 100644 |
| index 000000000..e7c5a3a50 |
| --- /dev/null |
| +++ b/internal/host/claimsoff_golden_test.go |
| @@ -0,0 +1,34 @@ |
| +package host |
| + |
| +import ( |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/hostactors" |
| + "github.com/carlosframework/platform/internal/hostbox" |
| +) |
| + |
| +// Golden vectors for the two claim-package values the claims-off agent |
| +// uses (claims cleanup R1). The group reference was derived independently: |
| +// "g-" + the first 20 hex digits of |
| +// sha256("carlos-box-ref-v1|123456789012|i-0a61f580df1acfa65"). |
| +func TestGroupBoxReferenceGolden(t *testing.T) { |
| + impls := map[string]func(string, string) string{ |
| + "groupReferenceOf": groupReferenceOf, |
| + // The claim activation's twin, until claims cleanup deletes hostactors. |
| + "hostactors.GroupBoxReference": hostactors.GroupBoxReference, |
| + } |
| + for name, f := range impls { |
| + if got := f("123456789012", "i-0a61f580df1acfa65"); got != "g-c48ba25b2d17574d23d9" { |
| + t.Errorf("%s = %q, want g-c48ba25b2d17574d23d9", name, got) |
| + } |
| + } |
| +} |
| + |
| +func TestClaimsShutdownLimitGolden(t *testing.T) { |
| + for name, d := range map[string]time.Duration{"claimsShutdownLimit": claimsShutdownLimit, "hostbox.RequestLimit": hostbox.RequestLimit} { |
| + if d != 120*time.Second { |
| + t.Errorf("%s = %v, want 2m0s", name, d) |
| + } |
| + } |
| +} |
diff --git a/internal/host/movesoffline.go b/internal/host/movesoffline.go| index 3052233d5..0859e78b7 100644 |
| --- a/internal/host/movesoffline.go |
| +++ b/internal/host/movesoffline.go |
| @@ -22,8 +22,8 @@ import ( |
| "github.com/carlosframework/platform/internal/layout" |
| "github.com/carlosframework/platform/internal/lease" |
| "github.com/carlosframework/platform/internal/moves" |
| - "github.com/carlosframework/platform/internal/park" |
| "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/regionname" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| ) |
| @@ -87,7 +87,7 @@ func offlineFenceOwner(id string) string { return "offline:" + id } |
| // offline-landed. offline-open is the target's to release (Task 5). |
| // |
| // Placements are compared as movesNamesBox compares them, by |
| -// park.PlacementMatches under the verified home binding, so the home's "" |
| +// regionname.PlacementMatches under the verified home binding, so the home's "" |
| // and its roster name are one. |
| func offlineHold(box moveCfg) func(rec provision.Record) (status, op string, ok bool) { |
| home, here := box.ParkHomeRegion, box.parkRegion() |
| @@ -98,11 +98,11 @@ func offlineHold(box moveCfg) func(rec provision.Record) (status, op string, ok |
| } |
| switch m.State { |
| case provision.OfflineStopping, provision.OfflineSealing, provision.OfflineSealed: |
| - if park.PlacementMatches(home, m.From, here) { |
| + if regionname.PlacementMatches(home, m.From, here) { |
| return "moving", m.ID, true |
| } |
| case provision.OfflineLanding, provision.OfflineLanded: |
| - if rec.Region == m.To && park.PlacementMatches(home, m.To, here) { |
| + if rec.Region == m.To && regionname.PlacementMatches(home, m.To, here) { |
| return "landing", m.ID, true |
| } |
| } |
| @@ -222,10 +222,10 @@ func (v *offlineView) keep(host string) bool { |
| if !ok || v.region == "" { |
| return false |
| } |
| - if park.PlacementMatches(v.home, m.To, v.region) { |
| + if regionname.PlacementMatches(v.home, m.To, v.region) { |
| return true |
| } |
| - if park.PlacementMatches(v.home, m.From, v.region) { |
| + if regionname.PlacementMatches(v.home, m.From, v.region) { |
| return m.State != provision.OfflineFinishing |
| } |
| return false |
| @@ -250,7 +250,7 @@ func (v *offlineView) elsewhere(host string) bool { |
| case provision.OfflineLanding, provision.OfflineLanded, provision.OfflineOpen, provision.OfflineFinishing: |
| region = m.To |
| } |
| - return !park.PlacementMatches(v.home, region, v.region) |
| + return !regionname.PlacementMatches(v.home, region, v.region) |
| } |
| // refreshOfflineView reads the record list once, outside a moves pass: at |
| @@ -403,7 +403,7 @@ func fenceAsWith(svc *activator.Service) func(ctx context.Context, host string, |
| // systemd slice under cgroupRoot (the cgroup v2 mount): every role and |
| // generation unit of the host runs in it. |
| func hostSliceCgroup(cgroupRoot, host string) string { |
| - return filepath.Join(cgroupRoot, filepath.FromSlash(path.Dir(instancectl.ClaimUnitControlGroup(host)))) |
| + return filepath.Join(cgroupRoot, filepath.FromSlash(path.Dir(instancectl.RunUnitControlGroup(host)))) |
| } |
| // offlineRound is the moves pass's round for a record with an offline move, |
| @@ -420,8 +420,8 @@ func (w *movesWorker) offlineRound(ctx context.Context, s release.Store, rec pro |
| return nil |
| } |
| here := cfg.parkRegion() |
| - source := here != "" && park.PlacementMatches(cfg.ParkHomeRegion, m.From, here) |
| - target := here != "" && park.PlacementMatches(cfg.ParkHomeRegion, m.To, here) |
| + source := here != "" && regionname.PlacementMatches(cfg.ParkHomeRegion, m.From, here) |
| + target := here != "" && regionname.PlacementMatches(cfg.ParkHomeRegion, m.To, here) |
| sealer := cfg.Box != "" && cfg.Box == m.Sealer |
| if !cfg.OfflineCapable { |
| if source || target || sealer { |
| @@ -498,7 +498,7 @@ func (w *movesWorker) offlineReassert(ctx context.Context, s release.Store) int |
| } |
| here := cfg.parkRegion() |
| roles := func(m *provision.MoveState) (bool, bool) { |
| - source := here != "" && park.PlacementMatches(cfg.ParkHomeRegion, m.From, here) |
| + source := here != "" && regionname.PlacementMatches(cfg.ParkHomeRegion, m.From, here) |
| return offlineReassertRoles(m, source, m.Sealer == cfg.Box) |
| } |
| var hosts []string |
diff --git a/internal/host/movesoffline_seal.go b/internal/host/movesoffline_seal.go| index f72f38d61..f98559c24 100644 |
| --- a/internal/host/movesoffline_seal.go |
| +++ b/internal/host/movesoffline_seal.go |
| @@ -26,8 +26,8 @@ import ( |
| "github.com/carlosframework/platform/internal/lease" |
| "github.com/carlosframework/platform/internal/moves" |
| "github.com/carlosframework/platform/internal/moves/archive" |
| - "github.com/carlosframework/platform/internal/park" |
| "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/regionname" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| ) |
| @@ -214,7 +214,7 @@ func (w *movesWorker) offlineTarget(ctx context.Context, s release.Store, m *pro |
| } |
| sort.Strings(codes) |
| for _, code := range codes { |
| - if park.PlacementMatches(w.cfg.ParkHomeRegion, m.To, park.PlacementRegion(code)) { |
| + if regionname.PlacementMatches(w.cfg.ParkHomeRegion, m.To, regionname.PlacementRegion(code)) { |
| return fleet.targets[code], nil |
| } |
| } |
diff --git a/internal/host/movessources.go b/internal/host/movessources.go| index 3b8a8ed1c..0a4178935 100644 |
| --- a/internal/host/movessources.go |
| +++ b/internal/host/movessources.go |
| @@ -56,6 +56,7 @@ import ( |
| "github.com/carlosframework/platform/internal/moves" |
| "github.com/carlosframework/platform/internal/park" |
| "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/regionname" |
| "github.com/carlosframework/platform/internal/release" |
| ) |
| @@ -73,7 +74,7 @@ const movesNoLiveRegion = "@none" |
| // for or queues in its own region, and the region its claim's engine must |
| // have go through it. An invalid code maps to "", which arms nothing and |
| // which every engine entry refuses. |
| -func (c moveCfg) parkRegion() string { return park.PlacementRegion(c.Region) } |
| +func (c moveCfg) parkRegion() string { return regionname.PlacementRegion(c.Region) } |
| // movesBoxRegion refuses a placement that disagrees with the verified roster. |
| // productionRosterRegion maps home only after checking the signed designation. |
diff --git a/internal/host/runexec.go b/internal/host/runexec.go| index 5266f47af..8168142a6 100644 |
| --- a/internal/host/runexec.go |
| +++ b/internal/host/runexec.go |
| @@ -11,7 +11,6 @@ import ( |
| "time" |
| "github.com/carlosframework/platform/internal/activator" |
| - "github.com/carlosframework/platform/internal/hostclaim" |
| "github.com/carlosframework/platform/internal/instancectl" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/registry" |
| @@ -100,7 +99,7 @@ func runResultForLaunch(err error) runs.Result { |
| // recordIncarnation is the incarnation request.json must carry for rec; |
| // "" when it cannot be computed, which matches no request. |
| func recordIncarnation(rec provision.Record) string { |
| - inc, err := hostclaim.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt) |
| + inc, err := provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt) |
| if err != nil { |
| return "" |
| } |
diff --git a/internal/hostclaim/claim.go b/internal/hostclaim/claim.go| index ee4caffcd..e917d2dc5 100644 |
| --- a/internal/hostclaim/claim.go |
| +++ b/internal/hostclaim/claim.go |
| @@ -7,7 +7,6 @@ |
| package hostclaim |
| import ( |
| - "crypto/sha256" |
| "encoding/hex" |
| "errors" |
| "fmt" |
| @@ -15,7 +14,7 @@ import ( |
| "time" |
| "github.com/carlosframework/platform/internal/controlname" |
| - "github.com/carlosframework/platform/internal/maintenanceguard" |
| + "github.com/carlosframework/platform/internal/provision" |
| ) |
| const ( |
| @@ -187,17 +186,15 @@ func Key(host string) (string, error) { |
| return "control/hosts/" + host + ".json", nil |
| } |
| -// Incarnation is §2's identity. A record with a zero CreatedAt (written |
| -// before CreatedAt existed) gets the domain-separated legacy identity. |
| +// Incarnation is §2's identity: provision.Incarnation, which claims-off |
| +// code calls directly, with a malformed legacy identity reported as |
| +// ErrMalformed for the claim code that still calls it here. |
| func Incarnation(account, app, host string, created time.Time) (string, error) { |
| - if created.IsZero() { |
| - if !controlname.ValidAccount(account) || !controlname.ValidApp(app) || !controlname.ValidHostShape(host) { |
| - return "", ErrMalformed |
| - } |
| - sum := sha256.Sum256([]byte("carlos-legacy-incarnation-v1\x00" + account + "\x00" + app + "\x00" + host)) |
| - return hex.EncodeToString(sum[:]), nil |
| + inc, err := provision.Incarnation(account, app, host, created) |
| + if errors.Is(err, provision.ErrMalformedIncarnation) { |
| + return "", ErrMalformed |
| } |
| - return maintenanceguard.RecordIdentity(account, app, host, created) |
| + return inc, err |
| } |
| // sidecarSuffix restates provision.SidecarSuffix (no import: avoids a cycle). |
diff --git a/internal/instancectl/claimunit.go b/internal/instancectl/claimunit.go| index 5d099ab3d..5abb6eba4 100644 |
| --- a/internal/instancectl/claimunit.go |
| +++ b/internal/instancectl/claimunit.go |
| @@ -5,7 +5,6 @@ import ( |
| "errors" |
| "fmt" |
| "os" |
| - "path" |
| "path/filepath" |
| "strconv" |
| "strings" |
| @@ -58,11 +57,9 @@ var ( |
| ErrClaimUnit = errors.New("instance control: the claim unit did not start as requested") |
| ) |
| -// ClaimUnitControlGroup is the host's run unit cgroup, relative to the |
| -// cgroup root. |
| -func ClaimUnitControlGroup(host string) string { |
| - return path.Join(parentSlices, SliceName(host), UnitName(RoleRun, host)) |
| -} |
| +// ClaimUnitControlGroup is RunUnitControlGroup, under the name the claim |
| +// code calls it by. |
| +func ClaimUnitControlGroup(host string) string { return RunUnitControlGroup(host) } |
| func claimTier(n int64) (cgroup.Limit, bool) { |
| switch n { |
diff --git a/internal/instancectl/names.go b/internal/instancectl/names.go| index f2adb04f9..d22c21677 100644 |
| --- a/internal/instancectl/names.go |
| +++ b/internal/instancectl/names.go |
| @@ -15,6 +15,7 @@ package instancectl |
| import ( |
| "errors" |
| "fmt" |
| + "path" |
| "path/filepath" |
| "strconv" |
| "strings" |
| @@ -138,6 +139,15 @@ func SliceName(host string) string { |
| return "carlos-instances-" + Escape(provision.InstanceID(host)) + ".slice" |
| } |
| +// RunUnitControlGroup is the host's run unit cgroup, relative to the |
| +// cgroup root: <parentSlices>/<SliceName>/<UnitName(RoleRun)>. The offline |
| +// move round reads the host's slice from it. It was ClaimUnitControlGroup |
| +// until claims cleanup R1, which keeps that name as a delegate for the |
| +// claim code. |
| +func RunUnitControlGroup(host string) string { |
| + return path.Join(parentSlices, SliceName(host), UnitName(RoleRun, host)) |
| +} |
| + |
| // UnitPrefixGen is the generation template (zero-downtime deploys spec |
| // §7.6): one instance per spawn of a host's run role. The four templates |
| // above stay for every box and binary still running them. |
diff --git a/internal/instancectl/rununit_golden_test.go b/internal/instancectl/rununit_golden_test.go| new file mode 100644 |
| index 000000000..27a3b2fb4 |
| --- /dev/null |
| +++ b/internal/instancectl/rununit_golden_test.go |
| @@ -0,0 +1,14 @@ |
| +package instancectl |
| + |
| +import "testing" |
| + |
| +// The run unit's cgroup, relative to the cgroup root. The offline move |
| +// round finds a host's slice from it (claims cleanup R1 renamed it from |
| +// ClaimUnitControlGroup, which the claim code still calls). |
| +func TestRunUnitControlGroupGolden(t *testing.T) { |
| + host := "alpha.shop.example.com" |
| + const want = "carlos.slice/carlos-instances.slice/carlos-instances-alpha.shop.example.com.slice/carlos-instance@alpha.shop.example.com.service" |
| + if got := RunUnitControlGroup(host); got != want || got != ClaimUnitControlGroup(host) { |
| + t.Fatalf("RunUnitControlGroup = %q, ClaimUnitControlGroup = %q, want %q", got, ClaimUnitControlGroup(host), want) |
| + } |
| +} |
diff --git a/internal/park/region_names.go b/internal/park/region_names.go| index f865694db..739b2cd23 100644 |
| --- a/internal/park/region_names.go |
| +++ b/internal/park/region_names.go |
| @@ -28,9 +28,10 @@ func (e Engine) OwnsRegion(region string) bool { |
| func (v View) sameRegion(a, b string) bool { return SameRegion(v.HomeRegion, a, b) } |
| -// PlacementMatches compares a record code with a nonempty engine identity. |
| +// PlacementMatches compares a record code with a nonempty engine identity |
| +// (regionname.PlacementMatches). |
| func PlacementMatches(home, code, engine string) bool { |
| - return SameRegion(home, PlacementRegion(code), engine) |
| + return regionname.PlacementMatches(home, code, engine) |
| } |
| // BoundHome joins the verified local binding and the admitted operation's |
diff --git a/internal/provision/census_propose_internal_test.go b/internal/provision/census_propose_internal_test.go| index 782e197fa..a6e93a9b8 100644 |
| --- a/internal/provision/census_propose_internal_test.go |
| +++ b/internal/provision/census_propose_internal_test.go |
| @@ -24,6 +24,7 @@ func proposeFixture(t *testing.T) (rootReadScan, rootReadInventory, string) { |
| Entries: []rootReadEntry{legacy.rootReadEntry, auth.rootReadEntry}, |
| Declarations: map[string]string{"internal/a/a.go:Wake": legacy.Digest, "internal/a/b.go:Route": auth.Digest}, |
| Coverage: map[string]string{"internal/a": strings.Repeat("c", 64)}, |
| + Dirs: map[string]bool{".": true, "internal": true, "internal/a": true}, |
| } |
| return got, inv, rootReadLegacySeal(inv) |
| } |
diff --git a/internal/provision/census_propose_test.go b/internal/provision/census_propose_test.go| index 415fa5501..b73e24b55 100644 |
| --- a/internal/provision/census_propose_test.go |
| +++ b/internal/provision/census_propose_test.go |
| @@ -7,9 +7,12 @@ package provision |
| // This file classifies each discrepancy, writes the overlay that closes the |
| // approvable ones (rows, @legacy fingerprints, envelope re-pins, the seal, |
| // the chain manifest line), and the approval card an independent reviewer |
| -// reads to approve it. Changes that need a disposition (a new unit, a removed one, |
| -// the scanner's field list) are decisions: it names them and writes |
| -// nothing. |
| +// reads to approve it. A deletion is an approval too (Paul's ruling 1 on |
| +// #280, 2026-10-25): a unit whose declaration the scan no longer finds, and |
| +// the envelope of a directory that is gone, since a deletion cannot add a |
| +// read. Changes that need a disposition (a new unit, a unit still declared |
| +// that stopped reading, the scanner's field list) are decisions: it names |
| +// them and writes nothing. |
| // |
| // make census-card print the card; writes nothing |
| // make census-propose NAME=<branch> CLAIMS=<file> write the overlay and the card |
| @@ -28,23 +31,26 @@ import ( |
| "testing" |
| ) |
| -// Change classes. The first three are approvals; the rest are decisions. |
| +// Change classes. The first four are approvals; the rest are decisions. |
| const ( |
| censusBody = "body" // digest moved, the same reads (offsets aside) |
| censusSites = "sites" // more or fewer reads of kinds the unit already makes |
| censusEnvelope = "envelope" // a package's source fingerprint moved |
| + censusRemoved = "removed" // a unit's declaration, or an envelope's directory, gone from the tree |
| censusReads = "reads" // a kind of read the unit did not make before |
| censusNew = "new" // an unclassified unit: needs a disposition |
| - censusRemoved = "removed" // a unit or envelope gone: needs a removal row |
| + censusQuiet = "quiet" // still declared and reads nothing now, or a directory still there with no scanned source |
| censusOther = "other" // a census discrepancy no change above explains |
| ) |
| // censusDecision: a new kind of read can make a unit's disposition wrong |
| // (a registry reader that starts opening files is not the unit that was |
| -// classified), so it is the owner's call, as a new or removed unit is |
| -// (Astra review, census-approvals P1). |
| +// classified), so it is the owner's call, as a new unit is (Astra review, |
| +// census-approvals P1). So is a unit that stays declared and stops reading: |
| +// it is not a deletion, so the scan cannot vouch that its reads went with |
| +// it. |
| func censusDecision(class string) bool { |
| - return class == censusReads || class == censusNew || class == censusRemoved || class == censusOther |
| + return class == censusReads || class == censusNew || class == censusQuiet || class == censusOther |
| } |
| type censusChange struct { |
| @@ -158,8 +164,16 @@ func classifyRootReads(got rootReadScan, inv rootReadInventory, seal string) []c |
| // Declared, reads nothing, unchanged: not a discrepancy. |
| case w.Class != "legacy" && w.Kinds == "" && declared: |
| cs = append(cs, censusChange{Key: key, Class: censusBody, Before: w, After: rootReadEntry{File: w.File, Unit: w.Unit, Digest: decl}}) |
| - default: |
| + case declared: |
| + cs = append(cs, censusChange{Key: key, Class: censusQuiet, Before: w, After: rootReadEntry{File: w.File, Unit: w.Unit, Digest: decl}}) |
| + case got.Files[w.File] || got.absent(w.File): |
| + // The scan proves the declaration gone, and every site with it: |
| + // its file was read without it, or the file is gone by Lstat. |
| cs = append(cs, censusChange{Key: key, Class: censusRemoved, Before: w}) |
| + default: |
| + // Not declared, but its file's path is a symlink or behind one, |
| + // or otherwise unproven: not a deletion the scan can vouch for. |
| + cs = append(cs, censusChange{Key: key, Class: censusQuiet, Before: w, After: rootReadEntry{File: w.File, Unit: w.Unit}}) |
| } |
| } |
| for dir, hash := range got.Coverage { |
| @@ -169,7 +183,11 @@ func classifyRootReads(got rootReadScan, inv rootReadInventory, seal string) []c |
| } |
| for dir, hash := range inv.Coverage { |
| if _, ok := got.Coverage[dir]; !ok { |
| - cs = append(cs, censusChange{Key: dir, Class: censusRemoved, OldHash: hash}) |
| + class := censusRemoved |
| + if !got.absent(dir) { |
| + class = censusQuiet |
| + } |
| + cs = append(cs, censusChange{Key: dir, Class: class, OldHash: hash}) |
| } |
| } |
| keys := map[string]bool{} |
| @@ -236,9 +254,13 @@ var censusName = regexp.MustCompile(`^[a-z0-9][a-z0-9-]*$`) |
| // proposeRootReads writes the overlay that closes every change in the scan, |
| // re-freezing each changed unit at the disposition it already has with its |
| -// claim appended, under census-ruling-<name>. It refuses decisions, a |
| -// change with no claim and a claim for no change, and checks its own work: |
| -// loaded onto a copy of inv, the overlay must leave the census clean. |
| +// claim appended, under census-ruling-<name>. A removed unit loses its row |
| +// (@remove) and, if frozen, has its declaration retired (@removed, with the |
| +// absent mark rootReadAbsentRemoval checks); a removed directory has its |
| +// envelope retired (@coverage <dir> -). It refuses decisions, a body or |
| +// sites change with no claim and a claim for no change (a removed unit's |
| +// claim is optional), and checks its own work: loaded onto a copy of inv, |
| +// the overlay must leave the census clean. |
| func proposeRootReads(got rootReadScan, inv rootReadInventory, seal, name string, claims map[string]string) (rootReadProposal, error) { |
| if !censusName.MatchString(name) { |
| return rootReadProposal{}, fmt.Errorf("census name %q: want lower-case letters, digits and dashes", name) |
| @@ -257,6 +279,12 @@ func proposeRootReads(got rootReadScan, inv rootReadInventory, seal, name string |
| units[c.Key] = true |
| } |
| } |
| + removed := map[string]bool{} |
| + for _, c := range cs { |
| + if c.Class == censusRemoved && c.OldHash == "" { |
| + removed[c.Key] = true |
| + } |
| + } |
| if len(decisions) > 0 { |
| return rootReadProposal{}, fmt.Errorf("a decision is needed, not an approval: %s; write those rows by hand and ask on #280", strings.Join(decisions, "; ")) |
| } |
| @@ -266,7 +294,7 @@ func proposeRootReads(got rootReadScan, inv rootReadInventory, seal, name string |
| } |
| } |
| for key, claim := range claims { |
| - if !units[key] { |
| + if !units[key] && !removed[key] { |
| return rootReadProposal{}, fmt.Errorf("claim for %s: not a change the census sees", key) |
| } |
| if strings.ContainsAny(claim, "\t\n\r") { |
| @@ -275,7 +303,7 @@ func proposeRootReads(got rootReadScan, inv rootReadInventory, seal, name string |
| } |
| ruling := "census-ruling-" + name |
| - var frozen, plain, cover []string |
| + var frozen, plain, gone, cover []string |
| counts := map[string]int{} |
| for _, c := range cs { |
| counts[c.Class]++ |
| @@ -283,6 +311,26 @@ func proposeRootReads(got rootReadScan, inv rootReadInventory, seal, name string |
| cover = append(cover, "@coverage\t"+c.Key+"\t"+c.NewHash) |
| continue |
| } |
| + if c.Class == censusRemoved && c.OldHash != "" { |
| + cover = append(cover, "@coverage\t"+c.Key+"\t-") |
| + continue |
| + } |
| + if c.Class == censusRemoved { |
| + b := c.Before |
| + gone = append(gone, "@remove\t"+b.File+"\t"+b.Unit) |
| + if _, isFrozen := inv.Frozen[c.Key]; isFrozen && inv.Removed[c.Key] == "" { |
| + owner := "H3" |
| + if rootReadKeptTask(b.Task) { |
| + owner = b.Task |
| + } |
| + claim := strings.TrimSpace(claims[c.Key]) |
| + if claim == "" { |
| + claim = "deleted: declaration and sites absent from the tree" |
| + } |
| + gone = append(gone, "@removed\t"+b.File+"\t"+b.Unit+"\t"+owner+"\t"+ruling+";"+censusAbsentMark+";basis="+claim) |
| + } |
| + continue |
| + } |
| e := classifiedRootRead{rootReadEntry: c.After, Class: c.Before.Class, Task: c.Before.Task, Basis: c.Before.Basis + ";rev3=" + ruling + ";basis=" + strings.TrimSpace(claims[c.Key])} |
| row := strings.Join([]string{e.File, e.Unit, e.Class, e.Task, e.Basis, e.Kinds, e.Digest}, "\t") |
| if e.Class == "legacy" { |
| @@ -294,7 +342,11 @@ func proposeRootReads(got rootReadScan, inv rootReadInventory, seal, name string |
| fmt.Sprintf("# Census overlay %s, "+censusProposeMark+". %s, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-%s.md.", name, ruling, name), |
| fmt.Sprintf("# %d body, %d sites, %d envelope: each changed unit re-frozen at its existing disposition with its claim appended.", counts[censusBody], counts[censusSites], counts[censusEnvelope]), |
| } |
| - overlay := strings.Join(append(append(append(header, frozen...), plain...), cover...), "\n") + "\n" |
| + if counts[censusRemoved] > 0 { |
| + header = append(header, fmt.Sprintf("# %d removed: each unit's declaration, or each envelope's directory, is absent from the scanned tree, so its row goes, a frozen declaration is retired as absent, and an envelope is retired.", counts[censusRemoved])) |
| + } |
| + lines := append(append(append(append(header, frozen...), plain...), gone...), cover...) |
| + overlay := strings.Join(lines, "\n") + "\n" |
| after := cloneRootReadInventory(inv) |
| f, err := os.CreateTemp("", "census-overlay-*.tsv") |
| @@ -332,14 +384,18 @@ func rootReadCard(name string, cs []censusChange, claims map[string]string, seal |
| var b strings.Builder |
| fmt.Fprintf(&b, "# Census approval: %s\n\n", name) |
| var decisions []censusChange |
| - var envelopes []string |
| - var units []censusChange |
| + var envelopes, retired []string |
| + var units, removed []censusChange |
| for _, c := range cs { |
| switch { |
| case censusDecision(c.Class): |
| decisions = append(decisions, c) |
| case c.Class == censusEnvelope: |
| envelopes = append(envelopes, "`"+c.Key+"`") |
| + case c.Class == censusRemoved && c.OldHash != "": |
| + retired = append(retired, "`"+c.Key+"`") |
| + case c.Class == censusRemoved: |
| + removed = append(removed, c) |
| default: |
| units = append(units, c) |
| } |
| @@ -367,9 +423,26 @@ func rootReadCard(name string, cs []censusChange, claims map[string]string, seal |
| if len(envelopes) > 0 { |
| fmt.Fprintf(&b, "Envelopes re-pinned: %s.\n\n", strings.Join(envelopes, ", ")) |
| } |
| - if len(units) > 0 || len(envelopes) > 0 { |
| + if len(removed) > 0 { |
| + b.WriteString("Removed units: the scan finds neither the declaration nor any of its sites.\n\n| unit | recorded disposition | basis | what changed |\n|---|---|---|---|\n") |
| + for _, c := range removed { |
| + claim := strings.TrimSpace(claims[c.Key]) |
| + if claim == "" { |
| + claim = "deleted" |
| + } |
| + fmt.Fprintf(&b, "| `%s` `%s` | %s, task %s | %s | %s |\n", c.Before.File, c.Before.Unit, c.Before.Class, c.Before.Task, c.Before.Basis, claim) |
| + } |
| + b.WriteString("\n") |
| + } |
| + if len(retired) > 0 { |
| + fmt.Fprintf(&b, "Envelopes retired: %s. Each directory is gone from the tree.\n\n", strings.Join(retired, ", ")) |
| + } |
| + if len(units) > 0 || len(envelopes) > 0 || len(removed) > 0 || len(retired) > 0 { |
| b.WriteString(censusReviewQuestion) |
| } |
| + if len(removed) > 0 || len(retired) > 0 { |
| + b.WriteString(censusRemovalQuestion) |
| + } |
| if len(units) > 0 { |
| b.WriteString("Recorded dispositions, which each change must still satisfy:\n\n") |
| for _, c := range units { |
| @@ -403,6 +476,30 @@ func rootReadCard(name string, cs []censusChange, claims map[string]string, seal |
| // approvals on a card (AGENTS.md, The census). |
| const censusReviewQuestion = "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.\n\n" |
| +// censusRemovalQuestion is what the reviewer answers for removed units and |
| +// retired envelopes on a card: a deletion cannot add a read, but code can |
| +// move, and a check root relied on can go with the code that held it. |
| +const censusRemovalQuestion = "A removed unit's recorded disposition and basis are in its table above. For a removed unit or a retired envelope, confirm from the diff that the code is deleted and not moved: a read that moved shows on this card as a change to the unit that took it, and a unit moved whole shows as a new unit, a decision. Escalate if a check, refusal or validation that root relies on goes with the deleted code and its callers' changes on this card do not account for that.\n\n" |
| + |
| +// censusAbsentMark follows the ruling in the basis of an @removed row |
| +// census-propose writes: the declaration must stay out of the tree |
| +// (rootReadAbsentRemoval). |
| +const censusAbsentMark = "absent" |
| + |
| +// rootReadAbsentRemoval reports whether a removal (owner;basis, as |
| +// inv.Removed holds it) is one census-propose wrote for a deleted unit: |
| +// basis census-ruling-<name>;absent[;...]. Such a removal holds only while |
| +// the scan finds no declaration, unlike the H3 retirement of a unit still |
| +// declared that reads nothing (census ruling zddr3). |
| +func rootReadAbsentRemoval(removal string) bool { |
| + _, basis, _ := strings.Cut(removal, ";") |
| + ruling, rest, ok := strings.Cut(basis, ";") |
| + if !ok || !strings.HasPrefix(ruling, "census-ruling-") || !censusName.MatchString(strings.TrimPrefix(ruling, "census-ruling-")) { |
| + return false |
| + } |
| + return rest == censusAbsentMark || strings.HasPrefix(rest, censusAbsentMark+";") |
| +} |
| + |
| // censusProposeMark is in the first line of every overlay census-propose |
| // writes: a re-run replaces only a file that carries it. |
| const censusProposeMark = "written by census-propose (#369)" |
| @@ -415,6 +512,7 @@ func cloneRootReadInventory(inv rootReadInventory) rootReadInventory { |
| out.Frozen = cloneMap(inv.Frozen) |
| out.Removed = cloneMap(inv.Removed) |
| out.Coverage = cloneMap(inv.Coverage) |
| + out.Retired = cloneMap(inv.Retired) |
| out.Legacy = cloneMap(inv.Legacy) |
| return out |
| } |
diff --git a/internal/provision/census_removal_fs_test.go b/internal/provision/census_removal_fs_test.go| new file mode 100644 |
| index 000000000..a60c1871e |
| --- /dev/null |
| +++ b/internal/provision/census_removal_fs_test.go |
| @@ -0,0 +1,266 @@ |
| +package provision |
| + |
| +// Census removals through the real scanner (Astra review of R0, P1 and |
| +// P2): a temp module scanned by rootReadProduction, so the absence proof |
| +// is the scanner's and the filesystem's, not a cleared map. A retired or |
| +// removed path must be absent by Lstat: no file, directory or symlink |
| +// there, and no symlinked ancestor. |
| + |
| +import ( |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func writeTree(t *testing.T, root string, files map[string]string) { |
| + t.Helper() |
| + for name, body := range files { |
| + path := filepath.Join(root, filepath.FromSlash(name)) |
| + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(path, []byte(body), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| +} |
| + |
| +// removalTree is a small module: a kept package, a package to delete (a Go |
| +// unit and a shell helper, both frozen legacy, and a test file), a package |
| +// whose one unit is declared per GOOS, and a helper under testdata, which |
| +// the scanner skips, for a symlink to point at. |
| +func removalTree(t *testing.T) string { |
| + t.Helper() |
| + // The temp module may sit inside someone's git tree; the census's own |
| + // run (the Makefile) disables VCS stamping the same way. |
| + t.Setenv("GOFLAGS", "-buildvcs=false") |
| + root := t.TempDir() |
| + tagged := func(goos string) string { |
| + return "//go:build " + goos + "\n\npackage tagged\n\nimport \"os\"\n\nfunc L() { os.Stat(\"/data/" + goos + "\") }\n" |
| + } |
| + writeTree(t, root, map[string]string{ |
| + "go.mod": "module fixture/root\n\ngo 1.24\n", |
| + "main.go": "package main\n\nfunc main() {}\n", |
| + "internal/keep/keep.go": "package keep\n\nimport \"os\"\n\nfunc Read() ([]byte, error) { return os.ReadFile(\"/data/keep\") }\n", |
| + "internal/gone/gone.go": "package gone\n\nimport \"os\"\n\nfunc Gone() ([]byte, error) { return os.ReadFile(\"/data/gone\") }\n", |
| + "internal/gone/run.sh": "cat /data/gone\n", |
| + "internal/gone/gone_test.go": "package gone\n\nimport \"testing\"\n\nfunc TestGone(t *testing.T) {}\n", |
| + "internal/tagged/t_linux.go": tagged("linux"), |
| + "internal/tagged/t_darwin.go": tagged("darwin"), |
| + "internal/tagged/t_windows.go": tagged("windows"), |
| + "testdata/helper/run.sh": "cat /data/elsewhere\n", |
| + "testdata/helper/gone.go": "package gone\n\nimport \"os\"\n\nfunc Gone() ([]byte, error) { return os.ReadFile(\"/data/elsewhere\") }\n", |
| + }) |
| + return root |
| +} |
| + |
| +func scanTree(t *testing.T, root string) rootReadScan { |
| + t.Helper() |
| + got, err := rootReadProduction(root) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return got |
| +} |
| + |
| +// inventoryOf classifies a clean scan: the units in legacy as frozen |
| +// accepted-legacy, the rest as authority, every envelope pinned. |
| +func inventoryOf(scan rootReadScan, legacy ...string) (rootReadInventory, string) { |
| + frozen := map[string]bool{} |
| + for _, k := range legacy { |
| + frozen[k] = true |
| + } |
| + inv := rootReadInventory{Entries: map[string]classifiedRootRead{}, Frozen: map[string]classifiedRootRead{}, Legacy: map[string]bool{}, Coverage: cloneMap(scan.Coverage), Fields: strings.Join(scan.Fields, ",")} |
| + for _, e := range scan.Entries { |
| + key := e.File + ":" + e.Unit |
| + c := classifiedRootRead{rootReadEntry: e, Class: "authority", Task: "E4", Basis: "fixture"} |
| + if frozen[key] { |
| + c = classifiedRootRead{rootReadEntry: e, Class: "legacy", Task: "accepted-legacy", Basis: "accepted-legacy;rev3=J1;basis=fixture"} |
| + inv.Frozen[key] = c |
| + inv.Legacy[rootReadLegacyFingerprint(c)] = true |
| + } |
| + inv.Entries[key] = c |
| + } |
| + return inv, rootReadLegacySeal(inv) |
| +} |
| + |
| +const ( |
| + goneUnit = "internal/gone/gone.go:Gone" |
| + goneShell = "internal/gone/run.sh:external" |
| +) |
| + |
| +func TestCensusRemovalThroughTheScanner(t *testing.T) { |
| + root := removalTree(t) |
| + base := scanTree(t, root) |
| + for _, k := range []string{goneUnit, goneShell, "internal/tagged/t_linux.go:L", "internal/tagged/t_darwin.go:L", "internal/tagged/t_windows.go:L"} { |
| + if !rootReadScanned(base, k) { |
| + t.Fatalf("the scan lacks %s: %v", k, base.Entries) |
| + } |
| + } |
| + inv, seal := inventoryOf(base, goneUnit, goneShell) |
| + if errs := censusDiscrepancies(base, inv, seal); len(errs) != 0 { |
| + t.Fatalf("fixture census: %v", errs) |
| + } |
| + gone := filepath.Join(root, "internal/gone") |
| + helper := filepath.Join(root, "testdata/helper") |
| + if err := os.RemoveAll(gone); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + got := scanTree(t, root) |
| + classes := classesOf(classifyRootReads(got, inv, seal)) |
| + for _, k := range []string{goneUnit, goneShell, "internal/gone"} { |
| + if classes[k] != censusRemoved { |
| + t.Fatalf("class of %s = %q (all %v)", k, classes[k], classes) |
| + } |
| + } |
| + p, err := proposeRootReads(got, inv, seal, "drop-gone", nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + after := cloneRootReadInventory(inv) |
| + if err := loadRootReadInventory(writeOverlay(t, p.Overlay), &after, true); err != nil { |
| + t.Fatal(err) |
| + } |
| + if errs := censusDiscrepancies(got, after, p.Seal); len(errs) != 0 || p.Seal != seal { |
| + t.Fatalf("after the overlay: %v (seal %s, was %s)\n%s", errs, p.Seal, seal, p.Overlay) |
| + } |
| + |
| + // After the retirement, each way back fails the census. |
| + for name, back := range map[string]func(){ |
| + "a tests-only directory": func() { |
| + writeTree(t, root, map[string]string{"internal/gone/gone_test.go": "package gone\n"}) |
| + }, |
| + "the directory with its source": func() { |
| + writeTree(t, root, map[string]string{"internal/gone/gone.go": "package gone\n\nfunc Gone() {}\n"}) |
| + }, |
| + "a symlink to a directory the scanner skips": func() { |
| + if err := os.Symlink(helper, gone); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, |
| + "a symlink to nowhere": func() { |
| + if err := os.Symlink(filepath.Join(root, "nowhere"), gone); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + back() |
| + defer os.RemoveAll(gone) |
| + again := scanTree(t, root) |
| + errs := censusDiscrepancies(again, after, p.Seal) |
| + if !containsPrefix(errs, "retired root source envelope still present internal/gone") { |
| + t.Fatalf("came back unseen: %v", errs) |
| + } |
| + }) |
| + } |
| + // The symlinked helper's shell file is invisible to the walk: the |
| + // census sees the resurrection only through the Lstat proof. |
| + if err := os.Symlink(helper, gone); err != nil { |
| + t.Fatal(err) |
| + } |
| + if again := scanTree(t, root); rootReadScanned(again, goneShell) || again.Dirs["internal/gone"] { |
| + t.Fatalf("the walk followed the symlink; this test no longer pins the Lstat proof") |
| + } |
| +} |
| + |
| +// Replacing a directory with a symlink, or leaving its tests behind, is |
| +// not a deletion: quiet, a decision census-propose refuses. |
| +func TestCensusRemovalRefusesWhatIsStillThere(t *testing.T) { |
| + for name, edit := range map[string]func(t *testing.T, root string){ |
| + "replaced by a symlink": func(t *testing.T, root string) { |
| + if err := os.RemoveAll(filepath.Join(root, "internal/gone")); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Symlink(filepath.Join(root, "testdata/helper"), filepath.Join(root, "internal/gone")); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, |
| + "its tests left behind": func(t *testing.T, root string) { |
| + for _, f := range []string{"internal/gone/gone.go", "internal/gone/run.sh"} { |
| + if err := os.Remove(filepath.Join(root, f)); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + }, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + root := removalTree(t) |
| + inv, seal := inventoryOf(scanTree(t, root), goneUnit, goneShell) |
| + edit(t, root) |
| + got := scanTree(t, root) |
| + classes := classesOf(classifyRootReads(got, inv, seal)) |
| + if classes["internal/gone"] != censusQuiet { |
| + t.Fatalf("envelope class %q (all %v)", classes["internal/gone"], classes) |
| + } |
| + if name == "replaced by a symlink" && (classes[goneUnit] != censusQuiet || classes[goneShell] != censusQuiet) { |
| + t.Fatalf("units behind a symlinked directory: %v", classes) |
| + } |
| + if _, err := proposeRootReads(got, inv, seal, "x", nil); err == nil || !strings.Contains(err.Error(), "decision") { |
| + t.Fatalf("err = %v, want a decision", err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// One GOOS's declaration deleted: that unit is removed, the package's |
| +// envelope re-pinned, and the other two stay as they were. |
| +func TestCensusRemovalOfATaggedDeclaration(t *testing.T) { |
| + root := removalTree(t) |
| + inv, seal := inventoryOf(scanTree(t, root), goneUnit, goneShell) |
| + if err := os.Remove(filepath.Join(root, "internal/tagged/t_darwin.go")); err != nil { |
| + t.Fatal(err) |
| + } |
| + got := scanTree(t, root) |
| + classes := classesOf(classifyRootReads(got, inv, seal)) |
| + want := map[string]string{"internal/tagged/t_darwin.go:L": censusRemoved, "internal/tagged": censusEnvelope} |
| + if len(classes) != len(want) || classes["internal/tagged/t_darwin.go:L"] != censusRemoved || classes["internal/tagged"] != censusEnvelope { |
| + t.Fatalf("classes %v, want %v", classes, want) |
| + } |
| + p, err := proposeRootReads(got, inv, seal, "drop-darwin", nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + after := cloneRootReadInventory(inv) |
| + if err := loadRootReadInventory(writeOverlay(t, p.Overlay), &after, true); err != nil { |
| + t.Fatal(err) |
| + } |
| + if errs := censusDiscrepancies(got, after, p.Seal); len(errs) != 0 { |
| + t.Fatalf("after the overlay: %v", errs) |
| + } |
| +} |
| + |
| +func TestRootReadPathAbsent(t *testing.T) { |
| + root := t.TempDir() |
| + writeTree(t, root, map[string]string{"real/x": "x", "target/x": "x", "file": "f"}) |
| + if err := os.Symlink(filepath.Join(root, "target"), filepath.Join(root, "link")); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Symlink(filepath.Join(root, "nowhere"), filepath.Join(root, "dangling")); err != nil { |
| + t.Fatal(err) |
| + } |
| + for rel, want := range map[string]bool{ |
| + "none": true, |
| + "none/x": true, |
| + "real/none": true, |
| + "real": false, |
| + "real/x": false, |
| + "link": false, |
| + "link/x": false, |
| + "link/none": false, |
| + "dangling": false, |
| + "dangling/x": false, |
| + "file/x": false, |
| + "real/../x": false, |
| + "": false, |
| + "/abs": false, |
| + "real//none": false, |
| + "./real/none": false, |
| + } { |
| + if got := rootReadPathAbsent(root, rel); got != want { |
| + t.Errorf("rootReadPathAbsent(%q) = %v, want %v", rel, got, want) |
| + } |
| + } |
| +} |
diff --git a/internal/provision/census_removal_test.go b/internal/provision/census_removal_test.go| new file mode 100644 |
| index 000000000..70727fd03 |
| --- /dev/null |
| +++ b/internal/provision/census_removal_test.go |
| @@ -0,0 +1,408 @@ |
| +package provision |
| + |
| +// Census removals (claims cleanup R0; Paul's ruling 1 on #280, 2026-10-25): |
| +// a removed unit, a retired frozen declaration and a deleted directory's |
| +// envelope are approvals when the scan proves them absent, since a deletion |
| +// cannot add a read. These tests pin the retired envelope, the generated |
| +// removal rows and what still fails. |
| + |
| +import ( |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func writeOverlay(t *testing.T, body string) string { |
| + t.Helper() |
| + path := filepath.Join(t.TempDir(), "overlay.tsv") |
| + if err := os.WriteFile(path, []byte(body), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + return path |
| +} |
| + |
| +// @coverage <dir> - retires the envelope of a directory that is gone. It |
| +// is refused while the directory is still in the tree, even holding only |
| +// tests, and a later pin brings the envelope back. |
| +func TestPlan14RetiredEnvelope(t *testing.T) { |
| + pinned := func() rootReadInventory { |
| + return rootReadInventory{Entries: map[string]classifiedRootRead{}, Coverage: map[string]string{"internal/gone": strings.Repeat("c", 64), "internal/kept": strings.Repeat("d", 64)}, Fields: ""} |
| + } |
| + scan := rootReadScan{Coverage: map[string]string{"internal/kept": strings.Repeat("d", 64)}, Dirs: map[string]bool{".": true, "internal": true, "internal/kept": true}} |
| + |
| + inv := pinned() |
| + if errs := compareRootReads(scan, inv); len(errs) != 1 || !strings.Contains(errs[0], "stale root source envelope internal/gone") { |
| + t.Fatalf("before the retirement: %v", errs) |
| + } |
| + if err := loadRootReadInventory(writeOverlay(t, "@coverage\tinternal/gone\t-\n"), &inv, true); err != nil { |
| + t.Fatal(err) |
| + } |
| + if errs := compareRootReads(scan, inv); len(errs) != 0 { |
| + t.Fatalf("retired envelope of a deleted directory: %v", errs) |
| + } |
| + |
| + // The directory is still there (only tests left, say): refused. |
| + present := scan |
| + present.Dirs = map[string]bool{".": true, "internal": true, "internal/kept": true, "internal/gone": true} |
| + if errs := compareRootReads(present, inv); len(errs) != 1 || errs[0] != "retired root source envelope still present internal/gone" { |
| + t.Fatalf("retired envelope of a present directory: %v", errs) |
| + } |
| + // A scan that walked no directories proves nothing. |
| + unwalked := scan |
| + unwalked.Dirs = nil |
| + if errs := compareRootReads(unwalked, inv); len(errs) != 1 { |
| + t.Fatalf("retired envelope with no directory list: %v", errs) |
| + } |
| + // The directory back with source: changed, and still retired. |
| + back := present |
| + back.Coverage = map[string]string{"internal/kept": strings.Repeat("d", 64), "internal/gone": strings.Repeat("e", 64)} |
| + if errs := compareRootReads(back, inv); len(errs) != 2 { |
| + t.Fatalf("retired directory back with source: %v", errs) |
| + } |
| + // A later pin ends the retirement. |
| + if err := loadRootReadInventory(writeOverlay(t, "@coverage\tinternal/gone\t"+strings.Repeat("e", 64)+"\n"), &inv, true); err != nil { |
| + t.Fatal(err) |
| + } |
| + if errs := compareRootReads(back, inv); len(errs) != 0 { |
| + t.Fatalf("re-pinned envelope: %v", errs) |
| + } |
| + |
| + for name, tc := range map[string]struct { |
| + body string |
| + delta bool |
| + }{ |
| + "in the base": {"@coverage\tinternal/gone\t-\n", false}, |
| + "of an unpinned dir": {"@coverage\tinternal/never\t-\n", true}, |
| + "twice in one overlay": {"@coverage\tinternal/gone\t-\n@coverage\tinternal/gone\t-\n", true}, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + inv := pinned() |
| + if err := loadRootReadInventory(writeOverlay(t, tc.body), &inv, tc.delta); err == nil { |
| + t.Fatal("retirement loaded") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// deletePackage edits the fixture scan as deleting internal/a would: both |
| +// units, their declarations, the envelope and the directory are gone. |
| +func deletePackage(got *rootReadScan) { |
| + got.Entries = nil |
| + got.Declarations = map[string]string{} |
| + got.Coverage = map[string]string{} |
| + got.Dirs = map[string]bool{".": true, "internal": true} |
| +} |
| + |
| +func classesOf(cs []censusChange) map[string]string { |
| + out := map[string]string{} |
| + for _, c := range cs { |
| + out[c.Key] = c.Class |
| + } |
| + return out |
| +} |
| + |
| +// A unit gone from the tree is removed, an approval; a unit still declared |
| +// that reads nothing now is quiet, a decision, as is a directory that lost |
| +// its source but is still there. |
| +func TestCensusClassifiesRemovedAndQuiet(t *testing.T) { |
| + got, inv, seal := proposeFixture(t) |
| + deletePackage(&got) |
| + want := map[string]string{"internal/a/a.go:Wake": censusRemoved, "internal/a/b.go:Route": censusRemoved, "internal/a": censusRemoved} |
| + if classes := classesOf(classifyRootReads(got, inv, seal)); len(classes) != len(want) { |
| + t.Fatalf("classes = %v, want %v", classes, want) |
| + } else { |
| + for k, v := range want { |
| + if classes[k] != v { |
| + t.Errorf("class of %s = %q, want %q", k, classes[k], v) |
| + } |
| + } |
| + } |
| + if censusDecision(censusRemoved) || !censusDecision(censusQuiet) { |
| + t.Fatal("removed must be an approval and quiet a decision") |
| + } |
| + |
| + quiet, inv, seal := proposeFixture(t) |
| + quiet.Entries = quiet.Entries[1:] |
| + quiet.Declarations["internal/a/a.go:Wake"] = strings.Repeat("7", 64) |
| + delete(quiet.Coverage, "internal/a") |
| + classes := classesOf(classifyRootReads(quiet, inv, seal)) |
| + if classes["internal/a/a.go:Wake"] != censusQuiet || classes["internal/a"] != censusQuiet { |
| + t.Fatalf("still declared, or a directory still there: %v", classes) |
| + } |
| + if _, err := proposeRootReads(quiet, inv, seal, "x", nil); err == nil || !strings.Contains(err.Error(), "decision") { |
| + t.Fatalf("quiet proposed: %v", err) |
| + } |
| +} |
| + |
| +// Deleting a package is the whole job: the overlay census-propose writes |
| +// loads, leaves the census clean under the same seal, names the ruling on |
| +// every removal and retires the envelope, and the card lists each removed |
| +// unit with its disposition for the reviewer. |
| +func TestCensusProposalRetiresADeletedPackage(t *testing.T) { |
| + got, inv, seal := proposeFixture(t) |
| + deletePackage(&got) |
| + if len(censusDiscrepancies(got, inv, seal)) == 0 { |
| + t.Fatal("the deletion made no discrepancy") |
| + } |
| + p, err := proposeRootReads(got, inv, seal, "drop-a", map[string]string{"internal/a/a.go:Wake": "deleted with internal/a; the wake moved nowhere"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + after := cloneRootReadInventory(inv) |
| + if err := loadRootReadInventory(writeOverlay(t, p.Overlay), &after, true); err != nil { |
| + t.Fatalf("%v\n%s", err, p.Overlay) |
| + } |
| + if errs := censusDiscrepancies(got, after, p.Seal); len(errs) != 0 { |
| + t.Fatalf("after the proposal: %v\n%s", errs, p.Overlay) |
| + } |
| + if p.Seal != seal { |
| + t.Errorf("a deletion moved the seal: %s -> %s", seal, p.Seal) |
| + } |
| + for _, line := range []string{ |
| + "@remove\tinternal/a/a.go\tWake", |
| + "@removed\tinternal/a/a.go\tWake\tH3\tcensus-ruling-drop-a;absent;basis=deleted with internal/a; the wake moved nowhere", |
| + "@remove\tinternal/a/b.go\tRoute", |
| + "@coverage\tinternal/a\t-", |
| + } { |
| + if !strings.Contains(p.Overlay, line+"\n") { |
| + t.Errorf("overlay lacks %q:\n%s", line, p.Overlay) |
| + } |
| + } |
| + // Route was never frozen: its row goes, and no @removed is written. |
| + if strings.Contains(p.Overlay, "@removed\tinternal/a/b.go") { |
| + t.Errorf("an unfrozen unit got a frozen removal:\n%s", p.Overlay) |
| + } |
| + for _, want := range []string{"internal/a/a.go", "Wake", "internal/a/b.go", "Route", "accepted-legacy;rev3=J1;basis=root-route", "root-route", "Envelopes retired: `internal/a`", censusRemovalQuestion, "deleted with internal/a"} { |
| + if !strings.Contains(p.Card, want) { |
| + t.Errorf("card lacks %q:\n%s", want, p.Card) |
| + } |
| + } |
| + if !strings.Contains(p.Card, "needs an approval, not a decision") { |
| + t.Errorf("card:\n%s", p.Card) |
| + } |
| +} |
| + |
| +// A deletion beside a changed or new read is still refused: census-propose |
| +// writes nothing while any decision is on the card. |
| +func TestCensusProposalRefusesADeletionWithAChangedRead(t *testing.T) { |
| + for name, edit := range map[string]func(*rootReadScan){ |
| + "a new kind of read in a surviving unit": func(g *rootReadScan) { |
| + g.Entries = g.Entries[:1] |
| + delete(g.Declarations, "internal/a/b.go:Route") |
| + change(g, "internal/a/a.go:Wake", "registry:Host@10,registry:DBPath@20,file:Open@30", strings.Repeat("8", 64)) |
| + }, |
| + "the deleted unit's name back in another file": func(g *rootReadScan) { |
| + deletePackage(g) |
| + g.Entries = []rootReadEntry{{File: "internal/z/b.go", Unit: "Route", Kinds: "registry:Host@5", Digest: strings.Repeat("2", 64)}} |
| + g.Declarations["internal/z/b.go:Route"] = strings.Repeat("2", 64) |
| + g.Coverage["internal/z"] = strings.Repeat("f", 64) |
| + g.Dirs["internal/z"] = true |
| + }, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + got, inv, seal := proposeFixture(t) |
| + edit(&got) |
| + if _, err := proposeRootReads(got, inv, seal, "x", nil); err == nil || !strings.Contains(err.Error(), "decision") { |
| + t.Fatalf("err = %v, want a decision", err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// A generated removal holds only while the unit stays gone. Unlike the H3 |
| +// census-ruling retirement (zddr3), it does not tolerate the declaration |
| +// coming back with no read; back with a read is unclassified; the |
| +// directory back fails its retired envelope. |
| +func TestCensusAbsentRemovalNeedsAbsence(t *testing.T) { |
| + got, inv, seal := proposeFixture(t) |
| + deletePackage(&got) |
| + p, err := proposeRootReads(got, inv, seal, "drop-a", nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + after := cloneRootReadInventory(inv) |
| + if err := loadRootReadInventory(writeOverlay(t, p.Overlay), &after, true); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !strings.Contains(p.Overlay, "census-ruling-drop-a;absent;basis=deleted: declaration and sites absent from the tree") { |
| + t.Errorf("default removal basis:\n%s", p.Overlay) |
| + } |
| + for name, edit := range map[string]func(*rootReadScan){ |
| + "declared again, no read": func(g *rootReadScan) { |
| + g.Declarations["internal/a/a.go:Wake"] = strings.Repeat("9", 64) |
| + g.Dirs["internal/a"] = true |
| + g.Coverage["internal/a"] = strings.Repeat("9", 64) |
| + }, |
| + "declared again, reading": func(g *rootReadScan) { |
| + g.Declarations["internal/a/b.go:Route"] = strings.Repeat("2", 64) |
| + g.Entries = []rootReadEntry{{File: "internal/a/b.go", Unit: "Route", Kinds: "registry:Host@5", Digest: strings.Repeat("2", 64)}} |
| + }, |
| + "the directory back, tests only": func(g *rootReadScan) { |
| + g.Dirs["internal/a"] = true |
| + }, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + g := got |
| + g.Declarations, g.Coverage, g.Dirs = cloneMap(got.Declarations), cloneMap(got.Coverage), cloneMap(got.Dirs) |
| + edit(&g) |
| + if errs := censusDiscrepancies(g, after, p.Seal); len(errs) == 0 { |
| + t.Fatal("accepted") |
| + } |
| + }) |
| + } |
| + // The removal's own check, apart from the envelope: a frozen absent |
| + // removal refuses a quiet declaration that H3's retirement would pass. |
| + key := "internal/a/a.go:Wake" |
| + quiet := rootReadScan{Declarations: map[string]string{key: strings.Repeat("9", 64)}} |
| + if errs := checkRootReadDeclarations(quiet, after); len(errs) != 1 || errs[0] != "removed legacy declaration still present "+key { |
| + t.Fatalf("absent removal with the declaration back: %v", errs) |
| + } |
| + h3 := cloneRootReadInventory(after) |
| + h3.Removed[key] = "H3;census-ruling-drop-a: still declared, and reads nothing now" |
| + if errs := checkRootReadDeclarations(quiet, h3); len(errs) != 0 { |
| + t.Fatalf("the H3 retirement changed: %v", errs) |
| + } |
| + for removal, want := range map[string]bool{ |
| + "H3;census-ruling-drop-a;absent;basis=x": true, |
| + "C,J4;census-ruling-drop-a;absent": true, |
| + "H3;census-ruling-drop-a: absent": false, |
| + "H3;drop-a;absent;basis=x": false, |
| + "H3;census-ruling-drop-a;absentee": false, |
| + } { |
| + if rootReadAbsentRemoval(removal) != want { |
| + t.Errorf("rootReadAbsentRemoval(%q) = %v, want %v", removal, !want, want) |
| + } |
| + } |
| +} |
| + |
| +// J4 (TestPlan14RootInputInventoryCoverage) sees only the overlays up to |
| +// activation-tools, so a later removal is a retirement: the full chain no |
| +// longer carries the row and the tree no longer declares the unit. A |
| +// family whose every row is retired may lose its witnesses in the same |
| +// change; a witness may not go while a surviving row of its family names |
| +// it; a surviving row with no production caller still fails. |
| +func TestPlan14J4RetiresAFamily(t *testing.T) { |
| + row := func(file, unit, task string) classifiedRootRead { |
| + return classifiedRootRead{rootReadEntry: rootReadEntry{File: file, Unit: unit}, Class: "authority", Task: task} |
| + } |
| + a1, a2, b := row("internal/x/a.go", "One", "A,J4"), row("internal/x/a.go", "Two", "A,J4"), row("internal/y/b.go", "Keep", "B,J4") |
| + key := func(e classifiedRootRead) string { return e.File + ":" + e.Unit } |
| + inv := rootReadInventory{Entries: map[string]classifiedRootRead{key(a1): a1, key(a2): a2, key(b): b}} |
| + callers := map[string]string{key(b): "main.go:main"} |
| + // Every witness but family A's is in the tree. |
| + tests := map[string]bool{} |
| + for name, f := range inputFamilies { |
| + if name == "A" { |
| + continue |
| + } |
| + for _, w := range []string{f.Hostile, f.Rename, f.Erasure, f.Retry, f.Positive} { |
| + tests[w] = true |
| + } |
| + } |
| + for _, w := range []string{inputFamilies["A"].Hostile, inputFamilies["A"].Rename, inputFamilies["A"].Erasure, inputFamilies["A"].Retry, inputFamilies["A"].Positive} { |
| + delete(tests, w) |
| + } |
| + check := func(full rootReadInventory, declared map[string]bool, exemptions map[string]inputExemption) []string { |
| + retired := func(k string) bool { return inputRetired(full, declared[k], k) } |
| + var failures []string |
| + for _, e := range inputSurviving(inv, retired) { |
| + failures = append(failures, checkInputRow(e, callers, tests)...) |
| + } |
| + live, liveErrs := inputLiveFamilies(full, func(k string) bool { return declared[k] }) |
| + failures = append(failures, liveErrs...) |
| + failures = append(failures, checkInputLiveWitnesses(live, tests)...) |
| + return append(failures, checkInputRetiredExemptions(exemptions, retired)...) |
| + } |
| + carried := func(rows ...classifiedRootRead) rootReadInventory { |
| + full := rootReadInventory{Entries: map[string]classifiedRootRead{}} |
| + for _, e := range rows { |
| + full.Entries[key(e)] = e |
| + } |
| + return full |
| + } |
| + |
| + // Family A retired whole, its witnesses gone with it. |
| + if errs := check(carried(b), map[string]bool{key(b): true}, nil); len(errs) != 0 { |
| + t.Fatalf("a retired family: %v", errs) |
| + } |
| + // One A row survives: its family's witnesses must stay. |
| + errs := check(carried(a2, b), map[string]bool{key(a2): true, key(b): true}, nil) |
| + if !containsPrefix(errs, "family A missing") { |
| + t.Fatalf("a surviving row's witnesses dropped: %v", errs) |
| + } |
| + // A surviving row with no production caller still fails. |
| + if !containsPrefix(errs, key(a2)+": no production caller") { |
| + t.Fatalf("a callerless surviving row: %v", errs) |
| + } |
| + // Removed from the chain but still declared: not retired, still checked. |
| + if errs := check(carried(b), map[string]bool{key(a1): true, key(b): true}, nil); !containsPrefix(errs, key(a1)+": no production caller") { |
| + t.Fatalf("a still-declared row escaped J4: %v", errs) |
| + } |
| + // A row only a later overlay added (outside J4's inventory) still names |
| + // family A and is still declared: A's witnesses stay required (Astra |
| + // review of R0, P1; servingPriorBinding in roster-binding is one). |
| + later := row("internal/z/later.go", "Bind", "A,J4") |
| + if errs := check(carried(b, later), map[string]bool{key(b): true, key(later): true}, nil); !containsPrefix(errs, "family A missing") { |
| + t.Fatalf("a later-only surviving row lost its witnesses: %v", errs) |
| + } |
| + // A tag J4 does not know beside a family it does: the census accepts |
| + // the row for its one recognized owner, so J4 fails on the tag and |
| + // still keeps A's witnesses (Astra review of R0, round 2). |
| + mixed := row("internal/z/later.go", "Mixed", "A,J4,unknown") |
| + errs = check(carried(b, mixed), map[string]bool{key(b): true, key(mixed): true}, nil) |
| + if !containsPrefix(errs, key(mixed)+": unknown family") || !containsPrefix(errs, "family A missing") { |
| + t.Fatalf("a later-only row with an unknown tag: %v", errs) |
| + } |
| + // Deleted too, it no longer holds them. |
| + if errs := check(carried(b, later), map[string]bool{key(b): true}, nil); len(errs) != 0 { |
| + t.Fatalf("a deleted later-only row: %v", errs) |
| + } |
| + // Only J4's scope counts: a later row of E4 and J tags alone names no family. |
| + scoped := row("internal/z/later.go", "Grant", "E4,J4") |
| + if live, errs := inputLiveFamilies(carried(scoped), func(string) bool { return true }); len(live) != 0 || len(errs) != 0 { |
| + t.Fatalf("an out-of-scope row named families: %v %v", live, errs) |
| + } |
| + // An exemption for a retired unit is stale: delete it with the unit. |
| + if errs := check(carried(b), map[string]bool{key(b): true}, map[string]inputExemption{key(a1): {Ruling: "x"}}); len(errs) != 1 || !strings.Contains(errs[0], "retired") { |
| + t.Fatalf("a retired unit's exemption: %v", errs) |
| + } |
| +} |
| + |
| +func containsPrefix(errs []string, prefix string) bool { |
| + for _, e := range errs { |
| + if strings.HasPrefix(e, prefix) { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +// inputDeclared answers from the source as the census names declarations. |
| +func TestPlan14J4DeclaredMatchesTheCensus(t *testing.T) { |
| + root := t.TempDir() |
| + if err := os.MkdirAll(filepath.Join(root, "internal/x"), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + src := "package x\n\nimport \"os\"\n\ntype T struct{}\n\nfunc (t *T) M() {}\n\nfunc F() { os.Exit(0) }\n\nvar (\n\ta = 1\n)\n\nconst c = 2\n" |
| + if err := os.WriteFile(filepath.Join(root, "internal/x/x.go"), []byte(src), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(filepath.Join(root, "internal/x/run.sh"), []byte("true\n"), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + declared := inputDeclared(root) |
| + for k, want := range map[string]bool{ |
| + "internal/x/x.go:type T": true, "internal/x/x.go:T.M": true, "internal/x/x.go:F": true, |
| + "internal/x/x.go:var#1": true, "internal/x/x.go:const c": true, "internal/x/run.sh:external": true, |
| + "internal/x/x.go:G": false, "internal/x/gone.go:F": false, "internal/x/gone.sh:external": false, |
| + } { |
| + got, err := declared(k) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if got != want { |
| + t.Errorf("declared(%s) = %v, want %v", k, got, want) |
| + } |
| + } |
| +} |
diff --git a/internal/provision/claims_cleanup_r1_census_test.go b/internal/provision/claims_cleanup_r1_census_test.go| new file mode 100644 |
| index 000000000..1ec2bd3ab |
| --- /dev/null |
| +++ b/internal/provision/claims_cleanup_r1_census_test.go |
| @@ -0,0 +1,30 @@ |
| +package provision |
| + |
| +// Record-write census entries for claims cleanup R1 (branch |
| +// claims-cleanup-r1: the live slices move out of the claim packages), |
| +// layered on edgeProtection2WriteCensusInventory (main's newest at |
| +// 96564cf3). Reviewed by the branch author; the census owner rules on #280 |
| +// with the root-read card. |
| +// - admitDBRead computes the request's incarnation with |
| +// provision.Incarnation instead of hostclaim.Incarnation, the same |
| +// function moved (its golden vectors are incarnation_golden_test.go). |
| +// Its writes are the same conditional creates under db-reads/ in the |
| +// deployment bucket: still nonrecord. No write site is added. |
| +func claimsCleanupR1WriteCensusInventory() []censusEntry { |
| + entries := append([]censusEntry(nil), edgeProtection2WriteCensusInventory()...) |
| + replacements := []censusEntry{ |
| + {"internal/console/apidbforward.go", "Server.admitDBRead", "nonrecord", "sel:Put", "cbdbd19a26552c186e582c80342321d7f74fc9719cd78644e6a3f42f4a41b9cd"}, |
| + } |
| + 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 { |
| + entries = append(entries, r) |
| + } |
| + } |
| + return entries |
| +} |
diff --git a/internal/provision/incarnation.go b/internal/provision/incarnation.go| new file mode 100644 |
| index 000000000..83c208887 |
| --- /dev/null |
| +++ b/internal/provision/incarnation.go |
| @@ -0,0 +1,32 @@ |
| +package provision |
| + |
| +import ( |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "errors" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/controlname" |
| + "github.com/carlosframework/platform/internal/maintenanceguard" |
| +) |
| + |
| +// ErrMalformedIncarnation is Incarnation refusing a legacy identity whose |
| +// account, app or host is not well formed. |
| +var ErrMalformedIncarnation = errors.New("provision: malformed incarnation identity") |
| + |
| +// Incarnation is an instance record's identity: what db forward and carlos |
| +// run requests carry, and what the console and the box each compute and |
| +// must agree on. A record with a zero CreatedAt (written before CreatedAt |
| +// existed) gets the domain-separated legacy identity; any other gets |
| +// maintenanceguard.RecordIdentity. It moved here from hostclaim in claims |
| +// cleanup R1 with its bytes unchanged (incarnation_golden_test.go). |
| +func Incarnation(account, app, host string, created time.Time) (string, error) { |
| + if created.IsZero() { |
| + if !controlname.ValidAccount(account) || !controlname.ValidApp(app) || !controlname.ValidHostShape(host) { |
| + return "", ErrMalformedIncarnation |
| + } |
| + sum := sha256.Sum256([]byte("carlos-legacy-incarnation-v1\x00" + account + "\x00" + app + "\x00" + host)) |
| + return hex.EncodeToString(sum[:]), nil |
| + } |
| + return maintenanceguard.RecordIdentity(account, app, host, created) |
| +} |
diff --git a/internal/provision/incarnation_golden_test.go b/internal/provision/incarnation_golden_test.go| new file mode 100644 |
| index 000000000..3b5052fe1 |
| --- /dev/null |
| +++ b/internal/provision/incarnation_golden_test.go |
| @@ -0,0 +1,66 @@ |
| +package provision_test |
| + |
| +import ( |
| + "errors" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/hostclaim" |
| + "github.com/carlosframework/platform/internal/provision" |
| +) |
| + |
| +// incarnationVectors are the identities db forward and carlos run carry |
| +// (console and box compute them apart and must agree). The hex values were |
| +// derived independently of the Go code: the legacy form is |
| +// sha256("carlos-legacy-incarnation-v1\x00" + account + "\x00" + app + "\x00" + host), |
| +// the created form maintenanceguard.RecordIdentity's length-prefixed digest |
| +// over account, app, host and the RFC 3339 nano stamp. Claims cleanup R1 |
| +// moved the function; these bytes must never move. |
| +var incarnationVectors = []struct { |
| + name string |
| + acct, app, host string |
| + at time.Time |
| + want string |
| +}{ |
| + {"legacy", "bab", "shop", "alpha.shop.example.com", time.Time{}, "b3d6855bf26845a17dcfa39fd8f94a00815ecc257aaf0540a6d5522efb1d976e"}, |
| + {"created", "bab", "shop", "alpha.shop.example.com", time.Date(2026, 10, 1, 12, 34, 56, 789000000, time.UTC), "e5250d740fc808db6befc8174112bbc3bb33033672030c9ce40472800fd0ebf6"}, |
| + {"created nanosecond", "bab", "shop", "alpha.shop.example.com", time.Date(2026, 10, 1, 12, 34, 56, 789000001, time.UTC), "a37493f256a913a376898eee3f332449ea2d96103a64c58b5e11a4c59b930c02"}, |
| + {"created non-UTC zone", "bab", "shop", "alpha.shop.example.com", time.Date(2026, 10, 1, 13, 34, 56, 789000000, time.FixedZone("x", 3600)), "e5250d740fc808db6befc8174112bbc3bb33033672030c9ce40472800fd0ebf6"}, |
| + {"legacy malformed account", "BAD", "shop", "alpha.shop.example.com", time.Time{}, ""}, |
| + {"created malformed account", "BAD", "shop", "alpha.shop.example.com", time.Date(2026, 10, 1, 12, 34, 56, 789000000, time.UTC), ""}, |
| + {"legacy malformed host", "bab", "shop", "", time.Time{}, ""}, |
| +} |
| + |
| +var incarnationImpls = map[string]func(string, string, string, time.Time) (string, error){ |
| + "provision.Incarnation": provision.Incarnation, |
| + // The claim code's delegate, until claims cleanup deletes hostclaim. |
| + "hostclaim.Incarnation": hostclaim.Incarnation, |
| +} |
| + |
| +func TestIncarnationGoldenVectors(t *testing.T) { |
| + for name, f := range incarnationImpls { |
| + for _, v := range incarnationVectors { |
| + got, err := f(v.acct, v.app, v.host, v.at) |
| + if v.want == "" { |
| + if err == nil || got != "" { |
| + t.Errorf("%s %s = %q, %v; want an error and no identity", name, v.name, got, err) |
| + } |
| + continue |
| + } |
| + if err != nil || got != v.want { |
| + t.Errorf("%s %s = %q, %v; want %q", name, v.name, got, err, v.want) |
| + } |
| + } |
| + } |
| +} |
| + |
| +// hostclaim's claim callers still see hostclaim.ErrMalformed for a malformed |
| +// legacy identity; claims-off callers see provision.ErrMalformedIncarnation. |
| +func TestIncarnationMalformedErrors(t *testing.T) { |
| + if _, err := provision.Incarnation("BAD", "shop", "alpha.shop.example.com", time.Time{}); !errors.Is(err, provision.ErrMalformedIncarnation) { |
| + t.Fatalf("provision.Incarnation error = %v", err) |
| + } |
| + if _, err := hostclaim.Incarnation("BAD", "shop", "alpha.shop.example.com", time.Time{}); !errors.Is(err, hostclaim.ErrMalformed) { |
| + t.Fatalf("hostclaim.Incarnation error = %v", err) |
| + } |
| +} |
diff --git a/internal/provision/plan14_input_inventory_test.go b/internal/provision/plan14_input_inventory_test.go| index ccc79ed5b..d13f3635e 100644 |
| --- a/internal/provision/plan14_input_inventory_test.go |
| +++ b/internal/provision/plan14_input_inventory_test.go |
| @@ -371,10 +371,11 @@ var inputExemptions = map[string]inputExemption{ |
| "internal/hostclaim/relocation.go:StartRelocation": {Ruling: "R-E2a"}, |
| "internal/hostrelocate/participant.go:Participant.Sweep": {Ruling: "R-E2a"}, |
| "internal/hostrelocate/worker.go:Worker.Start": {Ruling: "R-E2a"}, |
| - // This inventory stops at activation-tools, so seed's row outlives the |
| - // deleted function; the roster-binding overlay removes it from the full |
| - // census and declares servingPriorBinding at the same class. |
| - "internal/host/claimservinghandover.go:servingPriorRevision": {Ruling: "census-ruling-roster-binding: deleted, renamed servingPriorBinding (equality on the box binding), which takes over all its callers"}, |
| + // internal/host/claimservinghandover.go:servingPriorRevision was |
| + // exempt here (census-ruling-roster-binding: deleted, renamed |
| + // servingPriorBinding) because this inventory stops at activation-tools. |
| + // It is now retired (inputRetired): the full chain removed its row and |
| + // the tree no longer declares it. |
| } |
| // Update this checkpoint status when merging E's completion report. The 4a |
| @@ -445,6 +446,127 @@ func checkInputRow(e classifiedRootRead, callers map[string]string, tests map[st |
| return failures |
| } |
| +// inputRetired reports whether a row in J4's view has been retired since |
| +// (claims cleanup R0): the full census chain no longer carries it and the |
| +// tree no longer declares the unit. A row the chain removed whose unit is |
| +// still declared is not retired, so J4 keeps checking it. A retired row is |
| +// not caller-checked (its unit is gone); its family's witnesses stay |
| +// required while inputLiveFamilies still names the family. |
| +func inputRetired(full rootReadInventory, declared bool, key string) bool { |
| + _, carried := full.Entries[key] |
| + return !carried && !declared |
| +} |
| + |
| +// inputLiveFamilies is every family named by an authority row of the full |
| +// chain, after every overlay, that J4's scope covers (inputActivationEnabled) |
| +// and whose unit the tree still declares. A family's witnesses may go only |
| +// once it is not here (Astra review of R0, P1): a row only a later overlay |
| +// added keeps them required, though J4's caller check covers only its own |
| +// inventory, up to activation-tools. A row whose task list J4 cannot |
| +// parse is a failure, never a skip, and still keeps every family it does |
| +// name (Astra review of R0, round 2): the census accepts an authority row |
| +// with one recognized owner beside an unknown tag. |
| +func inputLiveFamilies(full rootReadInventory, declared func(key string) bool) (map[string]bool, []string) { |
| + live := map[string]bool{} |
| + var failures []string |
| + for key, e := range full.Entries { |
| + if e.Class != "authority" || !inputActivationEnabled(e) || !declared(key) { |
| + continue |
| + } |
| + families, err := inputFamilyFor(e) |
| + if err != nil { |
| + failures = append(failures, key+": "+err.Error()) |
| + for _, owner := range strings.Split(e.Task, ",") { |
| + if _, ok := inputFamilies[owner]; ok { |
| + live[owner] = true |
| + } |
| + } |
| + continue |
| + } |
| + for _, f := range families { |
| + live[f] = true |
| + } |
| + } |
| + return live, failures |
| +} |
| + |
| +// checkInputLiveWitnesses fails a live family with a witness slot that is |
| +// empty or names no test in the tree, as checkInputRow does for a row. |
| +func checkInputLiveWitnesses(live, tests map[string]bool) []string { |
| + var failures []string |
| + for name := range live { |
| + f := inputFamilies[name] |
| + for slot, test := range []string{f.Hostile, f.Rename, f.Erasure, f.Retry, f.Positive} { |
| + if test == "" || !tests[test] { |
| + failures = append(failures, "family "+name+" missing "+[]string{"hostile", "rename", "erasure", "retry", "positive"}[slot]+" fixture "+test) |
| + } |
| + } |
| + } |
| + return failures |
| +} |
| + |
| +// inputSurviving is the rows J4 checks: neither removed within its own |
| +// overlays nor retired since. |
| +func inputSurviving(inv rootReadInventory, retired func(key string) bool) map[string]classifiedRootRead { |
| + out := map[string]classifiedRootRead{} |
| + for key, e := range inv.Entries { |
| + if inv.Removed[key] != "" || retired(key) { |
| + continue |
| + } |
| + out[key] = e |
| + } |
| + return out |
| +} |
| + |
| +// checkInputRetiredExemptions fails an exemption whose unit is retired: it |
| +// goes with the unit, so it cannot waive a unit that later comes back. |
| +func checkInputRetiredExemptions(exemptions map[string]inputExemption, retired func(key string) bool) []string { |
| + var failures []string |
| + for key := range exemptions { |
| + if retired(key) { |
| + failures = append(failures, key+": exemption for a retired unit; delete it with the unit") |
| + } |
| + } |
| + return failures |
| +} |
| + |
| +// inputDeclared reports whether the tree still declares a census unit, |
| +// named as rootReadProduction names it: an external is its file; a Go unit |
| +// is a top-level declaration of its file (rootReadDeclName). Each file is |
| +// parsed once. |
| +func inputDeclared(root string) func(key string) (bool, error) { |
| + names := map[string]map[string]bool{} |
| + return func(key string) (bool, error) { |
| + file, unit, ok := strings.Cut(key, ":") |
| + if !ok { |
| + return false, fmt.Errorf("census key %q has no unit", key) |
| + } |
| + path := filepath.Join(root, filepath.FromSlash(file)) |
| + if _, err := os.Stat(path); os.IsNotExist(err) { |
| + return false, nil |
| + } else if err != nil { |
| + return false, err |
| + } |
| + if unit == "external" { |
| + return true, nil |
| + } |
| + if names[file] == nil { |
| + f, err := parser.ParseFile(token.NewFileSet(), path, nil, 0) |
| + if err != nil { |
| + return false, err |
| + } |
| + names[file] = map[string]bool{} |
| + grouped := map[string]int{} |
| + for _, decl := range f.Decls { |
| + if name, ok := rootReadDeclName(decl, grouped); ok { |
| + names[file][name] = true |
| + } |
| + } |
| + } |
| + return names[file][unit], nil |
| + } |
| +} |
| + |
| func TestPlan14RootInputInventoryCoverage(t *testing.T) { |
| // Reads the source tree and read-only package maps only, and spends |
| // most of its time type-checking the module, so it runs in parallel |
| @@ -460,12 +582,35 @@ func TestPlan14RootInputInventoryCoverage(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| + // This inventory stops at activation-tools; a unit deleted since, whose |
| + // row the full chain has removed, is retired (inputRetired). |
| + full, _ := rootReadChain(t, root) |
| + declared := inputDeclared(root) |
| + var declaredErr error |
| + retired := func(key string) bool { |
| + if _, carried := full.Entries[key]; carried { |
| + return false |
| + } |
| + d, err := declared(key) |
| + if err != nil { |
| + declaredErr = err |
| + return false |
| + } |
| + return inputRetired(full, d, key) |
| + } |
| failures := checkInputExemptions(inv, callers, inputExemptions, inputTrackEComplete) |
| - var report []string |
| - for key, e := range inv.Entries { |
| - if inv.Removed[key] != "" { |
| - continue |
| + failures = append(failures, checkInputRetiredExemptions(inputExemptions, retired)...) |
| + live, liveErrs := inputLiveFamilies(full, func(key string) bool { |
| + d, err := declared(key) |
| + if err != nil { |
| + declaredErr = err |
| } |
| + return d || err != nil |
| + }) |
| + failures = append(failures, liveErrs...) |
| + failures = append(failures, checkInputLiveWitnesses(live, tests)...) |
| + var report []string |
| + for _, e := range inputSurviving(inv, retired) { |
| failures = append(failures, checkInputRow(e, callers, tests)...) |
| if e.Class == "authority" { |
| family, familyErr := inputFamilyFor(e) |
| @@ -479,6 +624,9 @@ func TestPlan14RootInputInventoryCoverage(t *testing.T) { |
| report = append(report, fmt.Sprintf("%s\t%s\t%s\t%s\t%s\t%s", mode, e.File, e.Unit, strings.Join(family, "+"), callers[e.File+":"+e.Unit], e.Basis)) |
| } |
| } |
| + if declaredErr != nil { |
| + t.Fatal(declaredErr) |
| + } |
| sort.Strings(report) |
| for _, row := range report { |
| t.Log("J4\t" + row) |
diff --git a/internal/provision/plan14_root_reads_test.go b/internal/provision/plan14_root_reads_test.go| index 72cc46997..de6120c83 100644 |
| --- a/internal/provision/plan14_root_reads_test.go |
| +++ b/internal/provision/plan14_root_reads_test.go |
| @@ -28,6 +28,53 @@ type rootReadScan struct { |
| Entries []rootReadEntry |
| Coverage map[string]string |
| Fields []string |
| + // Dirs is every directory the scan walked, holding scanned source or |
| + // not, and Files every file it read. Root is the tree scanned, for the |
| + // Lstat proof in absent; an in-memory fixture leaves it empty. |
| + Dirs map[string]bool |
| + Files map[string]bool |
| + Root string |
| +} |
| + |
| +// absent reports whether the scan proves a path (slash-relative) gone: not |
| +// a walked directory or a read file, and, for a real tree, absent by Lstat |
| +// with no symlinked ancestor (rootReadPathAbsent). WalkDir does not follow |
| +// a directory symlink, so a walk alone cannot see a retired directory |
| +// brought back as one (Astra review of R0, P1). A scan with no directory |
| +// list proves nothing. |
| +func (s rootReadScan) absent(rel string) bool { |
| + if s.Dirs == nil || s.Dirs[rel] || s.Files[rel] { |
| + return false |
| + } |
| + return s.Root == "" || rootReadPathAbsent(s.Root, rel) |
| +} |
| + |
| +// rootReadPathAbsent walks rel's components below root by Lstat: absent |
| +// once a component does not exist, provided every component before it is |
| +// a real directory. A symlink, a file where a directory should be, an |
| +// Lstat error or a malformed path is not proof of absence. |
| +func rootReadPathAbsent(root, rel string) bool { |
| + if rel == "" || strings.HasPrefix(rel, "/") { |
| + return false |
| + } |
| + parts := strings.Split(rel, "/") |
| + p := root |
| + for _, part := range parts { |
| + if part == "" || part == "." || part == ".." { |
| + return false |
| + } |
| + } |
| + for _, part := range parts { |
| + p = filepath.Join(p, part) |
| + fi, err := os.Lstat(p) |
| + if os.IsNotExist(err) { |
| + return true |
| + } |
| + if err != nil || fi.Mode()&fs.ModeSymlink != 0 || !fi.IsDir() { |
| + return false |
| + } |
| + } |
| + return false |
| } |
| // Match names conservatively, including method values, aliases and writes. |
| @@ -159,7 +206,7 @@ func rootReadTyped(root string) (map[string]string, map[string]bool, error) { |
| } |
| func rootReadProduction(root string) (rootReadScan, error) { |
| - out := rootReadScan{Coverage: map[string]string{}, Declarations: map[string]string{}} |
| + out := rootReadScan{Coverage: map[string]string{}, Declarations: map[string]string{}, Dirs: map[string]bool{}, Files: map[string]bool{}, Root: root} |
| typed, active, err := rootReadTyped(root) |
| if err != nil { |
| return out, err |
| @@ -188,6 +235,11 @@ func rootReadProduction(root string) (rootReadScan, error) { |
| if p != root && (strings.HasPrefix(d.Name(), ".") || strings.HasPrefix(d.Name(), "_") || d.Name() == "testdata") { |
| return filepath.SkipDir |
| } |
| + rel, e := filepath.Rel(root, p) |
| + if e != nil { |
| + return e |
| + } |
| + out.Dirs[filepath.ToSlash(rel)] = true |
| return nil |
| } |
| if !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go") { |
| @@ -233,6 +285,10 @@ func rootReadProduction(root string) (rootReadScan, error) { |
| paths := make([]string, 0, len(files)) |
| for p := range files { |
| paths = append(paths, p) |
| + out.Files[p] = true |
| + } |
| + for p := range extra { |
| + out.Files[p] = true |
| } |
| sort.Strings(paths) |
| fields := map[string]bool{} |
| @@ -284,29 +340,8 @@ func rootReadProduction(root string) (rootReadScan, error) { |
| } |
| grouped := map[string]int{} |
| for _, decl := range f.Decls { |
| - var name string |
| - switch d := decl.(type) { |
| - case *ast.FuncDecl: |
| - name = d.Name.Name |
| - if d.Recv != nil { |
| - name = censusRecvName(d.Recv.List[0].Type) + "." + name |
| - } |
| - case *ast.GenDecl: |
| - if d.Tok == token.IMPORT { |
| - continue |
| - } |
| - if d.Lparen.IsValid() { |
| - grouped[d.Tok.String()]++ |
| - name = fmt.Sprintf("%s#%d", d.Tok, grouped[d.Tok.String()]) |
| - } else { |
| - switch s := d.Specs[0].(type) { |
| - case *ast.ValueSpec: |
| - name = d.Tok.String() + " " + s.Names[0].Name |
| - case *ast.TypeSpec: |
| - name = "type " + s.Name.Name |
| - } |
| - } |
| - default: |
| + name, ok := rootReadDeclName(decl, grouped) |
| + if !ok { |
| continue |
| } |
| start, end := fset.Position(decl.Pos()).Offset, fset.Position(decl.End()).Offset |
| @@ -382,6 +417,39 @@ func rootReadProduction(root string) (rootReadScan, error) { |
| return out, nil |
| } |
| +// rootReadDeclName names a top-level declaration as the census keys it: |
| +// a func or method ("T.M"), "type T", "var x" or "const x", or "var#N" for |
| +// the Nth grouped declaration of its token in the file (grouped counts |
| +// them). Imports and anything else are not units. |
| +func rootReadDeclName(decl ast.Decl, grouped map[string]int) (string, bool) { |
| + var name string |
| + switch d := decl.(type) { |
| + case *ast.FuncDecl: |
| + name = d.Name.Name |
| + if d.Recv != nil { |
| + name = censusRecvName(d.Recv.List[0].Type) + "." + name |
| + } |
| + case *ast.GenDecl: |
| + if d.Tok == token.IMPORT { |
| + return "", false |
| + } |
| + if d.Lparen.IsValid() { |
| + grouped[d.Tok.String()]++ |
| + name = fmt.Sprintf("%s#%d", d.Tok, grouped[d.Tok.String()]) |
| + } else { |
| + switch s := d.Specs[0].(type) { |
| + case *ast.ValueSpec: |
| + name = d.Tok.String() + " " + s.Names[0].Name |
| + case *ast.TypeSpec: |
| + name = "type " + s.Name.Name |
| + } |
| + } |
| + default: |
| + return "", false |
| + } |
| + return name, true |
| +} |
| + |
| type classifiedRootRead struct { |
| rootReadEntry |
| Class, Task, Basis string |
| @@ -392,8 +460,11 @@ type rootReadInventory struct { |
| Removed map[string]string |
| Entries map[string]classifiedRootRead |
| Coverage map[string]string |
| - Fields string |
| - Legacy map[string]bool |
| + // Retired is every envelope a "@coverage <dir> -" retired: its |
| + // directory must stay out of the tree. |
| + Retired map[string]bool |
| + Fields string |
| + Legacy map[string]bool |
| } |
| func loadRootReadInventory(path string, inv *rootReadInventory, delta bool) error { |
| @@ -461,7 +532,24 @@ func loadRootReadInventory(path string, inv *rootReadInventory, delta bool) erro |
| return fmt.Errorf("%s:%d: coverage", path, i+1) |
| } |
| key = "@coverage:" + col[1] |
| + if col[2] == "-" { |
| + // A retired envelope (claims cleanup R0): the directory is |
| + // gone, which compareRootReads checks against the scan. |
| + if !delta { |
| + return fmt.Errorf("%s:%d: an envelope is retired only by an overlay", path, i+1) |
| + } |
| + if _, ok := inv.Coverage[col[1]]; !ok { |
| + return fmt.Errorf("%s:%d: retirement of unknown envelope %s", path, i+1, col[1]) |
| + } |
| + delete(inv.Coverage, col[1]) |
| + if inv.Retired == nil { |
| + inv.Retired = map[string]bool{} |
| + } |
| + inv.Retired[col[1]] = true |
| + break |
| + } |
| inv.Coverage[col[1]] = col[2] |
| + delete(inv.Retired, col[1]) |
| case "@remove": |
| if !delta || len(col) != 3 { |
| return fmt.Errorf("%s:%d: removal", path, i+1) |
| @@ -577,6 +665,12 @@ func compareRootReads(got rootReadScan, want rootReadInventory) []string { |
| errs = append(errs, "stale root source envelope "+dir) |
| } |
| } |
| + // The directory must stay absent by Lstat, symlinks included. |
| + for dir := range want.Retired { |
| + if !got.absent(dir) { |
| + errs = append(errs, "retired root source envelope still present "+dir) |
| + } |
| + } |
| if strings.Join(got.Fields, ",") != want.Fields { |
| errs = append(errs, "changed registry schema") |
| } |
| @@ -1658,7 +1752,9 @@ func checkRootReadDeclarations(scan rootReadScan, inv rootReadInventory) []strin |
| // Census ruling zddr3: an H3 census-ruling removal may retire a |
| // unit that is still declared only when this scan finds no read in |
| // it. The basis text is never evidence; the scan is. |
| - retired := exists && strings.HasPrefix(removal, "H3;census-ruling-") && !rootReadScanned(scan, key) |
| + // A removal census-propose wrote for a deleted unit holds only |
| + // while the declaration stays gone (claims cleanup R0). |
| + retired := exists && strings.HasPrefix(removal, "H3;census-ruling-") && !rootReadScanned(scan, key) && !rootReadAbsentRemoval(removal) |
| if (exists && !retired) || classified { |
| errs = append(errs, "removed legacy declaration still present "+key) |
| } |
diff --git a/internal/provision/plans6a_census_test.go b/internal/provision/plans6a_census_test.go| index cd33d61dc..d672b860b 100644 |
| --- a/internal/provision/plans6a_census_test.go |
| +++ b/internal/provision/plans6a_census_test.go |
| @@ -1,7 +1,7 @@ |
| package provision |
| // Record-write census entries for plans 6a (billing sync), layered on |
| -// edgeProtection2WriteCensusInventory (main's newest at the merge of origin/main 96564cf3). |
| +// claimsCleanupR1WriteCensusInventory (main's newest at the merge of origin/main cb23eb51). |
| // Three key sites change body only; none gains a record write: |
| // - Server.registerCLIRoutes (with main's #164 gate-pass route) registers |
| // two operator billing doors |
| @@ -15,7 +15,7 @@ package provision |
| // |
| // Their literals are unchanged (lit:instances, lit:sidecars). |
| func plans6aWriteCensusInventory() []censusEntry { |
| - entries := append([]censusEntry(nil), edgeProtection2WriteCensusInventory()...) |
| + entries := append([]censusEntry(nil), claimsCleanupR1WriteCensusInventory()...) |
| replacements := []censusEntry{ |
| {"main.go", "main", "key-site", "lit:instances,lit:sidecars", "e639a4e3d3120c901661d4bcd2da4c956a5aaf0f7f6058d67e4ce7636edf7f89"}, |
| {"internal/console/authcli.go", "Server.registerCLIRoutes", "key-site", "lit:instances,lit:sidecars", "6dfc9d7a9383d6505fb0532daef0378d28e59c16be59245b4b22181b490545f4"}, |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index e47c5b762..595f39321 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -42,5 +42,7 @@ plan14-root-reads-rootfs-apps-2-new.tsv b9e0e5339dee58e5851774f049ae6096f5b7617d |
| plan14-root-reads-rootfs-apps-2.tsv b1b17467ff148c3a0b1dd3312b7a80498db11cc4b455e2331c6b0da2e369e2ee |
| plan14-root-reads-edge-protection-2-decisions.tsv 7d90eff62dcb3d2d211b9f0fa37ba1967f1f418884a11c1476cdaa50b187efd5 |
| plan14-root-reads-edge-protection-2.tsv a864cf31b6bf2c30b5aa8c2647835efdc456f34f4945eea12751daab2457728e |
| -plan14-root-reads-plans-6a-units.tsv 61c5a2d77fa39607d7ce7224a8914c3bed2de78ad38819ef4ff1665bb6d8848f |
| -plan14-root-reads-plans-6-checkout.tsv ec611e77887f625ca08877e6f1457cbf904b9efac0964172f0e162ff49c8f824 |
| +plan14-root-reads-offline-move-trim-t1.tsv a864cf31b6bf2c30b5aa8c2647835efdc456f34f4945eea12751daab2457728e |
| +plan14-root-reads-claims-cleanup-r1.tsv 9cef5e93a1e3520e02efe66455bf70c1170d380b6d6a72ede02036ce3dd41924 |
| +plan14-root-reads-plans-6a-units.tsv 9b27c8b855ca32a3f12119da92a7571542d2b0c4be4f3383e2ac482323b60ca8 |
| +plan14-root-reads-plans-6-checkout.tsv c6a920b27d3206e85ac923b308bdf287931954776681732937f7445dd88ec11b |
diff --git a/internal/provision/testdata/plan14-root-reads-claims-cleanup-r1.tsv b/internal/provision/testdata/plan14-root-reads-claims-cleanup-r1.tsv| new file mode 100644 |
| index 000000000..1c82ae095 |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-claims-cleanup-r1.tsv |
| @@ -0,0 +1,16 @@ |
| +# Census overlay claims-cleanup-r1, written by census-propose (#369). census-ruling-claims-cleanup-r1, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-claims-cleanup-r1.md. |
| +# 3 body, 0 sites, 9 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +@legacy 00d2e505f623cf6cebd25ed2c8d71bd5721ad7b7c7ade9d0be49b10f71c0470b internal/console/apiinstancemove_offline.go Server.offlineClaimEvidence legacy accepted-legacy accepted-legacy;rev3=census-ruling-moves-offline;basis=root-input (J4, as main's moves units); the console (cmd/console serve under console.service, user carlos-console): new, reads the host claim, the record's acquisition, a domains claim and the app's admission only to refuse an offline start (MV-O29, MV-O20); a failed read refuses with a 502, never reads as absence; deny-only;rev3=census-ruling-claims-cleanup-r1;basis=claims cleanup R1: the admission and backfill reads use the console's own keys and a local copy of hostops.BackfillPlan (same store Gets, same refusals) instead of hostops.AdmissionKey and CheckCreateFreeze; the host claim is still read through hostclaim.Read; no read added, the one scanned read (hostclaim.Read) unchanged file:Read@645 b9c29234b8db391f37db8b898901a0380b94ff0941e24b9d8ba240f530a79390 |
| +@legacy c7c644f83c1376f5dc136a13ba4009e8178325b5b2dac71c6ff6485d97385054 internal/console/apiruns.go Server.handleAPIRunCreate legacy accepted-legacy accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=the console (cmd/console serve under console.service, user carlos-console): the run create door reads the record, and rereads it after an unknown admit, through readRecord, judged under a unit admitted on and unjudged before; read sites unchanged, offsets moved;rev3=census-ruling-claims-cleanup-r1;basis=claims cleanup R1: the request's incarnation comes from provision.Incarnation, hostclaim.Incarnation's body moved unchanged (golden vectors); no read added or changed file:Open@2086 a45e07833e363d6c7563bd3263f400b79873a839e51cda286c9d712053dde273 |
| +internal/console/apiinstancemove_offline.go Server.offlineClaimEvidence legacy accepted-legacy accepted-legacy;rev3=census-ruling-moves-offline;basis=root-input (J4, as main's moves units); the console (cmd/console serve under console.service, user carlos-console): new, reads the host claim, the record's acquisition, a domains claim and the app's admission only to refuse an offline start (MV-O29, MV-O20); a failed read refuses with a 502, never reads as absence; deny-only;rev3=census-ruling-claims-cleanup-r1;basis=claims cleanup R1: the admission and backfill reads use the console's own keys and a local copy of hostops.BackfillPlan (same store Gets, same refusals) instead of hostops.AdmissionKey and CheckCreateFreeze; the host claim is still read through hostclaim.Read; no read added, the one scanned read (hostclaim.Read) unchanged file:Read@645 b9c29234b8db391f37db8b898901a0380b94ff0941e24b9d8ba240f530a79390 |
| +internal/console/apiruns.go Server.handleAPIRunCreate legacy accepted-legacy accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=the console (cmd/console serve under console.service, user carlos-console): the run create door reads the record, and rereads it after an unknown admit, through readRecord, judged under a unit admitted on and unjudged before; read sites unchanged, offsets moved;rev3=census-ruling-claims-cleanup-r1;basis=claims cleanup R1: the request's incarnation comes from provision.Incarnation, hostclaim.Incarnation's body moved unchanged (golden vectors); no read added or changed file:Open@2086 a45e07833e363d6c7563bd3263f400b79873a839e51cda286c9d712053dde273 |
| +internal/host/agent.go runAdoptUnderRootRelease authority B3,E1,E2,E3 rev3=census-ruling-self-serve-moves-1;basis=root claim/adopt/update controller uid 0: builds root's lifetime judge once from the host-claim switch and hands it to both productionRestartRequestPass calls; read sites unchanged, offsets moved; the preceding B3,E1,E2,E3 classification retained;rev3=census-ruling-claims-cleanup-r1;basis=claims cleanup R1: the claims shutdown timeout is the host constant claimsShutdownLimit (120s) instead of hostbox.RequestLimit (120s); no read added or changed whole:Route@11242,whole:Route@18538,whole:Route@18574,whole:Route@8533 1916559ef754fc27b761d2d489a4b34e1870ce050e6d00352788672209e67162 |
| +@coverage internal/console cce9d2eb49af5fcbcfde38c0c6f6d151cb9165bb846478fe5869f44acb8cfa64 |
| +@coverage internal/dbreads 3435a8265f4d16964920439675e1c2f982e5424c8d41248f009f643214d59ddc |
| +@coverage internal/host bb6ea03949a8e370305881229c70fc811c4ce6c6dd5710571e0ca4d396f1f7a1 |
| +@coverage internal/hostclaim 821d6bddd4d98009253602e5f2515b4ad077d6b694308fd7a718f688d227f21e |
| +@coverage internal/instancectl b73cb1ce1f6540bb232d737a6f429147c40bb62eda90b80b4930a0c1d0954cc1 |
| +@coverage internal/park 778a86513bc64068b93e257c09972fbc307ebe401a125a61003f3ad26a28f611 |
| +@coverage internal/provision f444c473b07f7497f3e294503c3d0f8f98e9d7377856d69ae2ecae7f71fc12d8 |
| +@coverage internal/regionname 5815be8b9d786cdf646ae30a3d23350096c3f0bd8200859067db2038affc68e6 |
| +@coverage internal/runs 0b7c525299df1f91b42dbcfb62f8a660ab4cb4256f849d7302dbe9d39b0925be |
diff --git a/internal/provision/testdata/plan14-root-reads-offline-move-trim-t1.tsv b/internal/provision/testdata/plan14-root-reads-offline-move-trim-t1.tsv| new file mode 100644 |
| index 000000000..3926a1ae1 |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-offline-move-trim-t1.tsv |
| @@ -0,0 +1,3 @@ |
| +# Census overlay offline-move-trim-t1, written by census-propose (#369). census-ruling-offline-move-trim-t1, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-offline-move-trim-t1.md. |
| +# 0 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +@coverage internal/activator e6134c33ab40c8528b1e01b35f4c923be76ea22cf79efc7ccb120a7524e98aca |
diff --git a/internal/provision/testdata/plan14-root-reads-plans-6-checkout.tsv b/internal/provision/testdata/plan14-root-reads-plans-6-checkout.tsv| index 841006aea..de12b367b 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-plans-6-checkout.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-plans-6-checkout.tsv |
| @@ -18,5 +18,5 @@ internal/console/store.go Store.migrate legacy accepted-legacy accepted-legacy;r |
| @coverage internal/billing 6f70b1b5235eeff6a4f6e6debf29128379946b810c03996a75a2779a4f036bbd |
| @coverage internal/billing/billingtest d2b79226ca223d73c35e4e58b0da1ec50a2765e1358a019319e79c3220a8274b |
| @coverage internal/billingstripe ea8f4e2a16003884007bc9579ccc3f5633180af974236f6dc5119c42b2e4d1e3 |
| -@coverage internal/console b49081c62bee8384032721bcd66e592c25ba99ab2f3ea833983cc50b8ab33218 |
| +@coverage internal/console 31dc9d4599eac5082338620b6f3ce0ef8f69acdd09cd71887edd6a6a94d89511 |
| @coverage internal/plans 74d41bf58428aa03367a66ea3e4e9f190285ffb4a563f8791b71ad011a57f7ea |
diff --git a/internal/provision/testdata/plan14-root-reads-plans-6a-units.tsv b/internal/provision/testdata/plan14-root-reads-plans-6a-units.tsv| index 0275ddb7f..846cdbec3 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-plans-6a-units.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-plans-6a-units.tsv |
| @@ -1,4 +1,4 @@ |
| -# Census overlay plans-6a-units, written by hand: 23 new units of plans 6a billing (console SQL on its own billing tables, account_plans and plan_cap_state, the billing webhook body, the Stripe client response body, and the price book file), a decision. census-ruling-plans-6a-units; the card is docs/superpowers/notes/census-proposal-plans-6-checkout.md. Regenerated after Astra round 3 (2026-10-25): migrateBillingAccounts changed (discover_failures), SetBillingDiscoveryRetry replaced by MarkBillingDiscovery and EndBillingDiscovery. |
| +# Census overlay plans-6a-units, written by hand: 23 new units of plans 6a billing (console SQL on its own billing tables, account_plans and plan_cap_state, the billing webhook body, the Stripe client response body, and the price book file), a decision. census-ruling-plans-6a-units; the card is docs/superpowers/notes/census-proposal-plans-6-checkout.md. Regenerated after Astra round 4 (2026-10-26): EndBillingDiscovery changed (one transaction with the problem resolve). |
| @legacy 058848562e19e53835d838c5b4ddde13c8da81fae081e57cbd4eae204af25fe0 internal/billingstripe/client.go Client.do legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-6a-units;basis=the console (cmd/console serve under console.service, user carlos-console), billing only (CARLOS_BILLING test or live): reads one Stripe API response body into memory, bounded to 1 MiB (io.ReadAll of an io.LimitReader); no filesystem read; requests go only to the configured base URL (api.stripe.com) with redirects refused; plans 6a file:ReadAll@1372 81ecef4a9ff10808f4ac61a07b770c16140feb4662fa2590fdef59adf1660d0f |
| @legacy 402179ec120bbe10184783ec7ff2f597ee13422c790edb73df9969d57a7e2f2e internal/console/accountplans.go billingSetPlan legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-6a-units;basis=root-input; console SQL on its own account_plans table, as Store.SetAccountPlan (J4): the same upsert statement (accountPlanUpsertSQL) run inside setBillingPlanTx's transaction with source billing; reached only through Server.applyBillingPlan, Plan 4d's shared plan transition; plans 6a file:QueryRow@287 a61887543cf2597f94f6a2cc653f2ae1411fad05f2f72f7f03951aab76fa6a7a |
| @legacy 8bd238d3a0be33a386551295d869663caf3bac9c8d563c04ba84cd68432958aa internal/console/accountplans.go setBillingPlanTx legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-6a-units;basis=root-input; console SQL on its own account_plans table, as its store siblings (J4): inside Store.SaveBillingSync's transaction reads the account and its plan row and writes only a row billing owns (source default or billing) when plan, packs or source change, through billingSetPlan; plans 6a file:QueryRow@259,file:QueryRow@508 2d92b3315668316e8542d93265e0b4486e68a65f5a2f9520f12e4b7a6990eb7a |
| @@ -7,7 +7,7 @@ |
| @legacy d75a9b858f9af7957967d283480b8a403954582a7c29b7f3b816e2249de7bed4 internal/console/billingstore.go Store.BillingProblems legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-6a-units;basis=root-input; console SQL on its own billing tables (billing_price_books, billing_accounts, billing_problems), as its store siblings (J4); plans 6a billing, dormant unless CARLOS_BILLING is set file:Query@215 d11e44fcf7e2104a94224603eccd98bcabcb362b542ad0e82096aa4ddf8ed7be |
| @legacy fd3375ab332dd7f196f0dacdfb26bc99d324b9d33cf05de0f15478a14005f9b9 internal/console/billingstore.go Store.CloseBillingProblem legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-6a-units;basis=root-input; console SQL on its own billing tables (billing_price_books, billing_accounts, billing_problems), as its store siblings (J4); plans 6a billing, dormant unless CARLOS_BILLING is set file:Exec@99 e7dde269b31cab46f2c0a4d2ca85341ccb6687f73fa8ca397b7a695b234c8e06 |
| @legacy 056a55171d436c9ee748b3e3894d4c7dcd6c460e0425bb78be968e1d7d8f31ba internal/console/billingstore.go Store.DiscoverableBillingAccounts legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-6a-units;basis=root-input; console SQL on its own billing tables (billing_price_books, billing_accounts, billing_problems), as its store siblings (J4); plans 6a billing, dormant unless CARLOS_BILLING is set file:Query@141 fbe66c8e73dd905a8a2a9ce98d05a93919919c52728308bd88bb0ee0fe472011 |
| -@legacy 59c8a5afd96fd178545cde780c1f3e8e187ca9285e66410f7c7b9e58bf58400d internal/console/billingstore.go Store.EndBillingDiscovery legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-6a-units;basis=root-input; console SQL on its own billing_accounts table, as its store siblings (J4): after one discovery pass, clears the account's marker and failure count, or increments and returns the count (Astra round 3); plans 6a file:Exec@107,file:QueryRow@260 d3a037eac2ad589e89ada56ee4974337318714bb2f4079e0986ed41f3bd4eefc |
| +@legacy b0dbffb9df021800ab1497a9cedd52bd766b95fb7652095b49398eb7d1ba3ee2 internal/console/billingstore.go Store.EndBillingDiscovery legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-6a-units;basis=root-input; console SQL on its own billing_accounts and billing_problems tables, as its store siblings (J4): after one discovery pass, either clears the account's marker and failure count and resolves its discovery_failing problem in one transaction (Astra round 4), or increments and returns the count; plans 6a file:Exec@212,file:Exec@375,file:QueryRow@698 afdfcda752a6bf51a793ec7bd38a6c31813b9ae8cec409eb61d772c3d5e566c7 |
| @legacy 5d55fae504cedcacbcb41da161f44cc288b97788ef75cc187f321affb395babb internal/console/billingstore.go Store.LiveBillingAccounts legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-6a-units;basis=root-input; console SQL on its own billing tables (billing_price_books, billing_accounts, billing_problems), as its store siblings (J4); plans 6a billing, dormant unless CARLOS_BILLING is set file:Query@111 3e48b56b487ce954544f28878d473e2f436681b654edffac01aa17d328a9c760 |
| @legacy 574c0c704cbe837c35e2b62921cb7b518d965f5f077b144fcadb2d04c2b0888f internal/console/billingstore.go Store.MarkBillingDiscovery legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-6a-units;basis=root-input; console SQL on its own billing_accounts table, as its store siblings (J4): sets one account's discover_retry marker before discovery syncs any candidate (Astra round 3); plans 6a file:Exec@73 eecd7c29f09ce5f094ecf3ddf4dc93257440564c88ea9d460280ab4122c15493 |
| @legacy 0a011a4e53352482026d67d5deffe6f3a00a5dd7e3527aca24491a8d58a5714b internal/console/billingstore.go Store.NotePriceBook legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-6a-units;basis=root-input; console SQL on its own billing tables (billing_price_books, billing_accounts, billing_problems), as its store siblings (J4); plans 6a billing, dormant unless CARLOS_BILLING is set file:Exec@99,file:QueryRow@329 3cf8826e10d32cc760bfe9226094859534661cfeb5412764c1f0bd056ac926ce |
| @@ -30,7 +30,7 @@ internal/console/billingstore.go Store.BillingProblem legacy accepted-legacy acc |
| internal/console/billingstore.go Store.BillingProblems legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-6a-units;basis=root-input; console SQL on its own billing tables (billing_price_books, billing_accounts, billing_problems), as its store siblings (J4); plans 6a billing, dormant unless CARLOS_BILLING is set file:Query@215 d11e44fcf7e2104a94224603eccd98bcabcb362b542ad0e82096aa4ddf8ed7be |
| internal/console/billingstore.go Store.CloseBillingProblem legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-6a-units;basis=root-input; console SQL on its own billing tables (billing_price_books, billing_accounts, billing_problems), as its store siblings (J4); plans 6a billing, dormant unless CARLOS_BILLING is set file:Exec@99 e7dde269b31cab46f2c0a4d2ca85341ccb6687f73fa8ca397b7a695b234c8e06 |
| internal/console/billingstore.go Store.DiscoverableBillingAccounts legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-6a-units;basis=root-input; console SQL on its own billing tables (billing_price_books, billing_accounts, billing_problems), as its store siblings (J4); plans 6a billing, dormant unless CARLOS_BILLING is set file:Query@141 fbe66c8e73dd905a8a2a9ce98d05a93919919c52728308bd88bb0ee0fe472011 |
| -internal/console/billingstore.go Store.EndBillingDiscovery legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-6a-units;basis=root-input; console SQL on its own billing_accounts table, as its store siblings (J4): after one discovery pass, clears the account's marker and failure count, or increments and returns the count (Astra round 3); plans 6a file:Exec@107,file:QueryRow@260 d3a037eac2ad589e89ada56ee4974337318714bb2f4079e0986ed41f3bd4eefc |
| +internal/console/billingstore.go Store.EndBillingDiscovery legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-6a-units;basis=root-input; console SQL on its own billing_accounts and billing_problems tables, as its store siblings (J4): after one discovery pass, either clears the account's marker and failure count and resolves its discovery_failing problem in one transaction (Astra round 4), or increments and returns the count; plans 6a file:Exec@212,file:Exec@375,file:QueryRow@698 afdfcda752a6bf51a793ec7bd38a6c31813b9ae8cec409eb61d772c3d5e566c7 |
| internal/console/billingstore.go Store.LiveBillingAccounts legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-6a-units;basis=root-input; console SQL on its own billing tables (billing_price_books, billing_accounts, billing_problems), as its store siblings (J4); plans 6a billing, dormant unless CARLOS_BILLING is set file:Query@111 3e48b56b487ce954544f28878d473e2f436681b654edffac01aa17d328a9c760 |
| internal/console/billingstore.go Store.MarkBillingDiscovery legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-6a-units;basis=root-input; console SQL on its own billing_accounts table, as its store siblings (J4): sets one account's discover_retry marker before discovery syncs any candidate (Astra round 3); plans 6a file:Exec@73 eecd7c29f09ce5f094ecf3ddf4dc93257440564c88ea9d460280ab4122c15493 |
| internal/console/billingstore.go Store.NotePriceBook legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-6a-units;basis=root-input; console SQL on its own billing tables (billing_price_books, billing_accounts, billing_problems), as its store siblings (J4); plans 6a billing, dormant unless CARLOS_BILLING is set file:Exec@99,file:QueryRow@329 3cf8826e10d32cc760bfe9226094859534661cfeb5412764c1f0bd056ac926ce |
diff --git a/internal/regionname/region.go b/internal/regionname/region.go| index d56e208f8..ad7fa7691 100644 |
| --- a/internal/regionname/region.go |
| +++ b/internal/regionname/region.go |
| @@ -56,3 +56,11 @@ func SameRegion(home, a, b string) bool { |
| return home != "" && PlacementRegion(home) == home && |
| ((a == home && b == HomeRegion) || (a == HomeRegion && b == home)) |
| } |
| + |
| +// PlacementMatches compares a record's placement code with a nonempty |
| +// engine identity under the verified home binding: the home's "" and its |
| +// roster name are one region. The console's doors and the box's offline |
| +// move round use it (it moved here from park in claims cleanup R1). |
| +func PlacementMatches(home, code, engine string) bool { |
| + return SameRegion(home, PlacementRegion(code), engine) |
| +} |
diff --git a/internal/regionname/region_golden_test.go b/internal/regionname/region_golden_test.go| new file mode 100644 |
| index 000000000..03d57825a |
| --- /dev/null |
| +++ b/internal/regionname/region_golden_test.go |
| @@ -0,0 +1,80 @@ |
| +package regionname_test |
| + |
| +import ( |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "fmt" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/park" |
| + "github.com/carlosframework/platform/internal/regionname" |
| +) |
| + |
| +// The placement rules the console's create, regions and move doors and the |
| +// box's offline move round share (claims cleanup R1 moved the callers off |
| +// park). placementTable renders every rule over every combination of these |
| +// inputs; its digest is pinned, and a few rows are pinned outright so a |
| +// failure says which rule moved. |
| +var placementHomes = []string{"", "ie", "@home", "Bad"} |
| +var placementCodes = []string{"", "ie", "uk", "@home", "home", "Bad", "a-1", "abcdefghijklmnopq"} |
| + |
| +type placementRules struct { |
| + region func(string) string |
| + code func(string, string) string |
| + same func(string, string, string) bool |
| + matches func(string, string, string) bool |
| +} |
| + |
| +var placementImpls = map[string]placementRules{ |
| + "regionname": {regionname.PlacementRegion, regionname.HomePlacementCode, regionname.SameRegion, regionname.PlacementMatches}, |
| + // park's delegates, until claims cleanup deletes park. |
| + "park": {park.PlacementRegion, park.HomePlacementCode, park.SameRegion, park.PlacementMatches}, |
| +} |
| + |
| +func placementTable(r placementRules) string { |
| + var b strings.Builder |
| + for _, c := range placementCodes { |
| + fmt.Fprintf(&b, "PR %q=%q\n", c, r.region(c)) |
| + } |
| + for _, h := range placementHomes { |
| + for _, c := range placementCodes { |
| + fmt.Fprintf(&b, "HPC %q %q=%q\n", h, c, r.code(h, c)) |
| + for _, e := range placementCodes { |
| + fmt.Fprintf(&b, "SR %q %q %q=%v PM=%v\n", h, c, e, r.same(h, c, e), r.matches(h, c, e)) |
| + } |
| + } |
| + } |
| + return b.String() |
| +} |
| + |
| +const placementTableDigest = "c47389f9e56f7a07d074d825372bcf9fe858614fd52c28c4fd806cd73f922500" |
| + |
| +func TestPlacementGoldenVectors(t *testing.T) { |
| + for name, r := range placementImpls { |
| + sum := sha256.Sum256([]byte(placementTable(r))) |
| + if got := hex.EncodeToString(sum[:]); got != placementTableDigest { |
| + t.Errorf("%s: placement table digest = %s, want %s", name, got, placementTableDigest) |
| + } |
| + for _, v := range []struct { |
| + got, want string |
| + }{ |
| + {r.region(""), "@home"}, {r.region("ie"), "ie"}, {r.region("@home"), ""}, {r.region("Bad"), ""}, {r.region("abcdefghijklmnopq"), ""}, |
| + {r.code("ie", "ie"), ""}, {r.code("ie", "uk"), "uk"}, {r.code("", "ie"), "ie"}, {r.code("ie", ""), ""}, |
| + } { |
| + if v.got != v.want { |
| + t.Errorf("%s: got %q, want %q", name, v.got, v.want) |
| + } |
| + } |
| + for _, v := range []struct { |
| + got, want bool |
| + }{ |
| + {r.same("ie", "ie", "@home"), true}, {r.same("", "ie", "@home"), false}, {r.same("ie", "", ""), false}, {r.same("@home", "@home", "@home"), true}, |
| + {r.matches("ie", "", "ie"), true}, {r.matches("ie", "", "@home"), true}, {r.matches("", "", "ie"), false}, {r.matches("ie", "uk", "uk"), true}, {r.matches("ie", "Bad", "Bad"), false}, |
| + } { |
| + if v.got != v.want { |
| + t.Errorf("%s: got %v, want %v", name, v.got, v.want) |
| + } |
| + } |
| + } |
| +} |
diff --git a/internal/runs/runs.go b/internal/runs/runs.go| index 227df8a47..a93e065e7 100644 |
| --- a/internal/runs/runs.go |
| +++ b/internal/runs/runs.go |
| @@ -170,7 +170,7 @@ type File struct { |
| } |
| // Request is runs/<id>/request.json (run spec §5.1). Incarnation is the |
| -// record's (hostclaim.Incarnation of account, app, host and CreatedAt). |
| +// record's (provision.Incarnation of account, app, host and CreatedAt). |
| type Request struct { |
| Schema int `json:"schema"` |
| ID string `json:"id"` |