carlos / platform Public

Merge origin/main into stateless-replicas-2-placement

Resolve the census chain conflict by keeping origin/main in order and
placing the stateless overlay last after region-ha-followups.
Re-seal as d28a31401c32770cc079014e82ae49197abb3815b384a77dc4fc8d00f73ed8c6.
Co-Authored-By: Codex (gpt-6-astra) <noreply@openai.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev e9cd5fc752037804690ac8fa0a002b2a4252663f parent 35f932bparent f18da98
27 files changed, +1,013 −26
  • docs/region-ha-runbook.md +55 −0
  • docs/superpowers/notes/census-proposal-region-ha-followups.md +29 −0
  • docs/superpowers/notes/census-proposal-stateless-replicas-2.md +1 −1
  • docs/superpowers/notes/census-region-ha-followups-claims.md +6 −0
  • docs/superpowers/notes/region-ha-followups-p3.md +21 −0
  • internal/activator/backend_exec.go +2 −0
  • internal/activator/haadopt.go +11 −3
  • internal/activator/haplacement_test.go +35 −0
  • internal/activator/hatakeover.go +35 −1
  • internal/activator/hatakeover_page_test.go +60 −0
  • internal/activator/termination_proof_test.go +2 −2
  • internal/edge/forwardha.go +48 −2
  • internal/edge/forwardha_export_test.go +132 −4
  • internal/edge/forwardha_test.go +22 −0
  • internal/edge/haplacement_wiring_test.go +211 −1
  • internal/host/hadeparture_identity.go +20 −1
  • internal/host/hadepartures_page_followups_test.go +161 −0
  • internal/host/hadepartures_proof_followups_test.go +116 −0
  • internal/host/hadepartures_retained_test.go +3 −3
  • internal/host/hadepartures_scan.go +14 −3
  • internal/host/hadepartures_wiring.go +1 −0
  • internal/lease/termination_proof.go +1 −1
  • internal/lease/termination_proof_test.go +1 −1
  • internal/provision/testdata/plan14-root-reads-chain.tsv +2 −1
  • internal/provision/testdata/plan14-root-reads-region-ha-followups.tsv +19 −0
  • internal/provision/testdata/plan14-root-reads-stateless-replicas-2.tsv +2 −2
  • internal/termfence/termination_proof.go +3 −0

CI passed — run details

Intent

Human

<task-notification> <task-id>bwtu0hj1t</task-id> <tool-use-id>toolu_01WvLCKxYWZK9N8ssY5AjDUd</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/7c5a7d70-0e28-42b9-896c-5d73b2d2a05d/tasks/bwtu0hj1t.output</output-file> <status>completed</status> <summary>Background command "Wait for the second main merge" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>aa4d99c645ccdf748</task-id> <tool-use-id>toolu_015myENFr7u4Yb9uFLLoQd9R</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/7c5a7d70-0e28-42b9-896c-5d73b2d2a05d/tasks/aa4d99c645ccdf748.output</output-file> <status>completed</status> <summary>Agent "Review merge 2 resolution" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>### Findings **Critical:** none. **Important:** none. **Minor** - `internal/registry/registry.go:4298-4306`: the comment on `snapshotWhenSetCols` keeps the branch's wording plus "and demo identity strings". Main's rewritten wording ("Default values digest exactly as before these columns existed…") was dropped. The meaning survives in the branch text, so this is documentation only. Fix: optional. - `internal/activator/wakeidentity.go:112-115`: in `leaseRouteChanged`, the replica-field case now comes before main's demo-descriptor case. A row whose replica and demo fields both change returns the bare `errRouteChangedUnderLease` rather than main's demo message. That can only happen on a mixed row, which is refused anyway. Fix: none needed. - `internal/console/appcopies.go:128-135`: for counts above one, `copiesRefusal` now also runs `demoMutationRefusal`, which reads the store (`AppLife`). If that read fails, the caller gets a 503 DEMO-CHECK-FAILED. It never runs at count 1, so apps that don't use copies are unaffected. Fix: none needed. ### Checked and clean Method: I took each side's `-U0` changed lines (from merge base `0b3098cb` to each parent) and compared them against the merge's diff from the other parent, for all 22 files both sides touched. - **No differences at all (0/0):** `activator/activator.go`, `console/apicli.go`, `apiinstanceseed.go`, `apiinstances.go`, `authcli.go`, `fleetbox.go`, `fleetrelabel.go`, `fleets.go`, `lifetimes_create.go`, `server.go`, `recordcreators_guard_test.go`, `host/agent.go`, `registry/forward.go`. - **`activator/wakeidentity.go`:** both lease fences are kept. The demo record check now runs before the replica block, and the replica block also refuses demo routes and records. For a demo route (no `FleetBoxes`, no assignment), the path from lease to single-box recheck matches main exactly. - **`activator/activator.go` (unchanged against both sides):** the branch's `FleetBoxes != "" → ErrFenced` check runs before `Acquire` and only fires when a set is present, so it never touches demo wakes. Main's `localDemoLease` check, `restoreDemoLocal` and escrow's `IsDemo` exclusion are intact. Demo wakes also require `Hibernate`, and set rows require it off, so the two can't overlap. - **`console/hostsused.go`:** main's wrapper/locked-helper split is kept. The copies name lock, demo reservation and then copies check all run before the regional/first-kind/owned rechecks, the mark and `CreateRecord`. The helper returns `&amp;rec`. The name lock does nothing for the demo publisher, which carries no copies admission, so there is no deadlock. - **`console/lifetimes_create.go`:** name lock, then demo reservation, then lifetime check, then copies check, all before `admit` and allocation. - **`console/store.go`:** the rebuild carries `copies_configured`, `copies_dirty` and `demo_id`, and keeps the lifetime mint expression. - **`provision/forward.go`, `provision.go`, `reconcile.go`:** - Both stamping functions run (`projectReplicaAssignment`, then `stampDemoRoute`). - `forwardCurrent` compares both families of fields. - `Record` carries both `Demo` and `ReplicaAssignment`. - `convergeOwned` refuses mixed demo/set state before any replica convergence. - In the retire loop, the branch's guards only `continue`, so main's skip for demo rows on fleet workers still applies. - **`registry/registry.go`:** - `routeCols`, `routeColCount` (77), `scanRoute` and `routeArgs` all match in order. - The `Upsert` conflict arm keeps main's `demo_*=excluded` assignments and its immutability WHERE guard, plus the branch's keep-when-zero CASEs. - The route fingerprint hashes `demo=` and `replicas=` only when they are set. - The snapshot fingerprint hashes `demo_id/host/lifetime` only when set, `demo_expires_at` only when non-zero, and `copies` and `replica_revision` in the pair set. - **Census files:** - `plan9_b8_census_test.go`: the placement inventory is layered on `demoWriteCensusInventory`. - `plan14-root-reads-chain.tsv`: main's lines are kept and the placement overlay is regenerated last. - Five record-write digests were refreshed, each with a merge note. - **Changes the merge added beyond the conflicts:** - `appcopies.go`: refuses demo app, account and fleet for counts above one, and refuses demo records. - `copiespublication.go`: refuses `rec.Demo` and the demo fleet's region. - `replicaplacement.go`: the placement pass skips the demo fleet. - `replicaassignment.go`: the shape check refuses `Demo`. - `demo_policy.go`: refuses `ReplicaAssignment`. - `registry/replicas.go`: `ValidReplicaProjection` and `setReplicaAssignment` refuse `IsDemo`. - None of these change anything when copies are 1 and there is no assignment. - **Replica writers vs demo columns:** `setReplicaAssignment` and `ClearReplicaAssignment` are targeted UPDATEs that leave the `demo_*` columns alone. `ReplaceReplicaAssignment` requires `next.ValidReplicaProjection()`, which now refuses demo rows. Nothing drops demo columns. - **Q2, reachability:** today these demo refusals are a backstop. Demo apps already hit `demoMutationRefusal` on every non-GET door before any copies route, and `ReplicaApps` needs an explicit count above one. The backstop does cover a demo fleet when demo admission is off, and an ordinary multi-copy app later placed onto the demo fleet. - **Q5, inertness:** with no copies config and no assignment, every new guard is gated on a count above one, a non-empty `FleetBoxes`, a non-nil `ReplicaAssignment` or `Demo`. Both fingerprints hash nothing extra. Behaviour matches main `6be08467`. - **Q6, test waits:** the test edits are `stateless_assignment_test.go` (two new cases), `TestCopiesRefusesDemoAppsAndFleets`, `TestReplicaPlacementSkipsDemoFleet`, `TestReplicaAssignmentRefusesDemo`, `TestReplicaAssignmentRefusesDemoRoute`, and two signature changes in the demo tests. None waits, polls or sleeps. - **Focused run:** I ran `go test ./internal/registry ./internal/provision -run 'TestReplicaAssignmentRefusesDemo|TestPlan9B8RecordWriteCensus|TestPlan14RootReadCensus'`, and both packages passed. The Go cache was writable. ### Verdict **Merge resolution:** Clean. It is a correct union: nothing from either side is dropped, demo records and fleets are kept out of replica sets at every layer, and apps that don't use copies behave as on main.</result> <usage><subagent_tokens>110897</subagent_tokens><tool_uses>21</tool_uses><duration_ms>206806</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>a5b6e6fef2a4cd7ce</task-id> <tool-use-id>toolu_01XH8DPpPJZNzhw9eDwrdKxA</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/7c5a7d70-0e28-42b9-896c-5d73b2d2a05d/tasks/a5b6e6fef2a4cd7ce.output</output-file> <status>completed</status> <summary>Agent "Census review merge 2 (#280)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>| unit | class | verdict | reason (file:line) | |---|---|---|---| | chain `plan14-root-reads-chain.tsv` | chain | APPROVE | Every line of origin/main 6be08467 is kept byte for byte and in order: dropping the last line gives exactly main's file. `agent-start-demo-1.tsv` (6ef1e3bc…) is parent, the same bytes as on main. `stateless-replicas-2.tsv` 51b40fb5… is last (chain.tsv:80-81). | | `internal/host/agent.go` `runAgent` | body (authority) | APPROVE | A three-way merge of the function against base 0b3098cb gives exactly the merged body: main's demo wiring plus the branch's worker. No new read; still 6 sites. | | `internal/registry/registry.go` `Registry.Fingerprint` | body (legacy) | APPROVE | The union of both sides' columns in one SELECT, with the scan in the same order (registry.go:3972, 3996). The replica hash runs only when a replica field is set, and the demo hash stays main's. Same SQL on the box's own registry. | | `internal/registry/registry.go` `upsertRoute` | body (legacy) | APPROVE | Clean three-way union. Main's demo descriptor/owner guard and the branch's same-owner set-preservation CASE lines are both in the one statement. No new query. | | `internal/registry/registry.go` `routeArgs`, `scanRoute` | reads | APPROVE | 77 columns: routeCols has 77 names and `routeColCount = 77` (registry.go:1110, 1113). Args and scan follow routeCols order: replica columns, then demo columns (registry.go:1132, 1707). Data comes only from the box's own registry. | | `internal/registry/replicas.go` `Registry.setReplicaAssignment` | new (legacy) | APPROVE | The only merge change is an added `rt.IsDemo()` refusal (replicas.go:87). That is stricter, and it reads a column already in the row. | | `internal/registry/replicas.go` `Route.ValidReplicaProjection` | new (legacy) | APPROVE | Adds `!t.IsDemo()` (replicas.go:36). Stricter, no new input. | | `internal/registry/forward.go` `Registry.PutForward` | reads | APPROVE | Clean three-way union of main's demo fields and the branch's replica fields. No new read source. | | `internal/activator/activator.go` `Service.doWakeOnce` | reads | APPROVE | Clean three-way union. FleetBoxes is the only replica read, and it was already approved. | | `internal/activator/wakeidentity.go` `Service.currentWakeRoute` | reads | APPROVE | Main's demo identity check sits after the record read and before the replica branch (wakeidentity.go:248). The replica path also refuses demo rows and demo records (wakeidentity.go:252). The record source `f.Record` is unchanged, and the early return keeps main's behaviour for unassigned routes. Demo records are never turned into stateless instances. | | `internal/activator/wakeidentity.go` `leaseRouteChanged` | reads | APPROVE | Both fences are kept: replica set/revision/incarnation, and demo descriptor (wakeidentity.go:112-115). Both compare only registry rows. | | `internal/provision/forward.go` `forwardRowFor` | sites (legacy) | APPROVE | Main added this function. The merge adds `projectReplicaAssignment` next to main's `stampDemoRoute` (forward.go:43-44). It copies only from the record it is given; no external read. A record with both demo and replica fields is refused at the shape gates (demo_policy.go:15, replicaassignment.go:47). | | `internal/provision/forward.go` `forwardCurrent` | reads | APPROVE | Equality is the union of main's demo terms and the branch's replica terms. It still requires `InertForward()` (forward.go:55). | | `internal/provision/reconcile.go` `RouteFor` | sites (authority) | APPROVE | Projection and stamping are kept side by side (reconcile.go:605-606). Paths are still derived from the host, not read from the record. | | `internal/provision/reconcile.go` `convergeOwned` | reads | APPROVE | Main's demo guard stays first. It now also refuses a demo record with a replica assignment or an existing FleetBoxes value (reconcile.go:892), which accounts for the read count going from ×3 to ×4. The branch's typed seed/set/clear calls follow, unchanged. | | `internal/provision/reconcile.go` `Reconcile` | reads | APPROVE | In the retire loop, both sides' `continue` guards are kept: the branch's replica guards, then main's demo retain at reconcile.go:2405. They only keep rows. Everything else auto-merges with no new read. | | `@coverage` envelopes (activator, host, provision, registry, release) | envelope | APPROVE | I diffed 6be08467→35f932b9 against the approved 0b3098cb→f96b76e9, excluding tests and testdata. host and release are identical, so their envelopes moved only because of main's own changes. activator, provision and registry differ only by the demo-refusal lines cited above, the column unions and comments. That includes `SetRecordRegion`'s replica refusal and `validateDemoRecord` refusing an assignment (demo_policy.go:15). | | `@fields` | other | APPROVE | Only main's DemoExpiresAt, DemoHost, DemoID and DemoLifetime are added. | | record-write: `Reconcile` (dd8f231f…) | key-site | APPROVE | Same keys (ParseRecordKey, RecordKey, `instances`). The only addition is the demo retain `continue`; no new writer. | | record-write: `Server.reconcileReplicaFleet` (d0af3968…) | key-site | APPROVE | Adds only an early return for the configured demo fleet (replicaplacement.go:332). Writes still go through `placeReplicaRecord`, under the same app/fleet locks and ETag. | | record-write: `Server.registerCLIRoutes` (c98f3780…) | key-site | APPROVE | Main's version plus the branch's single person-only copies route (`svcrole.Set{}`). No record writer added. | | record-write: `Server.createRecordMarkedLocked` (635e680f…) | record-writer | APPROVE | The branch's entry now targets main's locked helper instead of bringing back the removed wrapper entry (demo_census_test.go:9). The helper is main's body plus the copies name lock and admission, both placed after the demo reservation and before marks or `CreateRecord`, and it returns the admitted record (hostsused.go:658-694). The wrapper still takes the app lock, then the hostname lock (hostsused.go:651-655). | | record-write: `Server.createRecordWithLifetimeLocked` (6aa90509…) | key-site | APPROVE | Copies name lock, then main's demo reservation, then the existing lifetime check before copies admission, all before allocation (lifetimes_create.go:64-). | | record-write: field preservation | — | APPROVE | `SetRecordReplicaAssignment` is keyed by identity, holds `WithAppMutation`, and is fenced by RecordSeq and revision through `updateRecord`, a whole-record read-modify-write (replicaassignment.go:73-). `WriteRecord` runs both `replicaFieldsFixed` and `demoFixed`, before and after sequencing (record_sequence.go:143-146, 174), so main's demo fields survive the branch's replica writers. Demo records are refused at replica admission (replicaassignment.go:47). | No root read now opens, runs, queries or follows a path or input that a tenant, app or box agent can create, write or name. Every merge-touched unit combines two already-approved bodies (main's demo half and the branch's replica half), and the resolutions only add refusals. I re-ran `go test ./internal/provision -run 'TestPlan14RootReadCensus$|TestPlan9B8RecordWriteCensus$'` at 35f932b9 and it passed. I made no changes; the worktree is clean and my scratch files are removed. Census: APPROVED at 35f932b9. Seal 6ef1e3bc1dbacd5b548b1cbfe3a6d37bd5f701e03969feef2736212ee11713df → 51b40fb5e2478f2023bd5f50faa87691273bc0cc70e6d63dbb5ec4f68a8c98ff.</result> <usage><subagent_tokens>125723</subagent_tokens><tool_uses>42</tool_uses><duration_ms>365293</duration_ms></usage> </task-notification>

Attributed to this commit: 78.9 g CO₂e (10,069,172 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on stateless-replicas-2-placement, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/docs/region-ha-runbook.md b/docs/region-ha-runbook.md
new file mode 100644
index 000000000..5c0190a54
--- /dev/null
+++ b/docs/region-ha-runbook.md
@@ -0,0 +1,55 @@
+# Region HA operator runbook
+
+This page is for operators of a deployment that runs region HA (`CARLOS_REGION_HA=1`). It covers the settings a box needs and the jobs the platform leaves to an operator. The design is in `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md`.
+
+## Settings in host.env
+
+A fixed box is one you created by hand, not through Auto Scaling. It reads its region HA settings from root-owned `/etc/carlos/host.env`, mode 0600. The region-host module does not write that file. Write the lines, then restart `carlos-edge.service` on one box at a time. A restart costs about 1 to 11 seconds of held or refused requests on that box.
+
+```
+CARLOS_REGION_HA=1
+CARLOS_TERMINATION_QUEUE_URL=https://sqs.eu-west-1.amazonaws.com/123456789012/example-host-terminations
+CARLOS_HA_FIXED_BOX_IDENTITIES='{"box-a":"i-0123456789abcdef0","box-b":"i-0fedcba9876543210"}'
+```
+
+- `CARLOS_TERMINATION_QUEUE_URL` is this box's own termination queue, from the region-host module's `termination_queue_url` output. Each box polls its own queue. Without it, termination recovery does not start, and the journal says so.
+- `CARLOS_HA_FIXED_BOX_IDENTITIES` maps each fixed box's reference to its EC2 instance ID, as a JSON object.
+ - **Wrap the value in single quotes**, as above. This is how `carlos system host-env write` writes it. systemd removes the outer single quotes and reads the JSON as written. A shell that sources the file keeps the JSON's double quotes only because of the single quotes; without them it strips the double quotes and the value is no longer JSON.
+ - Only lower-case letters, digits, `{`, `}`, `"`, `:`, `,`, space and `-` are allowed. A reference is one DNS label. An instance ID is `i-` followed by 8 or 17 hexadecimal characters.
+ - The box's own entry must match its own instance ID, or termination recovery refuses to start (`identity_bindings`).
+ - Without the setting, a fixed box binds only itself. A fixed peer it has not bound then has no binding, and taking over its hosts after it is terminated falls back to asking EC2 directly.
+
+To roll back, restore the previous host.env and restart `carlos-edge.service`.
+
+## A fixed box has been terminated: remove its edges file
+
+When a fixed box is terminated, a surviving box recovers its duties. It takes over the box's hosts, timers and due wakes. It does not delete the departed box's edges file (`control/edges/<box>.json`) because the platform cannot prove which instance of a fixed box an edges file belongs to.
+
+Until the old edges file is removed, the departure stays open and pages once an hour (`ha_departure_edges_retained`).
+
+1. Check that the box is terminated in EC2.
+2. Read the page or journal line. It names the edges file.
+3. Delete that one object from the deployment bucket.
+4. Within a few minutes, the surviving box sees that the file is gone, finishes the departure and stops paging.
+
+Never give a new box the reference of a box that has left (next section).
+
+## A fixed box has been recreated: give it a new reference
+
+Every box publishes a signed identity record once, at `control/boxes/<box>.json`. The record is create-only, and the deployment bucket's policy (`BoxRecordsAreNeverDeleted`) refuses to delete it, for every principal. So a reference belongs to one instance for good. A new box under an old reference cannot publish its record or be verified, and the old box's departure would page every hour without end.
+
+Give a recreated fixed box a new reference instead. Do these steps in order:
+
+1. Check that the old box's termination has been seen. A surviving box logs the departure for the old instance ID.
+2. Create the new box under a new reference.
+3. Add the new reference and its instance ID to `CARLOS_HA_FIXED_BOX_IDENTITIES`. Keep the old box's entry until its departure has finished. Update the value on every fixed box in the region. If group boxes read it from the region's SSM parameter, update the parameter too, then rebuild each group box's host.env with `carlos system host-env write` (as root) or replace the box. A restart alone does not read SSM again. Restart `carlos-edge.service` on one box at a time.
+4. Remove the old box's edges file (previous section). The old departure then finishes and stops paging.
+5. Once the departure has finished, remove the old box's entry from `CARLOS_HA_FIXED_BOX_IDENTITIES` the same way. The old box record stays in the bucket. It grants nothing.
+
+## Copying a key from a box in another region
+
+A region-host role with SSM parameter scoping (`scope_ssm_parameter_reads`) can read only `/carlos/*` parameters in its own region. A box in one region can no longer read a parameter in another region, for example to copy the secrets key to a new region. The scoping is an explicit Deny, so adding an Allow to the role does not get past it.
+
+Copy the value with an operator credential instead of the box role. This needs no change to the role.
+
+If the box role itself must read it, widen `ssm_parameter_arn` to include that one parameter, or turn `scope_ssm_parameter_reads` off, through the deployment's infrastructure root and with scoped approval. Copy the value, then put the setting back, and check with an IAM policy simulation that the read is denied again.
diff --git a/docs/superpowers/notes/census-proposal-region-ha-followups.md b/docs/superpowers/notes/census-proposal-region-ha-followups.md
new file mode 100644
index 000000000..cfa0dddd9
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-region-ha-followups.md
@@ -0,0 +1,29 @@
+# Census approval: region-ha-followups
+
+Ruling `census-ruling-region-ha-followups`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/host/hadeparture_identity.go` `departureIdentities.Proof` | body | unchanged (1) | Allow live EC2 fallback only after clean absence of pair, ref and iid; identity read errors, mismatches and verification failures refuse. Additional reads use the existing registry identity lookup for ref and iid separately. |
+| `internal/host/hadepartures_scan.go` `Controller.retryScan` | body | unchanged (1) | Use the approved operator text for permission-fault and retained-edges notices and pages. Keep persisted retry timing, permission-episode suppression and the hourly page claim unchanged; no new read or completion authority. |
+| `internal/host/hadepartures_wiring.go` `armHADepartures` | body | unchanged (17) | Inject the existing PageOperator function into the backend when HA departures are armed; no new read or paging transport. |
+| `internal/activator/haadopt.go` `Service.AdoptHost` | sites | +whole:Route | Attach a per-acquire termination proof observer to finalizer acquisitions so refusals retain alarms; avoid duplicate fallback observations. The observer receives the existing route and departure ref for paging; no new storage read or takeover authority. |
+| `internal/activator/hatakeover.go` `ExecBackend.reportTakeover` | sites | +registry:Host ×3 | Page only departure-finalize proof refusals through the injected host sink, at warning level and once per host per hour. Send on a detached five-second context and log send failures. Read the existing route Host for page throttling, body and failure logging; no new storage read or takeover authority. |
+| `internal/edge/forwardha.go` `Edge.frontForwardHA` | sites | +registry:Host, +whole:Route | Report detached TCP/TLS failure after a canceled Placement or Recovery request through the existing NoteForward classifier, preserving Ref, Gen and PeerGen. Reuse the route Host to correlate the late result; no new storage read or routing authority. |
+
+Envelopes re-pinned: `internal/activator`, `internal/edge`, `internal/host`, `internal/lease`, `internal/termfence`.
+
+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. Reject 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. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `internal/host/hadeparture_identity.go` `departureIdentities.Proof`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=B3b: read immutable box bytes and local verified bindings; require AWS signature plus independent fixed/group binding, unique ref/iid, exact digest and known scope. Unknown walks persist one 1000-key page and at most 32 new GETs per turn; errors never prove absence.
+- `internal/host/hadepartures_scan.go` `Controller.retryScan`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=B4: Read only the bound departure to persist bounded retry timing and the existing hourly per-departure page claim. No completion authority. Fix r1/P15: bound detached retry bookkeeping to five seconds so cancellation still records backoff/page. Permission episodes use only the structured ha_departure_permission_fault code and key, never wake-state prose. B4 fix r4/P18: Retained fixed edges use the existing persisted 30/60/120/300-second retry and hourly departure claim, emitting only ha_departure_edges_retained plus the key. Skip generic prose paging for that code. B4 fix r5: After the existing durable hourly claim succeeds for retained fixed edges, keep the structured log and send PageOperator a warning with subject ha_departure_edges_retained and body code/key/box fields through the existing bounded alert sinks. Return delivery errors; never call the generic C3 page for this state. No new read site or completion authority. B5: Emit permission notice only on permission_new, the persisted fault-episode transition; suppress repeat hourly permission logs. Other departure pages retain the durable hourly claim.
+- `internal/host/hadepartures_wiring.go` `armHADepartures`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=B3 fix r1: Install proof adapter, adoption identity and suspicion callbacks before asynchronous startup. Lazily retry the same deployment/data clients; lifetime callback reads only the current host through ExecBackend.TerminationLifetime. Add bounded structured paging for unresolved per-iid records. No new bucket, tenant input path or acquire bypass. B4: Wire the shared lock reader and existing AdoptHost entry. Read local route, Pair and duty revision only after authoritative inventory eligibility; bind its record lifetime and refuse missing/mismatched local routes. No route synthesis or pool widening. B5: Publish the armed controller to the existing metrics sampler. No new loop, remote source or process authority.
+- `internal/activator/haadopt.go` `Service.AdoptHost`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=Serialize through the existing host operation state. Read local route/revision/receipt plus configured lock/manifest/wake objects; use only restricted ordinary acquire, exact guarded restore, ordinary unclean release and verified readback for adoption. No process launch, local-copy reuse or secret access. B3: pass the optional shared durable termination proof adapter into the existing restricted finalizer acquire. The adapter validates the exact classified peer and current host lifetime, uses the acquire data-bucket client, and cannot bypass expiry or CAS. No new read in this unit. B4: A first scanner import may reuse its staging lock observation; the ordinary acquire still rereads and compares the exact ETag/generation and expiry. Existing receipt replay keeps its fresh read. No new read path or takeover authority.
+- `internal/activator/hatakeover.go` `ExecBackend.reportTakeover`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=Final fix P2-1: report all refused proof results through the per-host alarm and distinguish visitor from departure-finalize. No reads or authority.
+- `internal/edge/forwardha.go` `Edge.frontForwardHA`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): the agent's edge decides at the front door whether to forward a visitor request: reads the route's HA flag and host from the box's own registry row and asks the activator; forwards only to a box in view over the existing signed hop; root never calls it;rev3=census-ruling-region-ha-dead-holder-backoff;basis=ForwardTarget returns a ForwardDecision (Ref, Refuse, Gen); a Refuse is answered at the front door with the existing unreachable answer (503, Retry-After: 10, same body, via answerHolderUnreachable), with no forward, dial, note or per-request step. A forward passes the decision to forwardHA and NoteForward carries Ref and Gen back. The round-1 connection callback (NoteConnected) is gone: the dial bound now lives in forwardTransport's forwardDialGate, which coalesces TCP dials per holder address in memory. The same 5 read sites; no new read; root never calls it.;rev3=census-ruling-region-ha-p1b3a;basis=Pass the existing route to a lazy cached wakeSnapshot closure, handle explicit local denial before all accounting, and refuse a disappeared Placement choice rather than falling through locally; whole Route read only, no new store or filesystem operation and no root authority.;rev3=census-ruling-edge-held-streams;basis=the edge in the agent (carlos-edge.service, user carlos): for a marked request to a hibernating HA route it uses the new HAForwarderFromMemory (ForwardTargetFromMemory) instead of ForwardTarget, so the hold path makes no holder-lock read; a non-stream marked request is left to this box's classification, and a holder not known from memory is answered with the one-retry event. The unmarked path is unchanged. Reads only the request mark and the already-loaded route and home map; no read added.
+
+Seal: `6ef1e3bc1dbacd5b548b1cbfe3a6d37bd5f701e03969feef2736212ee11713df` → `cfb026f1f9d59f325937cbddf26df2d94d5240d1f7846e80db713b8f6a15c387`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-region-ha-followups.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/census-proposal-stateless-replicas-2.md b/docs/superpowers/notes/census-proposal-stateless-replicas-2.md
index 20befc496..da5217dd2 100644
--- a/docs/superpowers/notes/census-proposal-stateless-replicas-2.md
+++ b/docs/superpowers/notes/census-proposal-stateless-replicas-2.md
@@ -68,6 +68,6 @@ New dispositions, which census-propose wrote and the reviewer checks against the
- reads `internal/registry/registry.go:scanRoute`: +registry:Copies, +registry:FleetBoxes, +registry:ReplicaIncarnation, +registry:ReplicaRevision; keeps legacy, task accepted-legacy
- reads `internal/registry/remote_dispatch.go:Registry.dispatchRemote`: +registry:Assignment ×2, +registry:Changed ×2, +registry:Host ×2, +registry:Observed ×4, +registry:On, +registry:ReplicaLife ×2, +registry:TValue, +whole:Route ×5; keeps hint, task E2
-Seal: `6ef1e3bc1dbacd5b548b1cbfe3a6d37bd5f701e03969feef2736212ee11713df` → `51b40fb5e2478f2023bd5f50faa87691273bc0cc70e6d63dbb5ec4f68a8c98ff`.
+Seal: `cfb026f1f9d59f325937cbddf26df2d94d5240d1f7846e80db713b8f6a15c387` → `d28a31401c32770cc079014e82ae49197abb3815b384a77dc4fc8d00f73ed8c6`.
Overlay: `internal/provision/testdata/plan14-root-reads-stateless-replicas-2.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/census-region-ha-followups-claims.md b/docs/superpowers/notes/census-region-ha-followups-claims.md
new file mode 100644
index 000000000..bce3436d1
--- /dev/null
+++ b/docs/superpowers/notes/census-region-ha-followups-claims.md
@@ -0,0 +1,6 @@
+internal/host/hadeparture_identity.go:departureIdentities.Proof Allow live EC2 fallback only after clean absence of pair, ref and iid; identity read errors, mismatches and verification failures refuse. Additional reads use the existing registry identity lookup for ref and iid separately.
+internal/activator/haadopt.go:Service.AdoptHost Attach a per-acquire termination proof observer to finalizer acquisitions so refusals retain alarms; avoid duplicate fallback observations. The observer receives the existing route and departure ref for paging; no new storage read or takeover authority.
+internal/host/hadepartures_wiring.go:armHADepartures Inject the existing PageOperator function into the backend when HA departures are armed; no new read or paging transport.
+internal/activator/hatakeover.go:ExecBackend.reportTakeover Page only departure-finalize proof refusals through the injected host sink, at warning level and once per host per hour. Send on a detached five-second context and log send failures. Read the existing route Host for page throttling, body and failure logging; no new storage read or takeover authority.
+internal/edge/forwardha.go:Edge.frontForwardHA Report detached TCP/TLS failure after a canceled Placement or Recovery request through the existing NoteForward classifier, preserving Ref, Gen and PeerGen. Reuse the route Host to correlate the late result; no new storage read or routing authority.
+internal/host/hadepartures_scan.go:Controller.retryScan Use the approved operator text for permission-fault and retained-edges notices and pages. Keep persisted retry timing, permission-episode suppression and the hourly page claim unchanged; no new read or completion authority.
diff --git a/docs/superpowers/notes/region-ha-followups-p3.md b/docs/superpowers/notes/region-ha-followups-p3.md
new file mode 100644
index 000000000..7bcc5766c
--- /dev/null
+++ b/docs/superpowers/notes/region-ha-followups-p3.md
@@ -0,0 +1,21 @@
+# Region HA follow-ups branch: P3 follow-up list
+
+From the per-task and branch reviews of branch region-ha-followups (2026-11-03/04). None starts a review round.
+
+- Item 1 r1 P3-1: "unbound" means no row in this box's local identity registry; the fixed-identity config and not-yet-loaded S3 box records are not consulted. State the definition above `departureIdentities.Proof`.
+- Item 1 r1 P3-2: no witness drives `AdoptHost` through a successful unbound fallback counting EC2 calls and log lines.
+- Item 1 r1 P3-3: the "context error" row of the Proof classification has no test.
+- Branch r1 P3-1: a binding made by the identity walk has no observation, so item 1 treats it as bound and refuses the visitor EC2 fallback on a box that never saw the peer alive.
+- Item 2 r1 P3-1: every finalizer page carries the reason `termination_unproven`, including lifetime changes and a proven termination whose follow-up failed. Map causes to codes.
+- Item 2 r1 P3-2: the page throttle is per box, in memory; each survivor pages hourly per host and a restart resets it.
+- Item 2 r1 P3-3: the production witness does not show the second adoption attempt reached the proof check.
+- Item 2 r1 P3-4: the `ref == ""` fallback in reportTakeover is unreachable.
+- Item 5 r1/r2 P3-4: the P1-1 witness's "B not suspect" checks rely on B's success note landing before A's failure note; comment it.
+- Item 5 r2 P3-5: time queued behind a healthy connect still comes out of the handshake budget (pre-existing).
+- Census P3-2 / branch P3-6: the retained-edges page subject is now prose, not `ha_departure_edges_retained`; check alert routing filters before the roll.
+- Branch r1 P3-3: the identity-map character set is enforced only by `carlos system host-env write`, not when a hand-written host.env is read.
+- Branch r1 P3-4: the runbook should quote the exact `publish-record` command and name the departure log line an operator searches for.
+- Branch r1 P3-5: the permission notice says "read and delete edges files"; the same fault also comes from opening the bucket and indexing the deletion.
+- Branch r1 P1-1 (fixed as docs): Ruling P17 assumed an operator could replace `control/boxes/<ref>.json`; the bucket policy `BoxRecordsAreNeverDeleted` forbids it. The runbook now says a recreated fixed box takes a new reference. If reusing a reference is ever needed, it needs a ruling to lift that policy statement.
+- Branch r2 P3-1: records of departed fixed references stay in the bucket for good; boxes that never bound one re-read it on each identity walk (backoff up to 300 s).
+- Branch r2 P3-2: the runbook's SSM scope sentence depends on `ssm_parameter_arn`; the role-level copy route does not mention KMS decrypt for a parameter encrypted in another region.
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go
index 48e6a264b..5913c2c1a 100644
--- a/internal/activator/backend_exec.go
+++ b/internal/activator/backend_exec.go
@@ -391,6 +391,8 @@ type ExecBackend struct {
// TerminationProofs replaces live-only takeover when the departure controller
// installs its verified identity resolver and shared durable proof cache.
TerminationProofs *lease.TerminationProofAdapter
+ // Page sends finalizer proof refusals through the host paging sinks. Nil disables paging.
+ Page func(ctx context.Context, level, subject, body string) error
// takeover is the takeover proof's log throttle (hatakeover.go).
takeover takeoverState
// sameBox is the same-box recovery's state (hasamebox.go): the hosts
diff --git a/internal/activator/haadopt.go b/internal/activator/haadopt.go
index 272895d8e..a0311d723 100644
--- a/internal/activator/haadopt.go
+++ b/internal/activator/haadopt.go
@@ -296,9 +296,17 @@ func (a *Service) AdoptHost(ctx context.Context, rt registry.Route, req Adoption
if err = phase("acquiring", expected, nil); err != nil {
return Deferred, err
}
- ctx = lease.WithTerminationProof(ctx, b.TerminationProofs)
- ctx = context.WithValue(ctx, adoptionCauseKey{}, true)
- held, err := lease.AcquireHAForDuty(ctx, b.Cfg.Bucket, b.Cfg.hibernatePrefix(rt.Host), b.Cfg.Region, hafresh.Marker{Box: self.Ref, IID: self.IID, Lifetime: req.Lifetime}, hafresh.Proofs{SameBoxEmpty: b.sameBoxEmpty(ctx, rt), OwnerTerminated: b.ownerTerminated(ctx, rt)}, func(v hafresh.View) error {
+ ctx = context.WithValue(ctx, adoptionCauseKey{}, req.Ref)
+ proofs := hafresh.Proofs{SameBoxEmpty: b.sameBoxEmpty(ctx, rt), OwnerTerminated: b.ownerTerminated(ctx, rt)}
+ if b.TerminationProofs != nil {
+ adapter := *b.TerminationProofs
+ adapter.Observe = func(iid string, gone bool, err error) { b.reportTakeover(ctx, rt, iid, gone, err) }
+ if b.OwnerTerminated != nil {
+ proofs.OwnerTerminated = func(iid string) (bool, error) { return b.OwnerTerminated(ctx, iid) }
+ }
+ ctx = lease.WithTerminationProof(ctx, &adapter)
+ }
+ held, err := lease.AcquireHAForDuty(ctx, b.Cfg.Bucket, b.Cfg.hibernatePrefix(rt.Host), b.Cfg.Region, hafresh.Marker{Box: self.Ref, IID: self.IID, Lifetime: req.Lifetime}, proofs, func(v hafresh.View) error {
if v.ETag != view.ETag || v.Lock.Generation != view.Lock.Generation {
return ErrDutyDeferred
}
diff --git a/internal/activator/haplacement_test.go b/internal/activator/haplacement_test.go
index c32fa8b35..b5382ef32 100644
--- a/internal/activator/haplacement_test.go
+++ b/internal/activator/haplacement_test.go
@@ -785,3 +785,38 @@ func TestPlacementCanceledRetry(t *testing.T) {
})
}
}
+
+func TestPlacementCanceledDialCompletion(t *testing.T) {
+ for _, kind := range []edge.ForwardKind{edge.Placement, edge.Recovery} {
+ t.Run(fmt.Sprintf("kind=%d", kind), func(t *testing.T) {
+ s := haService(t, "shop.example.com")
+ s.rt.HA = true
+ clk := &fakeClock{t: time.Now()}
+ s.a.holders.now = clk.now
+ if kind == edge.Recovery {
+ putLockFor(t, s.b, s.rt, leaseBody(t, heldByB, clk.now().Add(-time.Second)))
+ }
+ project := func() boxchoice.WakeSnapshot { return placementSnapshot(clk.now()) }
+ d := s.a.ForwardTarget(t.Context(), s.rt, project)
+ if d.Ref != "b" || d.Kind != kind {
+ t.Fatal(d)
+ }
+ r := placementResult(d, 0, "")
+ r.Outcome = edge.ForwardCanceled
+ s.a.NoteForward(s.rt.Host, r)
+ if next := s.a.ForwardTarget(t.Context(), s.rt, project); next != d {
+ t.Fatal("cancel changed decision", next)
+ }
+ r.Outcome = edge.ForwardUnreachable
+ s.a.NoteForward(s.rt.Host, r)
+ clk.advance(10*time.Second - time.Nanosecond)
+ if next := s.a.ForwardTarget(t.Context(), s.rt, project); next.Ref == "b" {
+ t.Fatal("failed dial was not excluded", next)
+ }
+ clk.advance(time.Nanosecond)
+ if next := s.a.ForwardTarget(t.Context(), s.rt, project); next.Ref != "b" {
+ t.Fatal("peer not readmitted after 10 seconds", next)
+ }
+ })
+ }
+}
diff --git a/internal/activator/hatakeover.go b/internal/activator/hatakeover.go
index 82d2653eb..9659d1403 100644
--- a/internal/activator/hatakeover.go
+++ b/internal/activator/hatakeover.go
@@ -2,10 +2,12 @@ package activator
import (
"context"
+ "fmt"
"log"
"sync"
"time"
+ "github.com/carlosframework/platform/internal/alerting"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/termfence"
)
@@ -38,7 +40,8 @@ func (b *ExecBackend) ownerTerminated(ctx context.Context, rt registry.Route) fu
func (b *ExecBackend) reportTakeover(ctx context.Context, rt registry.Route, iid string, gone bool, err error) {
cause := "visitor"
- if ctx.Value(adoptionCauseKey{}) == true {
+ ref, finalizer := ctx.Value(adoptionCauseKey{}).(string)
+ if finalizer {
cause = "departure-finalize"
}
if !gone || err != nil {
@@ -46,6 +49,19 @@ func (b *ExecBackend) reportTakeover(ctx context.Context, rt registry.Route, iid
err = termfence.ErrTerminationProof
}
b.takeover.alarm(rt.Host, iid, cause, err)
+ if finalizer && b.Page != nil && b.takeover.claimPage(rt.Host, time.Now()) {
+ if ref == "" {
+ ref = iid
+ }
+ // A fresh, bounded context: the scan's own may already be spent
+ // (the refusal can be its timeout), and the send must not eat
+ // the scan's budget for later hosts.
+ pctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
+ if perr := b.Page(pctx, alerting.LevelWarning, fmt.Sprintf(takeoverPageSubject, ref), fmt.Sprintf(takeoverPageBody, ref, rt.Host, "termination_unproven")); perr != nil {
+ log.Printf("ha_takeover host=%s page failed: %v", rt.Host, perr)
+ }
+ cancel()
+ }
return
}
if cause == "departure-finalize" {
@@ -63,6 +79,7 @@ const takeoverAlarmEvery = sameBoxAlarmEvery
type takeoverState struct {
mu sync.Mutex
alarmed map[string]time.Time
+ paged map[string]time.Time
}
// alarm logs a takeover refused because EC2 could not be asked, at most
@@ -83,3 +100,20 @@ func (s *takeoverState) alarm(host, iid, cause string, why error) {
log.Printf("ha_takeover host=%s iid=%s cause=%s confirmed=false error=true", host, iid, cause)
log.Printf("activator: ALERT %s: the takeover of %s's expired HA lock is refused: EC2 did not answer whether it is terminated: %v (the host stays down until EC2 confirms the holder terminated)", host, iid, why)
}
+
+// Operator page copy (approved by delegation, one Luna pass, 2026-11-03).
+const takeoverPageSubject = "Box %s's duties cannot be recovered"
+const takeoverPageBody = "The departed box %s still holds the lock for %s. This box could not prove that the departed box was terminated: %s. The host stays on that box until the proof can be read or the box comes back."
+
+func (s *takeoverState) claimPage(host string, now time.Time) bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if last, seen := s.paged[host]; seen && now.Sub(last) < time.Hour {
+ return false
+ }
+ if s.paged == nil {
+ s.paged = map[string]time.Time{}
+ }
+ s.paged[host] = now
+ return true
+}
diff --git a/internal/activator/hatakeover_page_test.go b/internal/activator/hatakeover_page_test.go
new file mode 100644
index 000000000..d3c6bc4cc
--- /dev/null
+++ b/internal/activator/hatakeover_page_test.go
@@ -0,0 +1,60 @@
+package activator
+
+import (
+ "context"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+func TestTakeoverPageHourlyPerHost(t *testing.T) {
+ var state takeoverState
+ now := time.Now()
+ var claims atomic.Int32
+ var wg sync.WaitGroup
+ for range 20 {
+ wg.Go(func() {
+ if state.claimPage("shop.example.com", now) {
+ claims.Add(1)
+ }
+ })
+ }
+ wg.Wait()
+ if claims.Load() != 1 {
+ t.Fatalf("concurrent pages=%d", claims.Load())
+ }
+ if state.claimPage("shop.example.com", now.Add(time.Hour-time.Nanosecond)) {
+ t.Fatal("paged within the hour")
+ }
+ if !state.claimPage("shop.example.com", now.Add(time.Hour)) {
+ t.Fatal("hourly retry suppressed")
+ }
+ if !state.claimPage("other.example.com", now) {
+ t.Fatal("another host suppressed")
+ }
+}
+
+// A finalizer refused because its scan context ran out still pages: the
+// send gets a fresh, bounded context of its own.
+func TestTakeoverPageSurvivesSpentScanContext(t *testing.T) {
+ var got []string
+ b := &ExecBackend{Page: func(ctx context.Context, level, subject, body string) error {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ if _, ok := ctx.Deadline(); !ok {
+ t.Error("page context has no deadline")
+ }
+ got = append(got, subject)
+ return nil
+ }}
+ ctx, cancel := context.WithCancel(context.WithValue(context.Background(), adoptionCauseKey{}, "box-a"))
+ cancel()
+ b.reportTakeover(ctx, registry.Route{Host: "shop.example.com"}, "i-0123456789abcdef0", false, context.Canceled)
+ if len(got) != 1 {
+ t.Fatalf("pages=%d, want 1 despite the spent scan context", len(got))
+ }
+}
diff --git a/internal/activator/termination_proof_test.go b/internal/activator/termination_proof_test.go
index 21ad20353..dffb553a5 100644
--- a/internal/activator/termination_proof_test.go
+++ b/internal/activator/termination_proof_test.go
@@ -51,7 +51,7 @@ func TestTerminationProofWiring(t *testing.T) {
t.Fatal("unverified identity granted acquire")
}
}
- if fallbacks != 1 || resolves != 1 {
+ if fallbacks != 0 || resolves != 1 {
t.Fatalf("fallbacks=%d resolves=%d", fallbacks, resolves)
}
cause := "visitor"
@@ -82,7 +82,7 @@ func TestTerminationProofUnboundTakeover(t *testing.T) {
b.Cfg.Region = "eu-west-1"
logs := captureLog(t)
b.TerminationProofs = &lease.TerminationProofAdapter{Cache: &termfence.ProofCache{}, Resolve: func(context.Context, string, string) (termfence.ProofIdentity, error) {
- return termfence.ProofIdentity{}, errors.New("unverified")
+ return termfence.ProofIdentity{}, termfence.ErrProofUnbound
}, Lifetime: func(context.Context, string, string, string) (string, error) {
if mode == "lifetime" {
return "wrong", nil
diff --git a/internal/edge/forwardha.go b/internal/edge/forwardha.go
index 7273c7cc5..aaae7b500 100644
--- a/internal/edge/forwardha.go
+++ b/internal/edge/forwardha.go
@@ -225,8 +225,18 @@ func (e *Edge) frontForwardHA(w http.ResponseWriter, r *http.Request, host strin
if d.Ref == "" {
return false
}
+ var observation *forwardDialObservation
+ if d.Kind != Holder {
+ observation = &forwardDialObservation{report: func() {
+ fw.NoteForward(up.route.Host, ForwardResult{Outcome: ForwardUnreachable, Ref: d.Ref, Gen: d.Gen, Kind: d.Kind, PeerGen: d.PeerGen})
+ }}
+ r = r.WithContext(context.WithValue(r.Context(), forwardDialObservationKey{}, observation))
+ }
res := e.forwardHA(w, r, host, d)
fw.NoteForward(up.route.Host, res)
+ if observation != nil {
+ observation.update(false, res.Outcome == ForwardCanceled)
+ }
if res.Outcome == ForwardNotInView && d.Kind == Placement {
answerHolderUnreachable(w, r)
return true
@@ -303,7 +313,7 @@ func answerHolderUnreachable(w http.ResponseWriter, r *http.Request) {
// to the same address are never this one.
//
// Its TCP dials go through one forwardDialGate, the transport being one per
-// holder address: at most one dial to a holder is in flight, however many
+// holder address: at most one TCP dial to a holder is in flight, however many
// requests need a connection and whatever the holder cache believes.
//
// It does the TLS itself (DialTLSContext) so that the deadline and the error
@@ -324,15 +334,27 @@ func (e *Edge) forwardTransport(dial string) *http.Transport {
}
ctx, cancel := context.WithTimeout(ctx, forwardDialTimeout)
defer cancel()
+ deadline, _ := ctx.Deadline()
raw, err := gate.dial(ctx, func(ctx context.Context) (net.Conn, error) {
return forwardDial(ctx, network, net.JoinHostPort(dial, backhaulPort))
})
if err != nil {
+ if observation, ok := ctx.Value(forwardDialObservationKey{}).(*forwardDialObservation); ok && !errors.Is(err, errForwardDialQueued) {
+ observation.update(true, false)
+ }
return nil, &forwardConnectError{err}
}
+ // A certificate result belongs to this host and request, never to
+ // the address's TCP waiters or standing failure. Let the handshake
+ // finish after cancellation, within the original dial deadline.
+ hctx, hcancel := context.WithDeadline(context.WithoutCancel(ctx), deadline)
+ defer hcancel()
conn := tls.Client(raw, &tls.Config{ServerName: name, RootCAs: backhaulRootCAs, MinVersion: tls.VersionTLS12})
- if err := conn.HandshakeContext(ctx); err != nil {
+ if err := conn.HandshakeContext(hctx); err != nil {
raw.Close()
+ if observation, ok := ctx.Value(forwardDialObservationKey{}).(*forwardDialObservation); ok {
+ observation.update(true, false)
+ }
return nil, &forwardConnectError{err}
}
return conn, nil
@@ -420,3 +442,27 @@ func (g *forwardDialGate) dial(ctx context.Context, connect func(context.Context
g.mu.Unlock()
return conn, err
}
+
+// A cancelled forward and its detached dial can finish in either order.
+// Report a real dial failure once both are known; NoteForward still owns all
+// suspicion and generation checks. A healthy dial or queue timeout adds no note.
+type forwardDialObservationKey struct{}
+type forwardDialObservation struct {
+ mu sync.Mutex
+ failed, canceled, reported bool
+ report func()
+}
+
+func (o *forwardDialObservation) update(failed, canceled bool) {
+ o.mu.Lock()
+ o.failed = o.failed || failed
+ o.canceled = o.canceled || canceled
+ report := o.failed && o.canceled && !o.reported
+ if report {
+ o.reported = true
+ }
+ o.mu.Unlock()
+ if report {
+ o.report()
+ }
+}
diff --git a/internal/edge/forwardha_export_test.go b/internal/edge/forwardha_export_test.go
index a498e58cb..1412bd8c7 100644
--- a/internal/edge/forwardha_export_test.go
+++ b/internal/edge/forwardha_export_test.go
@@ -2,13 +2,20 @@ package edge
import (
"context"
+ "crypto/tls"
+ "errors"
"fmt"
"io"
"net"
"net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
"sync/atomic"
"testing"
"time"
+
+ "github.com/carlosframework/platform/internal/boxchoice"
)
// The forward scene (forwardha_test.go) for forwardha_wiring_test.go, the
@@ -18,6 +25,7 @@ import (
// HAForwardHost is the born-HA host both boxes of the scene serve.
const HAForwardHost = fwHost
+const HAForwardOtherHost = fwAssetHost
// HAForwardHolder is the holder box's ref in the scene.
const HAForwardHolder = "betty"
@@ -54,7 +62,19 @@ func (s *HAForwardScene) Dials() int64 { return s.dials.Load() }
// Get is one visitor GET of path on HAForwardHost through annie.
func (s *HAForwardScene) Get(path string) (status int, retryAfter, body string, err error) {
- resp, err := s.x.a.client.Get("https://" + fwHost + path)
+ return s.GetContext(context.Background(), path)
+}
+
+func (s *HAForwardScene) GetContext(ctx context.Context, path string) (status int, retryAfter, body string, err error) {
+ return s.GetHostContext(ctx, fwHost, path)
+}
+
+func (s *HAForwardScene) GetHostContext(ctx context.Context, host, path string) (status int, retryAfter, body string, err error) {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://"+host+path, nil)
+ if err != nil {
+ return 0, "", "", err
+ }
+ resp, err := s.x.a.client.Do(req)
if err != nil {
return 0, "", "", err
}
@@ -77,13 +97,17 @@ func (s *HAForwardScene) HolderDown(blackholed bool) {
})
}
-func (s *HAForwardScene) EnablePlacement(t *testing.T) {
+func (s *HAForwardScene) EnablePlacement(t *testing.T, otherHosts ...string) {
t.Helper()
+ var hosts []string
+ for _, host := range append([]string{fwHost}, otherHosts...) {
+ hosts = append(hosts, fmt.Sprintf(`%q:{"role":"home","account":"abc","app":"shop"}`, host))
+ }
s.x.a.homes.privateDial = true
for _, ref := range []string{"annie", "betty"} {
putJSON(t, s.x.seed, "control/edges/"+ref+".json", fmt.Sprintf(
- `{"v":1,"box":%q,"eip":"127.0.0.1","region":"ie","generation":%q,"data_bucket":"bkt","secrets_key_fp":"fp","capabilities":["region-ha-1"],"hibernation_configured":true,"headroom":{"mem_free_mib":50,"mem_total_mib":100,"disk_free_mib":50,"disk_total_mib":100},"hosts":{%q:{"role":"home","account":"abc","app":"shop"}}}`,
- ref, time.Now().UTC().Format(time.RFC3339Nano), fwHost))
+ `{"v":1,"box":%q,"eip":"127.0.0.1","region":"ie","generation":%q,"data_bucket":"bkt","secrets_key_fp":"fp","capabilities":["region-ha-1"],"hibernation_configured":true,"headroom":{"mem_free_mib":50,"mem_total_mib":100,"disk_free_mib":50,"disk_total_mib":100},"hosts":{%s}}`,
+ ref, time.Now().UTC().Format(time.RFC3339Nano), strings.Join(hosts, ",")))
}
s.x.converge(t)
}
@@ -103,3 +127,107 @@ func (s *HAForwardScene) PausePeer(t *testing.T) {
}
t.Cleanup(func() { forwardDial = old })
}
+
+// HoldDial controls the real forward transport's connect boundary.
+func (s *HAForwardScene) HoldDial(t *testing.T, mode string) (<-chan struct{}, func()) {
+ t.Helper()
+ started, release := make(chan struct{}), make(chan struct{})
+ var startOnce, releaseOnce sync.Once
+ resume := func() { releaseOnce.Do(func() { close(release) }) }
+ old := forwardDial
+ forwardDial = func(ctx context.Context, network, _ string) (net.Conn, error) {
+ s.dials.Add(1)
+ startOnce.Do(func() { close(started) })
+ select {
+ case <-release:
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+ switch mode {
+ case "connect":
+ return nil, errors.New("connection refused")
+ case "tls":
+ a, b := net.Pipe()
+ b.Close()
+ return a, nil
+ }
+ var d net.Dialer
+ return d.DialContext(ctx, network, s.x.b.tlsAddr)
+ }
+ t.Cleanup(func() { resume(); forwardDial = old })
+ return started, resume
+}
+
+func (s *HAForwardScene) PlacementDecision(t *testing.T) ForwardDecision {
+ t.Helper()
+ rt, err := s.x.a.reg.Get(fwHost)
+ if err != nil || rt == nil {
+ t.Fatal("route", err)
+ }
+ return s.x.a.edge.act.(HAForwarder).ForwardTarget(t.Context(), *rt, func() boxchoice.WakeSnapshot { return s.x.a.homes.wakeSnapshot(*rt, time.Now()) })
+}
+
+// ShortenSecondDialWait leaves the first connect held while a real waiter expires.
+func (s *HAForwardScene) ShortenSecondDialWait(t *testing.T) (queuedDone, firstDone <-chan struct{}) {
+ t.Helper()
+ dial, ok := s.x.a.homes.boxInView(HAForwardHolder, time.Now())
+ if !ok {
+ t.Fatal("peer not in view")
+ }
+ tr := s.x.a.edge.forwardTransport(dial)
+ original := tr.DialTLSContext
+ var calls atomic.Int64
+ done, first := make(chan struct{}), make(chan struct{})
+ tr.DialTLSContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
+ switch calls.Add(1) {
+ case 1:
+ defer close(first)
+ case 2:
+ ctx, cancel := context.WithTimeout(ctx, 50*time.Millisecond)
+ defer cancel()
+ defer close(done)
+ return original(ctx, network, addr)
+ }
+ return original(ctx, network, addr)
+ }
+ return done, first
+}
+
+func (s *HAForwardScene) CloseIdleForwards() {
+ s.x.a.edge.forwardTransports.Range(func(_, v any) bool {
+ v.(*http.Transport).CloseIdleConnections()
+ return true
+ })
+}
+
+// HoldBadHostHandshake serves the healthy host's certificate for the other host.
+func (s *HAForwardScene) HoldBadHostHandshake(t *testing.T) (<-chan struct{}, func()) {
+ t.Helper()
+ started, release := make(chan struct{}), make(chan struct{})
+ var startOnce, releaseOnce sync.Once
+ resume := func() { releaseOnce.Do(func() { close(release) }) }
+ server := httptest.NewUnstartedServer(s.x.b.edge)
+ server.TLS = &tls.Config{MinVersion: tls.VersionTLS12, GetCertificate: func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
+ if hello.ServerName == HAForwardOtherHost {
+ startOnce.Do(func() { close(started) })
+ select {
+ case <-release:
+ case <-hello.Context().Done():
+ return nil, hello.Context().Err()
+ }
+ copy := *hello
+ copy.ServerName = HAForwardHost
+ hello = &copy
+ }
+ return s.x.b.live.Load().getCert(hello)
+ }}
+ server.StartTLS()
+ old := forwardDial
+ forwardDial = func(ctx context.Context, network, _ string) (net.Conn, error) {
+ s.dials.Add(1)
+ var d net.Dialer
+ return d.DialContext(ctx, network, server.Listener.Addr().String())
+ }
+ t.Cleanup(func() { resume(); s.CloseIdleForwards(); server.Close(); forwardDial = old })
+ return started, resume
+}
diff --git a/internal/edge/forwardha_test.go b/internal/edge/forwardha_test.go
index 124033727..a1d7c3445 100644
--- a/internal/edge/forwardha_test.go
+++ b/internal/edge/forwardha_test.go
@@ -1383,3 +1383,25 @@ func TestForwardHAClientCanceledOutcome(t *testing.T) {
}
}
}
+
+func TestForwardDialObservationCompletionOrder(t *testing.T) {
+ for _, firstFailure := range []bool{false, true} {
+ t.Run(fmt.Sprint(firstFailure), func(t *testing.T) {
+ var reports atomic.Int32
+ o := &forwardDialObservation{report: func() { reports.Add(1) }}
+ o.update(firstFailure, !firstFailure)
+ if reports.Load() != 0 {
+ t.Fatal("reported with only one outcome")
+ }
+ o.update(!firstFailure, firstFailure)
+ var wg sync.WaitGroup
+ for range 20 {
+ wg.Go(func() { o.update(true, true) })
+ }
+ wg.Wait()
+ if reports.Load() != 1 {
+ t.Fatalf("reports=%d", reports.Load())
+ }
+ })
+ }
+}
diff --git a/internal/edge/haplacement_wiring_test.go b/internal/edge/haplacement_wiring_test.go
index 0f7e37d8a..61797aa58 100644
--- a/internal/edge/haplacement_wiring_test.go
+++ b/internal/edge/haplacement_wiring_test.go
@@ -23,13 +23,15 @@ type placementAcquire struct {
held *lease.Held
acquires int
notes []edge.ForwardResult
+ noteHosts []string
}
func (a *placementAcquire) NoteForward(host string, res edge.ForwardResult) {
+ a.Service.NoteForward(host, res)
a.mu.Lock()
a.notes = append(a.notes, res)
+ a.noteHosts = append(a.noteHosts, host)
a.mu.Unlock()
- a.Service.NoteForward(host, res)
}
// Keep process launch at the fixture's existing HTTP app. A local dispatch
@@ -111,6 +113,7 @@ func testFrontPlacementPausedPeer(t *testing.T, previousHolder, stillHeld bool)
}
x.HolderDown(false)
a.notes = nil
+ a.noteHosts = nil
}
x.PausePeer(t)
type answer struct {
@@ -190,3 +193,210 @@ func testFrontPlacementPausedPeer(t *testing.T, previousHolder, stillHeld bool)
t.Fatalf("survivor lock: %+v %v", view, err)
}
}
+
+func TestPlacementCanceledDialRealWiring(t *testing.T) {
+ for _, mode := range []string{"connect", "tls", "healthy", "queued"} {
+ t.Run(mode, func(t *testing.T) {
+ t.Cleanup(lease.ProcessStateForTest())
+ fx := locktest.NewLockFixture(t)
+ self := hafresh.Self{Ref: "annie", IID: "i-a", Account: "111122223333", Region: "eu-west-1"}
+ lease.SetSelf(self)
+ if err := lease.SetObligationDir(t.TempDir()); err != nil {
+ t.Fatal(err)
+ }
+ prefix := activator.HibernatePrefix("", edge.HAForwardHost)
+ body, err := hafresh.MarkerBody(145, hafresh.Marker{V: 1, Box: "betty", IID: "i-b", Clean: true})
+ if err != nil {
+ t.Fatal(err)
+ }
+ fx.PutLock(prefix, body)
+ cfg := activator.Config{Bucket: fx.Bucket, Idle: time.Hour, Self: func() hafresh.Self { return self }}
+ a := &placementAcquire{Service: activator.New(cfg, &activator.ExecBackend{Cfg: cfg}, nil), bucket: fx.Bucket, prefix: prefix}
+ t.Cleanup(func() {
+ a.Service.Shutdown(context.Background())
+ if a.held != nil {
+ _ = a.held.Release(context.Background())
+ }
+ })
+ x := edge.NewHAForwardScene(t, a)
+ x.EnablePlacement(t)
+ var queuedDone, firstDialDone <-chan struct{}
+ if mode == "queued" {
+ queuedDone, firstDialDone = x.ShortenSecondDialWait(t)
+ }
+ started, resume := x.HoldDial(t, mode)
+ ctx, cancel := context.WithCancel(t.Context())
+ defer cancel()
+ done := make(chan struct{})
+ go func() { defer close(done); x.GetContext(ctx, "/") }()
+ select {
+ case <-started:
+ case <-time.After(3 * time.Second):
+ t.Fatal("dial never started")
+ }
+ if mode == "queued" {
+ status, retry, _, err := x.Get("/queued")
+ if err != nil || status != 503 || retry != "10" {
+ t.Fatalf("queued response: %d %q %v", status, retry, err)
+ }
+ select {
+ case <-queuedDone:
+ case <-time.After(time.Second):
+ t.Fatal("queued dial did not finish")
+ }
+ if x.Dials() != 1 {
+ t.Fatalf("waiter dialled: %d connects", x.Dials())
+ }
+ }
+ cancel()
+ select {
+ case <-done:
+ case <-time.After(time.Second):
+ t.Fatal("visitor did not return")
+ }
+ waitNote := func(outcome edge.ForwardOutcome) bool {
+ deadline := time.Now().Add(time.Second)
+ for time.Now().Before(deadline) {
+ a.mu.Lock()
+ found := false
+ for _, note := range a.notes {
+ if note.Outcome == outcome {
+ found = true
+ }
+ }
+ a.mu.Unlock()
+ if found {
+ return true
+ }
+ time.Sleep(time.Millisecond)
+ }
+ return false
+ }
+ if !waitNote(edge.ForwardCanceled) {
+ t.Fatal("missing canceled request outcome")
+ }
+ resume()
+ if mode == "queued" {
+ select {
+ case <-firstDialDone:
+ case <-time.After(3 * time.Second):
+ t.Fatal("detached first dial did not finish")
+ }
+ }
+ failed := mode == "connect" || mode == "tls"
+ if failed && !waitNote(edge.ForwardUnreachable) {
+ t.Fatal("detached dial failure never reached NoteForward")
+ }
+ if !failed && waitNote(edge.ForwardUnreachable) {
+ t.Fatal("cancel or queue timeout marked peer unreachable")
+ }
+ if mode == "queued" {
+ if next := x.PlacementDecision(t); next.Ref != edge.HAForwardHolder {
+ t.Fatal("queue timeout excluded peer", next)
+ }
+ return
+ }
+ status, _, got, err := x.Get("/")
+ want := "betty|" + edge.HAForwardHost + "|/"
+ if failed {
+ want = "annie|" + edge.HAForwardHost + "|/"
+ }
+ if err != nil || status != 200 || got != want {
+ t.Fatalf("next request: %d %q %v, want %q", status, got, err, want)
+ }
+ if failed && (x.Dials() != 1 || a.acquires != 1) {
+ t.Fatalf("dead peer redialled: dials=%d acquires=%d", x.Dials(), a.acquires)
+ }
+ if !failed && a.acquires != 0 {
+ t.Fatal("healthy peer excluded")
+ }
+ })
+ }
+}
+
+func TestForwardTLSFailureIsHostLocalRealWiring(t *testing.T) {
+ fx := locktest.NewLockFixture(t)
+ cfg := activator.Config{Bucket: fx.Bucket, Idle: time.Hour, Self: func() hafresh.Self { return hafresh.Self{Ref: "annie", IID: "i-a"} }}
+ a := &placementAcquire{Service: activator.New(cfg, &activator.ExecBackend{Cfg: cfg}, nil)}
+ t.Cleanup(func() { a.Service.Shutdown(context.Background()) })
+ // A is a true holder; its own failure must not change B's placement peer.
+ held, err := json.Marshal(hafresh.Lock{Generation: 9, ExpiresAt: time.Now().Add(time.Minute), Owner: hafresh.OwnerFor(hafresh.Self{Ref: "betty", IID: "i-b"}, 7, true)})
+ if err != nil {
+ t.Fatal(err)
+ }
+ fx.PutLock(activator.HibernatePrefix("", edge.HAForwardOtherHost), held)
+ marker, err := hafresh.MarkerBody(145, hafresh.Marker{V: 1, Box: "betty", IID: "i-b", Clean: true})
+ if err != nil {
+ t.Fatal(err)
+ }
+ fx.PutLock(activator.HibernatePrefix("", edge.HAForwardHost), marker)
+ x := edge.NewHAForwardScene(t, a)
+ x.EnablePlacement(t, edge.HAForwardOtherHost)
+ started, resume := x.HoldBadHostHandshake(t)
+ type answer struct {
+ status int
+ body string
+ err error
+ }
+ get := func(host, path string) <-chan answer {
+ done := make(chan answer, 1)
+ go func() {
+ status, _, body, err := x.GetHostContext(t.Context(), host, path)
+ done <- answer{status, body, err}
+ }()
+ return done
+ }
+ first := get(edge.HAForwardOtherHost, "/a")
+ select {
+ case <-started:
+ case <-time.After(time.Second):
+ t.Fatal("A handshake did not start")
+ }
+ start := time.Now()
+ concurrent := get(edge.HAForwardHost, "/b-concurrent")
+ var b answer
+ select {
+ case b = <-concurrent:
+ case <-time.After(time.Second):
+ t.Error("B waited behind A's TLS handshake")
+ resume()
+ b = <-concurrent
+ }
+ resume()
+ if bad := <-first; bad.err != nil || bad.status != 503 {
+ t.Fatalf("A: %+v, want bad certificate failure", bad)
+ }
+ if b.err != nil || b.status != 200 || b.body != "betty|"+edge.HAForwardHost+"|/b-concurrent" {
+ t.Errorf("concurrent B: %+v", b)
+ }
+ if next := x.PlacementDecision(t); next.Ref != edge.HAForwardHolder || next.Kind != edge.Placement {
+ t.Fatalf("B's peer marked suspect: %+v", next)
+ }
+ x.CloseIdleForwards()
+ before := x.Dials()
+ following := <-get(edge.HAForwardHost, "/b-following")
+ if following.err != nil || following.status != 200 || following.body != "betty|"+edge.HAForwardHost+"|/b-following" {
+ t.Errorf("following B: %+v", following)
+ }
+ if time.Since(start) >= 2*time.Second || x.Dials() != before+1 {
+ t.Fatalf("following B did not make a new connection inside 2s: elapsed=%v dials=%d -> %d", time.Since(start), before, x.Dials())
+ }
+ if next := x.PlacementDecision(t); next.Ref != edge.HAForwardHolder {
+ t.Fatalf("following B's peer marked suspect: %+v", next)
+ }
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ n := 0
+ for i, note := range a.notes {
+ if a.noteHosts[i] != edge.HAForwardHost {
+ continue
+ }
+ n++
+ if note.Kind != edge.Placement || note.Outcome != edge.ForwardDone || note.Status != 200 {
+ t.Errorf("B note: %+v", note)
+ }
+ }
+ if n != 2 {
+ t.Fatalf("B notes = %d, want 2", n)
+ }
+}
diff --git a/internal/host/hadeparture_identity.go b/internal/host/hadeparture_identity.go
index aaf05d746..1ba579756 100644
--- a/internal/host/hadeparture_identity.go
+++ b/internal/host/hadeparture_identity.go
@@ -187,9 +187,28 @@ func (r *departureIdentities) Observe(ctx context.Context, o hadeparture.BoxObse
b.Observation = o
return o, r.Registry.SaveHAIdentity(ctx, b)
}
+
+// Proof permits live confirmation only after clean not-found reads for the
+// pair, the ref and the iid. Any read/context/decode/verification error, a
+// binding under either identifier, unknown/placement-null/other-region
+// observation, or a missing second read fails closed.
func (r *departureIdentities) Proof(ctx context.Context, ref, iid string) (termfence.ProofIdentity, error) {
+ if ref == "" || iid == "" {
+ return termfence.ProofIdentity{}, errDepartureIdentity
+ }
o, ok, err := r.Resolve(ctx, ref, iid)
- if err != nil || !ok || !o.Known || o.PlacementNull || o.Box.Scope.CloudRegion != r.Region {
+ if err != nil {
+ return termfence.ProofIdentity{}, err
+ }
+ if !ok {
+ for _, key := range [][2]string{{ref, ""}, {"", iid}} {
+ if _, found, err := r.Registry.HAIdentity(ctx, key[0], key[1]); err != nil || found {
+ return termfence.ProofIdentity{}, errors.Join(errDepartureIdentity, err)
+ }
+ }
+ return termfence.ProofIdentity{}, termfence.ErrProofUnbound
+ }
+ if !o.Known || o.PlacementNull || o.Box.Scope.CloudRegion != r.Region {
return termfence.ProofIdentity{}, errDepartureIdentity
}
b, ok, err := r.Registry.HAIdentity(ctx, ref, iid)
diff --git a/internal/host/hadepartures_page_followups_test.go b/internal/host/hadepartures_page_followups_test.go
new file mode 100644
index 000000000..f6d1b87ab
--- /dev/null
+++ b/internal/host/hadepartures_page_followups_test.go
@@ -0,0 +1,161 @@
+package host
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/service/ec2"
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/hadeparture"
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/hostfiles"
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/lease/locktest"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/termfence"
+)
+
+func TestTerminationFinalizerPagesThroughWiring(t *testing.T) {
+ for _, mode := range []string{"identity", "missing-proof", "invalid-proof", "ec2"} {
+ t.Run(mode, func(t *testing.T) {
+ t.Cleanup(lease.ProcessStateForTest())
+ fx := locktest.NewLockFixture(t)
+ a, _, _ := departureArmFixtureBucket(t, fx.Bucket)
+ a.Backend.Registry = a.Registry
+ a.Backend.DataDir = filepath.Join(t.TempDir(), "data")
+ a.Backend.RunDirOverride = filepath.Join(t.TempDir(), "run")
+ a.Backend.Control = instancectl.NewClient("/unused/control.sock")
+ a.Backend.Cfg.Record = func(context.Context, registry.Route) (activator.RecordFacts, error) {
+ return activator.RecordFacts{LifetimeEntry: provision.LifetimeEntry{ID: "life", HA: true}}, nil
+ }
+ files, err := lease.NewFilesStore(t.Context(), fx.Bucket, a.Self.Scope.CloudRegion)
+ if err != nil {
+ t.Fatal(err)
+ }
+ a.Backend.FilesStore = files
+ rt := registry.Route{Host: "shop.example.com", Kind: "instance", Account: "bab", App: "shop", Status: "ready", HA: true, Provisioned: true, Hibernate: true, DBPath: provision.NestedDBPath(a.Backend.DataDir, "shop.example.com"), Socket: filepath.Join(a.Backend.RunDirOverride, "instances", provision.InstanceID("shop.example.com"), "app.sock")}
+ if err = a.Registry.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ stored, err := a.Registry.Get(rt.Host)
+ if err != nil {
+ t.Fatal(err)
+ }
+ rt = *stored
+ a.Service = activator.New(a.Backend.Cfg, a.Backend, a.Registry)
+ t.Cleanup(func() { a.Service.Shutdown(context.Background()) })
+ a.Service.DutyStore = a.Registry
+ lease.SetSelf(hafresh.Self{Ref: a.Self.Ref, IID: a.Self.InstanceID, Account: a.Self.Account, Region: a.Self.Scope.CloudRegion})
+ if err = lease.SetObligationDir(t.TempDir()); err != nil {
+ t.Fatal(err)
+ }
+ pub, err := hostfiles.Open(t.Context(), files, "instances/"+rt.Host+"/files/0/")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = hostfiles.StageWake(t.Context(), pub, hostfiles.WakeState{V: 1, Host: rt.Host, NextDue: 9999999999}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = pub.Commit(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ c, lifecycle, err := armHADepartures(t.Context(), a)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = lifecycle.Stop(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if mode != "ec2" {
+ if _, err = c.cfg.Identities.Observe(t.Context(), hadeparture.BoxObservation{Known: true, Box: hadeparture.Box{Ref: "dead", Scope: a.Self.Scope}, EdgesKey: "control/edges/dead.json", EdgesETag: "exact"}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ switch mode {
+ case "identity":
+ db, err := sql.Open("sqlite", a.Registry.Path())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ if _, err = db.Exec(`UPDATE ha_box_identities SET body=json_set(body,'$.Digest','bad')`); err != nil {
+ t.Fatal(err)
+ }
+ case "invalid-proof":
+ binding, err := a.Backend.TerminationProofs.Resolve(t.Context(), "dead", "i-1123456789abcdef0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = files.Put(t.Context(), binding.Key(), []byte(`{}`), ""); err != nil {
+ t.Fatal(err)
+ }
+ }
+ a.Confirmer.API = func(context.Context, string) (termfence.EC2, error) {
+ if mode == "ec2" {
+ return describeInstances(func(context.Context, *ec2.DescribeInstancesInput, ...func(*ec2.Options)) (*ec2.DescribeInstancesOutput, error) {
+ return &ec2.DescribeInstancesOutput{}, nil
+ }), nil
+ }
+ return nil, errors.New("unavailable")
+ }
+ a.Backend.OwnerTerminated = a.Confirmer.Terminated
+ body, _ := json.Marshal(hafresh.Lock{Generation: 5, Owner: hafresh.OwnerFor(hafresh.Self{Ref: "dead", IID: "i-1123456789abcdef0"}, 1, true), ExpiresAt: time.Now().Add(-time.Hour)})
+ fx.PutLock("instances/"+rt.Host, body)
+ type page struct{ Level, Subject, Body string }
+ var pages []page
+ armPaging(newAlertSinks("http://example.test/hook", func(_ string, raw []byte) error {
+ var p page
+ if err := json.Unmarshal(raw, &p); err != nil {
+ return err
+ }
+ pages = append(pages, p)
+ return nil
+ }, "", nil, &alertCounters{}))
+ t.Cleanup(func() { armPaging(nil) })
+ held, err := a.Backend.Acquire(t.Context(), rt)
+ if held != nil {
+ _ = held.Release(t.Context())
+ }
+ if err == nil {
+ t.Fatal("visitor acquired")
+ }
+ if len(pages) != 0 {
+ t.Fatal("visitor paged", pages)
+ }
+ observed, err := lease.ReadLock(t.Context(), fx.Bucket, "instances/"+rt.Host, a.Self.Scope.CloudRegion)
+ if err != nil {
+ t.Fatal(err)
+ }
+ duty, err := a.Registry.LoadDuty(t.Context(), rt.Host, "life")
+ if err != nil {
+ t.Fatal(err)
+ }
+ req := activator.Adoption{Departure: "departure-dead", Ref: "dead", IID: "i-1123456789abcdef0", Lifetime: "life", Pair: registry.Pair{Incarnation: rt.Incarnation, ServingSeq: rt.ServingSeq}, Revision: duty.Revision, Observed: observed}
+ for range 2 {
+ result, err := a.Service.AdoptHost(t.Context(), rt, req)
+ if result != activator.Deferred || err == nil {
+ t.Fatalf("adoption=%v err=%v", result, err)
+ }
+ }
+ if len(pages) != 1 {
+ t.Fatalf("pages=%+v, want one finalizer warning", pages)
+ }
+ if pages[0].Level != "warning" || !strings.Contains(pages[0].Body, rt.Host) || !strings.Contains(pages[0].Subject, "dead") {
+ t.Fatalf("page=%+v", pages[0])
+ }
+ for _, request := range fx.Requests() {
+ if request == "PUT instances/"+rt.Host+"/lock.json" {
+ t.Fatal("refused finalizer wrote lock")
+ }
+ }
+ })
+ }
+}
diff --git a/internal/host/hadepartures_proof_followups_test.go b/internal/host/hadepartures_proof_followups_test.go
new file mode 100644
index 000000000..ac34431aa
--- /dev/null
+++ b/internal/host/hadepartures_proof_followups_test.go
@@ -0,0 +1,116 @@
+package host
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/hadeparture"
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/lease/locktest"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+func TestTerminationProofIdentityRefusals(t *testing.T) {
+ for _, mode := range []string{"unbound", "read", "decode", "verification", "digest", "proof-bucket", "unknown", "placement-null", "other-region", "wrong-ref", "wrong-iid"} {
+ t.Run(mode, func(t *testing.T) {
+ t.Cleanup(lease.ProcessStateForTest())
+ fx := locktest.NewLockFixture(t)
+ a, _, describes := departureArmFixtureBucket(t, fx.Bucket)
+ a.Backend.Registry = a.Registry
+ a.Backend.Cfg.Record = func(context.Context, registry.Route) (activator.RecordFacts, error) {
+ return activator.RecordFacts{LifetimeEntry: provision.LifetimeEntry{ID: "life", HA: true}}, nil
+ }
+ lease.SetSelf(hafresh.Self{Ref: a.Self.Ref, IID: a.Self.InstanceID, Account: a.Self.Account, Region: a.Self.Scope.CloudRegion})
+ if err := lease.SetObligationDir(t.TempDir()); err != nil {
+ t.Fatal(err)
+ }
+ if err := a.Registry.Upsert(registry.Route{Host: "shop.example.com", Kind: "instance", Provisioned: true, HA: true}); err != nil {
+ t.Fatal(err)
+ }
+ c, l, err := armHADepartures(t.Context(), a)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = l.Stop(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ ref, iid := "dead", "i-1123456789abcdef0"
+ if mode != "unbound" {
+ _, err = c.cfg.Identities.Observe(t.Context(), hadeparture.BoxObservation{Known: true, Box: hadeparture.Box{Ref: ref, Scope: a.Self.Scope}, EdgesKey: "control/edges/dead.json", EdgesETag: "exact"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ db, err := sql.Open("sqlite", a.Registry.Path())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ var query string
+ switch mode {
+ case "read":
+ query = `ALTER TABLE ha_box_identities RENAME TO unavailable_identities`
+ case "decode":
+ query = `UPDATE ha_box_identities SET body='{'`
+ case "verification":
+ query = `UPDATE ha_box_identities SET body=json_set(body,'$.Raw','e30=')`
+ case "digest":
+ query = `UPDATE ha_box_identities SET body=json_set(body,'$.Digest','bad')`
+ case "proof-bucket":
+ query = `UPDATE ha_box_identities SET observation=json_set(observation,'$.Box.Scope.DataBucket','')`
+ case "unknown":
+ query = `UPDATE ha_box_identities SET observation=json_set(observation,'$.Known',json('false'))`
+ case "placement-null":
+ query = `UPDATE ha_box_identities SET observation=json_set(observation,'$.PlacementNull',json('true'))`
+ case "other-region":
+ query = `UPDATE ha_box_identities SET observation=json_set(observation,'$.Box.Scope.CloudRegion','us-east-1')`
+ case "wrong-ref":
+ ref = "other"
+ case "wrong-iid":
+ iid = "i-2123456789abcdef0"
+ }
+ if query != "" {
+ if _, err = db.Exec(query); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ body, _ := json.Marshal(hafresh.Lock{Generation: 1, Owner: hafresh.OwnerFor(hafresh.Self{Ref: ref, IID: iid}, 1, true), ExpiresAt: time.Now().Add(-time.Hour)})
+ fx.PutLock("instances/shop.example.com", body)
+ observed := 0
+ a.Backend.TerminationProofs.Observe = func(_ string, gone bool, err error) {
+ observed++
+ if mode != "unbound" && (gone || err == nil) {
+ t.Errorf("refusal observation gone=%t err=%v", gone, err)
+ }
+ }
+ held, err := lease.AcquireHA(lease.WithTerminationProof(t.Context(), a.Backend.TerminationProofs), fx.Bucket, "instances/shop.example.com", a.Self.Scope.CloudRegion, hafresh.Marker{Lifetime: "life"}, hafresh.Proofs{OwnerTerminated: func(iid string) (bool, error) { return a.Confirmer.Terminated(t.Context(), iid) }})
+ if held != nil {
+ defer held.Release(context.Background())
+ }
+ if mode == "unbound" {
+ if err != nil || *describes != 1 {
+ t.Fatalf("unbound: err=%v describes=%d", err, *describes)
+ }
+ } else {
+ if err == nil || *describes != 0 {
+ t.Errorf("identity %s: err=%v describes=%d", mode, err, *describes)
+ }
+ for _, request := range fx.Requests() {
+ if strings.HasPrefix(request, "PUT ") {
+ t.Errorf("refused identity wrote %s", request)
+ }
+ }
+ }
+ if observed != 1 {
+ t.Errorf("observations=%d", observed)
+ }
+ })
+ }
+}
diff --git a/internal/host/hadepartures_retained_test.go b/internal/host/hadepartures_retained_test.go
index ae57431d5..7400bb20f 100644
--- a/internal/host/hadepartures_retained_test.go
+++ b/internal/host/hadepartures_retained_test.go
@@ -173,7 +173,7 @@ func TestDepartureFixedRetainedBackoff(t *testing.T) {
if err := json.Unmarshal(raw, &p); err != nil {
t.Fatal(err)
}
- want := page{"page", "warning", "ha_departure_edges_retained", "code=ha_departure_edges_retained key=" + x.d.EdgesKey + " box=" + x.d.Box.Ref}
+ want := page{"page", "warning", fmt.Sprintf(departureRetainedSubject, x.d.Box.Ref), fmt.Sprintf(departureRetainedBody, x.d.Box.Ref, x.d.EdgesKey)}
if p != want {
t.Errorf("retained page=%+v want=%+v", p, want)
}
@@ -183,8 +183,8 @@ func TestDepartureFixedRetainedBackoff(t *testing.T) {
t.Cleanup(func() { armPaging(nil) })
notices := 0
x.c.cfg.Logf = func(f string, args ...any) {
- if strings.HasPrefix(f, "ha_departure_edges_retained") {
- if got := fmt.Sprintf(f, args...); got != "ha_departure_edges_retained key="+x.d.EdgesKey {
+ if strings.Contains(f, "(ha_departure_edges_retained)") {
+ if got := fmt.Sprintf(f, args...); got != fmt.Sprintf(departureRetainedNotice, x.d.EdgesKey) {
t.Errorf("unexpected notice %q", got)
}
notices++
diff --git a/internal/host/hadepartures_scan.go b/internal/host/hadepartures_scan.go
index afb09c68c..fbdbbb08a 100644
--- a/internal/host/hadepartures_scan.go
+++ b/internal/host/hadepartures_scan.go
@@ -305,6 +305,17 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) {
}
return true, c.retryScan(ctx, d, blockers, "scan", len(blockers) > 0 || blocked)
}
+
+// Operator text for two departure faults (copy approved by delegation, one
+// Luna pass, 2026-11-03). Each journal line ends with its machine code in
+// parentheses, so a search for the code still finds it.
+const (
+ departurePermissionNotice = "Termination recovery could not access %s. It will retry. Check that this box's role can read and delete edges files in the deployment bucket. (ha_departure_permission_fault)"
+ departureRetainedNotice = "The edges file %s for a terminated box is still in place. Termination recovery will finish when an operator deletes it. (ha_departure_edges_retained)"
+ departureRetainedSubject = "Remove box %s's edges file"
+ departureRetainedBody = "Box %s was terminated and its duties were recovered. Its edges file %s is still in place because a fixed box's edges file is never deleted automatically. Delete it after checking that no replacement box uses it. This page repeats every hour until then."
+)
+
func (c *Controller) retryScan(ctx context.Context, d registry.HADeparture, hosts []provision.DepartureHost, code string, page bool) error {
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
defer cancel()
@@ -316,7 +327,7 @@ func (c *Controller) retryScan(ctx context.Context, d registry.HADeparture, host
return err
}
if code == "permission_new" {
- c.logf("ha_departure_permission_fault key=%s", d.EdgesKey)
+ c.logf(departurePermissionNotice, d.EdgesKey)
return nil
}
if code == "permission" {
@@ -324,8 +335,8 @@ func (c *Controller) retryScan(ctx context.Context, d registry.HADeparture, host
}
if code == "ha_departure_edges_retained" {
if claimed {
- c.logf("ha_departure_edges_retained key=%s", d.EdgesKey)
- return PageOperator(ctx, alerting.LevelWarning, code, fmt.Sprintf("code=%s key=%s box=%s", code, d.EdgesKey, d.Box.Ref))
+ c.logf(departureRetainedNotice, d.EdgesKey)
+ return PageOperator(ctx, alerting.LevelWarning, fmt.Sprintf(departureRetainedSubject, d.Box.Ref), fmt.Sprintf(departureRetainedBody, d.Box.Ref, d.EdgesKey))
}
return nil
}
diff --git a/internal/host/hadepartures_wiring.go b/internal/host/hadepartures_wiring.go
index 69d5926b9..1ccfa3ec4 100644
--- a/internal/host/hadepartures_wiring.go
+++ b/internal/host/hadepartures_wiring.go
@@ -161,6 +161,7 @@ func armHADepartures(ctx context.Context, a departureArm) (*Controller, hadepart
}
return makeQueue(ctx)
}
+ a.Backend.Page = PageOperator
a.Confirmer.OnConfirmed = c.confirmed
a.Backend.TerminationProofs = &lease.TerminationProofAdapter{Cache: cache, Confirmer: a.Confirmer, Resolve: repo.Proof, Lifetime: func(ctx context.Context, bucket, prefix, region string) (string, error) {
if bucket != a.Backend.Cfg.Bucket || region != a.Backend.Cfg.Region {
diff --git a/internal/lease/termination_proof.go b/internal/lease/termination_proof.go
index ce04d220a..b90426cc0 100644
--- a/internal/lease/termination_proof.go
+++ b/internal/lease/termination_proof.go
@@ -63,7 +63,7 @@ func bindTerminationProof(ctx context.Context, client *s3.Client, bucket, prefix
}
binding, err := adapter.Resolve(ctx, owner.Ref, iid)
if err != nil {
- if fallback != nil {
+ if errors.Is(err, termfence.ErrProofUnbound) && fallback != nil {
gone, err := fallback(iid)
if !gone || err != nil {
return false, err
diff --git a/internal/lease/termination_proof_test.go b/internal/lease/termination_proof_test.go
index a86b1e3a2..deb3b9a94 100644
--- a/internal/lease/termination_proof_test.go
+++ b/internal/lease/termination_proof_test.go
@@ -65,7 +65,7 @@ func TestTerminationProofAcquireOnly(t *testing.T) {
lifetimeReads := 0
adapter := &TerminationProofAdapter{Cache: &termfence.ProofCache{}, Confirmer: confirm, Resolve: func(ctx context.Context, ref, iid string) (termfence.ProofIdentity, error) {
if strings.HasPrefix(mode, "unbound") || ref != "departed" || iid != "i-1123456789abcdef0" {
- return termfence.ProofIdentity{}, errors.New("unbound")
+ return termfence.ProofIdentity{}, termfence.ErrProofUnbound
}
return binding, nil
}, Lifetime: func(context.Context, string, string, string) (string, error) {
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index f5ef6a112..46cdf05f6 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -78,4 +78,5 @@ plan14-root-reads-region-ha-p1b3b-t.tsv c68e2453bfc8afaf3794eb4c08850428982fa695
plan14-root-reads-region-host-store-deny.tsv 951f33500fdf9e47408fd2b8fe8cab419eaf1f6b1803b6ccd169ff19fe7882c6
plan14-root-reads-managed-fleets-2a.tsv f85f8dabebc725fa75b88853af634fa9ca08323721f879e220da44c1e3fdbc38
plan14-root-reads-agent-start-demo-1.tsv 6ef1e3bc1dbacd5b548b1cbfe3a6d37bd5f701e03969feef2736212ee11713df
-plan14-root-reads-stateless-replicas-2.tsv 51b40fb5e2478f2023bd5f50faa87691273bc0cc70e6d63dbb5ec4f68a8c98ff
+plan14-root-reads-region-ha-followups.tsv cfb026f1f9d59f325937cbddf26df2d94d5240d1f7846e80db713b8f6a15c387
+plan14-root-reads-stateless-replicas-2.tsv d28a31401c32770cc079014e82ae49197abb3815b384a77dc4fc8d00f73ed8c6
diff --git a/internal/provision/testdata/plan14-root-reads-region-ha-followups.tsv b/internal/provision/testdata/plan14-root-reads-region-ha-followups.tsv
new file mode 100644
index 000000000..db57a8fdf
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-region-ha-followups.tsv
@@ -0,0 +1,19 @@
+# Census overlay region-ha-followups, written by census-propose (#369). census-ruling-region-ha-followups, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-region-ha-followups.md.
+# 3 body, 3 sites, 5 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@legacy 483c203479120cde40c786e23804ada71cb946154c040c4dc687af44c02a8df2 internal/host/hadeparture_identity.go departureIdentities.Proof legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=B3b: read immutable box bytes and local verified bindings; require AWS signature plus independent fixed/group binding, unique ref/iid, exact digest and known scope. Unknown walks persist one 1000-key page and at most 32 new GETs per turn; errors never prove absence.;rev3=census-ruling-region-ha-followups;basis=Allow live EC2 fallback only after clean absence of pair, ref and iid; identity read errors, mismatches and verification failures refuse. Additional reads use the existing registry identity lookup for ref and iid separately. registry:Raw@925 d81bcf013b1bf180184550c4fe1db5991cf4d77c863426a0350d2121b0fb6fa5
+@legacy 82819cd1bd69e3bd69d66deba797e44970909f13ed648943528e19e92db27028 internal/host/hadepartures_scan.go Controller.retryScan legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=B4: Read only the bound departure to persist bounded retry timing and the existing hourly per-departure page claim. No completion authority. Fix r1/P15: bound detached retry bookkeeping to five seconds so cancellation still records backoff/page. Permission episodes use only the structured ha_departure_permission_fault code and key, never wake-state prose. B4 fix r4/P18: Retained fixed edges use the existing persisted 30/60/120/300-second retry and hourly departure claim, emitting only ha_departure_edges_retained plus the key. Skip generic prose paging for that code. B4 fix r5: After the existing durable hourly claim succeeds for retained fixed edges, keep the structured log and send PageOperator a warning with subject ha_departure_edges_retained and body code/key/box fields through the existing bounded alert sinks. Return delivery errors; never call the generic C3 page for this state. No new read site or completion authority. B5: Emit permission notice only on permission_new, the persisted fault-episode transition; suppress repeat hourly permission logs. Other departure pages retain the durable hourly claim.;rev3=census-ruling-region-ha-followups;basis=Use the approved operator text for permission-fault and retained-edges notices and pages. Keep persisted retry timing, permission-episode suppression and the hourly page claim unchanged; no new read or completion authority. whole:HADeparture@1075 659e664756bc9750424ab043c40bbdc88e0764d873320faf0cf802b26a61614e
+@legacy 4b3bd237cdebfb9bb284f24d4892f973956e208951694a833a92f53e5c021b74 internal/host/hadepartures_wiring.go armHADepartures legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=B3 fix r1: Install proof adapter, adoption identity and suspicion callbacks before asynchronous startup. Lazily retry the same deployment/data clients; lifetime callback reads only the current host through ExecBackend.TerminationLifetime. Add bounded structured paging for unresolved per-iid records. No new bucket, tenant input path or acquire bypass. B4: Wire the shared lock reader and existing AdoptHost entry. Read local route, Pair and duty revision only after authoritative inventory eligibility; bind its record lifetime and refuse missing/mismatched local routes. No route synthesis or pool widening. B5: Publish the armed controller to the existing metrics sampler. No new loop, remote source or process authority.;rev3=census-ruling-region-ha-followups;basis=Inject the existing PageOperator function into the backend when HA departures are armed; no new read or paging transport. registry:Account@3494,registry:Account@7088,registry:App@7115,registry:IID@3515,registry:Incarnation@7275,registry:Pool@7134,registry:Region@3505,registry:Region@7155,registry:Revision@7510,registry:Revision@7907,registry:ServingSeq@7303,whole:DutyState@7629,whole:Pair@7492,whole:Pair@7885,whole:Pair@7891,whole:Route@7075,whole:Route@7784 f9f261f51c304508d6e989e75231debc648c5b613275dea26c70acea9757e55c
+@legacy 798811939bbc49ed2e48e5f0cf32221560070d13c68a7f5109c99a21b8a7380d internal/activator/haadopt.go Service.AdoptHost legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=Serialize through the existing host operation state. Read local route/revision/receipt plus configured lock/manifest/wake objects; use only restricted ordinary acquire, exact guarded restore, ordinary unclean release and verified readback for adoption. No process launch, local-copy reuse or secret access. B3: pass the optional shared durable termination proof adapter into the existing restricted finalizer acquire. The adapter validates the exact classified peer and current host lifetime, uses the acquire data-bucket client, and cannot bypass expiry or CAS. No new read in this unit. B4: A first scanner import may reuse its staging lock observation; the ordinary acquire still rereads and compares the exact ETag/generation and expiry. Existing receipt replay keeps its fresh read. No new read path or takeover authority.;rev3=census-ruling-region-ha-followups;basis=Attach a per-acquire termination proof observer to finalizer acquisitions so refusals retain alarms; avoid duplicate fallback observations. The observer receives the existing route and departure ref for paging; no new storage read or takeover authority. registry:AcquiredGeneration@2549,registry:AcquiredGeneration@2922,registry:AcquiredGeneration@3700,registry:AcquiredGeneration@4312,registry:AcquiredGeneration@4403,registry:AcquiredGeneration@5042,registry:AcquiredGeneration@5133,registry:DepartureIID@1797,registry:DepartureIID@5641,registry:DepartureRef@1761,registry:DepartureRef@5625,registry:ExpectedPair@8079,registry:Host@1162,registry:Host@1258,registry:Host@1330,registry:Host@1399,registry:Host@1665,registry:Host@2040,registry:Host@2766,registry:Host@3103,registry:Host@3490,registry:Host@5454,registry:Host@5875,registry:Host@6060,registry:Host@7084,registry:Host@7841,registry:Host@8143,registry:Host@861,registry:Host@8706,registry:Host@959,registry:Lifetime@5677,registry:Lifetime@8048,registry:LockETag@5712,registry:LockGeneration@1833,registry:LockGeneration@5724,registry:Phase@2881,registry:Phase@2898,registry:Phase@3240,registry:Phase@3278,registry:Phase@3334,registry:Phase@4344,registry:Phase@4436,registry:Phase@4986,registry:Phase@5074,registry:Receipt@5701,registry:Revision@3122,registry:Revision@5689,registry:Sequence@3026,registry:Sequence@3046,registry:WakeDigest@2985,registry:WakeDigest@3007,whole:HAAdoption@3139,whole:HAAdoption@6016,whole:HAWakeImport@2968,whole:HAWakeImport@5596,whole:HAWakeImport@5612,whole:HAWakeImport@5620,whole:HAWakeImport@5894,whole:HAWakeImport@7850,whole:HAWakeImport@8152,whole:HAWakeImport@8244,whole:Pair@3116,whole:Pair@5888,whole:Pair@8085,whole:Pair@8105,whole:Route@1128,whole:Route@1171,whole:Route@1178,whole:Route@138,whole:Route@193,whole:Route@2698,whole:Route@3400,whole:Route@453,whole:Route@4713,whole:Route@531,whole:Route@5543,whole:Route@6597,whole:Route@6642,whole:Route@6797,whole:Route@723,whole:Route@7352,whole:Route@7937,whole:Route@889 946a102ba08ce347a42263ecc03fe95b429e7acc93547972b38cd92be4c6f7ac
+@legacy 8f854e386e1dc80beb6c68dad70615ad8c14c963b821685d9cbadfa0a25f03db internal/activator/hatakeover.go ExecBackend.reportTakeover legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=Final fix P2-1: report all refused proof results through the per-host alarm and distinguish visitor from departure-finalize. No reads or authority.;rev3=census-ruling-region-ha-followups;basis=Page only departure-finalize proof refusals through the injected host sink, at warning level and once per host per hour. Send on a detached five-second context and log send failures. Read the existing route Host for page throttling, body and failure logging; no new storage read or takeover authority. registry:Host@1147,registry:Host@1299,registry:Host@347,registry:Host@429,registry:Host@870,registry:Host@973 21cd67e0d112da40a7587283a7651c4fe12fb1382124d93002bfee02d3c96897
+@legacy 9be352a054787e5ca61ba5bbad294e1c1a53ee4e15c81d6d70c9c9f38719cb07 internal/edge/forwardha.go Edge.frontForwardHA legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): the agent's edge decides at the front door whether to forward a visitor request: reads the route's HA flag and host from the box's own registry row and asks the activator; forwards only to a box in view over the existing signed hop; root never calls it;rev3=census-ruling-region-ha-dead-holder-backoff;basis=ForwardTarget returns a ForwardDecision (Ref, Refuse, Gen); a Refuse is answered at the front door with the existing unreachable answer (503, Retry-After: 10, same body, via answerHolderUnreachable), with no forward, dial, note or per-request step. A forward passes the decision to forwardHA and NoteForward carries Ref and Gen back. The round-1 connection callback (NoteConnected) is gone: the dial bound now lives in forwardTransport's forwardDialGate, which coalesces TCP dials per holder address in memory. The same 5 read sites; no new read; root never calls it.;rev3=census-ruling-region-ha-p1b3a;basis=Pass the existing route to a lazy cached wakeSnapshot closure, handle explicit local denial before all accounting, and refuse a disappeared Placement choice rather than falling through locally; whole Route read only, no new store or filesystem operation and no root authority.;rev3=census-ruling-edge-held-streams;basis=the edge in the agent (carlos-edge.service, user carlos): for a marked request to a hibernating HA route it uses the new HAForwarderFromMemory (ForwardTargetFromMemory) instead of ForwardTarget, so the hold path makes no holder-lock read; a non-stream marked request is left to this box's classification, and a holder not known from memory is answered with the one-retry event. The unmarked path is unchanged. Reads only the request mark and the already-loaded route and home map; no read added.;rev3=census-ruling-region-ha-followups;basis=Report detached TCP/TLS failure after a canceled Placement or Recovery request through the existing NoteForward classifier, preserving Ref, Gen and PeerGen. Reuse the route Host to correlate the late result; no new storage read or routing authority. registry:HA@225,registry:Hibernate@584,registry:Host@1833,registry:Host@2103,whole:Route@1244,whole:Route@1368,whole:Route@1836,whole:Route@2106,whole:Route@228,whole:Route@515,whole:Route@587 49fb997abc1b78de4456e64378c691fa191ca04541eddeedcddd80570989d298
+internal/host/hadeparture_identity.go departureIdentities.Proof legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=B3b: read immutable box bytes and local verified bindings; require AWS signature plus independent fixed/group binding, unique ref/iid, exact digest and known scope. Unknown walks persist one 1000-key page and at most 32 new GETs per turn; errors never prove absence.;rev3=census-ruling-region-ha-followups;basis=Allow live EC2 fallback only after clean absence of pair, ref and iid; identity read errors, mismatches and verification failures refuse. Additional reads use the existing registry identity lookup for ref and iid separately. registry:Raw@925 d81bcf013b1bf180184550c4fe1db5991cf4d77c863426a0350d2121b0fb6fa5
+internal/host/hadepartures_scan.go Controller.retryScan legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=B4: Read only the bound departure to persist bounded retry timing and the existing hourly per-departure page claim. No completion authority. Fix r1/P15: bound detached retry bookkeeping to five seconds so cancellation still records backoff/page. Permission episodes use only the structured ha_departure_permission_fault code and key, never wake-state prose. B4 fix r4/P18: Retained fixed edges use the existing persisted 30/60/120/300-second retry and hourly departure claim, emitting only ha_departure_edges_retained plus the key. Skip generic prose paging for that code. B4 fix r5: After the existing durable hourly claim succeeds for retained fixed edges, keep the structured log and send PageOperator a warning with subject ha_departure_edges_retained and body code/key/box fields through the existing bounded alert sinks. Return delivery errors; never call the generic C3 page for this state. No new read site or completion authority. B5: Emit permission notice only on permission_new, the persisted fault-episode transition; suppress repeat hourly permission logs. Other departure pages retain the durable hourly claim.;rev3=census-ruling-region-ha-followups;basis=Use the approved operator text for permission-fault and retained-edges notices and pages. Keep persisted retry timing, permission-episode suppression and the hourly page claim unchanged; no new read or completion authority. whole:HADeparture@1075 659e664756bc9750424ab043c40bbdc88e0764d873320faf0cf802b26a61614e
+internal/host/hadepartures_wiring.go armHADepartures legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=B3 fix r1: Install proof adapter, adoption identity and suspicion callbacks before asynchronous startup. Lazily retry the same deployment/data clients; lifetime callback reads only the current host through ExecBackend.TerminationLifetime. Add bounded structured paging for unresolved per-iid records. No new bucket, tenant input path or acquire bypass. B4: Wire the shared lock reader and existing AdoptHost entry. Read local route, Pair and duty revision only after authoritative inventory eligibility; bind its record lifetime and refuse missing/mismatched local routes. No route synthesis or pool widening. B5: Publish the armed controller to the existing metrics sampler. No new loop, remote source or process authority.;rev3=census-ruling-region-ha-followups;basis=Inject the existing PageOperator function into the backend when HA departures are armed; no new read or paging transport. registry:Account@3494,registry:Account@7088,registry:App@7115,registry:IID@3515,registry:Incarnation@7275,registry:Pool@7134,registry:Region@3505,registry:Region@7155,registry:Revision@7510,registry:Revision@7907,registry:ServingSeq@7303,whole:DutyState@7629,whole:Pair@7492,whole:Pair@7885,whole:Pair@7891,whole:Route@7075,whole:Route@7784 f9f261f51c304508d6e989e75231debc648c5b613275dea26c70acea9757e55c
+internal/activator/haadopt.go Service.AdoptHost legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=Serialize through the existing host operation state. Read local route/revision/receipt plus configured lock/manifest/wake objects; use only restricted ordinary acquire, exact guarded restore, ordinary unclean release and verified readback for adoption. No process launch, local-copy reuse or secret access. B3: pass the optional shared durable termination proof adapter into the existing restricted finalizer acquire. The adapter validates the exact classified peer and current host lifetime, uses the acquire data-bucket client, and cannot bypass expiry or CAS. No new read in this unit. B4: A first scanner import may reuse its staging lock observation; the ordinary acquire still rereads and compares the exact ETag/generation and expiry. Existing receipt replay keeps its fresh read. No new read path or takeover authority.;rev3=census-ruling-region-ha-followups;basis=Attach a per-acquire termination proof observer to finalizer acquisitions so refusals retain alarms; avoid duplicate fallback observations. The observer receives the existing route and departure ref for paging; no new storage read or takeover authority. registry:AcquiredGeneration@2549,registry:AcquiredGeneration@2922,registry:AcquiredGeneration@3700,registry:AcquiredGeneration@4312,registry:AcquiredGeneration@4403,registry:AcquiredGeneration@5042,registry:AcquiredGeneration@5133,registry:DepartureIID@1797,registry:DepartureIID@5641,registry:DepartureRef@1761,registry:DepartureRef@5625,registry:ExpectedPair@8079,registry:Host@1162,registry:Host@1258,registry:Host@1330,registry:Host@1399,registry:Host@1665,registry:Host@2040,registry:Host@2766,registry:Host@3103,registry:Host@3490,registry:Host@5454,registry:Host@5875,registry:Host@6060,registry:Host@7084,registry:Host@7841,registry:Host@8143,registry:Host@861,registry:Host@8706,registry:Host@959,registry:Lifetime@5677,registry:Lifetime@8048,registry:LockETag@5712,registry:LockGeneration@1833,registry:LockGeneration@5724,registry:Phase@2881,registry:Phase@2898,registry:Phase@3240,registry:Phase@3278,registry:Phase@3334,registry:Phase@4344,registry:Phase@4436,registry:Phase@4986,registry:Phase@5074,registry:Receipt@5701,registry:Revision@3122,registry:Revision@5689,registry:Sequence@3026,registry:Sequence@3046,registry:WakeDigest@2985,registry:WakeDigest@3007,whole:HAAdoption@3139,whole:HAAdoption@6016,whole:HAWakeImport@2968,whole:HAWakeImport@5596,whole:HAWakeImport@5612,whole:HAWakeImport@5620,whole:HAWakeImport@5894,whole:HAWakeImport@7850,whole:HAWakeImport@8152,whole:HAWakeImport@8244,whole:Pair@3116,whole:Pair@5888,whole:Pair@8085,whole:Pair@8105,whole:Route@1128,whole:Route@1171,whole:Route@1178,whole:Route@138,whole:Route@193,whole:Route@2698,whole:Route@3400,whole:Route@453,whole:Route@4713,whole:Route@531,whole:Route@5543,whole:Route@6597,whole:Route@6642,whole:Route@6797,whole:Route@723,whole:Route@7352,whole:Route@7937,whole:Route@889 946a102ba08ce347a42263ecc03fe95b429e7acc93547972b38cd92be4c6f7ac
+internal/activator/hatakeover.go ExecBackend.reportTakeover legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=Final fix P2-1: report all refused proof results through the per-host alarm and distinguish visitor from departure-finalize. No reads or authority.;rev3=census-ruling-region-ha-followups;basis=Page only departure-finalize proof refusals through the injected host sink, at warning level and once per host per hour. Send on a detached five-second context and log send failures. Read the existing route Host for page throttling, body and failure logging; no new storage read or takeover authority. registry:Host@1147,registry:Host@1299,registry:Host@347,registry:Host@429,registry:Host@870,registry:Host@973 21cd67e0d112da40a7587283a7651c4fe12fb1382124d93002bfee02d3c96897
+internal/edge/forwardha.go Edge.frontForwardHA legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): the agent's edge decides at the front door whether to forward a visitor request: reads the route's HA flag and host from the box's own registry row and asks the activator; forwards only to a box in view over the existing signed hop; root never calls it;rev3=census-ruling-region-ha-dead-holder-backoff;basis=ForwardTarget returns a ForwardDecision (Ref, Refuse, Gen); a Refuse is answered at the front door with the existing unreachable answer (503, Retry-After: 10, same body, via answerHolderUnreachable), with no forward, dial, note or per-request step. A forward passes the decision to forwardHA and NoteForward carries Ref and Gen back. The round-1 connection callback (NoteConnected) is gone: the dial bound now lives in forwardTransport's forwardDialGate, which coalesces TCP dials per holder address in memory. The same 5 read sites; no new read; root never calls it.;rev3=census-ruling-region-ha-p1b3a;basis=Pass the existing route to a lazy cached wakeSnapshot closure, handle explicit local denial before all accounting, and refuse a disappeared Placement choice rather than falling through locally; whole Route read only, no new store or filesystem operation and no root authority.;rev3=census-ruling-edge-held-streams;basis=the edge in the agent (carlos-edge.service, user carlos): for a marked request to a hibernating HA route it uses the new HAForwarderFromMemory (ForwardTargetFromMemory) instead of ForwardTarget, so the hold path makes no holder-lock read; a non-stream marked request is left to this box's classification, and a holder not known from memory is answered with the one-retry event. The unmarked path is unchanged. Reads only the request mark and the already-loaded route and home map; no read added.;rev3=census-ruling-region-ha-followups;basis=Report detached TCP/TLS failure after a canceled Placement or Recovery request through the existing NoteForward classifier, preserving Ref, Gen and PeerGen. Reuse the route Host to correlate the late result; no new storage read or routing authority. registry:HA@225,registry:Hibernate@584,registry:Host@1833,registry:Host@2103,whole:Route@1244,whole:Route@1368,whole:Route@1836,whole:Route@2106,whole:Route@228,whole:Route@515,whole:Route@587 49fb997abc1b78de4456e64378c691fa191ca04541eddeedcddd80570989d298
+@coverage internal/activator 32ff596a2f6f023a26f06f2b18c27b6f399ac1111846f1a0e20ac7d7ebe6c0e0
+@coverage internal/edge a3cbd20538b38c2e6c0b9174f13af4efb9a75de3106e1857af406c53c919b2bd
+@coverage internal/host f23595b5431d48ef6a02f1066738492b0ef8b5c4e03d4ff41e779c8eb85b52e2
+@coverage internal/lease 8f86fe32a2dead1e40c5137ffbeb122b0e9c4178a79c85d1907f8f9fd40404f6
+@coverage internal/termfence 7a07efdde97fd45351ba0692da510752b14a6f142efaa1f3061635eacd27aec9
diff --git a/internal/provision/testdata/plan14-root-reads-stateless-replicas-2.tsv b/internal/provision/testdata/plan14-root-reads-stateless-replicas-2.tsv
index af61c9c67..2292042ba 100644
--- a/internal/provision/testdata/plan14-root-reads-stateless-replicas-2.tsv
+++ b/internal/provision/testdata/plan14-root-reads-stateless-replicas-2.tsv
@@ -84,9 +84,9 @@ internal/host/runs.go runsWorker.pickupOwned legacy accepted-legacy accepted-leg
internal/provision/forward.go forwardRowFor legacy accepted-legacy accepted-legacy;rev3=census-ruling-agent-start-demo-1;basis=Copies the public descriptor into a forward row; no new external read.;rev3=census-ruling-stateless-replicas-2;basis=Projects declarative set fields from supplied record; keeps socket, database, execution and all other forbidden fields zero. merge of origin/main 6be08467: Stamp main demo descriptor and project replica fields; merge-only composition, mixed projections refuse. whole:Route@436,whole:Route@462,whole:Route@479 e7294d6a3c96e51646257200f5cedb26aaf491afea23be3d943b3e3f742c4db4
internal/provision/reconcile.go RouteFor authority C,E3 rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos); also root, in the claim root's landing registration (ClaimRootHTTP.rootLandingRoute) and the relocation install (relocationRecord): census-ruling-seeded-instances's body with two more fields from the record: the row's lifetime pair (rec.Incarnation, rec.MoveSeq), so a row minted outside a move takes the record's lifetime and its last move's sequence (0, 0 for a fieldless record with no move history); every caller gets it, the root ones included: the root callers (ClaimRootHTTP.rootLandingRoute, relocationRecord) now mint (0, move_seq) on a claims-on record, a non-zero sequence once that record has had an offline move (move_seq advances on claims-on offline moves too), which moves Fingerprint and SnapshotFingerprint once for that row; main's C,E3 authority retained; self-serve moves 1 Task 7 (fix round 1: root callers named);rev3=census-ruling-region-ha-p1a;basis=the agent's reconcile passes, and also root's callers (rootupdates.go, rootinventory_install.go and relocationinstall.go on HEAD): one more field copied from the record, HA: rec.HA, so a row minted from a record stamped HA carries the sticky born-HA mark; the record is the console-written instance record each caller already read; root's own code reads nothing of Route.HA, and Fingerprint does not include it (SnapshotFingerprint does, for a set mark); the same nine sites, no read added;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 2: the row is minted with the record's Runtime (the console-written instance record, guarded by WriteRecord's runtimeFixed); a rootfs row always gets the nested socket and db path under dataDir and no seed or seed source; the paths are computed from the host, not read from the record;rev3=census-ruling-fresh-box-446;basis=#446: a born-HA record mints the nested paths whatever nested says, as a rootfs row already does; same reads;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (Task 2, rule 6): the route also carries Assigned = rec.FleetBoxAt and Moved = rec.FleetBoxMoved, copied from the record it is handed. Read sites unchanged (13). In the agent; in root's claim landing registration (ClaimRootHTTP.rootLandingRoute, shelved claims code) the canonical route gains these two copied fields, which no root check compares (the comparison at rootinventory.go and ValidateAgentInventory read neither). No new input to root.;rev3=census-ruling-agent-start-demo-1;basis=Reads the record descriptor, carries it onto the route, and gives demos nested paths; no new external read.;rev3=census-ruling-stateless-replicas-2;basis=Projects count, canonical boxes, revision, CreatedAt-derived lifetime and stateless hint from the supplied record. No store read; hint does not authorize a database bypass. merge of origin/main 6be08467: Retain main demo nested paths and descriptor stamping beside replica projection; merge-only composition. registry:Addr@2781,registry:Addrs@2790,registry:DBPath@1735,registry:DBPath@2277,registry:DBPath@2699,registry:Health@2800,registry:Hibernate@2221,registry:Seed@2745,registry:SeedSource@2754,registry:Socket@1697,registry:Socket@2239,registry:Socket@2662,whole:Route@1635,whole:Route@1661,whole:Route@2838 96a0a5db54cb6351554666c79b20840b036e911b0990466309d5a0878c7c3f9e
@coverage . 372c4a4f4440d5991544754d725708e41e58ce456a58881d979d55942a717500
-@coverage internal/activator b20c444e03434c29a0d2a4cdbfc83d0af2f06942b10d6f0b46590f0717e69d02
+@coverage internal/activator fc9913c298143ea3cd3db106d7a7619a1d3cd9596f0ebb3107405700352041c4
@coverage internal/appconfig 32d5f27628b319917ed88ac39e0b22e25292f8f16ba5ef4e69a57ea35471bf77
-@coverage internal/host 0272fdd59f9cc0b02884c3a5ef38f94eebdb89f727b31f2397470532e349d825
+@coverage internal/host 4eb0865a9840c2c23f1fb37fd8afb8eb76015c97a2d32a45ae2095b0485071ed
@coverage internal/provision d0751594b0a344adc22450fc1567ac935d32ed5381dbdc0b90e9c1aada0eedb1
@coverage internal/registry b11e7d08ce42bc14c020d73e0544fade94560dcff673532ea67c0db767a714d8
@coverage internal/release b645fd5a9599a020041d660b20b3d9ce03bc7dbd29ff506cad20a90cdc327fe8
diff --git a/internal/termfence/termination_proof.go b/internal/termfence/termination_proof.go
index 7f5588a3b..c0e3a5f82 100644
--- a/internal/termfence/termination_proof.go
+++ b/internal/termfence/termination_proof.go
@@ -19,6 +19,9 @@ import (
const MaxTerminationProofBytes = 2048
+// ErrProofUnbound means the identity registry has no binding for either owner identifier.
+var ErrProofUnbound = errors.New("ha_termination_proof_unbound")
+
var ErrTerminationProof = errors.New("ha_termination_proof_invalid")
var proofIID = regexp.MustCompile(`^i-([0-9a-f]{8}|[0-9a-f]{17})$`)
var proofAccount = regexp.MustCompile(`^[0-9]{12}$`)