carlos / platform Public

Bound HA release steps by the agent shutdown deadline

Start the 90-second agent deadline at the edge signal receive point and
preserve shorter shutdown joins. Reserve final-sync and marker time while
keeping HA finalization synchronous and report unreleased entries at exit.

Cover clean, timed-out and stuck release paths, preserve normal budgets,
and add the Task 2 root-read census proposal.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 037fccf323e4f3a450d21e9e86becb2e7aec9256 parent b9a4e60
12 files changed, +475 −14
  • docs/superpowers/notes/census-proposal-region-ha-graceful-terminate-t2.md +25 −0
  • internal/activator/activator.go +29 −0
  • internal/activator/harelease.go +31 −3
  • internal/activator/harelease_shutdown_test.go +276 −0
  • internal/edge/edge.go +3 −2
  • internal/edge/shutdown.go +14 −0
  • internal/edge/shutdown_test.go +32 −0
  • internal/host/agent.go +6 −2
  • internal/host/claimfilesseed_shutdown.go +10 −6
  • internal/host/claimfilesseed_shutdown_test.go +37 −1
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-region-ha-graceful-terminate-t2.tsv +11 −0

Intent

Human

<task-notification> <task-id>b73h8b344</task-id> <tool-use-id>toolu_01YRW8KoGqotyFfC5aY1WReY</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/c23f0319-4761-45f6-bac7-f9471c7b9ab1/tasks/b73h8b344.output</output-file> <status>completed</status> <summary>Background command "W=/home/paulca/amadan.net/carlos/platform/.claude/worktrees/ha-graceful/.superpowers/sdd/2026-11-08-region-ha-graceful-terminate; until [ -f $W/task-1-fix1.done ]; do sleep 20; done; echo fix1 done" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>a710b21ebd67dd010</task-id> <tool-use-id>toolu_01GZwmuv7d8HDKM3DsQyarjB</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/c23f0319-4761-45f6-bac7-f9471c7b9ab1/tasks/a710b21ebd67dd010.output</output-file> <status>completed</status> <summary>Agent "Re-review Task 1 fix round 1" 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>### Finding Verdicts 1. **carlos-instance-control.service needs After=nftables.service, with a test and no cycle** — ADDRESSED. - `internal/host/units/carlos-instance-control.service:~29-31` adds only `After=nftables.service`, with a comment saying why. There is no Wants or Requires. - `internal/host/units_shutdown_test.go:158-166` asserts the `After=`. It also asserts that no `Wants=` or `Requires=` names nftables. - There is no cycle. The edge's `After=` already lists control (`carlos-edge.service:15`), and the group drop-in orders the edge after nftables (`carlos-edge-group.conf:3`). Control has no `Before=` against the edge, and the test still enforces that. The nftables-before-`network-pre.target` edge is modelled in the test (`units_shutdown_test.go:172`). The ordering chain is nftables, then control, then the edge. - The report's static `systemd-analyze` run exited 1 only because `/opt/carlos/carlos` is missing. It shows no ordering cycle. 2. **Fold the carlos-edge-group.conf directives into the carlos-edge.service node before the cycle DFS** — ADDRESSED. - `units_shutdown_test.go:140-143` appends the drop-in's properties onto `units[edge]` and then deletes the separate node. - The DFS now walks `after`, so the folded edge carries nftables in its `[Unit]After`. The assertion at line 147 confirms it. - The drop-in is embedded at lines 99-100 and parsed like any unit (comments and blank lines skipped). 3. **carlos-instance-control.service header comment still says "Socket-activated"** — ADDRESSED. - Lines 1-4 now say the edge's `Wants=` starts it at boot, it stays up through the edge's stop (T1/DR-4), and the socket still activates it if it is not running. ### New Breakage in the Fix Diff None. - Minor: the header comment's rewrap leaves a short orphan line, "Its whole job is", at `carlos-instance-control.service:5`. It is cosmetic only. - The census overlay and proposal were regenerated for the control unit. The report shows `TestPlan14RootReadCensus`, `TestCensusScopeIsTheRootBinary` and `TestPlan14RootInputInventoryCoverage` passing. It also shows vet, gofmt and `git diff --check` clean. - The report does not show an explicit run of `TestEdgeShutdownKeepsControlAvailable`. Nothing in the diff raises a doubt about it. I did not re-run it. ### Out-of-Scope Observations None. ### Verdict **Fix round:** All findings addressed, no new Critical/Important breakage.</result> <usage><subagent_tokens>46090</subagent_tokens><tool_uses>4</tool_uses><duration_ms>19716</duration_ms></usage> </task-notification>

Attributed to this commit: 12.1 g CO₂e (1,440,710 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-graceful-terminate, 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/superpowers/notes/census-proposal-region-ha-graceful-terminate-t2.md b/docs/superpowers/notes/census-proposal-region-ha-graceful-terminate-t2.md
new file mode 100644
index 000000000..816ed2f5c
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-region-ha-graceful-terminate-t2.md
@@ -0,0 +1,25 @@
+# Census approval: region-ha-graceful-terminate-t2
+
+Ruling `census-ruling-region-ha-graceful-terminate-t2`. 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/activator/harelease.go` `Service.releaseHAClean` | body | unchanged (6) | Cap Final, Finish and marker contexts by the shutdown deadline and reserves; keep calls synchronous and stop proof unchanged; record successful marker completion under the service mutex. No read added. |
+| `internal/edge/edge.go` `RunWithActivatorReady` | body | unchanged (5) | Invoke the agent shutdown timestamp hook synchronously at SIGTERM/SIGINT receipt before closing admission in dev and TLS paths. No read added. |
+| `internal/host/agent.go` `runAgent` | body | unchanged (9) | Derive one signal-time deadline with a 90-second budget; cap departure stop and startup/seed/service shutdown joins by it. No read added. |
+| `internal/host/claimfilesseed_shutdown.go` `joinAgentShutdown` | body | unchanged (0) | Bound existing cleanup, startup joins and 60-second service context by the absolute signal-time deadline without extending shorter budgets. No read added. |
+
+Envelopes re-pinned: `internal/activator`, `internal/edge`, `internal/host`.
+
+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/activator/harelease.go` `Service.releaseHAClean`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: an HA entry's release, in order: host slice read empty through haHostEmpty (else errHostSliceUnproven and nothing written; the same check, moved into that helper by final fix F1), stop and join the files publisher, its final publish (2 min budget), the replica's final sync (Finish, 30 s), the local release record, then the release marker PUT (10 s), clean only when the final publish was complete and the sync and record succeeded; a failed PUT is a persisted lease obligation; +registry:Host, +whole:Route x4;rev3=census-ruling-region-ha-p1b3b-t;basis=Record advisory local-release basis only after ReleaseMarker succeeds. Add a whole-route argument to local duty bookkeeping; release order and lease authority unchanged.;rev3=census-ruling-region-ha-g2-fixes;basis=Latch unexpected lease loss before release and mark intentional release so ErrSpent alone is not treated as loss; no new read.
+- `internal/edge/edge.go` `RunWithActivatorReady`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-certwarm-wake;basis=registers the cert warm's nudge on OnReload and on the home map's new served-hosts wake (#386); nudge only sends on a buffered channel; no read added, same 5 sites;rev3=census-ruling-edge-roll-blip;basis=the :80/:443 (and dev) listeners are bound on the calling goroutine with net.Listen via listen()/listenAddr (same empty-address defaults as ListenAndServe) before the serve goroutines, which now call Serve/ServeTLS on them, and one log line names the bound addresses; no read added, same 5 sites;rev3=census-ruling-edge-held-streams;basis=the edge in the agent (carlos-edge.service, user carlos): the inline home-map arming (newHomeMap, one boot Refresh, Store, run) moves unchanged into the new Edge.ArmHomeMap and is called here as e.ArmHomeMap(); same refresh, same timeout, same order. The reads are moved, none added.;rev3=census-ruling-agent-start-demo-1;basis=Logs the combined explicit wildcard parents through demoWildcardDomains; no new watcher or read loop.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: invoke the local admission Close before HTTP/HTTPS draining and door shutdown in both dev and normal listeners. Preserve merged main's startup behavior and its census basis; the same five read sites, no new reads.;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: defer stopping and joining the edge's replica jobs at shutdown. Existing five direct read sites unchanged; no new reader or authority.;rev3=census-ruling-region-ha-p3b;basis=Wrap dev, HTTP and HTTPS listeners through ConfigureGroupHairpin before serving. Indirectly read protected root boot identity and group-ingress.json; kernel local/peer addresses mark local ingress, never HTTP headers. Agent edge uses verified public source for accounting; direct read sites unchanged and absent marker keeps original listeners. CI fix removes interface enumeration: local peer must match snapshot primary IPv4, an ingress IPv4 installed locally by root, or loopback; kernel destination must still be an ingress EIP on port 80/443. Merge 45cebde4 retains deferred stopReplicaProbes alongside group listener wrapping and shutdown admission closure.;rev3=census-ruling-demo-api-site-route;basis=Change the startup failure context from load routes to initialize because origin validation now runs during construction. Existing five read sites unchanged; no new read or runtime authority.
+- `internal/host/agent.go` `runAgent`: authority, task B,C,D,F. Basis: rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): builds the box's lifetime judge once (newBoxJudge, nil with host claims on) and hands it to the seed placement, the moves and runs workers and every loop it starts; read sites unchanged, offsets moved; B,C,D,F authority retained; self-serve moves 1 Task 8: derives the box's lifetimes switch from the judge once (lifetimes := boxJudge != nil) and hands it to the edges file loop; read sites unchanged, offsets moved;rev3=census-ruling-plans-4d-lapse;basis=arms two more plans hooks from the same snapshot: e.SetPlanDisabledFor(planDisabledFor) beside SetPlanGovernedFor, and svc.SetDisabledFor(planDisabledRoute) beside SetMaxRunFor (plans 4d); the reads live in those units (plans-4d-units decision); read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 9b81d97b (with main's plan rate ceiling, edge request records, regional box names, self-serve moves plan 1, plans 4d-1 lapse and its other later changes under main's own census rulings) plus the rootfs placement wiring in the activator start: an agentRootfs built from eb.NestedOK, CARLOS_DEPLOYMENT_SINGLE_TENANT, CARLOS_POOLS, the claim flag, swapArming's answer, the control client's /ready/rootfs and, on a fleet box whose identity resolved, fleetOwnerCheck over the deploy store main already opens for the fleet label (fleetStore), then arm and armedRootfs.Store; this body reads nothing new itself; the closures it wires read later, at a rootfs wake and each status tick: GET /ready/rootfs over the control socket, NestedOK's checks, and release.FleetOwnerKey for the judged row's own account and this box's fleet from the deploy store;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Tasks 7 and 11, #329 plan 3 Task 7 and plan 1 Task 7's policy cache: the control client is built once and handed to eb.Control, to the status tick (egressStatus) and to a new egressNudgeLoop goroutine; armSizeSource(svc, "/sys/fs/cgroup") after the activator Service; armPolicyCache() after armChangeIndex; statusLoop takes egressStatus. The reads are those units' own (decision rows); this body reads nothing new: the same five sites, offsets moved, in the agent; B,C,D,F authority retained.;rev3=census-ruling-remote-instance-metrics;basis=builds the metrics loop's owners closure (metricsOwners over the agent's registry, the activator and cgm.Leftover) when an activator exists and hands it to metricsLoop; reads nothing new itself;rev3=census-ruling-edge-asset-cache-3;basis=adds file:Statfs. runAgent keeps its authority (B,C,D,F). The new site is assetcache.Statfs, an exported assetcache.FS interface value (var Statfs FS = statfsFS{}), not a function value and not a call in runAgent: the ready hook passes it to armEdgeAssetCache as the store's filesystem, and armEdgeAssetCache calls its Space method on the configured data directory (dataDir(): $CARLOS_DATA_DIR, else /data), which calls unix.Statfs there (statfsFS.Space, accepted legacy at census-ruling-edge-asset-cache-2). No request-supplied pathname reaches it.;rev3=census-ruling-remote-metrics-nested;basis=main's body (merged origin/main acfa4f80, under main's own census rulings) plus: snapshots the nested layout (snapshotNestedUnits over /sys/fs/cgroup/carlos.slice/carlos-instances.slice) once at start, before the activator, and hands the metrics loop a unitSources struct (stamped units, routeHostNames, that root and the snapshot); reads nothing new itself;rev3=census-ruling-region-ha-p1a;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): wires region HA P1a into the activator: cfg.Record = haRecordFacts(openDeployStore, boxJudge) (the box's lifetime judge this body already builds with newBoxJudge, nil with host claims on; CI fix) and cfg.Self = lease.CurrentSelf; eb.Lifetimes (the process's lifetime index), eb.Registry, eb.StartupSwept (seedSweptAtStart.Load), eb.FilesStore from newProductionFilesStore (now lease.NewFilesStore, rootaws-loaded, a log line on failure) and lease.SetObligationDir(<data>/.ha-owed) (logged on failure; HA acquires then refuse); this body reads nothing new itself, the same five sites; the reads are those units' own (haRecordFacts and lease's SetObligationDir are new rows on this card); merge of origin/main d7ae1d76: main's own later changes to this body are kept as main has them, under main's rulings (census-ruling-remote-instance-metrics: the metricsOwners closure for metricsLoop; census-ruling-edge-asset-cache-3: the +file:Statfs site, assetcache.Statfs handed to the asset ready hook); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b1;basis=region HA P1b-1: builds one termfence.Confirmer (Self from lease.CurrentSelf at each call, EC2 DescribeInstances method only, client from rootaws.LoadDefaultConfig with retries off, built lazily on first use) and sets eb.OwnerTerminated; this body reads nothing new itself, the same six sites;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 7: the startup Sweep literal hands its answer to startupSwept, which logs as before and, only on a clean sweep, marks rootfs admission swept (MarkRootfsSwept); same Sweep call, no read added;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (controller ruling after branch review R1, and Paul's R2 ruling): sets svc.Fleet = fleetWakeFor(os.Getenv, identity, identErr, fleetStore) from the identity it already resolves once and the deployment store the fleet loops already opened, and logs an ERROR naming the identity error when the box is on a fleet with an invalid identity. fleetWakeFor reads CARLOS_REGION and CARLOS_FLEET from the same environment. Read sites unchanged (6). Agent, not root; a platform box is unchanged.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12: one call more beside armRunsPass, armInteractivePass(svc, reg, rolloutSink, boxJudge), in the same activator Configure hook, handing it the same box judge; fix round 1 (Astra P2, shutdown): after svc.Shutdown(ctx), shutdownInteractive(ctx) ends and joins every interactive session under the same shutdown budget; the worker's own reads are its units' (interactive.go); this body reads nothing new, the same six sites; merge of origin/main 6f1f6ca6: main's svc.Fleet = fleetWakeFor(...) and its invalid-identity ERROR line are kept as main has them (census-ruling-managed-fleets-1b); this branch's change is the same as above; read sites unchanged (6);rev3=census-ruling-fix-set-aside-exdev;basis=set-aside EXDEV fix: one field more on the agent ExecBackend literal, RawInstanceDir: layout.RawInstanceDir (a pure path join: <dataDir>/.instances/<InstanceID(host)>), so the start rule set-aside moves a copy out through the raw directory instead of through the nosymfollow bind; this body reads nothing new, the same six sites;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: one more assignment beside eb.FilesStore: eb.EscrowKey = haEscrowKey(os.Getenv("CARLOS_SECRETS_KEY")), the agent's own environment parsed by appconfig.ParsePrivateKey as the moves pass parses it (unset or unparseable: a log line and nil, and HA publication refuses on the box). No path is opened or read, no read site added; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 4: one more goroutine beside configSyncLoop: go escrowLoop(agentCtx, reg, svc), the escrow sweep every 30 s over the same registry and Service. This body reads nothing new itself; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 5: one more call beside eb.EscrowKey: wireRawSecretPages(eb, PageOperator, metricsBoxLabel(os.Getenv, readMachineID())), which sets eb.OnRawSecret to page an operator (alerting.Page through PageOperator, LevelIncident) on its own goroutine with a 20 s timeout; metricsBoxLabel and readMachineID are the reads this body already makes for the moves refusal log; no new read site; the same six sites, offsets moved; B,C,D,F authority retained. Merge of origin/main 90c4d3aa: main's own later changes to this body are kept as main has them, under main's rulings; this branch's change is the same as above. Merge of origin/main 00bf5b8c (fleet set-aside EXDEV fix): main's change to this body is kept as main has it, under its own census ruling; this branch's change is unchanged.;rev3=census-ruling-probe-burst-limit;basis=two more sink wirings beside setAnalyticsSink: setProtectionSink(e.SetProtectionRecordOnly) and setAssetOwnersSource(e.AssetOwners), function values the telemetry pass calls; this body reads nothing new, the same six sites; authority B,C,D,F retained; no new root read or write kind;rev3=census-ruling-region-ha-p1b3a;basis=Arm HA placement exactly once on the existing Service before activatorStart and edges publication, wiring AwakeApps and the PageOperator callback; existing six read sites unchanged, no new root authority.;rev3=census-ruling-stateless-replicas-1;basis=Final review I3: start the concrete coordinator's renewal worker with agent setup; existing closeReplicaCoordinator shutdown cancels and joins it before release. No new read sites or credentials. Merge origin/main c59715e7: retain main's armHAPlacement(svc, PageOperator) wiring beside the existing activator setup; stateless coordinator and shutdown wiring remain. Same read sites; no new root read or credential.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): in the edge-ready callback, calls act.SetHeldWakeHook(e.HeldWake) when act is non-nil (installing the non-blocking wake callback) and stores e.HeldStreamsForStatus in heldStreamsSource. Wiring of in-memory callbacks only; no read added.;rev3=census-ruling-region-ha-p1b3b-t;basis=Wire Service.SetDutyView to the live edge DutySnapshot in the ready callback. No new read; no new loop or cloud operation. B2 wires the registry as the persistent DutyStore before service startup; no new cloud or filesystem path. B3b: arm one journal-backed termination consumer before service startup using agentCtx and the shared confirmer; expose edge tick and join at edge shutdown. No new direct read sites.;rev3=census-ruling-agent-start-demo-1;basis=Passes the existing registry, data store and hibernation prefix into the demo worker, and the existing instance-control client into the demo before-exec hook. No alternate data store or polling loop. Merge resolution against origin/main 9bd45488 retains main's HA departure controller, lifecycle and duty wiring alongside the demo data store and worker; no read site added by the resolution.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: install closed fixed admission before every launch source, bind activator/backend and edge, wire the real termination Started lifecycle and role reader after the change index; close before cancellation/child shutdown. No new external reads or cloud authority. Fix R1: move bind/lifecycle/edge-option wiring into wireAgentAdmission and worker listing into runWorkerBootPassAfterAdmission. Worker boot waits for admission before listing then uses unchanged bounded wakes and per-host serialization; whole Route read moves to the helper. No new storage, cloud, or root execution authority. Preserve merged main's agent wiring and census basis; the branch removes one whole Route use by moving worker iteration to the helper, with no added read kind.;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: arms a fleet-only worker using the existing registry, activator, backend and authenticated console transport. Owned worker stops and joins at shutdown. No new bucket reader. merge of origin/main 9b8b2c50: retain HA duty/departure lifecycle, wake-slot and existing agent wiring alongside the replica placement worker; no new read introduced by resolution. merge of origin/main 6be08467: Retain main demo configuration, admission, build and expiry wiring alongside the replica worker; merge-only body change, no additional read. merge of origin/main 7920cccf: Retain main box-role/group admission wiring and boot publication beside the owned replica worker and shutdown; main moves the boot registry List into runWorkerBootPassAfterAdmission, removing its inline whole Route site. No new read introduced by conflict resolution.;rev3=census-ruling-stateless-replicas-3;basis=Task 1 fix round 1 M3: retain the private snapshot source and cancel/join ownership, but use the replica-health-specific retry loop. It logs its first failure only and retains the existing exponential backoff capped at 30 seconds; unsupported builds return nil. Existing five direct read sites unchanged; no new credentials, bucket reader or app lifecycle action. Fix round 1 Q20: publish Edge.ReplicaSnapshots as a separate in-memory status source, leaving the tenant-visible Upstreams source unchanged. No new external reader or authority.;rev3=census-ruling-region-ha-p3b;basis=Load root-written group marker/configuration, configure signed boot binding and agent receipt completer, wire cancellable admission into departure work and expose cached GroupReaderSnapshot. New indirect boot reads use protected root files; agent-owned receipt controls duplicate initial completion only, never root restart permission. Same five direct sites. Merge 45cebde4 retains the replica health socket lifecycle and setReplicaSource beside GroupReaderSnapshot; no extra read beyond main.;rev3=census-ruling-agent-start-demo-2;basis=agent.go:309-329 opens demo-traffic.db beside the operator-configured registry when a demo domain exists, closes it at shutdown and wires drain-before-purge; :1010-1019 shares the worker and write gate; :1164-1177 installs the fleet identity and closed-until-worker serving callback. One added whole Route pass; the new indirect filesystem/SQL reads are claimed in openDemoTraffic and worker/store units. No request chooses the database pathname.;rev3=census-ruling-region-ha-p1b3b-s;basis=Wire the service duty view to authoritative cached sidecar manifest placement in LifetimeIndex and the edge sidecar projection; missing policy denies duty. Existing instance duty wiring remains.;rev3=census-ruling-region-ha-g2-t3;basis=T3a: wire eb.Page = PageOperator beside OwnerTerminated before departures arm, so suspect-holder pages work if departure setup fails; no new read; existing nine sites and authority unchanged; pages through the existing sink. T3b: publish the same backend through an atomic pointer for the metrics observer, and clear it on return; no new external read or authority.;rev3=census-ruling-agent-start-demo-3;basis=Wire the claim activator and root snapshot client into the demo worker; pass moved readiness to status reporting. Census read-site delta: unchanged (9).;rev3=census-ruling-region-ha-g2-fixes;basis=Wire local pool evidence, live withdrawal activator, startup ingress scan and alias publication, and edge lookup; no new direct sites; new indirect record/claim reads use existing store/judge paths described in ingress helpers.;rev3=census-ruling-region-ha-g2r-fixes;basis=W3: starts the existing record-view backstop loop with a departure-inventory listener (non-blocking, coalesced signal) even without an armed RecordView; it requests the existing full pass (backstopFullDue) there. Same nine read sites; no new read or authority.
+- `internal/host/claimfilesseed_shutdown.go` `joinAgentShutdown`: authority, task C,J4. Basis: rev3=PROPOSED-seed; FS-R7/9; agent; seed-active joined shutdown shares bounded cleanup; inactive seed has no seed join and starts a fresh 60-second service context after both startup joins
+
+Seal: `a2014042114a4dd671e52a07bbb686b9ef4b6aa97798cc95e1095680c66fd9b2` → `506b0a9bbaca58f56bfbd9ceff3747bccf7c5575207a94b26f5637613a37c1f0`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-region-ha-graceful-terminate-t2.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/internal/activator/activator.go b/internal/activator/activator.go
index 04d963595..1325afa63 100644
--- a/internal/activator/activator.go
+++ b/internal/activator/activator.go
@@ -491,6 +491,7 @@ type actEntry struct {
haRecovery *haLeaseLoss
haRefused chan struct{}
haReleasing bool
+ haReleased bool
haAcquireUntil time.Time
duty bool
statelessPrepared *statelessPreparation
@@ -6140,6 +6141,11 @@ func (a *Service) Shutdown(ctx context.Context) {
// Proofs that start or run from here end with this budget too
// (legacyRunGone, #292): none may outlive Shutdown.
a.shutdownCtx = ctx
+ var shutdownEntries []*actEntry
+ for _, e := range a.entries {
+ shutdownEntries = append(shutdownEntries, e)
+ }
+ defer a.logHAUnreleasedAtExit(shutdownEntries)
sweepStop, sweepDone := a.sweepStop, a.sweepDone
var discoveries []chan struct{}
for _, l := range a.haLoss.hosts {
@@ -6298,6 +6304,29 @@ func (a *Service) Shutdown(ctx context.Context) {
}
}
+func (a *Service) logHAUnreleasedAtExit(entries []*actEntry) {
+ a.mu.Lock()
+ var unresolved []string
+ for _, e := range entries {
+ if _, ha := haEntryRep(e); !ha || e.haReleased {
+ continue
+ }
+ state := "waking"
+ switch e.state {
+ case actAwake:
+ state = "awake"
+ case actStopping:
+ state = "stopping"
+ }
+ unresolved = append(unresolved, fmt.Sprintf("activator: shutdown: %s: HA lease not released (%s); it frees at expiry", e.host, state))
+ }
+ a.mu.Unlock()
+ slices.Sort(unresolved)
+ for _, line := range unresolved {
+ log.Print(line)
+ }
+}
+
// logUnresolvedAtExit names what Shutdown's budget ran out on: failed
// wakes not proven stopped, whose leases are kept, lease releases that
// failed and were not resolved by a retry, release commands not proven
diff --git a/internal/activator/harelease.go b/internal/activator/harelease.go
index bebf4ecc5..85333846c 100644
--- a/internal/activator/harelease.go
+++ b/internal/activator/harelease.go
@@ -34,6 +34,9 @@ const (
haFinalFilesBudget = 2 * time.Minute
haFinalSyncBudget = 30 * time.Second
haMarkerBudget = 10 * time.Second
+
+ haShutdownSyncReserve = 30 * time.Second
+ haShutdownMarkerReserve = 10 * time.Second
)
// haReleaser is the backend half of an HA release (ExecBackend's;
@@ -186,7 +189,7 @@ func (a *Service) releaseHAClean(ctx context.Context, e *actEntry) error {
if f != nil {
// A budget of its own: a large tree's final read must not eat the
// final sync's.
- fctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), haFinalFilesBudget)
+ fctx, cancel := a.haReleaseContext(ctx, haFinalFilesBudget, haShutdownSyncReserve+haShutdownMarkerReserve)
gen, complete, ferr = f.Final(fctx)
cancel()
files = f.baseline()
@@ -194,7 +197,7 @@ func (a *Service) releaseHAClean(ctx context.Context, e *actEntry) error {
// The final sync's budget starts now, never before the files publish:
// a long one must not leave it a spent context, and the database's
// last writes unsynced.
- sctx, scancel := context.WithTimeout(context.WithoutCancel(ctx), haFinalSyncBudget)
+ sctx, scancel := a.haReleaseContext(ctx, haFinalSyncBudget, haShutdownMarkerReserve)
txid, finErr := hr.Finish(sctx)
scancel()
m := hb.haReleaseBase(rt)
@@ -209,7 +212,7 @@ func (a *Service) releaseHAClean(ctx context.Context, e *actEntry) error {
}
// The marker's PUT gets its own budget too, as Close's release does:
// a final sync that ran long must not leave it a dead context.
- mctx, mcancel := context.WithTimeout(context.WithoutCancel(ctx), haMarkerBudget)
+ mctx, mcancel := a.haReleaseContext(ctx, haMarkerBudget, 0)
a.mu.Lock()
if haUnexpectedLoss(e, servingError(e)) {
a.latchHALossLocked(e)
@@ -220,6 +223,9 @@ func (a *Service) releaseHAClean(ctx context.Context, e *actEntry) error {
merr := hr.ReleaseMarker(mctx, m)
mcancel()
if merr == nil {
+ a.mu.Lock()
+ e.haReleased = true
+ a.mu.Unlock()
a.rememberDutyRelease(ctx, rt, m)
log.Printf("activator: %s: released with a marker (clean %v, txid %d, files %s)", rt.Host, m.Clean, txid, gen)
}
@@ -232,6 +238,28 @@ func (a *Service) releaseHAClean(ctx context.Context, e *actEntry) error {
return errors.Join(ferr, finErr, rerr, merr)
}
+func (a *Service) haReleaseContext(ctx context.Context, cap, reserve time.Duration) (context.Context, context.CancelFunc) {
+ a.mu.Lock()
+ shutdown := a.shutdownCtx
+ shuttingDown := a.shuttingDown
+ a.mu.Unlock()
+ now := time.Now()
+ deadline := now.Add(cap)
+ if shuttingDown && shutdown != nil {
+ if d, ok := shutdown.Deadline(); ok {
+ cutoff := d.Add(-reserve)
+ floor := now.Add(time.Second)
+ if cutoff.Before(floor) {
+ cutoff = floor
+ }
+ if cutoff.Before(deadline) {
+ deadline = cutoff
+ }
+ }
+ }
+ return context.WithDeadline(context.WithoutCancel(ctx), deadline)
+}
+
// retryPendingMarkers is the sweep's retry of every owed release marker
// (lease.RetryPending: one PUT each, a minute after its failure, doubling
// to ten minutes apart, the in-memory-only ones written to disk first).
diff --git a/internal/activator/harelease_shutdown_test.go b/internal/activator/harelease_shutdown_test.go
new file mode 100644
index 000000000..2244fea32
--- /dev/null
+++ b/internal/activator/harelease_shutdown_test.go
@@ -0,0 +1,276 @@
+package activator
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/hostfiles"
+)
+
+type shutdownReleaseCall struct {
+ at, deadline time.Time
+ marker hafresh.Marker
+}
+
+type shutdownRep struct {
+ Rep
+ haRep
+ finish func(context.Context) (uint64, error)
+ marker func(context.Context, hafresh.Marker) error
+}
+
+func (r *shutdownRep) Finish(ctx context.Context) (uint64, error) { return r.finish(ctx) }
+func (r *shutdownRep) ReleaseMarker(ctx context.Context, m hafresh.Marker) error {
+ return r.marker(ctx, m)
+}
+
+func shutdownCall(ctx context.Context) shutdownReleaseCall {
+ d, _ := ctx.Deadline()
+ return shutdownReleaseCall{at: time.Now(), deadline: d}
+}
+
+func shutdownFixture(t *testing.T) (*haSvc, *actEntry, chan shutdownReleaseCall, chan shutdownReleaseCall, chan shutdownReleaseCall) {
+ t.Helper()
+ s, e := haServiceEntry(t, "shutdown.example.com")
+ s.a.stopFiles(e)
+ files, finish, marker := make(chan shutdownReleaseCall, 1), make(chan shutdownReleaseCall, 1), make(chan shutdownReleaseCall, 1)
+ original := e.rep
+ hr := original.(haRep)
+ stage := e.files.stageEscrow
+ e.files.stageEscrow = func(ctx context.Context, p *hostfiles.Publisher, reads []escrowRead) error {
+ files <- shutdownCall(ctx)
+ return stage(ctx, p, reads)
+ }
+ e.rep = &shutdownRep{Rep: original, haRep: hr,
+ finish: func(ctx context.Context) (uint64, error) { finish <- shutdownCall(ctx); return hr.Finish(ctx) },
+ marker: func(ctx context.Context, m hafresh.Marker) error {
+ call := shutdownCall(ctx)
+ call.marker = m
+ err := hr.ReleaseMarker(ctx, m)
+ marker <- call
+ return err
+ },
+ }
+ t.Cleanup(func() {
+ if ab, ok := original.(interface{ Abandon(context.Context) }); ok {
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ ab.Abandon(ctx)
+ }
+ })
+ return s, e, files, finish, marker
+}
+
+func awaitShutdownCall(t *testing.T, ch <-chan shutdownReleaseCall) shutdownReleaseCall {
+ t.Helper()
+ select {
+ case c := <-ch:
+ return c
+ case <-time.After(5 * time.Second):
+ t.Fatal("release step did not run")
+ return shutdownReleaseCall{}
+ }
+}
+
+func TestHAShutdownFinalDeadlineReservesMarker(t *testing.T) {
+ s, e, _, finish, marker := shutdownFixture(t)
+ final := make(chan shutdownReleaseCall, 1)
+ abort := make(chan struct{})
+ e.files.stageEscrow = func(ctx context.Context, _ *hostfiles.Publisher, _ []escrowRead) error {
+ final <- shutdownCall(ctx)
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-abort:
+ return errors.New("test cleanup")
+ }
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+ deadline, _ := ctx.Deadline()
+ done := make(chan struct{})
+ go func() { s.a.Shutdown(ctx); close(done) }()
+ t.Cleanup(func() { close(abort); cancel(); <-done; <-e.stopped })
+ f := awaitShutdownCall(t, final)
+ if remaining := f.deadline.Sub(f.at); remaining < 900*time.Millisecond || remaining > time.Second {
+ t.Fatalf("Final budget = %s, want floor-clamped 1s", remaining)
+ }
+ awaitShutdownCall(t, finish)
+ m := awaitShutdownCall(t, marker)
+ <-done
+ if m.marker.Clean || !m.at.Before(deadline) || ctx.Err() != nil {
+ t.Fatalf("marker = %+v, shutdown error = %v", m, ctx.Err())
+ }
+ if v := s.lockView(t); v.Lock.Release == nil || v.Lock.Release.Clean {
+ t.Fatalf("want stored UNCLEAN marker: %+v", v.Lock.Release)
+ }
+}
+
+func TestHAShutdownStuckFinishWritesNoMarker(t *testing.T) {
+ logs := lockedLog(t)
+ s, e, _, _, marker := shutdownFixture(t)
+ entered, unblock := make(chan struct{}), make(chan struct{})
+ r := e.rep.(*shutdownRep)
+ finish := r.finish
+ r.finish = func(ctx context.Context) (uint64, error) { close(entered); <-unblock; return finish(ctx) }
+ ctx, cancel := context.WithTimeout(context.Background(), 1500*time.Millisecond)
+ deadline, _ := ctx.Deadline()
+ done := make(chan struct{})
+ go func() { s.a.Shutdown(ctx); close(done) }()
+ t.Cleanup(func() { close(unblock); cancel(); <-done; <-e.stopped })
+ select {
+ case <-entered:
+ case <-time.After(time.Second):
+ t.Fatal("Finish did not start")
+ }
+ select {
+ case <-done:
+ case <-time.After(2 * time.Second):
+ t.Fatal("Shutdown blocked on Finish")
+ }
+ if time.Now().After(deadline.Add(500 * time.Millisecond)) {
+ t.Fatal("Shutdown exceeded deadline")
+ }
+ select {
+ case <-marker:
+ t.Fatal("marker written while Finish blocked")
+ default:
+ }
+ select {
+ case <-e.stopped:
+ t.Fatal("stopped closed while Finish blocked")
+ default:
+ }
+ if v := s.lockView(t); v.Lock.Release != nil {
+ t.Fatal("marker in store while Finish blocked")
+ }
+ if !strings.Contains(logs.String(), "activator: shutdown: shutdown.example.com: HA lease not released (stopping); it frees at expiry") {
+ t.Fatalf("missing unresolved HA log: %s", logs.String())
+ }
+}
+
+func TestHAShutdownHealthyBudgets(t *testing.T) {
+ s, _, files, finish, marker := shutdownFixture(t)
+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
+ defer cancel()
+ deadline, _ := ctx.Deadline()
+ s.a.Shutdown(ctx)
+ calls := []shutdownReleaseCall{awaitShutdownCall(t, files), awaitShutdownCall(t, finish), awaitShutdownCall(t, marker)}
+ cutoffs := []time.Time{deadline.Add(-40 * time.Second), deadline.Add(-10 * time.Second), deadline}
+ caps := []time.Duration{2 * time.Minute, 30 * time.Second, 10 * time.Second}
+ for i, c := range calls {
+ if c.deadline.After(cutoffs[i]) || c.deadline.Sub(c.at) > caps[i] {
+ t.Errorf("step %d deadline %s exceeds cutoff %s or cap %s", i, c.deadline, cutoffs[i], caps[i])
+ }
+ }
+ if !calls[2].marker.Clean {
+ t.Fatal("healthy shutdown marker unclean")
+ }
+ if v := s.lockView(t); v.Lock.Release == nil || !v.Lock.Release.Clean {
+ t.Fatalf("want stored CLEAN marker: %+v", v.Lock.Release)
+ }
+}
+
+func TestHANormalReleaseBudgetsUnchanged(t *testing.T) {
+ s, e, files, finish, marker := shutdownFixture(t)
+ s.unit.stopped()
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ if err := s.a.releaseHAClean(ctx, e); err != nil {
+ t.Fatal(err)
+ }
+ calls := []shutdownReleaseCall{awaitShutdownCall(t, files), awaitShutdownCall(t, finish), awaitShutdownCall(t, marker)}
+ caps := []time.Duration{2 * time.Minute, 30 * time.Second, 10 * time.Second}
+ for i, c := range calls {
+ if budget := c.deadline.Sub(c.at); budget > caps[i] || budget < caps[i]-time.Second {
+ t.Errorf("step %d budget %s, want %s", i, budget, caps[i])
+ }
+ }
+ if !calls[2].marker.Clean {
+ t.Fatal("cancelled caller prevented clean release")
+ }
+}
+
+func TestHAShutdownJoinsMarker(t *testing.T) {
+ logs := lockedLog(t)
+ s, e, _, _, marker := shutdownFixture(t)
+ entered, unblock := make(chan struct{}), make(chan struct{})
+ r := e.rep.(*shutdownRep)
+ publish := r.marker
+ r.marker = func(ctx context.Context, m hafresh.Marker) error { close(entered); <-unblock; return publish(ctx, m) }
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ done := make(chan struct{})
+ go func() { s.a.Shutdown(ctx); close(done) }()
+ t.Cleanup(func() {
+ select {
+ case <-unblock:
+ default:
+ close(unblock)
+ }
+ <-done
+ <-e.stopped
+ })
+ select {
+ case <-entered:
+ case <-time.After(2 * time.Second):
+ t.Fatal("marker did not start")
+ }
+ select {
+ case <-e.stopped:
+ t.Fatal("stopped closed with marker in flight")
+ default:
+ }
+ select {
+ case <-done:
+ t.Fatal("Shutdown returned with marker in flight")
+ case <-time.After(50 * time.Millisecond):
+ }
+ close(unblock)
+ awaitShutdownCall(t, marker)
+ <-done
+ if strings.Contains(logs.String(), "HA lease not released") {
+ t.Fatalf("released host logged as unreleased: %s", logs.String())
+ }
+}
+
+func TestHAShutdownCancelledContextKeepsReleaseBudget(t *testing.T) {
+ s, e, files, finish, marker := shutdownFixture(t)
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+ deadline, _ := ctx.Deadline()
+ cancel()
+ s.a.mu.Lock()
+ s.a.shuttingDown, s.a.shutdownCtx = true, ctx
+ s.a.mu.Unlock()
+ s.unit.stopped()
+ if err := s.a.releaseHAClean(ctx, e); err != nil {
+ t.Fatal(err)
+ }
+ f := awaitShutdownCall(t, files)
+ sync := awaitShutdownCall(t, finish)
+ m := awaitShutdownCall(t, marker)
+ if f.deadline.Sub(f.at) > time.Second || sync.deadline.After(deadline.Add(-10*time.Second)) || m.deadline.After(deadline) {
+ t.Fatalf("release budgets exceeded: %+v %+v %+v", f, sync, m)
+ }
+ if !m.marker.Clean {
+ t.Fatal("cancellation killed release")
+ }
+}
+
+func TestHAShutdownLogsFailedMarkerAfterEntryRemoved(t *testing.T) {
+ logs := lockedLog(t)
+ s, e, _, _, _ := shutdownFixture(t)
+ e.rep.(*shutdownRep).marker = func(context.Context, hafresh.Marker) error { return errors.New("test marker failure") }
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ s.a.Shutdown(ctx)
+ if s.a.entryCount() != 0 {
+ t.Fatal("stop did not finish")
+ }
+ if !strings.Contains(logs.String(), "activator: shutdown: shutdown.example.com: HA lease not released (stopping); it frees at expiry") {
+ t.Fatalf("failed marker not logged: %s", logs.String())
+ }
+}
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 127dac2c5..d1841571e 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -114,6 +114,7 @@ type Activator interface {
// its backend. The host→backend map is swapped atomically, so reloads and
// zero-downtime deploys never drop a live connection.
type Edge struct {
+ shutdownStarted func(time.Time)
haIngress atomic.Pointer[haIngressLookup]
haIngressBlocked atomic.Pointer[map[string]bool]
// ReplicaProbe is configured before the first syncReplicaProbes call.
@@ -4634,7 +4635,7 @@ func RunWithActivatorReady(args []string, act Activator, cache *Cache, ready fun
}
}()
<-stop
- e.closeTenantAdmission()
+ e.beginShutdown()
log.Printf("edge: draining and shutting down")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
@@ -4834,7 +4835,7 @@ func RunWithActivatorReady(args []string, act Activator, cache *Cache, ready fun
// accepting and drain in-flight HTTP before exiting. Proxied WebSockets are
// hijacked (not drained); they reconnect through the new edge.
<-stop
- e.closeTenantAdmission()
+ e.beginShutdown()
log.Printf("edge: draining and shutting down")
if e.closeDoor != nil {
e.closeDoor()
diff --git a/internal/edge/shutdown.go b/internal/edge/shutdown.go
new file mode 100644
index 000000000..7d8f3c6f0
--- /dev/null
+++ b/internal/edge/shutdown.go
@@ -0,0 +1,14 @@
+package edge
+
+import "time"
+
+func WithShutdownStarted(started func(time.Time)) RunOption {
+ return func(e *Edge) { e.shutdownStarted = started }
+}
+
+func (e *Edge) beginShutdown() {
+ if e.shutdownStarted != nil {
+ e.shutdownStarted(time.Now())
+ }
+ e.closeTenantAdmission()
+}
diff --git a/internal/edge/shutdown_test.go b/internal/edge/shutdown_test.go
new file mode 100644
index 000000000..fb22d5e52
--- /dev/null
+++ b/internal/edge/shutdown_test.go
@@ -0,0 +1,32 @@
+package edge
+
+import (
+ "testing"
+ "time"
+)
+
+type shutdownAdmission struct{ close func() }
+
+func (a shutdownAdmission) TenantAdmitted() bool { return true }
+func (a shutdownAdmission) CloseTenantAdmission() { a.close() }
+
+func TestShutdownClockStartsBeforeAdmissionCloses(t *testing.T) {
+ var started time.Time
+ e := &Edge{}
+ WithShutdownStarted(func(at time.Time) { started = at })(e)
+ before := time.Now()
+ closed := false
+ WithHAAdmission(shutdownAdmission{close: func() {
+ closed = true
+ if started.Before(before) || started.After(time.Now()) {
+ t.Fatalf("shutdown timestamp not set before admission close: %s", started)
+ }
+ }})(e)
+ e.beginShutdown()
+ if !closed {
+ t.Fatal("admission did not close")
+ }
+ WithShutdownStarted(nil)(e)
+ WithHAAdmission(nil)(e)
+ e.beginShutdown()
+}
diff --git a/internal/host/agent.go b/internal/host/agent.go
index 15811bbe9..3af68c137 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -1123,7 +1123,9 @@ func runAgent(args []string, buildClaims ClaimFactory) {
// The ready hook fires synchronously before listening, so
// tunnelLoop is handed off to its own goroutine rather than called here —
// calling it directly would block the front door forever.
+ var shutdownDeadline time.Time
edgeOpts := append([]edge.RunOption{
+ edge.WithShutdownStarted(func(at time.Time) { shutdownDeadline = at.Add(agentShutdownBudget) }),
// Certificate issuance is a deployment-global duty, so it runs where
// the housekeeper runs (housekeeper.go). The gate goes DOWN into the
// edge as a func — this package imports internal/edge and never the
@@ -1289,14 +1291,16 @@ func runAgent(args []string, buildClaims ClaimFactory) {
admission.Close()
if departureLife != nil {
- stopCtx, stopCancel := context.WithTimeout(context.Background(), 5*time.Second)
+ stopBase, stopBaseCancel := context.WithDeadline(context.Background(), shutdownDeadline)
+ stopCtx, stopCancel := context.WithTimeout(stopBase, 5*time.Second)
if err := departureLife.Stop(stopCtx); err != nil {
log.Printf("ha_departure_stop code=deadline")
}
stopCancel()
+ stopBaseCancel()
}
var seedErr error
- shutdownCtx, shutdownCancel, seedErr = joinAgentShutdown(seedCtx, seedCancel, seedServer, cancelStartup, startupDone, dutiesDone)
+ shutdownCtx, shutdownCancel, seedErr = joinAgentShutdown(shutdownDeadline, seedCtx, seedCancel, seedServer, cancelStartup, startupDone, dutiesDone)
if seedErr != nil {
safeClaimClose = false
log.Printf("Files seed failed: %s.", seedErr)
diff --git a/internal/host/claimfilesseed_shutdown.go b/internal/host/claimfilesseed_shutdown.go
index 5e40090e6..701e78d12 100644
--- a/internal/host/claimfilesseed_shutdown.go
+++ b/internal/host/claimfilesseed_shutdown.go
@@ -7,8 +7,10 @@ import (
"github.com/carlosframework/platform/internal/activator"
)
-func joinAgentShutdown(seedCtx context.Context, seedCancel context.CancelFunc, seedServer *filesSeedServer, cancelStartup context.CancelFunc, startupDone, dutiesDone <-chan struct{}) (context.Context, context.CancelFunc, error) {
- base := context.Background()
+const agentShutdownBudget = 90 * time.Second
+
+func joinAgentShutdown(deadline time.Time, seedCtx context.Context, seedCancel context.CancelFunc, seedServer *filesSeedServer, cancelStartup context.CancelFunc, startupDone, dutiesDone <-chan struct{}) (context.Context, context.CancelFunc, error) {
+ base, deadlineCancel := context.WithDeadline(context.Background(), deadline)
cancel := func() {}
if seedCtx != nil {
base, cancel = activator.CleanupContext(base, 60*time.Second)
@@ -17,10 +19,12 @@ func joinAgentShutdown(seedCtx context.Context, seedCancel context.CancelFunc, s
if seedCtx != nil {
seedCancel()
join, stop := activator.CleanupContext(seedCtx, 30*time.Second)
- err := seedServer.close(join)
+ bounded, boundCancel := context.WithDeadline(join, deadline)
+ err := seedServer.close(bounded)
+ boundCancel()
stop()
if err != nil {
- return base, cancel, err
+ return base, func() { cancel(); deadlineCancel() }, err
}
}
join, stop := context.WithTimeout(base, 5*time.Second)
@@ -29,7 +33,7 @@ func joinAgentShutdown(seedCtx context.Context, seedCancel context.CancelFunc, s
joinAgentStartup(join, dutiesDone)
if seedCtx == nil {
// Main starts this clock after joining startup duties.
- base, cancel = context.WithTimeout(context.Background(), 60*time.Second)
+ base, cancel = context.WithTimeout(base, 60*time.Second)
}
- return base, cancel, nil
+ return base, func() { cancel(); deadlineCancel() }, nil
}
diff --git a/internal/host/claimfilesseed_shutdown_test.go b/internal/host/claimfilesseed_shutdown_test.go
index ef9d4fce9..8d8d200c8 100644
--- a/internal/host/claimfilesseed_shutdown_test.go
+++ b/internal/host/claimfilesseed_shutdown_test.go
@@ -10,7 +10,7 @@ func TestAgentNoCensusShutdownBudget(t *testing.T) {
cancelled := make(chan struct{})
go func() { <-cancelled; time.Sleep(200 * time.Millisecond); close(startup); close(duties) }()
began := time.Now()
- ctx, cancel, err := joinAgentShutdown(nil, nil, nil, func() { close(cancelled) }, startup, duties)
+ ctx, cancel, err := joinAgentShutdown(time.Now().Add(90*time.Second), nil, nil, nil, func() { close(cancelled) }, startup, duties)
defer cancel()
if err != nil {
t.Fatal(err)
@@ -23,3 +23,39 @@ func TestAgentNoCensusShutdownBudget(t *testing.T) {
t.Fatal("no-census shutdown lost its fresh 60 seconds", deadline, ctx.Err())
}
}
+
+func TestAgentShutdownDeadlineIncludesStartupJoin(t *testing.T) {
+ startup, duties := make(chan struct{}), make(chan struct{})
+ signalAt := time.Now().Add(-agentShutdownBudget + 100*time.Millisecond)
+ deadline := signalAt.Add(agentShutdownBudget)
+ cancelled := false
+ ctx, cancel, err := joinAgentShutdown(deadline, nil, nil, nil, func() { cancelled = true }, startup, duties)
+ defer cancel()
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, ok := ctx.Deadline()
+ if !cancelled || !ok || !got.Equal(deadline) {
+ t.Fatalf("cancelled=%v deadline=%s want=%s", cancelled, got, deadline)
+ }
+ if ctx.Err() == nil {
+ t.Fatal("startup join did not consume remaining shutdown time")
+ }
+ if time.Now().After(deadline.Add(500 * time.Millisecond)) {
+ t.Fatal("startup join exceeded absolute deadline")
+ }
+}
+
+func TestAgentShutdownExpiredDeadline(t *testing.T) {
+ deadline := time.Now().Add(-time.Second)
+ began := time.Now()
+ ctx, cancel, err := joinAgentShutdown(deadline, nil, nil, nil, func() {}, make(chan struct{}), make(chan struct{}))
+ defer cancel()
+ if err != nil || ctx.Err() == nil {
+ t.Fatalf("err=%v context error=%v", err, ctx.Err())
+ }
+ got, _ := ctx.Deadline()
+ if !got.Equal(deadline) || time.Since(began) > 500*time.Millisecond {
+ t.Fatalf("expired deadline extended: %s", got)
+ }
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 0184a6750..128f64336 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -121,3 +121,4 @@ plan14-root-reads-region-ha-dr2.tsv 7247af7f4de84593d83c6f60c0147d0a04836146197d
plan14-root-reads-dr1-left-link.tsv 160744b3062d0ab9a0cb3c7be3a391ae38cf89ffe410ddd5d179e0c3cb509b66
plan14-root-reads-claim-source.tsv 9cdff432a5de2ffeaa147fdafd6a486c61c27a0c38f77466bddc86b149332c7d
plan14-root-reads-region-ha-graceful-terminate-t1.tsv a2014042114a4dd671e52a07bbb686b9ef4b6aa97798cc95e1095680c66fd9b2
+plan14-root-reads-region-ha-graceful-terminate-t2.tsv 506b0a9bbaca58f56bfbd9ceff3747bccf7c5575207a94b26f5637613a37c1f0
diff --git a/internal/provision/testdata/plan14-root-reads-region-ha-graceful-terminate-t2.tsv b/internal/provision/testdata/plan14-root-reads-region-ha-graceful-terminate-t2.tsv
new file mode 100644
index 000000000..181d50517
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-region-ha-graceful-terminate-t2.tsv
@@ -0,0 +1,11 @@
+# Census overlay region-ha-graceful-terminate-t2, written by census-propose (#369). census-ruling-region-ha-graceful-terminate-t2, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-region-ha-graceful-terminate-t2.md.
+# 4 body, 0 sites, 3 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@legacy b55f1400a16ea04b9bd35110b13bc8d8ae7a094320c1cddea2e2693aa7a27580 internal/activator/harelease.go Service.releaseHAClean legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: an HA entry's release, in order: host slice read empty through haHostEmpty (else errHostSliceUnproven and nothing written; the same check, moved into that helper by final fix F1), stop and join the files publisher, its final publish (2 min budget), the replica's final sync (Finish, 30 s), the local release record, then the release marker PUT (10 s), clean only when the final publish was complete and the sync and record succeeded; a failed PUT is a persisted lease obligation; +registry:Host, +whole:Route x4;rev3=census-ruling-region-ha-p1b3b-t;basis=Record advisory local-release basis only after ReleaseMarker succeeds. Add a whole-route argument to local duty bookkeeping; release order and lease authority unchanged.;rev3=census-ruling-region-ha-g2-fixes;basis=Latch unexpected lease loss before release and mark intentional release so ErrSpent alone is not treated as loss; no new read.;rev3=census-ruling-region-ha-graceful-terminate-t2;basis=Cap Final, Finish and marker contexts by the shutdown deadline and reserves; keep calls synchronous and stop proof unchanged; record successful marker completion under the service mutex. No read added. registry:Host@2074,whole:Route@102,whole:Route@1122,whole:Route@1260,whole:Route@1983,whole:Route@244 8fea35be14306c3705c1f8223712af85340301c8d2acf1d80bda45ba99b63981
+@legacy fea88648fd241c3f85cd1d30a477774a7897c3f3ce6da0b94995114592f55e3a internal/edge/edge.go RunWithActivatorReady legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-certwarm-wake;basis=registers the cert warm's nudge on OnReload and on the home map's new served-hosts wake (#386); nudge only sends on a buffered channel; no read added, same 5 sites;rev3=census-ruling-edge-roll-blip;basis=the :80/:443 (and dev) listeners are bound on the calling goroutine with net.Listen via listen()/listenAddr (same empty-address defaults as ListenAndServe) before the serve goroutines, which now call Serve/ServeTLS on them, and one log line names the bound addresses; no read added, same 5 sites;rev3=census-ruling-edge-held-streams;basis=the edge in the agent (carlos-edge.service, user carlos): the inline home-map arming (newHomeMap, one boot Refresh, Store, run) moves unchanged into the new Edge.ArmHomeMap and is called here as e.ArmHomeMap(); same refresh, same timeout, same order. The reads are moved, none added.;rev3=census-ruling-agent-start-demo-1;basis=Logs the combined explicit wildcard parents through demoWildcardDomains; no new watcher or read loop.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: invoke the local admission Close before HTTP/HTTPS draining and door shutdown in both dev and normal listeners. Preserve merged main's startup behavior and its census basis; the same five read sites, no new reads.;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: defer stopping and joining the edge's replica jobs at shutdown. Existing five direct read sites unchanged; no new reader or authority.;rev3=census-ruling-region-ha-p3b;basis=Wrap dev, HTTP and HTTPS listeners through ConfigureGroupHairpin before serving. Indirectly read protected root boot identity and group-ingress.json; kernel local/peer addresses mark local ingress, never HTTP headers. Agent edge uses verified public source for accounting; direct read sites unchanged and absent marker keeps original listeners. CI fix removes interface enumeration: local peer must match snapshot primary IPv4, an ingress IPv4 installed locally by root, or loopback; kernel destination must still be an ingress EIP on port 80/443. Merge 45cebde4 retains deferred stopReplicaProbes alongside group listener wrapping and shutdown admission closure.;rev3=census-ruling-demo-api-site-route;basis=Change the startup failure context from load routes to initialize because origin validation now runs during construction. Existing five read sites unchanged; no new read or runtime authority.;rev3=census-ruling-region-ha-graceful-terminate-t2;basis=Invoke the agent shutdown timestamp hook synchronously at SIGTERM/SIGINT receipt before closing admission in dev and TLS paths. No read added. data-literal@129,data-literal@148,data-literal@284,data-literal@417,file:Open@1013 642e66b97227628084f81a5f72c28e7189489d22118193c7cb4a7b804930aac5
+internal/activator/harelease.go Service.releaseHAClean legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: an HA entry's release, in order: host slice read empty through haHostEmpty (else errHostSliceUnproven and nothing written; the same check, moved into that helper by final fix F1), stop and join the files publisher, its final publish (2 min budget), the replica's final sync (Finish, 30 s), the local release record, then the release marker PUT (10 s), clean only when the final publish was complete and the sync and record succeeded; a failed PUT is a persisted lease obligation; +registry:Host, +whole:Route x4;rev3=census-ruling-region-ha-p1b3b-t;basis=Record advisory local-release basis only after ReleaseMarker succeeds. Add a whole-route argument to local duty bookkeeping; release order and lease authority unchanged.;rev3=census-ruling-region-ha-g2-fixes;basis=Latch unexpected lease loss before release and mark intentional release so ErrSpent alone is not treated as loss; no new read.;rev3=census-ruling-region-ha-graceful-terminate-t2;basis=Cap Final, Finish and marker contexts by the shutdown deadline and reserves; keep calls synchronous and stop proof unchanged; record successful marker completion under the service mutex. No read added. registry:Host@2074,whole:Route@102,whole:Route@1122,whole:Route@1260,whole:Route@1983,whole:Route@244 8fea35be14306c3705c1f8223712af85340301c8d2acf1d80bda45ba99b63981
+internal/edge/edge.go RunWithActivatorReady legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-certwarm-wake;basis=registers the cert warm's nudge on OnReload and on the home map's new served-hosts wake (#386); nudge only sends on a buffered channel; no read added, same 5 sites;rev3=census-ruling-edge-roll-blip;basis=the :80/:443 (and dev) listeners are bound on the calling goroutine with net.Listen via listen()/listenAddr (same empty-address defaults as ListenAndServe) before the serve goroutines, which now call Serve/ServeTLS on them, and one log line names the bound addresses; no read added, same 5 sites;rev3=census-ruling-edge-held-streams;basis=the edge in the agent (carlos-edge.service, user carlos): the inline home-map arming (newHomeMap, one boot Refresh, Store, run) moves unchanged into the new Edge.ArmHomeMap and is called here as e.ArmHomeMap(); same refresh, same timeout, same order. The reads are moved, none added.;rev3=census-ruling-agent-start-demo-1;basis=Logs the combined explicit wildcard parents through demoWildcardDomains; no new watcher or read loop.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: invoke the local admission Close before HTTP/HTTPS draining and door shutdown in both dev and normal listeners. Preserve merged main's startup behavior and its census basis; the same five read sites, no new reads.;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: defer stopping and joining the edge's replica jobs at shutdown. Existing five direct read sites unchanged; no new reader or authority.;rev3=census-ruling-region-ha-p3b;basis=Wrap dev, HTTP and HTTPS listeners through ConfigureGroupHairpin before serving. Indirectly read protected root boot identity and group-ingress.json; kernel local/peer addresses mark local ingress, never HTTP headers. Agent edge uses verified public source for accounting; direct read sites unchanged and absent marker keeps original listeners. CI fix removes interface enumeration: local peer must match snapshot primary IPv4, an ingress IPv4 installed locally by root, or loopback; kernel destination must still be an ingress EIP on port 80/443. Merge 45cebde4 retains deferred stopReplicaProbes alongside group listener wrapping and shutdown admission closure.;rev3=census-ruling-demo-api-site-route;basis=Change the startup failure context from load routes to initialize because origin validation now runs during construction. Existing five read sites unchanged; no new read or runtime authority.;rev3=census-ruling-region-ha-graceful-terminate-t2;basis=Invoke the agent shutdown timestamp hook synchronously at SIGTERM/SIGINT receipt before closing admission in dev and TLS paths. No read added. data-literal@129,data-literal@148,data-literal@284,data-literal@417,file:Open@1013 642e66b97227628084f81a5f72c28e7189489d22118193c7cb4a7b804930aac5
+internal/host/agent.go runAgent authority B,C,D,F rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): builds the box's lifetime judge once (newBoxJudge, nil with host claims on) and hands it to the seed placement, the moves and runs workers and every loop it starts; read sites unchanged, offsets moved; B,C,D,F authority retained; self-serve moves 1 Task 8: derives the box's lifetimes switch from the judge once (lifetimes := boxJudge != nil) and hands it to the edges file loop; read sites unchanged, offsets moved;rev3=census-ruling-plans-4d-lapse;basis=arms two more plans hooks from the same snapshot: e.SetPlanDisabledFor(planDisabledFor) beside SetPlanGovernedFor, and svc.SetDisabledFor(planDisabledRoute) beside SetMaxRunFor (plans 4d); the reads live in those units (plans-4d-units decision); read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 9b81d97b (with main's plan rate ceiling, edge request records, regional box names, self-serve moves plan 1, plans 4d-1 lapse and its other later changes under main's own census rulings) plus the rootfs placement wiring in the activator start: an agentRootfs built from eb.NestedOK, CARLOS_DEPLOYMENT_SINGLE_TENANT, CARLOS_POOLS, the claim flag, swapArming's answer, the control client's /ready/rootfs and, on a fleet box whose identity resolved, fleetOwnerCheck over the deploy store main already opens for the fleet label (fleetStore), then arm and armedRootfs.Store; this body reads nothing new itself; the closures it wires read later, at a rootfs wake and each status tick: GET /ready/rootfs over the control socket, NestedOK's checks, and release.FleetOwnerKey for the judged row's own account and this box's fleet from the deploy store;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Tasks 7 and 11, #329 plan 3 Task 7 and plan 1 Task 7's policy cache: the control client is built once and handed to eb.Control, to the status tick (egressStatus) and to a new egressNudgeLoop goroutine; armSizeSource(svc, "/sys/fs/cgroup") after the activator Service; armPolicyCache() after armChangeIndex; statusLoop takes egressStatus. The reads are those units' own (decision rows); this body reads nothing new: the same five sites, offsets moved, in the agent; B,C,D,F authority retained.;rev3=census-ruling-remote-instance-metrics;basis=builds the metrics loop's owners closure (metricsOwners over the agent's registry, the activator and cgm.Leftover) when an activator exists and hands it to metricsLoop; reads nothing new itself;rev3=census-ruling-edge-asset-cache-3;basis=adds file:Statfs. runAgent keeps its authority (B,C,D,F). The new site is assetcache.Statfs, an exported assetcache.FS interface value (var Statfs FS = statfsFS{}), not a function value and not a call in runAgent: the ready hook passes it to armEdgeAssetCache as the store's filesystem, and armEdgeAssetCache calls its Space method on the configured data directory (dataDir(): $CARLOS_DATA_DIR, else /data), which calls unix.Statfs there (statfsFS.Space, accepted legacy at census-ruling-edge-asset-cache-2). No request-supplied pathname reaches it.;rev3=census-ruling-remote-metrics-nested;basis=main's body (merged origin/main acfa4f80, under main's own census rulings) plus: snapshots the nested layout (snapshotNestedUnits over /sys/fs/cgroup/carlos.slice/carlos-instances.slice) once at start, before the activator, and hands the metrics loop a unitSources struct (stamped units, routeHostNames, that root and the snapshot); reads nothing new itself;rev3=census-ruling-region-ha-p1a;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): wires region HA P1a into the activator: cfg.Record = haRecordFacts(openDeployStore, boxJudge) (the box's lifetime judge this body already builds with newBoxJudge, nil with host claims on; CI fix) and cfg.Self = lease.CurrentSelf; eb.Lifetimes (the process's lifetime index), eb.Registry, eb.StartupSwept (seedSweptAtStart.Load), eb.FilesStore from newProductionFilesStore (now lease.NewFilesStore, rootaws-loaded, a log line on failure) and lease.SetObligationDir(<data>/.ha-owed) (logged on failure; HA acquires then refuse); this body reads nothing new itself, the same five sites; the reads are those units' own (haRecordFacts and lease's SetObligationDir are new rows on this card); merge of origin/main d7ae1d76: main's own later changes to this body are kept as main has them, under main's rulings (census-ruling-remote-instance-metrics: the metricsOwners closure for metricsLoop; census-ruling-edge-asset-cache-3: the +file:Statfs site, assetcache.Statfs handed to the asset ready hook); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b1;basis=region HA P1b-1: builds one termfence.Confirmer (Self from lease.CurrentSelf at each call, EC2 DescribeInstances method only, client from rootaws.LoadDefaultConfig with retries off, built lazily on first use) and sets eb.OwnerTerminated; this body reads nothing new itself, the same six sites;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 7: the startup Sweep literal hands its answer to startupSwept, which logs as before and, only on a clean sweep, marks rootfs admission swept (MarkRootfsSwept); same Sweep call, no read added;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (controller ruling after branch review R1, and Paul's R2 ruling): sets svc.Fleet = fleetWakeFor(os.Getenv, identity, identErr, fleetStore) from the identity it already resolves once and the deployment store the fleet loops already opened, and logs an ERROR naming the identity error when the box is on a fleet with an invalid identity. fleetWakeFor reads CARLOS_REGION and CARLOS_FLEET from the same environment. Read sites unchanged (6). Agent, not root; a platform box is unchanged.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12: one call more beside armRunsPass, armInteractivePass(svc, reg, rolloutSink, boxJudge), in the same activator Configure hook, handing it the same box judge; fix round 1 (Astra P2, shutdown): after svc.Shutdown(ctx), shutdownInteractive(ctx) ends and joins every interactive session under the same shutdown budget; the worker's own reads are its units' (interactive.go); this body reads nothing new, the same six sites; merge of origin/main 6f1f6ca6: main's svc.Fleet = fleetWakeFor(...) and its invalid-identity ERROR line are kept as main has them (census-ruling-managed-fleets-1b); this branch's change is the same as above; read sites unchanged (6);rev3=census-ruling-fix-set-aside-exdev;basis=set-aside EXDEV fix: one field more on the agent ExecBackend literal, RawInstanceDir: layout.RawInstanceDir (a pure path join: <dataDir>/.instances/<InstanceID(host)>), so the start rule set-aside moves a copy out through the raw directory instead of through the nosymfollow bind; this body reads nothing new, the same six sites;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: one more assignment beside eb.FilesStore: eb.EscrowKey = haEscrowKey(os.Getenv("CARLOS_SECRETS_KEY")), the agent's own environment parsed by appconfig.ParsePrivateKey as the moves pass parses it (unset or unparseable: a log line and nil, and HA publication refuses on the box). No path is opened or read, no read site added; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 4: one more goroutine beside configSyncLoop: go escrowLoop(agentCtx, reg, svc), the escrow sweep every 30 s over the same registry and Service. This body reads nothing new itself; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 5: one more call beside eb.EscrowKey: wireRawSecretPages(eb, PageOperator, metricsBoxLabel(os.Getenv, readMachineID())), which sets eb.OnRawSecret to page an operator (alerting.Page through PageOperator, LevelIncident) on its own goroutine with a 20 s timeout; metricsBoxLabel and readMachineID are the reads this body already makes for the moves refusal log; no new read site; the same six sites, offsets moved; B,C,D,F authority retained. Merge of origin/main 90c4d3aa: main's own later changes to this body are kept as main has them, under main's rulings; this branch's change is the same as above. Merge of origin/main 00bf5b8c (fleet set-aside EXDEV fix): main's change to this body is kept as main has it, under its own census ruling; this branch's change is unchanged.;rev3=census-ruling-probe-burst-limit;basis=two more sink wirings beside setAnalyticsSink: setProtectionSink(e.SetProtectionRecordOnly) and setAssetOwnersSource(e.AssetOwners), function values the telemetry pass calls; this body reads nothing new, the same six sites; authority B,C,D,F retained; no new root read or write kind;rev3=census-ruling-region-ha-p1b3a;basis=Arm HA placement exactly once on the existing Service before activatorStart and edges publication, wiring AwakeApps and the PageOperator callback; existing six read sites unchanged, no new root authority.;rev3=census-ruling-stateless-replicas-1;basis=Final review I3: start the concrete coordinator's renewal worker with agent setup; existing closeReplicaCoordinator shutdown cancels and joins it before release. No new read sites or credentials. Merge origin/main c59715e7: retain main's armHAPlacement(svc, PageOperator) wiring beside the existing activator setup; stateless coordinator and shutdown wiring remain. Same read sites; no new root read or credential.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): in the edge-ready callback, calls act.SetHeldWakeHook(e.HeldWake) when act is non-nil (installing the non-blocking wake callback) and stores e.HeldStreamsForStatus in heldStreamsSource. Wiring of in-memory callbacks only; no read added.;rev3=census-ruling-region-ha-p1b3b-t;basis=Wire Service.SetDutyView to the live edge DutySnapshot in the ready callback. No new read; no new loop or cloud operation. B2 wires the registry as the persistent DutyStore before service startup; no new cloud or filesystem path. B3b: arm one journal-backed termination consumer before service startup using agentCtx and the shared confirmer; expose edge tick and join at edge shutdown. No new direct read sites.;rev3=census-ruling-agent-start-demo-1;basis=Passes the existing registry, data store and hibernation prefix into the demo worker, and the existing instance-control client into the demo before-exec hook. No alternate data store or polling loop. Merge resolution against origin/main 9bd45488 retains main's HA departure controller, lifecycle and duty wiring alongside the demo data store and worker; no read site added by the resolution.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: install closed fixed admission before every launch source, bind activator/backend and edge, wire the real termination Started lifecycle and role reader after the change index; close before cancellation/child shutdown. No new external reads or cloud authority. Fix R1: move bind/lifecycle/edge-option wiring into wireAgentAdmission and worker listing into runWorkerBootPassAfterAdmission. Worker boot waits for admission before listing then uses unchanged bounded wakes and per-host serialization; whole Route read moves to the helper. No new storage, cloud, or root execution authority. Preserve merged main's agent wiring and census basis; the branch removes one whole Route use by moving worker iteration to the helper, with no added read kind.;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: arms a fleet-only worker using the existing registry, activator, backend and authenticated console transport. Owned worker stops and joins at shutdown. No new bucket reader. merge of origin/main 9b8b2c50: retain HA duty/departure lifecycle, wake-slot and existing agent wiring alongside the replica placement worker; no new read introduced by resolution. merge of origin/main 6be08467: Retain main demo configuration, admission, build and expiry wiring alongside the replica worker; merge-only body change, no additional read. merge of origin/main 7920cccf: Retain main box-role/group admission wiring and boot publication beside the owned replica worker and shutdown; main moves the boot registry List into runWorkerBootPassAfterAdmission, removing its inline whole Route site. No new read introduced by conflict resolution.;rev3=census-ruling-stateless-replicas-3;basis=Task 1 fix round 1 M3: retain the private snapshot source and cancel/join ownership, but use the replica-health-specific retry loop. It logs its first failure only and retains the existing exponential backoff capped at 30 seconds; unsupported builds return nil. Existing five direct read sites unchanged; no new credentials, bucket reader or app lifecycle action. Fix round 1 Q20: publish Edge.ReplicaSnapshots as a separate in-memory status source, leaving the tenant-visible Upstreams source unchanged. No new external reader or authority.;rev3=census-ruling-region-ha-p3b;basis=Load root-written group marker/configuration, configure signed boot binding and agent receipt completer, wire cancellable admission into departure work and expose cached GroupReaderSnapshot. New indirect boot reads use protected root files; agent-owned receipt controls duplicate initial completion only, never root restart permission. Same five direct sites. Merge 45cebde4 retains the replica health socket lifecycle and setReplicaSource beside GroupReaderSnapshot; no extra read beyond main.;rev3=census-ruling-agent-start-demo-2;basis=agent.go:309-329 opens demo-traffic.db beside the operator-configured registry when a demo domain exists, closes it at shutdown and wires drain-before-purge; :1010-1019 shares the worker and write gate; :1164-1177 installs the fleet identity and closed-until-worker serving callback. One added whole Route pass; the new indirect filesystem/SQL reads are claimed in openDemoTraffic and worker/store units. No request chooses the database pathname.;rev3=census-ruling-region-ha-p1b3b-s;basis=Wire the service duty view to authoritative cached sidecar manifest placement in LifetimeIndex and the edge sidecar projection; missing policy denies duty. Existing instance duty wiring remains.;rev3=census-ruling-region-ha-g2-t3;basis=T3a: wire eb.Page = PageOperator beside OwnerTerminated before departures arm, so suspect-holder pages work if departure setup fails; no new read; existing nine sites and authority unchanged; pages through the existing sink. T3b: publish the same backend through an atomic pointer for the metrics observer, and clear it on return; no new external read or authority.;rev3=census-ruling-agent-start-demo-3;basis=Wire the claim activator and root snapshot client into the demo worker; pass moved readiness to status reporting. Census read-site delta: unchanged (9).;rev3=census-ruling-region-ha-g2-fixes;basis=Wire local pool evidence, live withdrawal activator, startup ingress scan and alias publication, and edge lookup; no new direct sites; new indirect record/claim reads use existing store/judge paths described in ingress helpers.;rev3=census-ruling-region-ha-g2r-fixes;basis=W3: starts the existing record-view backstop loop with a departure-inventory listener (non-blocking, coalesced signal) even without an armed RecordView; it requests the existing full pass (backstopFullDue) there. Same nine read sites; no new read or authority.;rev3=census-ruling-region-ha-graceful-terminate-t2;basis=Derive one signal-time deadline with a 90-second budget; cap departure stop and startup/seed/service shutdown joins by it. No read added. file:Exec@19204,file:Open@1707,file:Statfs@50430,registry:App@12803,registry:Host@46512,whole:Route@12795,whole:Route@45670,whole:Route@46635,whole:Route@46697 1005ce50f1a6e41c0bda54ffb4496225b89ccda3e5a6c309f512092985871fec
+internal/host/claimfilesseed_shutdown.go joinAgentShutdown authority C,J4 rev3=PROPOSED-seed; FS-R7/9; agent; seed-active joined shutdown shares bounded cleanup; inactive seed has no seed join and starts a fresh 60-second service context after both startup joins;rev3=census-ruling-region-ha-graceful-terminate-t2;basis=Bound existing cleanup, startup joins and 60-second service context by the absolute signal-time deadline without extending shorter budgets. No read added. 63920e130858ee9c335d7d5dea917084a4d822a68e38f192762603a226db076e
+@coverage internal/activator a654ba429969722d125bec9fe29a370b0fb00a05433893a7b3c1ee81631d6a6d
+@coverage internal/edge 4be0f2e669dc9c84f38b21e807447e61afa275982f46f918c22d21dac203fc9d
+@coverage internal/host 86eb1b452c8b834432eb2a7b3c5eb5d27c3aaeaf4edfbeb0f6120ba9bb72f3be