carlos / platform Public

region HA T1/DR-4: planned terminations release HA leases at once

A terminated group member wrote no release marker, so its HA instances
answered 503 until the lease expired (~15 min). At poweroff systemd
stopped instance-control and D-Bus in parallel with the edge, so the
stop proof a release needs failed; release budgets also outlived the
agent's 60 s shutdown wait.

- edge ordered After= the control socket/service and dbus.service, so
  they stop after it; TimeoutStopSec=120; control After=nftables and
  Restart=on-failure (no Wants: its start probe needs the edge cgroup)
- one agent shutdown deadline, SIGTERM + 90 s; HA release steps are
  budgeted inside it; no marker unless Final and Finish returned
- rootrunner witness with a real EC2 terminate: main writes no marker,
  this branch writes a clean one 3.2 s after TerminateInstances
- spec section 9.9

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from region-ha-graceful-terminate into main.
claude agent, operated by paul@keymail.dev 209a36c7287e6800fd59e10718648583a878e153 parent 326d467
24 files changed, +1,673 −35
  • docs/superpowers/notes/census-proposal-region-ha-graceful-terminate-t1.md +21 −0
  • docs/superpowers/notes/census-proposal-region-ha-graceful-terminate-t2.md +25 −0
  • docs/superpowers/plans/2026-11-08-region-ha-graceful-terminate.md +219 −0
  • docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md +78 −1
  • internal/activator/activator.go +30 −1
  • internal/activator/cmd.go +3 −3
  • 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/host/haplacement_root_linux_test.go +39 −7
  • internal/host/haterminate_rootrunner_linux_test.go +670 −0
  • internal/host/plan14_generation_registry_root_linux_test.go +2 −0
  • internal/host/startup_largebox_linux_test.go +1 −1
  • internal/host/units/carlos-edge.service +9 −1
  • internal/host/units/carlos-instance-control.service +16 −7
  • internal/host/units_shutdown_test.go +131 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +2 −0
  • internal/provision/testdata/plan14-root-reads-region-ha-graceful-terminate-t1.tsv +7 −0
  • internal/provision/testdata/plan14-root-reads-region-ha-graceful-terminate-t2.tsv +11 −0

CI passed — run details

diff --git a/docs/superpowers/notes/census-proposal-region-ha-graceful-terminate-t1.md b/docs/superpowers/notes/census-proposal-region-ha-graceful-terminate-t1.md
new file mode 100644
index 000000000..1a4499df8
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-region-ha-graceful-terminate-t1.md
@@ -0,0 +1,21 @@
+# Census approval: region-ha-graceful-terminate-t1
+
+Ruling `census-ruling-region-ha-graceful-terminate-t1`. 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/units/carlos-edge.service` `external` | body | unchanged (1) | Region HA T1/DR-4 fix round 2: keep edge after control service, socket and D-Bus with TimeoutStopSec=120, but do not Want or Require control: its start probe needs the edge cgroup, so the agent socket-activates it after edge starts. Static ordering only; no new root read, input, command, path or capability. Instance templates unchanged. |
+| `internal/host/units/carlos-instance-control.service` `external` | body | unchanged (1) | Region HA T1/DR-4 final fix: retain After=nftables.service without Wants or Requires; add Restart=on-failure and RestartSec=1 so a crashed control restarts before a later edge stop can block socket activation and shutdown proofs; rewrap the header and explain this ordering. Same ExecStart and protections; no new root read, input, path, command or capability. |
+
+Envelopes re-pinned: `internal/activator`, `internal/host/units`.
+
+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/units/carlos-edge.service` `external`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input
+- `internal/host/units/carlos-instance-control.service` `external`: authority, task B3,C,D,E1,J4. Basis: root-input;kept=B3,C,D,E1;scope=protected-decision-only;rev3=census-ruling-agent-start-demo-3;basis=Correct the runtime-write comment to include escaped demo snapshot .mount units alongside per-generation drop-ins; service directives are unchanged.
+
+Seal: `9cdff432a5de2ffeaa147fdafd6a486c61c27a0c38f77466bddc86b149332c7d` → `3273ecae03559a8d450027f4cdf4dff24af9c54705231bc4f7c77b72582b517c`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-region-ha-graceful-terminate-t1.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
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..5cd9ec5b6
--- /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: `3273ecae03559a8d450027f4cdf4dff24af9c54705231bc4f7c77b72582b517c` → `687cf7744aecdf8a238dcdb80562b0ef191b3e247c28851de44c01866dbeca13`.
+
+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/docs/superpowers/plans/2026-11-08-region-ha-graceful-terminate.md b/docs/superpowers/plans/2026-11-08-region-ha-graceful-terminate.md
new file mode 100644
index 000000000..94d1e6fcc
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-08-region-ha-graceful-terminate.md
@@ -0,0 +1,219 @@
+# Region HA T1/DR-4: a planned member termination hands its leases off in seconds
+
+Branch `region-ha-graceful-terminate` from origin/main 326d4677.
+Spec: `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md`
+(§5.2 marker at release, §9 termination and takeover). This plan adds §9.9.
+Root-cause read (Astra, 2026-11-08): `.superpowers/sdd/2026-11-08-region-ha-graceful-terminate/rca-report.md`
+(git-ignored; the facts it rests on are restated below).
+
+## Problem
+
+A group member holding HA leases is terminated (ASG terminate, EC2 ACPI
+power-off, systemd shutdown). No release marker is written, so every HA
+instance it held answers 503 until the lease expires (~13-15 min; dev
+2026-11-08 02:31-02:44Z, G2 drills 1-2).
+
+Proven in code (rca-report §A, §B, §D):
+
+1. With generations on, a stopped entry reaches `finishStop` and
+ `releaseHAClean` only after `releasable` proves the generation gone through
+ `StopGen`, a root RPC to `carlos-instance-control.service`
+ (`activator.go:5001-5014`, `opset.go:257-339`, `containment.go:460-469`).
+ At system shutdown nothing orders that service (or its socket) after the
+ edge, so systemd stops it in parallel, and a socket with a pending stop job
+ refuses activation (systemd `socket.c` 2138-2146). The proof fails, the stop
+ stays pending, no marker.
+2. The agent's unprivileged `systemctl show` (exit observation) uses the system
+ D-Bus; `dbus.service` is not ordered after the edge either.
+3. The release budgets (files 2 min, sync 30 s, marker 10 s, each
+ `WithoutCancel`) do not fit the agent's 60 s Shutdown wait, which itself
+ starts only after the edge drain and joins; systemd's default 90 s
+ `TimeoutStopSec` then SIGKILLs. A release still running is abandoned.
+
+Instance templates keep `BindsTo=` + `After=carlos-edge.service` (they stop
+before the edge at shutdown). Reversing that deadlocks the agent's blocking
+`systemctl stop` behind the edge's own stop job (rca-report §E). Not changed.
+
+## Global constraints (binding on every task)
+
+- Single writer. A marker (clean or unclean) is written only after every
+ writer of the host is proven stopped AND the files publisher and the replica
+ finalizer have RETURNED. A timeout never stands in for that proof. If the
+ finalizer or publisher has not returned by the deadline: no marker, lease
+ left to expiry (today's crash path). Never wrap Finish/Final in a goroutine
+ and write a marker while it may still run.
+- "No takeover before proof AND expiry" is unchanged for the unclean path
+ (`hafresh/acquire.go`); a marker lets the next holder take over at once
+ (existing path, unchanged).
+- Hard-crash behaviour unchanged (no marker, wait for expiry).
+- Edge restarts (`systemctl restart carlos-edge`, rolls) behave as today:
+ instance units still stop before the edge via BindsTo/After.
+- Exact values: agent shutdown deadline `agentShutdownBudget = 90 * time.Second`
+ measured from receipt of SIGTERM; `carlos-edge.service` `TimeoutStopSec=120`;
+ marker reserve `haShutdownMarkerReserve = 10 * time.Second`; final-sync
+ reserve inside the shutdown deadline `haShutdownSyncReserve = 30 * time.Second`
+ (files Final gets until deadline - 40 s, the sync until deadline - 10 s, the
+ marker until the deadline; each also keeps its existing cap of 2 min / 30 s /
+ 10 s; a budget never drops below 1 s).
+- Go: `TMPDIR=/tmp/g` for socket-binding packages (activator, edge, host);
+ run only touched packages with `-run`; never `go test ./...`. Default
+ GOCACHE. Scratch in `$TMPDIR` or the SDD workspace.
+- Commits: subject < 80 chars, body after a blank line, end with
+ `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`.
+- NEVER run `amadan branch merge` (in any form) — the controller merges.
+
+## Task 1: keep instance-control and D-Bus up until the edge has stopped
+
+Files: `internal/host/units/carlos-edge.service` (embedded; find every test
+that pins its content or parses it, e.g. grep for `carlos-edge.service` in
+`internal/host/*_test.go` and the unit installer `ensureSystemUnits`),
+`internal/host/units/carlos-instance-control.service`,
+`internal/activator/cmd.go` and `internal/activator/activator.go` comments
+that say "systemd's 90 s TimeoutStopSec".
+
+Change the edge unit's `[Unit]`:
+
+```
+Wants=network-online.target
+After=network-online.target data-instances.mount run-carlos-instances.mount run-carlos-logs.mount carlos-instance-control.socket carlos-instance-control.service dbus.service
+```
+
+and `[Service]` `TimeoutStopSec=120`, each with a comment stating why:
+systemd stops units in reverse start order, so the edge (holding HA leases)
+stops before the root control service, its socket and D-Bus, whose RPCs and
+reads are the stop proofs a release needs (region HA T1/DR-4). Do not add
+`Wants=` or `Requires=` on control; the agent socket-activates it after the
+edge starts. Do not touch `BindsTo`/`After` on any instance template.
+
+Shipped correction: run `20261108T034728-f08de2` stayed not ready for five minutes because control's start probe needs the edge's cgroup; drop `Wants=control` and keep `After=control`.
+
+Add `After=nftables.service` to control so startup hairpin recovery runs
+after nftables loads its rules, with no `Wants=` or `Requires=` on nftables.
+
+Check the change does not create an ordering cycle with the control service:
+it is `After=` the three mounts and nftables, and `Requires=` its socket and
+the mounts; the group drop-in `carlos-edge-group.conf` also orders the edge
+after nftables. Write a Go test that parses the embedded units and asserts:
+edge `Wants` and `Requires` do not contain
+`carlos-instance-control.service`; edge `After` contains
+`carlos-instance-control.service`, `carlos-instance-control.socket`,
+`dbus.service`; `TimeoutStopSec=120`; control has `After=nftables.service`
+without pulling nftables in; and that no embedded
+`carlos-instance*` template or `carlos-instance-control.service` has
+`Before=carlos-edge.service` or orders itself after anything that is ordered
+after the edge (a direct cycle check over the embedded units is enough).
+If `systemd-analyze verify` is available locally, run it on a scratch copy of
+the units and report the output (not a gate).
+
+Update the two comments that name a 90 s systemd stop budget.
+
+## Task 2: one shutdown deadline from SIGTERM; HA release fits inside it
+
+Files: `internal/host/agent.go` (SIGTERM handling, `svc.Shutdown` call site,
+lines ~1290-1348), `internal/host/claimfilesseed_shutdown.go`
+(`joinAgentShutdown`), `internal/activator/activator.go` (`Shutdown`,
+`shutdownCtx`), `internal/activator/harelease.go` (`releaseHAClean`).
+
+1. The agent records the instant it receives SIGTERM/SIGINT (where the edge's
+ `<-stop` fires, or the agent's own signal context; find the single earliest
+ point) and derives one deadline `sigterm + agentShutdownBudget`. The
+ context `joinAgentShutdown` returns (today a fresh 60 s) must not end
+ later than that deadline; existing shorter inner budgets stay. Do not
+ lengthen any existing step. If wiring the instant through the edge is
+ invasive, take it as the time `e.Run`'s stop channel fires via an exported
+ hook or a package-level `atomic` set by the agent's signal handler; pick the
+ smallest correct seam and say which in the report.
+2. `releaseHAClean`: when the service is shutting down and `a.shutdownCtx`
+ has a deadline D, each step's budget is the minimum of its existing cap and
+ the time left before its own cut-off: files Final until
+ D - (haShutdownSyncReserve + haShutdownMarkerReserve), Finish until
+ D - haShutdownMarkerReserve, the marker PUT until D; floor 1 s. Outside
+ shutdown nothing changes. Keep `WithoutCancel` (a cancelled shutdown ctx must
+ not kill the marker), only the deadlines move. The marker is still written
+ only after Final and Finish have returned (constraint 1).
+3. `Shutdown` already waits on each stopping entry's `stopped` channel. Confirm
+ (and say in the report, with file:line) that `stopped` closes only after
+ `finishStop`'s release returned, so a marker in flight is joined until D.
+ At exit, log one line per HA entry still not released:
+ `activator: shutdown: <host>: HA lease not released (<state>); it frees at expiry`
+ (extend `logUnresolvedAtExit` or add beside it), and one line per HA host
+ released during shutdown is already logged by releaseHAClean.
+
+Tests (activator package, fakes as the existing harelease tests use; find
+them with grep `releaseHAClean\|ReleaseMarker` in `internal/activator/*_test.go`):
+- shutdown with D = now+20 s and a files publisher whose Final blocks until its
+ ctx ends: Final's ctx deadline is <= D-40s floor-clamped (1 s), Finish and
+ the marker still run, the marker is written UNCLEAN before D.
+- shutdown with a Finish that never returns: Shutdown returns by D (+ small
+ slack) and NO marker is written (the fake records no ReleaseMarker call).
+- shutdown, everything healthy: CLEAN marker; budgets were capped (the fakes
+ record their ctx deadlines).
+- not shutting down: budgets are the existing 2 min / 30 s / 10 s.
+Mutation check (in a scratch copy, never in place): remove the cap in (2) and
+show the first test fails; report it.
+
+## Task 3: production-wired witness — a real EC2 terminate of a runner holding a lease
+
+Goal: measure, on a real arm64 EC2 (root runner, dev account kass,
+eu-west-1, see `~/.cache/tmp/claude-1001/own/after236/root-runner.py` and
+`root-runner-contract.md` beside it), the time from the EC2
+TerminateInstances call to the HA release marker, through production units
+and the real agent, and show main fails where the branch passes.
+
+Build on the cold root harness (`newColdRootHarness` in
+`internal/host/haplacement_root_linux_test.go`; it installs the real
+embedded units, the real agent as `/opt/carlos/carlos`, generations, HA, and
+an in-process S3 fixture `leasetest.NewS3Server`). New file
+`internal/host/haterminate_rootrunner_linux_test.go`, build tags
+`linux && rootrunner`, test `TestRootHATerminateRelease`:
+
+1. Re-exec itself as a transient systemd unit (`systemd-run --unit
+ ha-terminate-witness --property Before=carlos-edge.service
+ --property DefaultDependencies=no --property Conflicts=
+ ...` or the minimal property set that makes systemd stop it only AFTER
+ carlos-edge.service at poweroff and not kill it early); the outer test
+ (running under SSM) waits for a `ready` file then exits 0, leaving the
+ unit running. Document the exact properties chosen and why.
+2. Inside the unit: start the harness, wake one HA host so its lease is held
+ (generations on, nested layout, as the harness's HA tests do), check the
+ lease is held by this box, then write `ready`.
+3. The S3 fixture mirrors every write to the host's lock object, and every
+ 10 s a heartbeat, synchronously to REAL S3 before replying:
+ `s3://carlos-dev-640012953448/root-runner/<run>/events/<unixnano>-<kind>.json`
+ (kind = lock-write | heartbeat | unit-stop), body = the lock JSON (marker
+ fields: release present, clean flag) or heartbeat time. The runner role
+ may write only `root-runner/*`. `<run>` comes from an env var the driver
+ sets. On its own SIGTERM (after the edge has stopped), it uploads
+ `journalctl -u carlos-edge.service -u carlos-instance-control.service
+ -u 'carlos-instance*' -b --no-pager -o short-iso-precise` to
+ `.../<run>/journal.txt` and a final `unit-stop` event.
+4. No other network beyond IMDS, the regional S3 endpoint and SSM.
+
+Driver (outside the repo, `~/.cache/region-ha-graceful/witness.py`, copied
+from root-runner.py): build the tagged test binary for linux/arm64, launch a
+runner, run the outer test over SSM, wait for its success, record t_term, call
+`ec2 terminate-instances`, then poll `root-runner/<run>/events/` for up to
+20 min; print: t_term, first lock-write after t_term (marker? clean?), the
+delta, last heartbeat, and save the journal. It must ALWAYS terminate the
+instance (it does by design here) and print LEAKED on failure.
+
+Runs (controller executes; sandbox off; AWS profile `kass`):
+- baseline: the witness test file applied on origin/main 326d4677 (a scratch
+ worktree), expected: no marker before the box dies.
+- branch: expected: marker within 60 s of t_term (target: well under).
+
+Report the two timelines. The witness is the acceptance gate for the fix.
+
+## Task 4: spec, docs, census, CI
+
+- Spec §9.9 "Planned termination" (new subsection in the spec named above,
+ plus a revision line at the top): what a graceful stop guarantees (marker
+ within the shutdown deadline when the proofs and final durability finish;
+ else no marker and expiry), the unit ordering facts, the deadline values, and
+ that an ASG termination lifecycle hook is NOT used (ruling, see ledger) and
+ when it would be needed.
+- AGENTS.md: only if it states the edge's stop budget or unit ordering.
+- Census (#280): if CI's `TestPlan14RootReadCensus` fails, run
+ `make census-card` / `make census-propose NAME=region-ha-graceful-terminate
+ CLAIMS=<file>` per AGENTS.md; the controller gets the cross-model approval.
+- CI green on the branch tip.
diff --git a/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md b/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md
index 1739d77a4..f2f648c3e 100644
--- a/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md
+++ b/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md
@@ -1,6 +1,6 @@
# Region HA without claims: N-box regions behind a load balancer
-Design, 2026-10-26, **rev 6.3** (§23 B10 addendum, 2026-11-05): rev 6 APPROVED by Paul on 2026-10-26, plus his ruling N-HA7 the same day (a scope ruling, not a redesign: §2.1, §8.4, §13, §19). Astra rounds 1 to 3 are complete, and the review budget is spent (AGENTS.md, stopping rules). Branch `design-region-ha-no-claims`, cut from `origin/main` at ddf3b929. Nothing here is built.
+Design, 2026-10-26, **rev 6.4** (§9.9 T1/DR-4, 2026-11-08): rev 6 APPROVED by Paul on 2026-10-26, plus his ruling N-HA7 the same day (a scope ruling, not a redesign: §2.1, §8.4, §13, §19). Astra rounds 1 to 3 are complete, and the review budget is spent (AGENTS.md, stopping rules). Branch `design-region-ha-no-claims`, cut from `origin/main` at ddf3b929. Nothing here is built.
This spec supersedes every claim-dependent part of "Region HA, spec 2: two-box regions" (`2026-10-15-region-ha-two-box-regions-design.md`, rev 21, cited **S2 §n**) and of spec 1 (`2026-10-04-region-ha-box-placement-design.md`, cited **S1 §n**). §16 lists what it reuses from S2, plan 2a (6834659c) and plan 2b (b1118925), and the removals this series owns. Line citations are to this worktree unless they name a module path.
@@ -11,6 +11,7 @@ This spec supersedes every claim-dependent part of "Region HA, spec 2: two-box r
- **Rev 5** applied round 3 (`docs/superpowers/notes/reviews/ASTRA-FINDINGS-region-ha-no-claims-r3.md`, 11ad7337, **astra-3.N**) directly, with Paul's approval of 2026-10-26.
- **Rev 6** is a scope cut Paul approved on 2026-10-26. Duty handoff drew a P1 in all three rounds, so the duty-file transfer protocol is deleted, not fixed again (stopping rule 2). Duties stay in local registries, as today. One scan-and-import moves them when a box leaves (§7.4).
- **Rev 6.2** adds the approved N-HA14 serialized operator ASG Standby maintenance exception to §12.1 (Paul, 2026-11-01).
+- **Rev 6.4** records T1/DR-4 planned termination: shutdown ordering, release budgets and the real-terminate witness (§9.9, 2026-11-08).
Under stopping rule 2, the families I2, I3 and I4 drew findings two rounds running. I2 and I4 are now stated as invariants, enforced in one place and checked by the simulation (§3.1). I3 drew a P1 in all three rounds, so rev 6 cuts its transfer protocol and restates I3 over the scan alone.
@@ -464,6 +465,82 @@ These are estimates; dev measures each one (§21).
- **A box that has lost S3** waits for the alarm and the runbook (§9.5).
- **A graceful termination** needs no takeover: the shutdown sleeps every instance and writes markers (`activator.go:5186-5194`).
+### 9.9 Planned termination
+
+T1/DR-4 makes a planned shutdown write a release marker when stop proofs,
+final durability and marker publication finish within the shutdown budget.
+The baseline could stop instance-control and D-Bus in parallel with the edge.
+With generations enabled, the required `StopGen` proof then failed and release
+was never reached. Separately, release's independent budgets could outlast
+the agent's 60 s wait, leaving release abandoned at process exit.
+
+`carlos-edge.service` now has `After=carlos-instance-control.socket
+carlos-instance-control.service dbus.service` and `TimeoutStopSec=120`.
+The 120 s timeout applies to every box's edge, whether or not it runs HA.
+Reverse stop ordering keeps those active dependencies available until the
+edge stops. There is no `Wants=` on control: its start probe needs the edge's
+cgroup, so the agent socket-activates it after the edge starts. Starting
+control first in run `20261108T034728-f08de2` left the box not ready for five
+minutes. Control has `After=nftables.service` for startup hairpin recovery.
+Instance templates retain `BindsTo=` and `After=carlos-edge.service`, stopping
+before the edge; reversing that order would put blocking `systemctl stop`
+behind the edge's own stop job.
+
+The agent sets its deadline to receipt of SIGTERM + 90 s, before admission
+closure and HTTP drain. Existing shorter waits remain. For the effective
+shutdown deadline D, release uses these cutoffs:
+
+| Phase | Cutoff | Existing cap |
+|---|---|---|
+| Files `Final` | D - 40 s | 2 min |
+| Replica `Finish` | D - 10 s | 30 s |
+| Marker PUT | D | 10 s |
+
+Each phase gets the smaller of its cap and the time to its cutoff, floored
+at 1 s. Outside shutdown the existing caps apply. Contexts are cooperative;
+admission closure, publisher/sweeper joins and local release-record work can
+overrun D. The 120 s systemd timeout is the process-stop backstop, not a
+marker guarantee.
+
+The single-writer rule holds on timeout too: no marker until every host
+writer is proven stopped, the publisher is joined, and `Final` and `Finish`
+have returned. Bounded completion with a durability error can produce an
+unclean marker. A stuck finalizer produces no marker; takeover still needs
+lease expiry plus owner termination proof (§9.4 unchanged). A deadline is
+never proof that storage writes have stopped.
+
+`TestRootHATerminateRelease` (`internal/host/haterminate_rootrunner_linux_test.go`)
+uses the real agent, embedded units, systemd poweroff and EC2
+`TerminateInstances`. Lease S3 is a loopback fixture whose writes are mirrored
+to real S3 off-box; this is not a real-S3 lease latency measurement.
+The ledger records these UTC timelines on 2026-11-08:
+
+- Baseline main, run `20261108T033846-e40376`: no marker; control stopped at
+ +4.6 s, before the edge, and the stop RPC failed with broken pipe.
+- Fixed `a434b157`, run `20261108T040905-1fa711`, acceptance PASS:
+ terminate at 04:11:02.207; generation stop at 04:11:04.770; edge SIGTERM at
+ 04:11:05.292; clean release logged at 04:11:05.446; edge stopped at
+ 04:11:05.456; control stopped at 04:11:05.471. The mirrored clean marker
+ arrived +3.21 s after `TerminateInstances`.
+- Earlier fixed run `20261108T035758-9ef70e` had a clean marker at +3.13 s,
+ but was INVALID because the observer lost the journal/unit-stop evidence.
+
+No ASG termination lifecycle hook is used (T1/DR-4 ruling). Revisit it only
+if EC2 cuts OS shutdown short; the witness did not show that. Cancellation
+and joining of Litestream work remains open as G2 F-A. Control now has
+`Restart=on-failure` and `RestartSec=1`: with the edge ordered after control,
+a socket-activated start of a dead control queues behind the edge's stop
+job and stalls the agent's shutdown proofs. Restarting on failure keeps
+control available. If control still cannot run, shutdown cannot prove
+termination and writes no marker. That failure remains safe.
+
+On group members, the hairpin drop-in's `ExecStop` runs
+`systemctl start carlos-hairpin-reset.service` before the edge receives
+SIGTERM. The reset service has `TimeoutStartSec=70`, and this stop command
+counts against the edge's `TimeoutStopSec=120`. The witness does not cover
+this group-member path. A dev group-member terminate check after release
+will close that coverage gap.
+
## 10. Load balancer health
Keep `internal/lbhealth`, with its six conditions (`internal/lbhealth/lbhealth.go:154-178`), and its endpoint (`internal/edge/lbhealth.go:21-39`). A **serving latch** replaces the claim's `SetHosting` caller (`internal/host/claimwiring.go:102-106`).
diff --git a/internal/activator/activator.go b/internal/activator/activator.go
index 38dbaaedb..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 {
@@ -6154,7 +6160,7 @@ func (a *Service) Shutdown(ctx context.Context) {
// already past that check rather than letting the stop below wait it out.
// The wait is right for a Bounce or an idle sleep — no deadline, and
// letting the exec finish is tidier — but a shutdown has a deadline it
- // does not control: systemd's TimeoutStopSec is 90s by default, and
+ // does not control: the agent unit's TimeoutStopSec is 120s, and
// workerSpawnTimeout alone is 2 minutes. An agent that blocks on one
// host's bucket materialize gets SIGKILLed mid-shutdown, which strands
// leases and sockets for EVERY host on the box — far worse than
@@ -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/cmd.go b/internal/activator/cmd.go
index 0ee66d2f8..da1a3dd75 100644
--- a/internal/activator/cmd.go
+++ b/internal/activator/cmd.go
@@ -83,9 +83,9 @@ var cmdWakeBound = 60 * time.Second
// cmdStopBound bounds finishStop's wait for a run: the start in flight
// (cmdStartBound), the stop (DeadlineControl), the cgroup (actStopTimeout)
// and both streams (cmdAcceptGrace + cmdDrainBound each), with room.
-// Shutdown runs inside systemd's 90 s TimeoutStopSec for the agent: a
-// settle (about 62 s) fits; a start in flight on top may not, and an agent
-// killed mid-stop leaves the lease to its TTL.
+// Shutdown runs inside the agent unit's 120 s TimeoutStopSec. A settle
+// (about 62 s) fits, but other shutdown phases share that budget. An agent
+// killed mid-stop can leave the lease without a release marker.
const cmdStopBound = 2 * time.Minute
// cmdStartBound bounds RunCmd's StartCmd, well below cmdStopBound, so a
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..fcc86ac72
--- /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 < 500*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(), 4*time.Second)
+ 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(3 * time.Second):
+ t.Fatal("Finish did not start")
+ }
+ select {
+ case <-done:
+ case <-time.After(time.Until(deadline.Add(2 * time.Second))):
+ t.Fatal("Shutdown blocked on Finish")
+ }
+ if time.Now().After(deadline.Add(2 * time.Second)) {
+ 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/host/haplacement_root_linux_test.go b/internal/host/haplacement_root_linux_test.go
index 036175c58..232d1ab4a 100644
--- a/internal/host/haplacement_root_linux_test.go
+++ b/internal/host/haplacement_root_linux_test.go
@@ -116,6 +116,10 @@ func TestColdPlacementRootGuardArm(t *testing.T) {
}
func TestColdPlacementRootAgent(t *testing.T) {
+ if os.Getenv("COLD_ROOT_MODE") == "terminate" {
+ terminateRootAgent(t)
+ return
+ }
ref := os.Getenv("COLD_ROOT_BOX")
if ref == "" {
t.Skip("installed edge child payload")
@@ -593,9 +597,13 @@ type coldRootHarness struct {
sophieEndpoint string
}
-func newColdRootHarness(t *testing.T, mode string) *coldRootHarness {
+func newColdRootHarness(t *testing.T, mode string, wrapS3 ...func(http.Handler) http.Handler) *coldRootHarness {
egressRootPrereqs(t)
uid, gid := generationRunnerRegistryUser(t)
+ deploymentDir := lifecycleHome + "/deployment"
+ if mode == "terminate" {
+ deploymentDir = "/data/terminate-deployment"
+ }
for _, path := range []string{lifecycleHome, "/data", "/opt/carlos", "/run/carlos", "/run/carlos-control", "/etc/carlos", "/var/lib/carlos-claims", "/var/lib/carlos-release"} {
lifecycleCheck(t, "exclusive root "+path, os.Mkdir(path, 0755))
t.Cleanup(func() { lifecycleCheck(t, "remove owned root "+path, os.RemoveAll(path)) })
@@ -613,12 +621,12 @@ func newColdRootHarness(t *testing.T, mode string) *coldRootHarness {
t.Logf("root fixture journal:\n%s", out)
})
lifecycleCheck(t, "private root authority", os.Chmod("/var/lib/carlos-claims", 0700))
- for _, path := range []string{lifecycleHome + "/deployment", "/data/.instances", "/data/instances", "/run/carlos/.instances", "/run/carlos/instances", "/run/carlos/.logs", "/run/carlos/logs", "/opt/carlos/versions"} {
+ for _, path := range []string{deploymentDir, "/data/.instances", "/data/instances", "/run/carlos/.instances", "/run/carlos/instances", "/run/carlos/.logs", "/run/carlos/logs", "/opt/carlos/versions"} {
lifecycleCheck(t, "tree", os.MkdirAll(path, 0755))
}
// openServiceRegistry creates the database as carlos. Match bootstrap and
// the lifecycle fixture before that first open, not only after staging.
- for _, path := range []string{lifecycleHome, lifecycleHome + "/deployment", "/data", "/data/.instances", "/data/instances", "/run/carlos", "/run/carlos/.instances", "/run/carlos/instances", "/run/carlos/.logs", "/run/carlos/logs"} {
+ for _, path := range []string{lifecycleHome, deploymentDir, "/data", "/data/.instances", "/data/instances", "/run/carlos", "/run/carlos/.instances", "/run/carlos/instances", "/run/carlos/.logs", "/run/carlos/logs"} {
lifecycleCheck(t, "bootstrap service owner "+path, os.Chown(path, uid, gid))
}
for _, path := range []string{"/data/.instances", "/data/instances", "/run/carlos/.logs", "/run/carlos/logs"} {
@@ -628,6 +636,9 @@ func newColdRootHarness(t *testing.T, mode string) *coldRootHarness {
model.AddBucket("data")
s3, _ := leasetest.NewS3Server(model)
var s3Handler http.Handler = lifecycleS3(s3, model)
+ for _, wrap := range wrapS3 {
+ s3Handler = wrap(s3Handler)
+ }
if mode == "competing" {
s3Handler = coldRootRaceS3(s3Handler)
}
@@ -637,12 +648,13 @@ func newColdRootHarness(t *testing.T, mode string) *coldRootHarness {
t.Cleanup(receiverServer.Close)
t.Cleanup(server.Close)
lifecycleEnvironment(t, server.URL)
+ t.Setenv("CARLOS_DEPLOYMENT_DIR", deploymentDir)
t.Setenv("CARLOS_HOST_CLAIM", "")
t.Setenv("CARLOS_REGION_HA", "true")
t.Setenv("AWS_REGION", "eu-west-1")
t.Setenv("AWS_DEFAULT_REGION", "eu-west-1")
key := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{1}, ed25519.SeedSize))
- store := release.NewDirStore(lifecycleHome + "/deployment")
+ store := release.NewDirStore(deploymentDir)
identity := handoverRecoveryIdentity(t, hostbox.Actor{Box: "box", Enrollment: strings.Repeat("a", 32), Revision: 1, Binding: "1", Region: "ie", FleetHomeRegion: "ie", ControlBucket: "deployment"})
identity.HomeRegion = "ie"
actor, err := identity.Verify(t.Context())
@@ -693,7 +705,11 @@ func newColdRootHarness(t *testing.T, mode string) *coldRootHarness {
out, err := exec.Command("systemctl", args...).CombinedOutput()
return string(out), err
}
- for _, name := range []string{"carlos-edge.service", "carlos-instance-probe.service"} {
+ units := []string{"carlos-edge.service", "carlos-instance-probe.service"}
+ if mode == "terminate" {
+ units = append(units, "carlos-instance-gen@.service")
+ }
+ for _, name := range units {
raw, err := unitsFS.ReadFile("units/" + name)
lifecycleCheck(t, "production unit", err)
path := filepath.Join("/etc/systemd/system", name)
@@ -709,7 +725,7 @@ func newColdRootHarness(t *testing.T, mode string) *coldRootHarness {
coldRootCertificate(t, store, caFile)
_, err = store.Put(t.Context(), "control/edge-mesh-key", []byte(strings.Repeat("a", 64)), "")
lifecycleCheck(t, "mesh key", err)
- env := map[string]string{"COLD_ROOT_SHARED": lifecycleHome, "RHASIM_MUTATE": os.Getenv("RHASIM_MUTATE"), "COLD_ROOT_MODE": mode, "COLD_ROOT_BOX": "leo", "COLD_ROOT_HTTPS": "127.0.0.1:443", "PLAN14_LIFECYCLE_GUARD": "1", "CARLOS_HOST_CLAIM": "", "CARLOS_REGION_HA": "true", "CARLOS_HIBERNATE_BUCKET": "data", "CARLOS_HIBERNATE_REGION": "eu-west-1", "CARLOS_HIBERNATE_PREFIX": "instances", "CARLOS_DATA_DIR": "/data", "CARLOS_OPT_DIR": "/opt/carlos", "CARLOS_DEPLOYMENT_DIR": lifecycleHome + "/deployment", "CARLOS_DEPLOYMENT_BUCKET": actor.ControlBucket, "CARLOS_RELEASE_PUBKEY": base64.StdEncoding.EncodeToString(key.Public().(ed25519.PublicKey)), "CARLOS_SECRETS_KEY": secret, "CARLOS_S3_ENDPOINT": activationS3Fixture(t, store), "COLD_ROOT_DATA_ENDPOINT": server.URL, "AWS_ACCESS_KEY_ID": "test-key", "AWS_SECRET_ACCESS_KEY": "test-secret", "AWS_EC2_METADATA_DISABLED": "true", "AWS_CONFIG_FILE": "/nonexistent", "AWS_SHARED_CREDENTIALS_FILE": "/nonexistent", "AWS_REGION": "eu-west-1", "SSL_CERT_FILE": caFile, "TMPDIR": "/run/carlos", "PATH": os.Getenv("PATH")}
+ env := map[string]string{"COLD_ROOT_SHARED": lifecycleHome, "RHASIM_MUTATE": os.Getenv("RHASIM_MUTATE"), "COLD_ROOT_MODE": mode, "COLD_ROOT_BOX": "leo", "COLD_ROOT_HTTPS": "127.0.0.1:443", "PLAN14_LIFECYCLE_GUARD": "1", "CARLOS_HOST_CLAIM": "", "CARLOS_REGION_HA": "true", "CARLOS_HIBERNATE_BUCKET": "data", "CARLOS_HIBERNATE_REGION": "eu-west-1", "CARLOS_HIBERNATE_PREFIX": "instances", "CARLOS_DATA_DIR": "/data", "CARLOS_OPT_DIR": "/opt/carlos", "CARLOS_DEPLOYMENT_DIR": deploymentDir, "CARLOS_DEPLOYMENT_BUCKET": actor.ControlBucket, "CARLOS_RELEASE_PUBKEY": base64.StdEncoding.EncodeToString(key.Public().(ed25519.PublicKey)), "CARLOS_SECRETS_KEY": secret, "CARLOS_S3_ENDPOINT": activationS3Fixture(t, store), "COLD_ROOT_DATA_ENDPOINT": server.URL, "AWS_ACCESS_KEY_ID": "test-key", "AWS_SECRET_ACCESS_KEY": "test-secret", "AWS_EC2_METADATA_DISABLED": "true", "AWS_CONFIG_FILE": "/nonexistent", "AWS_SHARED_CREDENTIALS_FILE": "/nonexistent", "AWS_REGION": "eu-west-1", "SSL_CERT_FILE": caFile, "TMPDIR": "/run/carlos", "PATH": os.Getenv("PATH")}
var lines []string
for name, value := range env {
lines = append(lines, name+"="+value)
@@ -745,6 +761,17 @@ func newColdRootHarness(t *testing.T, mode string) *coldRootHarness {
lifecycleCheck(t, "stage signed app", err)
lifecycleCheck(t, "point live", release.PointLive("/opt/carlos", lifecycleHost, "bab", "v1", "lifecycle"))
lifecycleCheck(t, "point sibling live", release.PointLive("/opt/carlos", lifecycleSibling, "bab", "v1", "lifecycle"))
+ if mode == "terminate" {
+ for _, host := range []string{lifecycleHost, lifecycleSibling} {
+ lifecycleCheck(t, "install managed fixture build", release.MaterializeHost(t.Context(), reg, store, key.Public().(ed25519.PublicKey), "/opt/carlos", "/data", host))
+ row, err := reg.Get(host)
+ lifecycleCheck(t, "installed fixture row", err)
+ if row == nil || row.Version != "v1" {
+ t.Fatalf("fixture build was not adopted: %+v", row)
+ }
+ }
+ }
+
if mode == "departure-sidecar" {
lifecycleCheck(t, "point sidecar live", release.PointLive("/opt/carlos", departureSidecarHost, "bab", "v1", "lifecycle"))
}
@@ -797,7 +824,7 @@ func newColdRootHarness(t *testing.T, mode string) *coldRootHarness {
if strings.HasPrefix(mode, "departure-") {
departureRootIdentities(t, store)
}
- lifecycleCheck(t, "fault publication owner", filepath.Walk(lifecycleHome+"/deployment/control", func(path string, _ os.FileInfo, err error) error {
+ lifecycleCheck(t, "fault publication owner", filepath.Walk(deploymentDir+"/control", func(path string, _ os.FileInfo, err error) error {
if err != nil {
return err
}
@@ -816,6 +843,11 @@ func newColdRootHarness(t *testing.T, mode string) *coldRootHarness {
lifecycleCheck(t, "scenario environment", os.WriteFile("/etc/carlos/host.env", []byte(strings.Join(envLines, "\n")+"\n"), 0600))
out, err = ctl("start", "carlos-edge.service")
lifecycleCheck(t, out, err)
+ if mode == "terminate" {
+ f := &coldRootHarness{t: t, model: model, store: store, reg: reg, ctl: ctl, env: env}
+ f.waitLeo()
+ return f
+ }
ingress := "/data/cold-sophie"
lifecycleCheck(t, "ingress dir", os.Mkdir(ingress, 0755))
lifecycleCheck(t, "ingress owner", os.Chown(ingress, uid, gid))
diff --git a/internal/host/haterminate_rootrunner_linux_test.go b/internal/host/haterminate_rootrunner_linux_test.go
new file mode 100644
index 000000000..e81bf16bf
--- /dev/null
+++ b/internal/host/haterminate_rootrunner_linux_test.go
@@ -0,0 +1,670 @@
+//go:build linux && rootrunner
+
+package host
+
+import (
+ "bytes"
+ "context"
+ "database/sql"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "os/signal"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "sync"
+ "syscall"
+ "testing"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/credentials"
+ "github.com/aws/aws-sdk-go-v2/credentials/ec2rolecreds"
+ "github.com/aws/aws-sdk-go-v2/feature/ec2/imds"
+ "github.com/aws/aws-sdk-go-v2/service/s3"
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+ "golang.org/x/crypto/acme/autocert"
+)
+
+const terminateWitnessUnit = "ha-terminate-witness.service"
+const terminateWitnessRoot = "/var/lib/ha-terminate-witness"
+const terminateWitnessBucket = "carlos-dev-640012953448"
+const terminateLockPath = "/data/instances/" + lifecycleHost + "/lock.json"
+
+// The fixture tenant accepts the production generation socket as well as the
+// legacy socket handled by the lifecycle fixture. It keeps SQLite open until
+// the installed instance unit terminates it.
+func init() {
+ if len(os.Args) != 5 || os.Args[1] != "--socket" || os.Args[3] != "--db" || os.Args[4] != provision.NestedDBPath("/data", lifecycleHost) {
+ return
+ }
+ pattern := "^" + regexp.QuoteMeta(provision.InstanceRunDir(lifecycleHost)) + `/g[1-9][0-9]*/app\.sock$`
+ if !regexp.MustCompile(pattern).MatchString(os.Args[2]) {
+ return
+ }
+ db, err := sql.Open("sqlite", os.Args[4])
+ if err != nil {
+ panic(err)
+ }
+ if _, err = db.Exec("PRAGMA journal_mode=WAL; CREATE TABLE IF NOT EXISTS lifecycle (value TEXT)"); err != nil {
+ panic(err)
+ }
+ listener, err := net.Listen("unix", os.Args[2])
+ if err != nil {
+ panic(err)
+ }
+ if err = http.Serve(listener, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "lifecycle tenant") })); err != nil {
+ panic(err)
+ }
+ os.Exit(0)
+}
+
+// This payload uses the agent entry and shutdown code, including its generation
+// arming checks. The cold placement payload normally composes a smaller service.
+func terminateRootAgent(t *testing.T) {
+ store := release.NewDirStore(os.Getenv("CARLOS_DEPLOYMENT_DIR"))
+ t.Setenv("CARLOS_DEPLOYMENT_BUCKET", "")
+ t.Setenv("CARLOS_S3_ENDPOINT", os.Getenv("COLD_ROOT_DATA_ENDPOINT"))
+ t.Setenv("AWS_ENDPOINT_URL_S3", os.Getenv("COLD_ROOT_DATA_ENDPOINT"))
+ t.Setenv("CARLOS_SWAP", "overlap")
+ t.Setenv("CARLOS_REGION", "ie")
+ t.Setenv("CARLOS_AWS_REGION", "eu-west-1")
+ t.Setenv("CARLOS_HIBERNATE_IDLE", "1h")
+ t.Setenv("CARLOS_PUBLIC_IP", "127.0.0.1")
+ t.Setenv("CARLOS_PRIVATE_IP", "127.0.0.1")
+ coldRootSeedCertificates(t, store, autocert.DirCache("/data/acme"))
+ for _, ref := range []string{"leo", "sophie"} {
+ lifecycleCheck(t, "remove unused logical peer", store.Delete(t.Context(), edgesFileKey(ref)))
+ }
+ RunAgent([]string{"--registry", "/data/registry.db", "--https", "127.0.0.1:443", "--http", "127.0.0.1:80"})
+}
+
+type terminateEvent struct {
+ At time.Time `json:"at"`
+ Kind string `json:"kind"`
+ Lock json.RawMessage `json:"lock,omitempty"`
+ Error string `json:"error,omitempty"`
+ Units string `json:"units,omitempty"`
+}
+
+type terminateMirror struct {
+ client *s3.Client
+ prefix string
+ mu sync.Mutex
+ failure string
+ command func(context.Context, string, ...string) ([]byte, error)
+}
+
+func newTerminateMirror(t *testing.T, run string) *terminateMirror {
+ // No default config chain: the fixture installs fake credentials and S3
+ // overrides. This client always uses IMDSv2 and the regional HTTPS endpoint.
+ transport := &http.Transport{Proxy: nil}
+ client := &http.Client{Transport: transport, Timeout: 15 * time.Second}
+ metadata := imds.New(imds.Options{HTTPClient: client, Endpoint: "http://169.254.169.254", ClientEnableState: imds.ClientEnabled})
+ creds := aws.NewCredentialsCache(ec2rolecreds.New(func(o *ec2rolecreds.Options) { o.Client = metadata }))
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel()
+ _, err := creds.Retrieve(ctx)
+ lifecycleCheck(t, "runner role credentials", err)
+ return &terminateMirror{client: s3.NewFromConfig(aws.Config{Region: "eu-west-1", Credentials: creds, HTTPClient: client, RetryMaxAttempts: 2}, func(o *s3.Options) {
+ o.BaseEndpoint = aws.String("https://s3.eu-west-1.amazonaws.com")
+ o.UsePathStyle = true
+ }), prefix: "root-runner/" + run + "/"}
+}
+
+func (m *terminateMirror) put(key string, raw []byte) error {
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+ defer cancel()
+ _, err := m.client.PutObject(ctx, &s3.PutObjectInput{Bucket: aws.String(terminateWitnessBucket), Key: aws.String(m.prefix + key), Body: bytes.NewReader(raw)})
+ return err
+}
+
+func (m *terminateMirror) event(e terminateEvent) error {
+ raw, err := json.Marshal(e)
+ if err != nil {
+ return err
+ }
+ return m.put(fmt.Sprintf("events/%d-%s.json", e.At.UnixNano(), e.Kind), raw)
+}
+
+func (m *terminateMirror) wrap(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPut || r.URL.Path != terminateLockPath {
+ next.ServeHTTP(w, r)
+ return
+ }
+ raw, err := io.ReadAll(r.Body)
+ if err != nil {
+ http.Error(w, err.Error(), 500)
+ return
+ }
+ r.Body = io.NopCloser(bytes.NewReader(raw))
+ // Serialize lock mutation and its mirror; never acknowledge a successful
+ // fixture PUT until its exact bytes have been stored off the runner.
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ rec := httptest.NewRecorder()
+ next.ServeHTTP(rec, r)
+ if rec.Code >= 200 && rec.Code < 300 {
+ err = m.event(terminateEvent{At: time.Now().UTC(), Kind: "lock-write", Lock: json.RawMessage(raw)})
+ if err != nil {
+ m.failure = err.Error()
+ fmt.Fprintf(os.Stderr, "lock mirror failed: %v\n", err)
+ http.Error(w, "lock mirror failed", 500)
+ return
+ }
+ }
+ for k, v := range rec.Header() {
+ w.Header()[k] = v
+ }
+ w.WriteHeader(rec.Code)
+ _, _ = w.Write(rec.Body.Bytes())
+ })
+}
+
+const terminateJournalChunkLimit = 256 << 10
+const terminateJournalTotalLimit = 16 << 20
+const terminateJournalCountLimit = 900
+
+type terminateBoundedOutput struct {
+ buffer bytes.Buffer
+ limit int
+}
+
+func (b *terminateBoundedOutput) Write(p []byte) (int, error) {
+ if len(p) > b.limit-b.buffer.Len() {
+ return 0, fmt.Errorf("observer command output exceeds %d bytes", b.limit)
+ }
+ return b.buffer.Write(p)
+}
+
+func (m *terminateMirror) run(ctx context.Context, name string, args ...string) ([]byte, error) {
+ ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
+ defer cancel()
+ if m.command != nil {
+ return m.command(ctx, name, args...)
+ }
+ cmd := exec.CommandContext(ctx, name, args...)
+ out := &terminateBoundedOutput{limit: terminateJournalChunkLimit}
+ cmd.Stdout, cmd.Stderr = out, out
+ err := cmd.Run()
+ return out.buffer.Bytes(), err
+}
+
+func (m *terminateMirror) observerPut(ctx context.Context, key string, raw []byte) error {
+ ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
+ defer cancel()
+ _, err := m.client.PutObject(ctx, &s3.PutObjectInput{Bucket: aws.String(terminateWitnessBucket), Key: aws.String(m.prefix + key), Body: bytes.NewReader(raw)})
+ return err
+}
+
+func (m *terminateMirror) observerEvent(ctx context.Context, e terminateEvent) error {
+ raw, err := json.Marshal(e)
+ if err != nil {
+ return err
+ }
+ return m.observerPut(ctx, fmt.Sprintf("events/%d-%s.json", e.At.UnixNano(), e.Kind), raw)
+}
+
+func (m *terminateMirror) observerError(ctx context.Context, step string, err error) {
+ if err == nil || ctx.Err() != nil {
+ return
+ }
+ message := err.Error()
+ if len(message) > 2048 {
+ message = message[:2048]
+ }
+ fmt.Fprintf(os.Stderr, "observer %s: %s\n", step, message)
+ _ = m.observerEvent(ctx, terminateEvent{At: time.Now().UTC(), Kind: step + "-error", Error: message})
+}
+
+func (m *terminateMirror) journal(ctx context.Context, cursors [2]string) ([]byte, [2]string, error) {
+ var journal []byte
+ for i := range cursors {
+ args := []string{"-b", "--no-pager", "--quiet", "--utc", "-o", "short-iso-precise", "--show-cursor"}
+ if cursors[i] != "" {
+ args = append(args, "--after-cursor="+cursors[i])
+ }
+ if i == 0 {
+ args = append(args, "-u", "carlos-edge.service", "-u", "carlos-instance-control.service", "-u", "carlos-instance*", "-u", terminateWitnessUnit)
+ } else {
+ args = append(args, "_PID=1")
+ }
+ raw, err := m.run(ctx, "journalctl", args...)
+ if err != nil {
+ return nil, cursors, fmt.Errorf("journal source %d: %w", i, err)
+ }
+ for _, line := range strings.SplitAfter(string(raw), "\n") {
+ if strings.HasPrefix(line, "-- cursor: ") {
+ cursors[i] = strings.TrimSpace(strings.TrimPrefix(line, "-- cursor: "))
+ } else {
+ journal = append(journal, line...)
+ }
+ }
+ if len(journal) > terminateJournalChunkLimit {
+ return nil, cursors, fmt.Errorf("journal chunk exceeds %d bytes", terminateJournalChunkLimit)
+ }
+ }
+ return journal, cursors, nil
+}
+
+type terminateJournalStream struct {
+ cursors [2]string
+ seq, size int
+}
+
+func (m *terminateMirror) streamJournal(ctx context.Context, stream *terminateJournalStream) error {
+ if stream.seq >= terminateJournalCountLimit || stream.size >= terminateJournalTotalLimit {
+ return fmt.Errorf("journal stream limit reached")
+ }
+ raw, cursors, err := m.journal(ctx, stream.cursors)
+ if err != nil {
+ return err
+ }
+ if len(raw) > terminateJournalTotalLimit-stream.size {
+ return fmt.Errorf("journal stream byte limit reached")
+ }
+ if len(raw) > 0 {
+ if err := m.observerPut(ctx, fmt.Sprintf("journal/%06d.txt", stream.seq), raw); err != nil {
+ return err
+ }
+ stream.seq++
+ stream.size += len(raw)
+ }
+ stream.cursors = cursors
+ return nil
+}
+
+func (m *terminateMirror) observe(ctx context.Context) {
+ journalTick := time.NewTicker(2 * time.Second)
+ heartbeatTick := time.NewTicker(10 * time.Second)
+ defer journalTick.Stop()
+ defer heartbeatTick.Stop()
+ stream := &terminateJournalStream{}
+ streamFailed := false
+ attempts := 0
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-journalTick.C:
+ if attempts < terminateJournalCountLimit {
+ attempts++
+ if err := m.streamJournal(ctx, stream); err != nil {
+ if !streamFailed {
+ m.observerError(ctx, "journal-stream", err)
+ }
+ streamFailed = true
+ } else {
+ streamFailed = false
+ }
+ if attempts == terminateJournalCountLimit {
+ m.observerError(ctx, "journal-stream", fmt.Errorf("journal polling limit reached"))
+ }
+ }
+ case <-heartbeatTick.C:
+ m.mu.Lock()
+ failure := m.failure
+ m.mu.Unlock()
+ err := m.observerEvent(ctx, terminateEvent{At: time.Now().UTC(), Kind: "heartbeat", Error: failure})
+ m.observerError(ctx, "heartbeat", err)
+ }
+ }
+}
+
+func (m *terminateMirror) finish(at time.Time) {
+ ctx := context.Background()
+ m.observerError(ctx, "sigterm", m.observerEvent(ctx, terminateEvent{At: at, Kind: "sigterm"}))
+ units, err := m.run(ctx, "systemctl", "show", "carlos-edge.service", "carlos-instance-control.service", "-p", "Id", "-p", "ActiveState", "-p", "SubState", "-p", "MainPID")
+ m.observerError(ctx, "unit-state", err)
+ m.mu.Lock()
+ failure := m.failure
+ m.mu.Unlock()
+ m.observerError(ctx, "unit-stop", m.observerEvent(ctx, terminateEvent{At: time.Now().UTC(), Kind: "unit-stop", Units: string(units), Error: failure}))
+ journal, _, err := m.journal(ctx, [2]string{})
+ if err != nil {
+ m.observerError(ctx, "journal", err)
+ } else {
+ m.observerError(ctx, "journal", m.observerPut(ctx, "journal.txt", journal))
+ }
+}
+
+func TestRootHATerminateRelease(t *testing.T) {
+ run := os.Getenv("HA_TERMINATE_RUN")
+ if run == "" {
+ t.Skip("HA_TERMINATE_RUN is unset")
+ }
+ if !regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9-]{0,79}$`).MatchString(run) {
+ t.Fatal("HA_TERMINATE_RUN must name this driver's isolated root-runner prefix")
+ }
+ if os.Geteuid() != 0 {
+ t.Fatal("requires the designated throwaway root runner")
+ }
+ if os.Getenv("HA_TERMINATE_PAYLOAD") != "1" {
+ terminateRootLaunch(t, run)
+ return
+ }
+ stopped := make(chan os.Signal, 1)
+ signal.Notify(stopped, syscall.SIGTERM, syscall.SIGINT)
+ defer signal.Stop(stopped)
+ mirror := newTerminateMirror(t, run)
+ f := newColdRootHarness(t, "terminate", mirror.wrap)
+ // An HTTP wake must succeed through the real agent before the driver can
+ // terminate. The active gen unit below also rules out silently declined swap.
+ deadline := time.Now().Add(2 * time.Minute)
+ var code int
+ var body string
+ for time.Now().Before(deadline) {
+ code, body, _ = f.request("leo", lifecycleHost)
+ if code == 200 && body == "lifecycle tenant" {
+ break
+ }
+ time.Sleep(time.Second)
+ }
+ if code != 200 || body != "lifecycle tenant" {
+ t.Fatalf("real agent wake: %d %q", code, body)
+ }
+ units, err := f.ctl("list-units", "--all", "--plain", "--no-legend", "carlos-instance-gen@*.service")
+ lifecycleCheck(t, "generation units", err)
+ running := false
+ for _, line := range strings.Split(units, "\n") {
+ fields := strings.Fields(line)
+ if len(fields) >= 4 && strings.Contains(fields[0], lifecycleHost) && fields[2] == "active" && fields[3] == "running" {
+ running = true
+ }
+ }
+ if !running {
+ t.Fatalf("no running generation unit: %s", units)
+ }
+ t.Logf("generation unit: %s", units)
+ view, err := lease.ReadLock(t.Context(), "data", "instances/"+lifecycleHost, "eu-west-1")
+ lifecycleCheck(t, "held lock", err)
+ iid, account, region, err := readIdentity(&http.Client{Timeout: 5 * time.Second}, imdsBase)
+ lifecycleCheck(t, "runner identity", err)
+ owner, ok := hafresh.ParseOwner(view.Lock.Owner)
+ if !ok || !owner.HA || owner.IID != iid || iid == "" || account != "640012953448" || region != "eu-west-1" || view.Absent || view.Lock.Release != nil || !view.Lock.ExpiresAt.After(time.Now()) {
+ t.Fatalf("lock not held by this runner: %+v identity=%s/%s/%s", view, iid, account, region)
+ }
+ raw, err := json.Marshal(view.Lock)
+ lifecycleCheck(t, "ready lock encode", err)
+ mirror.mu.Lock()
+ failure := mirror.failure
+ mirror.mu.Unlock()
+ if failure != "" {
+ t.Fatal("mirror failed before ready: " + failure)
+ }
+ lifecycleCheck(t, "initial heartbeat", mirror.event(terminateEvent{At: time.Now().UTC(), Kind: "heartbeat"}))
+ observeCtx, stopObserver := context.WithCancel(context.Background())
+ defer stopObserver()
+ go mirror.observe(observeCtx)
+ lifecycleCheck(t, "off-box ready", mirror.put("ready.json", raw))
+ lifecycleCheck(t, "local ready", os.WriteFile(filepath.Join(terminateWitnessRoot, "ready"), raw, 0600))
+ <-stopped
+ stopObserver()
+ mirror.finish(time.Now().UTC())
+ // Shutdown owns the machine now. Avoid test cleanups that would start
+ // systemctl jobs or unmount fixtures during the poweroff transaction.
+ os.Exit(0)
+}
+
+func terminateRootLaunch(t *testing.T, run string) {
+ lifecycleCheck(t, "exclusive witness state", os.Mkdir(terminateWitnessRoot, 0700))
+ exe, err := os.Executable()
+ lifecycleCheck(t, "witness executable", err)
+ // Default dependencies retain shutdown.target Conflicts/Before. Startup
+ // Before=edge reverses at shutdown: edge stops first. After=network.target
+ // keeps network teardown behind the fixture's final S3 writes.
+ out, err := exec.Command("systemd-run", "--unit="+terminateWitnessUnit, "--property=Type=exec", "--property=Before=carlos-edge.service", "--property=After=network.target network-online.target", "--property=DefaultDependencies=yes", "--property=TimeoutStopSec=90s", "--setenv=HA_TERMINATE_PAYLOAD=1", "--setenv=HA_TERMINATE_RUN="+run, "--setenv=TMPDIR=/var/tmp", exe, "-test.run=^TestRootHATerminateRelease$", "-test.v", "-test.timeout=30m").CombinedOutput()
+ lifecycleCheck(t, string(out), err)
+ out, err = exec.Command("systemctl", "show", terminateWitnessUnit, "-p", "Before", "-p", "After", "-p", "Conflicts", "-p", "DefaultDependencies", "-p", "TimeoutStopUSec").CombinedOutput()
+ lifecycleCheck(t, "effective witness properties", err)
+ t.Logf("effective witness properties:\n%s", out)
+ props := map[string]string{}
+ for _, line := range strings.Split(string(out), "\n") {
+ k, v, _ := strings.Cut(line, "=")
+ props[k] = v
+ }
+ has := func(key, value string) bool {
+ for _, word := range strings.Fields(props[key]) {
+ if word == value {
+ return true
+ }
+ }
+ return false
+ }
+ if !has("Before", "carlos-edge.service") || !has("Before", "shutdown.target") || !has("Conflicts", "shutdown.target") || !has("After", "network.target") || props["DefaultDependencies"] != "yes" {
+ t.Fatalf("unsafe witness shutdown ordering: %s", out)
+ }
+ deadline := time.Now().Add(5 * time.Minute)
+ for time.Now().Before(deadline) {
+ if raw, err := os.ReadFile(filepath.Join(terminateWitnessRoot, "ready")); err == nil {
+ t.Logf("READY lock=%s", raw)
+ return
+ }
+ out, err := exec.Command("systemctl", "is-active", terminateWitnessUnit).CombinedOutput()
+ if err != nil {
+ journal, _ := exec.Command("journalctl", "-u", terminateWitnessUnit, "-u", "carlos-edge.service", "-u", "carlos-instance-control.service", "-b", "--no-pager", "-n", "150").CombinedOutput()
+ t.Fatalf("witness stopped: %s\n%s", out, journal)
+ }
+ time.Sleep(time.Second)
+ }
+ out, _ = exec.Command("journalctl", "-u", terminateWitnessUnit, "-u", "carlos-edge.service", "-u", "carlos-instance-control.service", "-b", "--no-pager", "-n", "150").CombinedOutput()
+ t.Fatalf("witness readiness timeout:\n%s", out)
+}
+
+func TestHATerminateMirror(t *testing.T) {
+ for _, status := range []int{http.StatusOK, http.StatusServiceUnavailable} {
+ t.Run(fmt.Sprint(status), func(t *testing.T) {
+ entered, allow := make(chan []byte, 1), make(chan struct{})
+ remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ t.Error(err)
+ }
+ entered <- body
+ <-allow
+ w.WriteHeader(status)
+ }))
+ defer remote.Close()
+ mirror := &terminateMirror{prefix: "root-runner/test/", client: s3.NewFromConfig(aws.Config{Region: "eu-west-1", Credentials: credentials.NewStaticCredentialsProvider("fake", "fake", ""), RetryMaxAttempts: 1}, func(o *s3.Options) {
+ o.BaseEndpoint = aws.String(remote.URL)
+ o.UsePathStyle = true
+ })}
+ lock := `{"generation":1,"owner":"held"}`
+ fixture := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("ETag", `"fixture"`); w.WriteHeader(200) })
+ handler := mirror.wrap(fixture)
+ reply := httptest.NewRecorder()
+ done := make(chan struct{})
+ go func() {
+ handler.ServeHTTP(reply, httptest.NewRequest("PUT", terminateLockPath, strings.NewReader(lock)))
+ close(done)
+ }()
+ var raw []byte
+ select {
+ case raw = <-entered:
+ case <-time.After(5 * time.Second):
+ t.Fatal("mirror never started")
+ }
+ select {
+ case <-done:
+ t.Error("fixture replied before mirror completed")
+ default:
+ }
+ close(allow)
+ select {
+ case <-done:
+ case <-time.After(5 * time.Second):
+ t.Fatal("mirror never completed")
+ }
+ var event terminateEvent
+ if err := json.Unmarshal(raw, &event); err != nil || string(event.Lock) != lock || event.Kind != "lock-write" {
+ t.Fatalf("wrong event %s: %v", raw, err)
+ }
+ if status == 200 {
+ if reply.Code != 200 || reply.Header().Get("ETag") != `"fixture"` || mirror.failure != "" {
+ t.Fatalf("successful mirror: %v failure=%s", reply, mirror.failure)
+ }
+ } else if reply.Code != 500 || mirror.failure == "" {
+ t.Fatal("mirror failure was acknowledged as a successful lock write")
+ }
+ rejected := mirror.wrap(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(412) }))
+ rejectedReply := httptest.NewRecorder()
+ rejected.ServeHTTP(rejectedReply, httptest.NewRequest("PUT", terminateLockPath, strings.NewReader(lock)))
+ select {
+ case <-entered:
+ t.Fatal("rejected PUT was mirrored")
+ default:
+ }
+ if rejectedReply.Code != 412 {
+ t.Fatal(rejectedReply.Code)
+ }
+ })
+ }
+}
+
+func TestHATerminateMirrorFinish(t *testing.T) {
+ for _, fail := range []string{"", "sigterm", "systemctl", "unit-stop", "journalctl", "journal.txt", "all-uploads"} {
+ t.Run("failure="+fail, func(t *testing.T) {
+ var steps []string
+ var events []terminateEvent
+ remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ key := strings.TrimPrefix(r.URL.Path, "/"+terminateWitnessBucket+"/")
+ step := key
+ if strings.HasPrefix(key, "events/") {
+ var event terminateEvent
+ if err := json.NewDecoder(r.Body).Decode(&event); err != nil {
+ t.Error(err)
+ }
+ step = event.Kind
+ events = append(events, event)
+ }
+ steps = append(steps, step)
+ if step == fail || fail == "all-uploads" {
+ w.WriteHeader(http.StatusServiceUnavailable)
+ }
+ }))
+ defer remote.Close()
+ mirror := &terminateMirror{client: s3.NewFromConfig(aws.Config{Region: "eu-west-1", Credentials: credentials.NewStaticCredentialsProvider("x", "x", ""), RetryMaxAttempts: 1}, func(o *s3.Options) {
+ o.BaseEndpoint = aws.String(remote.URL)
+ o.UsePathStyle = true
+ })}
+ mirror.command = func(ctx context.Context, name string, args ...string) ([]byte, error) {
+ steps = append(steps, name)
+ if _, ok := ctx.Deadline(); !ok {
+ t.Error("command has no deadline")
+ }
+ if name == fail {
+ return nil, fmt.Errorf("injected %s failure", name)
+ }
+ if name == "systemctl" {
+ return []byte("Id=carlos-edge.service\nActiveState=inactive\n"), nil
+ }
+ return []byte("2026-11-08T04:00:00+00:00 journal\n-- cursor: test\n"), nil
+ }
+ at := time.Now().UTC()
+ mirror.finish(at)
+ if steps[0] != "sigterm" || events[0].At != at || events[0].Units != "" || events[0].Error != "" {
+ t.Fatalf("first event must be timestamp-only sigterm: %v %+v", steps, events[0])
+ }
+ positions := map[string]int{}
+ for i, step := range steps {
+ if _, ok := positions[step]; !ok {
+ positions[step] = i
+ }
+ }
+ for _, step := range []string{"systemctl", "unit-stop", "journalctl"} {
+ if _, ok := positions[step]; !ok {
+ t.Fatalf("did not attempt %s after failure: %v", step, steps)
+ }
+ }
+ if positions["systemctl"] >= positions["unit-stop"] || positions["unit-stop"] >= positions["journalctl"] {
+ t.Fatalf("wrong shutdown evidence order: %v", steps)
+ }
+ if fail != "" && fail != "all-uploads" {
+ errorStep := map[string]string{"systemctl": "unit-state", "journalctl": "journal", "journal.txt": "journal"}[fail]
+ if errorStep == "" {
+ errorStep = fail
+ }
+ if _, ok := positions[errorStep+"-error"]; !ok {
+ t.Fatalf("failure not reported: %v", steps)
+ }
+ }
+ })
+ }
+}
+
+func TestHATerminateMirrorJournal(t *testing.T) {
+ var keys []string
+ var bodies []string
+ fail := true
+ remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ raw, _ := io.ReadAll(r.Body)
+ keys = append(keys, r.URL.Path)
+ bodies = append(bodies, string(raw))
+ if fail {
+ w.WriteHeader(http.StatusServiceUnavailable)
+ }
+ }))
+ defer remote.Close()
+ mirror := &terminateMirror{client: s3.NewFromConfig(aws.Config{Region: "eu-west-1", Credentials: credentials.NewStaticCredentialsProvider("x", "x", ""), RetryMaxAttempts: 1}, func(o *s3.Options) {
+ o.BaseEndpoint = aws.String(remote.URL)
+ o.UsePathStyle = true
+ })}
+ var calls [][]string
+ mirror.command = func(ctx context.Context, name string, args ...string) ([]byte, error) {
+ calls = append(calls, args)
+ if args[len(args)-1] == "_PID=1" {
+ return []byte("systemd stop job\n-- cursor: manager\n"), nil
+ }
+ return []byte("edge: draining and shutting down\n-- cursor: units\n"), nil
+ }
+ ctx := context.Background()
+ stream := &terminateJournalStream{}
+ if mirror.streamJournal(ctx, stream) == nil || *stream != (terminateJournalStream{}) {
+ t.Fatalf("failed upload advanced journal: %+v", stream)
+ }
+ fail = false
+ if err := mirror.streamJournal(ctx, stream); err != nil {
+ t.Fatal(err)
+ }
+ if stream.seq != 1 || stream.cursors != [2]string{"units", "manager"} || stream.size != len(bodies[1]) {
+ t.Fatalf("wrong progress: %+v", stream)
+ }
+ if err := mirror.streamJournal(ctx, stream); err != nil {
+ t.Fatal(err)
+ }
+ if keys[0] != keys[1] || !strings.HasSuffix(keys[2], "/journal/000001.txt") || strings.Contains(bodies[1], "-- cursor:") || !strings.Contains(bodies[1], "systemd stop job") {
+ t.Fatalf("wrong chunks: %v %v", keys, bodies)
+ }
+ if !strings.Contains(strings.Join(calls[4], " "), "--after-cursor=units") || !strings.Contains(strings.Join(calls[5], " "), "--after-cursor=manager") {
+ t.Fatalf("cursors not resumed: %v", calls)
+ }
+ for _, capped := range []terminateJournalStream{{seq: terminateJournalCountLimit}, {size: terminateJournalTotalLimit}, {size: terminateJournalTotalLimit - 1}} {
+ if err := mirror.streamJournal(ctx, &capped); err == nil {
+ t.Fatal("stream exceeded bound")
+ }
+ }
+ mirror.command = func(context.Context, string, ...string) ([]byte, error) {
+ return bytes.Repeat([]byte("x"), terminateJournalChunkLimit+1), nil
+ }
+ if err := mirror.streamJournal(ctx, &terminateJournalStream{}); err == nil {
+ t.Fatal("oversized chunk accepted")
+ }
+ mirror.command = nil
+ if raw, err := mirror.run(ctx, "head", "-c", "262145", "/dev/zero"); err == nil || len(raw) > terminateJournalChunkLimit {
+ t.Fatalf("real command exceeded bound: size=%d err=%v", len(raw), err)
+ }
+ out := &terminateBoundedOutput{limit: 3}
+ if _, err := out.Write([]byte("four")); err == nil || out.buffer.Len() != 0 {
+ t.Fatal("command output bound not enforced")
+ }
+}
diff --git a/internal/host/plan14_generation_registry_root_linux_test.go b/internal/host/plan14_generation_registry_root_linux_test.go
index 8b0114686..20de50ce6 100644
--- a/internal/host/plan14_generation_registry_root_linux_test.go
+++ b/internal/host/plan14_generation_registry_root_linux_test.go
@@ -5,6 +5,7 @@ package host
import (
"flag"
"fmt"
+ "github.com/carlosframework/platform/internal/cgroup"
"github.com/carlosframework/platform/internal/instanceexec"
"github.com/carlosframework/platform/internal/version"
"os"
@@ -16,6 +17,7 @@ import (
// The test binary must take the same private registry entrypoint as carlos.
func TestMain(m *testing.M) {
+ cgroup.RunShimIfRequested()
// The installed carlos-dbread@ unit runs this binary as
// /opt/carlos/carlos system db-worker (dbreads_rootrunner_linux_test.go).
if len(os.Args) == 3 && os.Args[1] == "system" && os.Args[2] == "db-worker" {
diff --git a/internal/host/startup_largebox_linux_test.go b/internal/host/startup_largebox_linux_test.go
index facd09ab6..5de40268c 100644
--- a/internal/host/startup_largebox_linux_test.go
+++ b/internal/host/startup_largebox_linux_test.go
@@ -481,7 +481,7 @@ func TestRunAgentStartupWiring(t *testing.T) {
if calleeName(call) != "joinAgentShutdown" {
continue
}
- want := []string{"seedCtx", "seedCancel", "seedServer", "cancelStartup", "startupDone", "dutiesDone"}
+ want := []string{"shutdownDeadline", "seedCtx", "seedCancel", "seedServer", "cancelStartup", "startupDone", "dutiesDone"}
if len(call.Args) != len(want) {
t.Fatal("shutdown helper argument count", len(call.Args))
}
diff --git a/internal/host/units/carlos-edge.service b/internal/host/units/carlos-edge.service
index 121ebdd4e..1b2d7a031 100644
--- a/internal/host/units/carlos-edge.service
+++ b/internal/host/units/carlos-edge.service
@@ -9,7 +9,12 @@ Description=carlos edge (TLS terminator, host router, activator, release adoptio
# requirements: an edge that starts without them would start unprotected,
# so it does not start at all.
Requires=data-instances.mount run-carlos-instances.mount run-carlos-logs.mount
-After=network-online.target data-instances.mount run-carlos-instances.mount run-carlos-logs.mount
+# systemd stops units in reverse start order. Keep root control, its socket
+# and D-Bus available until the edge has stopped: their RPCs and reads prove
+# termination before HA leases can be released (region HA T1/DR-4).
+After=network-online.target data-instances.mount run-carlos-instances.mount run-carlos-logs.mount carlos-instance-control.socket carlos-instance-control.service dbus.service
+# Control's start probe needs the edge's cgroup. Let the agent's first
+# request socket-activate control after the edge starts (region HA T1/DR-4).
Wants=network-online.target
[Service]
@@ -22,6 +27,9 @@ ExecStart=/opt/carlos/carlos agent
ExecReload=/bin/kill -HUP $MAINPID
Restart=always
RestartSec=1
+# Allow stop proofs and HA release to finish before systemd's forced kill;
+# this is the process-stop backstop, not a release guarantee (region HA T1/DR-4).
+TimeoutStopSec=120
# --- hardening (ported from lchat-router.service; see Eleven's
# docs/instance-router.md § Hardening) ---
diff --git a/internal/host/units/carlos-instance-control.service b/internal/host/units/carlos-instance-control.service
index f0786113a..e5c385b42 100644
--- a/internal/host/units/carlos-instance-control.service
+++ b/internal/host/units/carlos-instance-control.service
@@ -1,10 +1,11 @@
-# The root instance-control service (isolated-exec design §5). Socket-
-# activated, so it runs only while there is work. Its whole job is
-# systemctl start/stop/set-property on the three instance templates' units
-# and their host slices, on the agent's request, plus running the readiness
-# probe. Every unit name it passes to systemctl is built from a validated
-# host by the platform's own naming; nothing from a request reaches
-# systemctl as a string.
+# The root instance-control service (isolated-exec design §5). The agent
+# socket-activates it after the edge starts, and it stays up through the
+# edge's stop (T1/DR-4 ordering).
+# Its whole job is systemctl start/stop/set-property on the three instance
+# templates' units and their host slices, on the agent's request, plus
+# running the readiness probe. Every unit name it passes to systemctl is
+# built from a validated host by the platform's own naming; nothing from a
+# request reaches systemctl as a string.
#
# Runs as ROOT deliberately, with no new-privileges lockout and no syscall
# filter, for the systemctl child (the same rationale as
@@ -26,9 +27,17 @@
Description=carlos instance control (root: start/stop carlos-instance*@ units for the agent)
Requires=carlos-instance-control.socket data-instances.mount run-carlos-instances.mount run-carlos-logs.mount
After=data-instances.mount run-carlos-instances.mount run-carlos-logs.mount
+# Startup hairpin recovery may revoke or roll back saved rules, so wait for
+# nftables to load them. Ordering alone leaves non-group boxes unaffected.
+After=nftables.service
[Service]
ExecStart=/opt/carlos/carlos instance-control
+# The edge is ordered After= control (T1/DR-4), so a socket-activated start
+# of a dead control queues behind any edge stop job and stalls the agent's
+# shutdown proofs. Restarting on failure keeps control up.
+Restart=on-failure
+RestartSec=1
ProtectSystem=strict
# /run/systemd/system: per-generation runtime drop-ins (zero-downtime
# deploys, plan 2 D1) and escaped .mount units for demo snapshot disks.
diff --git a/internal/host/units_shutdown_test.go b/internal/host/units_shutdown_test.go
new file mode 100644
index 000000000..70b41d59f
--- /dev/null
+++ b/internal/host/units_shutdown_test.go
@@ -0,0 +1,131 @@
+package host
+
+import (
+ _ "embed"
+ "slices"
+ "strings"
+ "testing"
+)
+
+//go:embed units/carlos-edge-group.conf
+var edgeGroupShutdownDropIn string
+
+func TestEdgeShutdownKeepsControlAvailable(t *testing.T) {
+ names, err := unitNames()
+ if err != nil {
+ t.Fatal(err)
+ }
+ names = append(names, "carlos-edge-group.conf")
+ units := make(map[string]map[string][]string)
+ for _, name := range names {
+ props := make(map[string][]string)
+ section := ""
+ body := edgeGroupShutdownDropIn
+ if name != "carlos-edge-group.conf" {
+ body = readUnit(t, name)
+ }
+ for _, line := range strings.Split(body, "\n") {
+ line = strings.TrimSpace(line)
+ if line == "" || strings.HasPrefix(line, "#") {
+ continue
+ }
+ if strings.HasPrefix(line, "[") {
+ section = line
+ continue
+ }
+ key, value, ok := strings.Cut(line, "=")
+ if !ok {
+ continue
+ }
+ key = section + strings.TrimSpace(key)
+ if strings.TrimSpace(value) == "" {
+ delete(props, key)
+ } else {
+ props[key] = append(props[key], strings.Fields(value)...)
+ }
+ }
+ units[name] = props
+ }
+ const edge = "carlos-edge.service"
+ for key, values := range units["carlos-edge-group.conf"] {
+ units[edge][key] = append(units[edge][key], values...)
+ }
+ delete(units, "carlos-edge-group.conf")
+ for key, wants := range map[string][]string{
+ "[Unit]Wants": {"network-online.target"},
+ "[Unit]After": {"carlos-instance-control.service", "carlos-instance-control.socket", "dbus.service", "nftables.service"},
+ } {
+ for _, want := range wants {
+ if !slices.Contains(units[edge][key], want) {
+ t.Errorf("%s %s lacks %s", edge, key, want)
+ }
+ }
+ }
+ if got := units[edge]["[Service]TimeoutStopSec"]; len(got) != 1 || got[0] != "120" {
+ t.Errorf("%s TimeoutStopSec = %v, want 120", edge, got)
+ }
+ const control = "carlos-instance-control.service"
+ if got := units[control]["[Service]Restart"]; len(got) != 1 || got[0] != "on-failure" {
+ t.Errorf("%s Restart = %v, want on-failure", control, got)
+ }
+ if got := units[control]["[Service]RestartSec"]; len(got) != 1 || got[0] != "1" {
+ t.Errorf("%s RestartSec = %v, want 1", control, got)
+ }
+ // The probe at control start needs the edge's cgroup, so the agent
+ // socket-activates control after the edge starts.
+ for _, key := range []string{"[Unit]Wants", "[Unit]Requires"} {
+ if slices.Contains(units[edge][key], control) {
+ t.Errorf("%s must not add %s=%s: control's start probe needs the edge's cgroup", edge, key, control)
+ }
+ }
+ if !slices.Contains(units[control]["[Unit]After"], "nftables.service") {
+ t.Errorf("%s must order startup after nftables.service for hairpin recovery", control)
+ }
+ for _, key := range []string{"[Unit]Wants", "[Unit]Requires"} {
+ if slices.Contains(units[control][key], "nftables.service") {
+ t.Errorf("%s must not add %s=nftables.service on non-group boxes", control, key)
+ }
+ }
+
+ after := make(map[string][]string)
+ // nftables is supplied by the host and orders itself before network-pre.
+ after["network-pre.target"] = append(after["network-pre.target"], "nftables.service")
+ for name, props := range units {
+ after[name] = append(after[name], props["[Unit]After"]...)
+ for _, before := range props["[Unit]Before"] {
+ after[before] = append(after[before], name)
+ }
+ template := strings.HasPrefix(name, "carlos-instance") && strings.Contains(name, "@")
+ if template || name == "carlos-instance-control.service" {
+ if slices.Contains(props["[Unit]Before"], edge) {
+ t.Errorf("%s must not declare Before=%s", name, edge)
+ }
+ }
+ if template {
+ for _, key := range []string{"[Unit]BindsTo", "[Unit]After"} {
+ if !slices.Contains(props[key], edge) {
+ t.Errorf("%s lost %s=%s", name, key, edge)
+ }
+ }
+ }
+ }
+ visited, visiting := make(map[string]bool), make(map[string]bool)
+ var visit func(string, []string)
+ visit = func(name string, path []string) {
+ if visiting[name] {
+ t.Errorf("embedded unit ordering cycle: %s", strings.Join(append(path, name), " -> "))
+ return
+ }
+ if visited[name] {
+ return
+ }
+ visiting[name] = true
+ for _, dependency := range after[name] {
+ visit(dependency, append(path, name))
+ }
+ visiting[name], visited[name] = false, true
+ }
+ for name := range after {
+ visit(name, nil)
+ }
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index bca61cb2b..e036b3fc3 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -120,3 +120,5 @@ plan14-root-reads-claim-countdown.tsv 5b31785441c6a48ddae93e9f3c0f8962f7983b55d8
plan14-root-reads-region-ha-dr2.tsv 7247af7f4de84593d83c6f60c0147d0a04836146197dd60c2ed2bf78919cad22
plan14-root-reads-dr1-left-link.tsv 160744b3062d0ab9a0cb3c7be3a391ae38cf89ffe410ddd5d179e0c3cb509b66
plan14-root-reads-claim-source.tsv 9cdff432a5de2ffeaa147fdafd6a486c61c27a0c38f77466bddc86b149332c7d
+plan14-root-reads-region-ha-graceful-terminate-t1.tsv 3273ecae03559a8d450027f4cdf4dff24af9c54705231bc4f7c77b72582b517c
+plan14-root-reads-region-ha-graceful-terminate-t2.tsv 687cf7744aecdf8a238dcdb80562b0ef191b3e247c28851de44c01866dbeca13
diff --git a/internal/provision/testdata/plan14-root-reads-region-ha-graceful-terminate-t1.tsv b/internal/provision/testdata/plan14-root-reads-region-ha-graceful-terminate-t1.tsv
new file mode 100644
index 000000000..2bcb0baac
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-region-ha-graceful-terminate-t1.tsv
@@ -0,0 +1,7 @@
+# Census overlay region-ha-graceful-terminate-t1, written by census-propose (#369). census-ruling-region-ha-graceful-terminate-t1, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-region-ha-graceful-terminate-t1.md.
+# 2 body, 0 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@legacy 1a917d3b2b5f31cff4133f996d9ce0fc60c27fd9c41cda21d21253b0c7df2de6 internal/host/units/carlos-edge.service external legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-region-ha-graceful-terminate-t1;basis=Region HA T1/DR-4 fix round 2: keep edge after control service, socket and D-Bus with TimeoutStopSec=120, but do not Want or Require control: its start probe needs the edge cgroup, so the agent socket-activates it after edge starts. Static ordering only; no new root read, input, command, path or capability. Instance templates unchanged. file:external@0 6389ef660a0c78e8be24008dc470b2b067d17c6c09740304961ad72635b122cd
+internal/host/units/carlos-edge.service external legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-region-ha-graceful-terminate-t1;basis=Region HA T1/DR-4 fix round 2: keep edge after control service, socket and D-Bus with TimeoutStopSec=120, but do not Want or Require control: its start probe needs the edge cgroup, so the agent socket-activates it after edge starts. Static ordering only; no new root read, input, command, path or capability. Instance templates unchanged. file:external@0 6389ef660a0c78e8be24008dc470b2b067d17c6c09740304961ad72635b122cd
+internal/host/units/carlos-instance-control.service external authority B3,C,D,E1,J4 root-input;kept=B3,C,D,E1;scope=protected-decision-only;rev3=census-ruling-agent-start-demo-3;basis=Correct the runtime-write comment to include escaped demo snapshot .mount units alongside per-generation drop-ins; service directives are unchanged.;rev3=census-ruling-region-ha-graceful-terminate-t1;basis=Region HA T1/DR-4 final fix: retain After=nftables.service without Wants or Requires; add Restart=on-failure and RestartSec=1 so a crashed control restarts before a later edge stop can block socket activation and shutdown proofs; rewrap the header and explain this ordering. Same ExecStart and protections; no new root read, input, path, command or capability. file:external@0 c4e5717cbd5356d12423a300a6f19a03c05c9ddf1bbeb74351670f532e72177c
+@coverage internal/activator 98723d85739969db615d6b0f589fa04a31e62dc80d3b64d3b1094b5edf3eeade
+@coverage internal/host/units 770d1e5d7aba033d37d8be7519f75fd735f92859aa4370c7fb837c07eda42fec
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