carlos / platform Public

region HA: page and alarm on suspect holders after 10 minutes (T3)

Spec §20. The activator tracks hosts refused for a lease whose owner is
not confirmed terminated (visitor refusals and refused same-box
recoveries), pages once per owner per hour after 10 minutes, and logs
ha_suspect_holder. Group members publish SuspectHolderHosts in their
existing metric batch; a group-only CloudWatch alarm group_suspect_holder
notifies the group alerts topic (folded into G0: 1/2/0). Runbook section
added. Opus task reviews clean; census region-ha-g2-t3 approved (#280).

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

Squashed from region-ha-g2-prep into main.
claude agent, operated by paul@keymail.dev d65513387104d661af639dd51cf65244e2fcd348 parent 98baa65
19 files changed, +1,350 −6
  • docs/region-ha-runbook.md +6 −0
  • docs/superpowers/notes/census-proposal-region-ha-g2-t3.md +27 −0
  • docs/superpowers/plans/2026-11-05-region-ha-g2-prep.md +528 −0
  • infra/modules/region-host/group_alarms.tf +18 −0
  • infra/modules/region-host/tests/group_alarms.tftest.hcl +10 −2
  • internal/activator/backend_exec.go +3 −2
  • internal/activator/hasamebox.go +6 −1
  • internal/activator/hasuspectholder.go +135 −0
  • internal/activator/hasuspectholder_test.go +362 −0
  • internal/activator/hatakeover.go +4 −0
  • internal/groupadmission/observation.go +1 −0
  • internal/host/agent.go +3 −0
  • internal/host/group_metrics.go +19 −0
  • internal/host/group_metrics_test.go +53 −1
  • internal/host/suspects_test.go +144 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-region-ha-g2-t3.tsv +16 −0
  • scripts/check-region-group-plan.py +1 −0
  • scripts/check_region_group_plan_test.py +13 −0

CI failed — run details

diff --git a/docs/region-ha-runbook.md b/docs/region-ha-runbook.md
index b31c49cff..aa4b889b9 100644
--- a/docs/region-ha-runbook.md
+++ b/docs/region-ha-runbook.md
@@ -71,3 +71,9 @@ A region-host role with SSM parameter scoping (`scope_ssm_parameter_reads`) can
Copy the value with an operator credential instead of the box role. This needs no change to the role.
If the box role itself must read it, widen `ssm_parameter_arn` to include that one parameter, or turn `scope_ssm_parameter_reads` off, through the deployment's infrastructure root and with scoped approval. Copy the value, then put the setting back, and check with an IAM policy simulation that the read is denied again.
+
+## A box is holding hosts it does not serve (ha_suspect_holder)
+
+1. Confirm in EC2 that the instance is terminated or is still running.
+2. If it is a group member, terminate it in its group with `--no-should-decrement-desired-capacity`.
+3. Never terminate a fixed box without a separate decision. Check its storage access and its agent first.
diff --git a/docs/superpowers/notes/census-proposal-region-ha-g2-t3.md b/docs/superpowers/notes/census-proposal-region-ha-g2-t3.md
new file mode 100644
index 000000000..8365df4d6
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-region-ha-g2-t3.md
@@ -0,0 +1,27 @@
+# Census approval: region-ha-g2-t3
+
+Ruling `census-ruling-region-ha-g2-t3`. 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 |
+|---|---|---|---|
+| `infra/modules/region-host/group_alarms.tf` `external` | body | unchanged (1) | T3b: add one group-mode SuspectHolderHosts Maximum alarm, 60 seconds, 1 of 1, threshold greater than zero, missing data notBreaching, existing regional SNS actions and ASG dimension. No replacement, scale, IAM, storage or root runtime authority. |
+| `infra/modules/region-host/tests/group_alarms.tftest.hcl` `external` | body | unchanged (1) | T3b: pin fixed-mode zero count, group shape, regional SNS actions and non-breaching missing data for the new alarm; mock-provider test only, no root runtime read. |
+| `internal/host/agent.go` `runAgent` | body | unchanged (9) | 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. |
+| `internal/activator/hasamebox.go` `ExecBackend.sameBoxEmpty` | sites | +registry:Host | T3a: record refused same-box recovery using the existing route Host and lease.CurrentSelf instance id; no new external read; +registry:Host for the tracker call; the emptiness proof and S3-free refusal stay unchanged; pages through the existing sink. |
+| `internal/activator/hatakeover.go` `ExecBackend.reportTakeover` | sites | +registry:Host ×2 | T3a: track visitor refusals and clear a host after confirmed termination; no new external read; reads only the existing route Host (+registry:Host x2) and the classified owner instance id; pages through the existing sink; departure-finalize keeps its existing immediate hourly page. |
+
+Envelopes re-pinned: `infra/modules/region-host`, `infra/modules/region-host/tests`, `internal/activator`, `internal/groupadmission`, `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:
+
+- `infra/modules/region-host/group_alarms.tf` `external`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add default-off termination queue age alarm, using existing queue name and regional SNS topic; no IAM, queue, consumer or instance changes. Copy sweep 1: apply approved variable and alarm descriptions verbatim; no resource, threshold, action or read changes.;rev3=census-ruling-region-ha-p3b;basis=Add group capacity, memory, clock, missing-clock and launch-failure notifications; preserve account-owner SNS rights and scope CloudWatch/EventBridge publishers by source account/ARN. Operator-applied Terraform, no box file read; notifications grant no replacement authority.
+- `infra/modules/region-host/tests/group_alarms.tftest.hcl` `external`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add plan-only mock queue alarm defaults, thresholds, missing-data and regional notification assertions.;rev3=census-ruling-region-ha-p3b;basis=Mock group metric producers, alarm dimensions/windows/missing data and complete scoped SNS policy; retain fixed alarm expectations. Test-only Terraform input, no root runtime read.;rev3=census-ruling-region-ha-p3b1-fixes;basis=Supply the real-shape group queue URL in the group alarm mock so the launch URL equality guard is exercised. Mock plans only; no runtime reads.
+- `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.
+- `internal/activator/hasamebox.go` `ExecBackend.sameBoxEmpty`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: the closure lease.AcquireHA calls as the same-box proof for taking this box's own expired HA lock: true only when sameBoxProven holds, else logs an ALERT at most once a minute and answers false; +registry:Host x2, +whole:Route
+- `internal/activator/hatakeover.go` `ExecBackend.reportTakeover`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=Final fix P2-1: report all refused proof results through the per-host alarm and distinguish visitor from departure-finalize. No reads or authority.;rev3=census-ruling-region-ha-followups;basis=Page only departure-finalize proof refusals through the injected host sink, at warning level and once per host per hour. Send on a detached five-second context and log send failures. Read the existing route Host for page throttling, body and failure logging; no new storage read or takeover authority.
+
+Seal: `05f08edeb46837a18f1abca302ad21d8c7782edef8af00cc4082f5ed4ea35ad6` → `6462853d58331c23d0b2f9ee3b52ccec5198b061d864cc97ba6e7b931017f02a`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-region-ha-g2-t3.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/plans/2026-11-05-region-ha-g2-prep.md b/docs/superpowers/plans/2026-11-05-region-ha-g2-prep.md
new file mode 100644
index 000000000..c8aebd189
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-05-region-ha-g2-prep.md
@@ -0,0 +1,528 @@
+# Region HA G2 prep: build plan
+
+Controller plan for the G2/G3 prep build (branch `region-ha-g2-prep`, from
+origin/main e129f535). Sources: `~/.cache/region-ha-next/G2-CARD.md`
+(blockers T1-T10), `G3-CARD.md`, the addendum on branch
+`region-ha-g2-addendum` (762ae83c), spec
+`docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md`
+(rev 6.2: §9.7 clock, §13 precondition 3, §20 suspect holders).
+
+Rulings that bind this plan (Paul via agent manager 8a3d302, 2026-11-05):
+- G2 acceptance = the four I4 drills plus the riding rows; drain, role and
+ readiness carry to G3/P6/G5.
+- T8 first, merged before the v0.34.6 cut. T3 aims for the same cut.
+- G3 code only: chrony in host-init and the group boot template; a diagnostic
+ readiness check for §13 precondition 3 over a named pool's hosts.
+- Operator tools T1, T2, T4, T6 as reviewed, dev-only scripts that touch
+ nothing at build time.
+
+## Global Constraints
+
+- Go: run only touched packages' tests with `-run`. Never `go test ./...`.
+ Leave GOCACHE at its default. Socket-binding packages (activator, edge,
+ host) need `TMPDIR=/tmp/g` (mkdir it) and run outside the sandbox.
+- The build must still cross-compile for darwin and windows
+ (`GOOS=darwin go build ./...` and `GOOS=windows go build ./...` on the
+ packages touched); linux-only code goes behind build tags.
+- No cloud reads or writes, no AWS calls, no releases, applies or drills at
+ build time. Scripts are written and tested offline only.
+- No tenant or customer names in code, docs or tests: use neutral examples.
+- User-facing strings (log lines an operator reads, page subjects, CLI
+ output) follow house voice: no em dashes; full stops.
+- Commit subjects under 80 characters.
+
+## Task 1: T8, names-2 release pin for fixed-box updates
+
+**Why.** `internal/host/systemleg.go:329-362`: while any group (`g-`) edges
+namespace exists, a fixed box's automatic system update proceeds only when the
+target artifact's SHA-256 is in `firstNames2Release.Digests[platform]` and the
+version is at or above `FirstRelease`. `firstNames2Release` is empty today, so
+fixed boxes refuse EVERY update while a group lives. A digest list alone cannot
+name future releases, so a box would still refuse every later release.
+
+**Ruling (8a3d302 for Paul, 2026-11-05): digests plus release tags.**
+
+1. Pin v0.34.5 as the first names-2 release with its verified digests:
+
+ ```go
+ var firstNames2Release = namesReleasePin{
+ FirstRelease: "v0.34.5",
+ Digests: map[string][]string{
+ "linux-arm64": {"310ab5b97a52fa0d4c033393c3d2649adeda2c53e842fff81cd0c7ef57e16cd4"},
+ "linux-amd64": {"400d62739efe8994f93d0ca96dc3a6d0d499e6f4ea53db64069177dea8360176"},
+ },
+ }
+ ```
+
+ These match the public release's SHA256SUMS.txt
+ (github.com/carlosframework/releases v0.34.5), the release build's local
+ dist, and (linux-arm64) the dev stable pointer. Keep the comment above it
+ true: say what was pinned, from where, and how a later local build is
+ added.
+
+2. ALSO accept a target whose signed pointer release says it came from the
+ console's public-release ingest: `SystemRelease.Source == "release:" +
+ SystemRelease.Version`, where Version matches `^v[0-9]+\.[0-9]+\.[0-9]+$`
+ exactly (reuse `publicrelease.TagRe` if the import is clean, otherwise an
+ equal local regexp) AND parses at or above `FirstRelease`. The console sets
+ that Source only after it fetched the public release and checked its
+ checksums (`internal/console/apisystemupdate.go:536-560`); the pointer is
+ ed25519-signed. Verified 2026-11-05 on the real dev and flagship
+ `control/system/router/stable.json`: every current and history release
+ has `source: "release:<version>"` and no `release_tag`.
+3. Refusals that must hold: a pre-release or otherwise unparseable version
+ (`v0.35.0-rc1`, `0.35.0`, `v0.35`) never passes by Source; a Source of
+ `"file"` (local upload), empty, or a mismatched tag (`release:v0.35.0`
+ on Version `v0.36.0`) needs a pinned digest; a release-sourced version
+ below `FirstRelease` refuses; an empty `FirstRelease` refuses everything
+ (unchanged). The freshness, `groupObserved` and `hasGroup` rules above
+ the version check stay exactly as they are.
+4. Carry the Source into `systemPending` at observe
+ (`systemleg.go:161`) and in the attended group prepare path
+ (`internal/host/group_maintenance_prepare.go:183`), so both callers see
+ the same evidence. Do not change any other caller.
+5. Tests in `internal/host/systemleg_test.go` (extend
+ `TestSystemLegGroupReaderRollback` or add `TestSystemLegNames2ReleasePin`),
+ driving the real observe → tick path with a signed pointer as the
+ existing tests do:
+ - the production `firstNames2Release` value: v0.34.5 linux-arm64 digest
+ passes with a live group namespace;
+ - a release-sourced v0.34.6 with an unknown digest passes;
+ - a release-sourced v0.34.4 refuses; `file` source v0.34.9 with an
+ unknown digest refuses; `file` source with the pinned digest passes;
+ mismatched Source tag refuses; pre-release and unparseable versions
+ refuse by Source;
+ - refusals mean zero artifact fetches, request writes and marker touches
+ (use the existing counters).
+ Watch each new refusal test fail first against a mutation (for example,
+ drop the Source tag equality) and record it in the report.
+6. Run: `TMPDIR=/tmp/g go test ./internal/host -run 'TestSystemLeg|TestGroupReadersReady|TestGroupMaintenance' -count=1`
+ plus `GOOS=darwin go build ./internal/host/ ./cmd/...` and the same for
+ windows. If `internal/host` census tests exist for `systemleg.go`
+ (`git grep -n systemleg internal/provision/*census*`), run them too and
+ report whether the root-read census changed.
+
+## Task 2: T3a, suspect-holder tracking and page (spec §20)
+
+**Controller ruling (2026-11-05):** page visitor refusals and refused same-box recoveries only; refusals that never reach a proof (legacy lock, owner without an instance id) are reported by Task 5, not paged. Final copy for T3-L1..T3-P4 and T3-R1 is in `.superpowers/sdd/2026-11-05-region-ha-g2-prep/copy-t3.md` once the copy pass lands; until then use the draft text below.
+
+**Why.** Spec §20 says: "Suspect holders: any host refused for over 10 minutes for a lease whose owner is not confirmed dead, including a refused same-box recovery (§9.6). The runbook says terminate that box in its group (§9.5)." §9.5 says the alarm "fires after 10 minutes".
+
+What exists today:
+- **Visitor refusals.** A refused takeover is logged at most once a minute per host. `reportTakeover` calls `takeover.alarm` (`internal/activator/hatakeover.go:41-65`, `:87-102`).
+- **Finalizer refusals.** Only `departure-finalize` refusals page, hourly per host (`hatakeover.go:52-64`, `claimPage` at `:108-119`).
+- **Same-box refusals.** These log only (`internal/activator/hasamebox.go:68-77`, `alarm` at `:152-166`).
+- **Duration.** Nothing measures how long a host has been refused.
+
+Where refusals happen:
+- **Visitor path.** Every refused HA acquire of another box's expired lock reaches `reportTakeover`. This happens either through the `ownerTerminated` wrapper (`hatakeover.go:30-39`) or through `TerminationProofAdapter.Observe`, which is deferred so it always runs (`internal/lease/termination_proof.go:39-44`). Both are wired at `internal/activator/hawake.go:384-391` and `internal/activator/haadopt.go:300-304`.
+- **Same-box path.** A refused same-box recovery reaches `sameBox.alarm` (`hasamebox.go:71`).
+- **Clearing.** Every successful acquire passes `markAcquiredHere` (`internal/activator/backend_exec.go:825-827`).
+
+Visitor and duty wakes already pay one lock GET each, so tracking rides existing reads and adds no S3, EC2 or SQS request.
+
+**What to build.** New file `internal/activator/hasuspectholder.go`. Do not reuse the name `hasuspect`: `hasuspect_test.go` is the forward-dial "holder suspect" concept, which is a different thing.
+
+1. Add `suspectHolders` state on `ExecBackend`, beside `takeover` and `sameBox` (`backend_exec.go:398-401`). Keep it per host: first refusal, last refusal and owner instance id. Add a `now func() time.Time` test seam (nil means `time.Now`).
+2. Add `note(host, ownerIID string, sameBox bool, now)`:
+ - start the clock on the first refusal;
+ - restart it if the owner instance id changes, or if no refusal was seen for 30 minutes (2 × `lease.LeaseTTL`);
+ - when `now - first >= 10*time.Minute`, log once per crossing and try to page.
+3. Paging: at most once per owner instance per hour per box. Key the page on the owner instance id (self for same-box), not on the host, because the runbook action is per box. The body lists up to 10 hosts refused for that owner, sorted, then "and N more". Send through `b.Page` with `alerting.LevelWarning`, on a fresh 5 s context, as `hatakeover.go:59-63` does. If `b.Page` is nil, log only.
+4. Call `note` from:
+ - `reportTakeover`'s refused branch (`hatakeover.go:47`), **only when `cause == "visitor"`**. Finalizer refusals already page at `:52`; do not page them twice;
+ - `sameBoxEmpty`'s refusal branch (`hasamebox.go:70-72`), with the owner being this box's own instance id from `lease.CurrentSelf().IID`.
+5. Clear a host's entry:
+ - in `markAcquiredHere` (`hasamebox.go:170`), on any successful acquire;
+ - in `reportTakeover` when `gone && err == nil`.
+6. Export `func (b *ExecBackend) SuspectHolderHosts(now time.Time) int`. It counts hosts whose first refusal is at least 10 minutes old and whose last refusal is under 5 minutes old. Task 3 reads it. It must be safe to call concurrently and must hold no lock across I/O.
+7. Wiring: `b.Page` is set only by `armHADepartures` (`internal/host/hadepartures_wiring.go:169`). Also set `eb.Page = PageOperator` in `runAgent` beside `eb.OwnerTerminated` (`internal/host/agent.go:547-549`), so a box whose departure controller failed to arm still pages. Finalizer paging does not change, because finalizers only exist when departures are armed.
+8. Runbook: add a section "A box is holding hosts it does not serve (ha_suspect_holder)" to `docs/region-ha-runbook.md`, with the steps for a group member and for a fixed box (copy below).
+
+**Refusals that must hold.**
+- No page before 10 minutes of refusals, and none for a host whose acquire succeeded in between.
+- No page for `departure-finalize` refusals: they keep their existing immediate hourly page.
+- No new S3, EC2 or SQS call anywhere in the change. `sameBoxEmpty` stays S3-free (`hasamebox.go:66-67`).
+- The tracker never changes a decision. Lock writes on refused wakes stay zero (`TestTakeoverDescribeFailureKeepsHostDown` asserts `lockWrites == 0`).
+- The existing log lines at `hatakeover.go:100-101` and `hasamebox.go:165` stay byte-identical. Grep-based tooling reads them.
+- Pages are never sent on a context the scan may already have spent.
+
+**User-facing strings (one copy pass, house voice: no em dashes, full stops).**
+
+| id | where | text |
+|---|---|---|
+| T3-L1 | log, first crossing per host | `activator: ALERT %s: the host has been refused for over 10 minutes. Its lease belongs to instance %s, which is not confirmed terminated. (ha_suspect_holder)` |
+| T3-L2 | log, same box | `activator: ALERT %s: the host has been refused for over 10 minutes. This box could not prove its earlier processes for it have stopped. (ha_suspect_holder_same_box)` |
+| T3-P1 | page subject | `Instance %s is holding hosts it does not serve` |
+| T3-P2 | page body | `Instance %s let its leases expire and is not confirmed terminated. These hosts have been down for over 10 minutes: %s. If the instance is in an Auto Scaling group, terminate it in its group. The hosts then move to a surviving box. If it is a fixed box, check its storage access and its agent first. This page repeats every hour while the hosts stay down. (ha_suspect_holder)` |
+| T3-P3 | page subject, same box | `Box %s cannot recover hosts after a restart` |
+| T3-P4 | page body, same box | `This box could not prove that its earlier processes for these hosts have stopped: %s. No other box may take them, so they have been down for over 10 minutes. If the box is in an Auto Scaling group, terminate it in its group. If it is a fixed box, check the agent's startup sweep and cgroup delegation. This page repeats every hour while the hosts stay down. (ha_suspect_holder_same_box)` |
+| T3-R1 | runbook heading and body | heading as in step 8, plus a three-step body: confirm in EC2, terminate a group member with `--no-should-decrement-desired-capacity`, never terminate a fixed box without a separate decision. |
+
+**Tests.** New file `internal/activator/hasuspectholder_test.go`, driving the production `Acquire` through `takeoverBackend` (`hatakeover_test.go:51-63`) with a `terminatedOracle` that answers "not terminated", and a fake clock on the tracker:
+- 9m59s of refusals: zero pages. 10m: exactly one page, whose subject names the owner instance. Further refusals within the hour: no page. At +1h: one more page.
+- Two hosts with the same owner: one page listing both. A different owner: a separate page.
+- The oracle flips to terminated and the acquire succeeds: the entry is cleared. A later refusal for a new owner starts again at zero, with no page before 10 minutes.
+- `cause == "departure-finalize"` (context `adoptionCauseKey{}`): no suspect page. `TestTakeoverPageHourlyPerHost` and `TestTakeoverPageSurvivesSpentScanContext` (`hatakeover_page_test.go`) are unchanged and still pass.
+- Same box: drive `sameBoxEmpty` refusals (the `hasamebox_test.go:41` setup) to 10 minutes. Expect one T3-P3 page.
+- `SuspectHolderHosts`: 0 before 10 minutes; 1 after; 0 again 5 minutes after the last refusal.
+- `lockWrites == 0` throughout. The page receives a context with a deadline.
+- A concurrency test: 20 goroutines refusing the same host at the crossing produce one page (the pattern of `hatakeover_page_test.go:13-38`).
+
+Failing first: run the suite against two mutations and record both in the report:
+- remove the `>= 10*time.Minute` check: the 9m59s test must fail;
+- remove the clear in `markAcquiredHere`: the recovery test must fail.
+
+**Run.**
+```
+mkdir -p /tmp/g
+TMPDIR=/tmp/g go test ./internal/activator -run 'TestSuspectHolder|TestTakeover|TestSameBox|TestNoTakeover|TestAcquireMarks|TestRestartedAgent|TestAbandonedAgent' -count=1
+TMPDIR=/tmp/g go test ./internal/host -run 'TestArmHADepartures|TestAgent' -count=1
+GOOS=darwin go build ./internal/activator/ ./internal/host/ ./cmd/...
+GOOS=windows go build ./internal/activator/ ./internal/host/ ./cmd/...
+go test ./internal/provision -run 'TestPlan14RootReadCensus$' -count=1
+```
+**Census: touched.** Expect `ExecBackend.reportTakeover` and `ExecBackend.sameBoxEmpty` sites and body (+registry:Host). Expect the `runAgent` body, and envelope re-pins for `internal/activator` and `internal/host`. Run `make census-card`, write a CLAIMS file ("no new read; reads only the existing route Host and the classified owner instance id; pages through the existing sink"), then `make census-propose NAME=region-ha-g2-t3a CLAIMS=<file>`. An Astra reviewer approves on #280.
+
+---
+
+## Task 3: T3b, the suspect-holder metric and group alarm
+
+**Ruling (8a3d302 for Paul, 2026-11-05):** fold the alarm into G0. Expected G0 counts are now 1 to add, 2 to change, 0 to destroy; the gate allow-list gains the alarm (this task). The G2 card is already updated.
+
+**Why.** The Task 2 page goes through `PageOperator`, which uses `alerting.Page` (`internal/host/alertsink.go:137-139`, `internal/alerting/alerting.go:191-196`). Group members have no sink:
+- `group-init.sh.tftpl` writes no `CARLOS_ALERT_SNS_TOPIC_ARN` or `CARLOS_ALERT_WEBHOOK`;
+- `group_iam.tf` grants no `sns:Publish`;
+- so `Sinks.Page` logs "no sink configured" and returns nil (`alerting.go:118-123`).
+
+In G2 the fixed boxes withdraw `hapair` (card G1.3), so only members see the refusals. A page from Task 2 alone reaches nobody.
+
+The group's established path is a datum in the existing one-per-minute `PutMetricData` batch, plus a CloudWatch alarm to the group topic. Examples are the clock samples (`internal/host/group_metrics.go:159-182`, appended at `internal/host/memwatch.go:157-165`) and the `group_clock` alarm (`infra/modules/region-host/group_alarms.tf:92-108`). This adds no API call. It adds one custom series (about $0.30 a month) and one alarm ($0.10 a month).
+
+**What to build.**
+1. Add `SuspectHolderHosts int` to `groupadmission.Observation` (`internal/groupadmission/observation.go`). Fill it in `admissionMetrics.observe` (`group_metrics.go:50-60`) from a new `suspects func(time.Time) int` field. Nil means 0. Wire it in `memwatch.go:128` from the agent's `*activator.ExecBackend` (Task 2's `SuspectHolderHosts`) through a package-level `atomic.Pointer` set in `runAgent`. This follows the `processAlertCounters` seam pattern (`alertsink.go:69-72`).
+2. In `groupMetricData` (`group_metrics.go:159`), append `datum("SuspectHolderHosts", n, Count, dims)` with the group dimension only. Do not change the fixed-box `admissionMetricData` (`group_metrics.go:63-74`): fixed boxes page through their own sinks.
+3. Add the alarm `aws_cloudwatch_metric_alarm.group_suspect_holder` in `group_alarms.tf`:
+ - count `var.mode == "group" ? 1 : 0`;
+ - `Carlos/Host`, `SuspectHolderHosts`, `Maximum`, period 60, 1 of 1, threshold 0, `GreaterThanThreshold`;
+ - **`treat_missing_data = "notBreaching"`**;
+ - actions `local.group_alarm_actions` (`:31`);
+ - dimensions `AutoScalingGroupName`.
+4. Add `('aws_cloudwatch_metric_alarm', 'group_suspect_holder')` to `GROUP_DISPOSABLE` in `scripts/check-region-group-plan.py:47-66`.
+
+**Refusals that must hold.**
+- Existing datums stay byte-identical, including the InstanceId-only memory and PSI datums. The existing pins in `group_metrics_test.go` stay green.
+- Switch-off and flagship boxes publish exactly the same `PutMetricData` input as before.
+- Missing data never alarms (members of an older release).
+- No second metrics loop and no per-box S3 object.
+- A gate plan naming any other new resource still refuses.
+
+**User-facing string.**
+
+| id | where | text |
+|---|---|---|
+| T3-A1 | `alarm_description` | `A group member has refused a host for over 10 minutes because its lease belongs to an instance that is not confirmed terminated. Read the members' ha_suspect_holder lines, then terminate that instance in its group.` |
+
+**Tests.**
+- `internal/host/group_metrics_test.go`: a group observation with `SuspectHolderHosts = 2` emits exactly one extra datum (name, unit, group dimension, value 2). A fixed admitted box's datums are unchanged. Nil `suspects` gives 0.
+- `infra/modules/region-host/tests/group_alarms.tftest.hcl`:
+ - extend the count-zero condition at `:65`;
+ - extend the action and missing-data check at `:219` with an explicit `notBreaching` case for the new alarm;
+ - extend the shape check at `:231-235`.
+- `scripts/check_region_group_plan_test.py`: a cleanup manifest naming `group_suspect_holder` inside a proven group module passes. One naming an unknown alarm still refuses.
+
+Failing first:
+- set `treat_missing_data = "breaching"`: the tftest must fail;
+- drop the datum: the Go test must fail.
+
+**Run.**
+```
+TMPDIR=/tmp/g go test ./internal/host -run 'TestGroupMetric|TestAdmission|TestMemwatch' -count=1
+go test ./internal/groupadmission -count=1
+(cd infra/modules/region-host && tofu init -backend=false && tofu test -filter=tests/group_alarms.tftest.hcl)
+python3 -m unittest scripts/check_region_group_plan_test.py scripts/group_alarm_plan_test.py
+GOOS=darwin go build ./internal/host/ ./cmd/... && GOOS=windows go build ./internal/host/ ./cmd/...
+```
+No applies. `tofu test` uses the mock providers already in those files. **Census: touched.** `infra/` is in scope whole-file, as are `internal/host` and `internal/groupadmission`. Use NAME `region-ha-g2-t3b`.
+
+**Controller note.** The alarm only exists after a targeted apply. If ruling 1 folds it into G0, update the card's expected counts to **1 to add, 2 to change, 0 to destroy**.
+
+---
+
+## Task 4: Chrony on fixed boxes (spec §9.7, G3 decision 5)
+
+**Ruling (8a3d302 for Paul, 2026-11-05):** converge script plus a written host-init diff for both infra repos (new boxes only). Never re-run user_data on a live box.
+
+**Why.** §9.7: "chrony (Amazon Time Sync) is required on every box ... each box publishes its chrony offset, and an alarm fires above 1 s".
+
+**Group boxes are already done.** No code change is needed for them:
+- `group-init.sh.tftpl:99` installs `chrony`;
+- `:151-170` writes `server 169.254.169.123 prefer iburst minpoll 4 maxpoll 4` to `/etc/chrony/conf.d/carlos-group.conf`, enables and restarts `chrony.service`, waits for a `^*`/`^+` source on 169.254.169.123, and runs `chronyc waitsync 20 2`;
+- this is pinned by `internal/host/group_boot_test.go:111`, `:221-222`, `:316` and `scripts/region_group_ssm_boot_test.py:18`.
+
+**The publisher exists.** It runs `/usr/bin/chronyc -c tracking` with a 4 KiB limit and a strict chrony 4.4 parse (`internal/host/group_metrics.go:76-145`), only where `CARLOS_GROUP_ADMISSION=1` (`:26-28`). The edge unit allows `AF_INET` (`internal/host/units/carlos-edge.service:51`), so UDP 127.0.0.1:323 works as `User=carlos` (P3 plan, P3-8).
+
+**Fixed boxes have no chrony.** Their first-boot script is the consumer's `var.user_data` (`infra/modules/region-host/main.tf:566-567`), kept in other repos: platform-infrastructure `dev/host-init.sh` and `.tftpl`, which install only `unattended-upgrades curl awscli` and zram, and the flagship carloku-infrastructure root. user_data never re-runs on a live box. On flagship a user_data diff stops and starts the box (G3 card, standing hazards). **So this repo cannot deliver "chrony in host-init". That is a capability cut.** What it can deliver is a reviewed root converge script that does exactly what the group template does, run by SSM on a named fixed box in an attended window.
+
+**What to build.**
+1. `scripts/region-ha-g3/chrony-fixed-box.sh` (bash, root, idempotent):
+ - refuse unless uid is 0 and `/etc/carlos` exists;
+ - `apt-get -y -q install chrony` with `NEEDRESTART_MODE=l` (this removes systemd-timesyncd through Debian's time-daemon conflict; print both packages' states before and after);
+ - write the same one-line conf to `/etc/chrony/conf.d/carlos-fixed.conf` through a staging file and `install -o root -g root -m 0644`;
+ - `systemctl enable chrony.service`, `systemctl restart chrony.service`;
+ - the same 20-try source wait and `chronyc waitsync 20 2`;
+ - then the sandbox witness: `systemd-run --wait --pipe --quiet -p User=carlos -p NoNewPrivileges=yes -p ProtectSystem=strict -p RestrictAddressFamilies='AF_INET AF_INET6 AF_UNIX' -p SystemCallFilter=@system-service /usr/bin/chronyc -c tracking`, printing its CSV.
+ It never restarts `carlos-edge`, never edits `host.env` and never reboots.
+2. Add a `--check` mode that reads only (package state, conf, sources, sandbox witness) and changes nothing.
+3. Runbook: add "Install chrony on a fixed box" to `docs/region-ha-runbook.md`, saying when to run it (before G3 step 4, G3 card) and what passing output looks like.
+4. Controller hand-off, written in the task report and **not built here**: the matching host-init diff for platform-infrastructure `dev/host-init.sh` and `.tftpl`, for new boxes only, with "do not apply to running boxes".
+
+**Refusals that must hold.**
+- Not root, or no `/etc/carlos`: exit non-zero before any change.
+- A conf path that is a symlink: refuse.
+- No source within 20 s: exit non-zero and say so. Leave chrony installed, which is safe, and print the rollback (`apt-get install systemd-timesyncd`).
+- The script contains no `systemctl restart carlos`, `reboot`, `kill`, or any host.env write. A test greps for these.
+
+**User-facing strings.** These are the script's output lines, kept in a list at the top of the script for one copy pass: pass, the three failure lines and the rollback hint.
+
+**Tests (offline).** `scripts/region_ha_g3_chrony_test.py` (unittest) runs the script under `bash` with a temporary `PATH` of shims for `apt-get`, `systemctl`, `chronyc`, `systemd-run`, `install` and `id`, which record their argv:
+- the happy path calls the exact sequence in order;
+- `--check` calls only read commands;
+- a non-root `id` refuses before any shim;
+- a never-synchronising `chronyc` exits non-zero after 20 tries with no further steps;
+- the forbidden-command grep;
+- the conf line equals the one in `group-init.sh.tftpl` (the test reads the template).
+
+Failing first: change the conf line in the script; the template-equality test must fail.
+
+**Run.**
+```
+bash -n scripts/region-ha-g3/chrony-fixed-box.sh
+python3 -m unittest scripts/region_ha_g3_chrony_test.py
+TMPDIR=/tmp/g go test ./internal/host -run 'TestGroupBoot|TestGroupMetric' -count=1
+```
+shellcheck is not installed here. Say so in the report. **Census:** `scripts/` is out of scope. `docs/region-ha-runbook.md` is Markdown and outside `infra/`, so it is not in scope.
+
+---
+
+## Task 5: §13 precondition 3, a read-only readiness check over a named pool
+
+**Controller rulings (2026-11-05):** `files_published_at` does not exist in code; use a clean marker plus a complete files manifest as its proxy, and name the proxy in the output. A never-woken born-HA host (no replica) is not ready, as the spec says.
+
+**Why.** §13 precondition 3 wants, from `carlos system region readiness <region>`:
+- every instance has a replica, a complete `files_published_at` and no unclean last marker;
+- no old-format lock;
+- no non-hibernating socket instance.
+
+G3 decision 3 narrows this to the HA pool's hosts. P2b-2's door (`2026-11-04-region-ha-p2b-console.md:215-231`, slot 2026-11-11) reports **box** eligibility and roles, and says "Full readiness: Not yet reported" (R21). It has no executable plan and no branch beyond `region-ha-p2b-build` (P2b-1). This task supplies the **host** facts P2b-2 does not cover. It is a diagnostic, never a gate.
+
+**Where it lives: `scripts/region-ha-g3/pool-readiness.py`. Not a CLI verb, because:**
+- a verb is root-binary surface, so it needs a census and a release;
+- it would sit beside, and duplicate, P2b-2's `carlos system region readiness` (copy R03);
+- a script is operator-run and out of the census (AGENTS.md "What is in scope"), and is absorbed later by porting its five checks into P2b-2's console observation, using the same reason codes.
+
+**What to build.**
+- Arguments, all required except `--prefix`:
+ - `--profile`, `--region`;
+ - `--deployment-bucket` (records: `apps/<sqid>/<app>/instances/<host>.json`, `internal/provision/provision.go:38`, `internal/release/release.go:356`);
+ - `--data-bucket` (hibernate prefix `instances/<host>`, `internal/activator/activator.go:164-166`);
+ - `--pool`, and `--account <sqid>` (repeatable);
+ - `--prefix` (default `instances`).
+ It calls `aws s3api` through one runner function (the pattern of `scripts/region-group-roll.py:606`), so tests inject a fake.
+- Enumeration. Pool membership is console database state, so the output says that only the named accounts were read:
+ - per account, list `apps/<sqid>/` with delimiter `/`;
+ - per app, list `apps/<sqid>/<app>/instances/`;
+ - GET each record and keep those with `ha: true`, `pool == --pool`, and the right region.
+- Checks per kept host:
+ 1. **socket.** `kind` defaults to instance, no `addrs`/`addr`, empty `runtime`, and `hibernate` false, explicit or defaulted. This is the create door's own rule (`internal/console/hacreate.go:20`; defaults at `provision.go:480-548`).
+ 2. **lock.** GET `<prefix>/<host>/lock.json`, classified the way `hafresh` does:
+ - `absent`: never woken;
+ - not HA-format (`hafresh.View.HAOn`, `internal/hafresh/lock.go:94-104`): `lock_old_format`;
+ - a marker with `clean: false`: `marker_unclean`;
+ - a clean marker: ok;
+ - HA owner unexpired: `awake`, verdict `unknown`, re-run when asleep;
+ - HA owner expired: `lock_expired_unreleased`, an unpaid release or a suspect holder (§5.2, §9.4);
+ - HA owner with no `iid=` (`hafresh/owner.go` `ParseOwner`): `lock_old_format`.
+ 3. **replica.** `list-objects-v2 --prefix <prefix>/<host>/ltx/ --max-keys 1` (layout per `internal/activator/rootfsmarker.go:63`; confirm against litestream's s3 path helper before coding). No key: `no_replica`.
+ 4. **files.** GET `<prefix>/<host>/files/0/manifest.json` (`internal/activator/hawake.go:656-658`, `hostfiles.ManifestKey` at `internal/hostfiles/manifest.go:83`). Missing, `v != 2`, or any entry or platform item with `torn` or a non-empty `skipped`: `files_incomplete`. **`files_published_at` does not exist in code (no grep hit).** The proxy is a clean marker (complete final publish, §5.2) plus this check. Ruling 3.
+- Output: one JSON line per host:
+ `{"host","account","app","pool","verdict":"ready|not_ready|unknown","reasons":[...],"lock":{...},"reads":{"list":n,"get":n}}`
+ then one summary line with totals and the request count. Exit code 0 always: it is a diagnostic. `--strict` returns 1 when not ready, for the operator's own use only.
+
+**S3 cost (operator-run only).** At most (A + P + H) LISTs plus (R + 2H) GETs, plus one LIST per extra 1,000 keys. A is accounts, P is apps, R is records read, H is pool hosts. For A=2, P=4, R=20, H=10 that is 16 LISTs and 40 GETs, about $0.0001. No loop, no timer, no box-side call.
+
+**Refusals that must hold.**
+- No write, PUT, DELETE, `--recursive` or `s3 cp` to S3. The runner refuses any `s3api` verb outside `list-objects-v2` and `get-object`.
+- A record that fails to parse, or whose body disagrees with its key, is `unknown` with a reason, never ready.
+- Never-woken hosts are `not_ready` (`no_replica`) unless ruling 3 says otherwise.
+- `awake` is never `ready`.
+- No account named: refuse to run.
+
+**User-facing strings.** The reason-code descriptions (one sentence each), the summary line and the "only the named accounts were read" line. One copy pass, listed at the top of the script.
+
+**Tests (offline).** `scripts/region_ha_g3_pool_readiness_test.py` with a fake runner over fixture objects:
+- every lock class in the shared `scripts/testdata/region-ha-locks.json` (absent, legacy `host:pid`, marker clean, marker unclean, held, expired, no-iid HA owner) maps to its code;
+- a socket record is flagged; a rootfs resident is not (the `hacreate.go:20` exemption);
+- a manifest with `torn: true`, `skipped: "x"` or `v: 1` gives `files_incomplete`;
+- read counts match the formula;
+- the runner refuses `put-object`;
+- no `--account` refuses.
+
+Failing first: treat an unexpired HA owner as `ready`; the awake test must fail.
+
+**Run.** `python3 -m unittest scripts/region_ha_g3_pool_readiness_test.py`. **Census:** out of scope (`scripts/`).
+
+---
+
+## Task 6: T1, the drill probe `scripts/region-ha-g2/g2-probe.py`
+
+**Why.** The G2 card's T1 row asks for, per second per fixture:
+- a GET through each NLB address and through the backhaul box, sent with `--resolve` from outside the VPC;
+- an `X-Request-Id` per request;
+- status, serving box and latency;
+- a lock reader every 5 s per fixture;
+- JSONL output, with a budget.
+
+The addendum §5 T1 is the public contract. The earlier windows used ad hoc `curl` loops.
+
+**What to build.**
+- Arguments, nothing hard-coded:
+ - `--fixture HOST` (repeatable), `--entry NAME=IP` (repeatable, for example `nlb-a=192.0.2.10`);
+ - `--write-entry NAME` (the entry used for one `POST /write?n=<seq>` per second per fixture);
+ - `--bucket`, `--prefix` (default `instances`), `--profile`, `--region`;
+ - `--lock-every 5`, `--max-lock-gets 20000`, `--duration`, `--out FILE`.
+- One thread per (fixture, entry). Each second it runs `curl -sS -o - -w <json> --resolve HOST:443:IP --max-time 5 -H "X-Request-Id: <uuid4>" https://HOST/`. It parses `box=`, `hits=` and `rid=` from the Task 7 body.
+- Each record: `{"t","kind":"get|write|lock","fixture","entry","rid","rid_echo","status","box","hits","max","ms","err"}`.
+- The lock reader runs `aws s3 cp s3://<bucket>/<prefix>/<host>/lock.json -` every `--lock-every` seconds and records generation, `expires_at`, the owner's iid and ref, and marker clean or absent. It uses the shared lock fixtures' classifier.
+- Budget: count lock GETs, refuse to start if `fixtures × duration / lock-every > max-lock-gets`, and stop the lock reader (not the HTTP probes) when the cap is reached, with one line saying so.
+- At exit, print a summary per fixture and entry: counts by status and by serving box, the longest run of non-200s, and for writes the acknowledged `n` set saved to `--out.acks`. `--compare RANGES_FILE` computes lost acknowledged writes against Task 7's `GET /ranges`.
+
+**Refusals that must hold.**
+- No fixture or no entry: refuse.
+- An entry whose IP is not a literal IPv4 or IPv6 address: refuse.
+- No `aws` verb other than `s3 cp ... -`, read-only to stdout. The runner enforces it.
+- No retries hide failures: each request is one record.
+- The output file is opened with `O_EXCL` (never overwrites an earlier run's evidence).
+
+**User-facing strings.** The summary headings, the budget refusal and the "lock reader stopped at the cap" line.
+
+**Tests (offline).** `scripts/region_ha_g2_probe_test.py`, loading the hyphenated module with importlib as `scripts/region_group_roll_test.py:20-23` does, with a fake curl and aws runner and a fake clock:
+- the JSONL schema per kind;
+- `rid_echo` true and false;
+- body parse with a missing field gives `null`, not 0;
+- the budget refusal at start and the stop at the cap;
+- `--compare` finds exactly the missing acknowledged `n`;
+- a non-literal entry refuses;
+- a non-`cp` aws verb refuses.
+
+Failing first: count a timeout as status 200; the schema test must fail.
+
+**Run.** `python3 -m unittest scripts/region_ha_g2_probe_test.py`. The card's 5-minute dry run against an existing fixture is window work, not build work.
+
+---
+
+## Task 7: T2 and T6, the numbered-write fixture app (with `/fetch`)
+
+**Why.** The G2 card's T2 and T6 rows ask for:
+- three born-HA fixtures in the test pool, one per replication class, each acknowledging a numbered write and reporting its box and row count;
+- a hairpin fixture with `GET /fetch` that calls its own hostname through an NLB address.
+
+The base is the `hacheck` app used for the existing pool fixture. Its source is at `~/.cache/release-v0.28.25/hacheck/main.go`, not in this repo, and the README's wakecheck source is not on disk. It takes `--socket` and `--db` as the activator passes them (`internal/activator/backend_exec.go:2530`). Its stdout reaches the `carlos-edge` journal through the agent's log listener (`internal/activator/loglistener.go:71-80`). The replication classes are `stream`, `batched` and `daily` (`internal/registry/registry.go:565-577`).
+
+**What to build.** `scripts/region-ha-g2/fixture/main.go`: `package main` in the main module, as `scripts/witness-pointer/` is. It uses the existing `modernc.org/sqlite` (`go.mod:32`) and adds no dependency.
+- Flags `--socket`, `--db`. Use WAL, `busy_timeout`, and a table `w(n INTEGER PRIMARY KEY, box TEXT, at TEXT)`.
+- `POST /write?n=<int>`: `INSERT OR IGNORE`. Reply only after the commit returns. Body: `g2fixture box=<hostname> hits=<count> max=<max n> rid=<X-Request-Id or ->`.
+- `GET /`: the same body without writing.
+- `GET /ranges`: the stored `n` as compressed ranges `1-120,125-300`.
+- `GET /fetch` (T6): read `G2_HAIRPIN_ADDR` (`host:port`; unset gives 503 `hairpin address not configured.`). Do an HTTPS GET of `https://<r.Host>/` dialled to that address with SNI `r.Host` and a 5 s timeout. Reply `fetch status=<code> ms=<n>` or `fetch error=<class>`.
+- After writing each response, log exactly `g2fixture status=<code> host=<r.Host> path=<path> rid=<rid>`. This line is the T4 interface; keep it as an exported constant tested on both sides.
+- `scripts/region-ha-g2/FIXTURES.md`, the creation steps for the window (no account or host names; placeholders):
+ - `carlos apps create`, `carlos instances enable`;
+ - build with `GOOS=linux GOARCH=arm64 CGO_ENABLED=0 go build`;
+ - `carlos deploy --app <app> --version <v> --channel edge <binary>`;
+ - `carlos instances create --host <label>.<domain>` for `g2-stream`, `g2-batched`, `g2-daily` and `g2-hairpin`;
+ - read back `ha: true` and the pool;
+ - `carlos env set G2_HAIRPIN_ADDR=<nlb-ip>:443` for the hairpin app;
+ - then `carlos route --host <h> --replication <class>` **on every serving box over SSM, and again on every replacement before each drill**. That command edits only the box it runs on (`cli.go:793-825`, "ON THIS BOX"), and records do not carry the class. Read it back in the `REPLICATION` column.
+
+**Refusals that must hold.**
+- `n` not a positive integer: 400. An acknowledgement is never sent before the commit. A failed insert: 500 with no `hits=`.
+- `/fetch` never follows redirects and never dials an address other than `G2_HAIRPIN_ADDR`.
+- No tenant names in code or docs.
+
+**User-facing strings.** The body formats, the two `/fetch` errors and the `FIXTURES.md` prose. One copy pass, with the body formats frozen because Task 6 parses them.
+
+**Tests.** `scripts/region-ha-g2/fixture/main_test.go`, through `httptest` against a temporary database:
+- write then read gives `hits` and `max`;
+- a duplicate `n` is ignored;
+- `/ranges` compresses gaps;
+- an acknowledgement after a forced commit failure is absent (inject a closed database);
+- `/fetch` against a local TLS `httptest` server reached through `G2_HAIRPIN_ADDR` with an SNI check;
+- the log-line constant format.
+
+Failing first: write the response before `Exec`; the commit-failure test must fail.
+
+**Run.**
+```
+go test ./scripts/region-ha-g2/fixture -count=1
+GOOS=linux GOARCH=arm64 CGO_ENABLED=0 go build -o /dev/null ./scripts/region-ha-g2/fixture
+GOOS=darwin go build -o /dev/null ./scripts/region-ha-g2/fixture
+GOOS=windows go build -o /dev/null ./scripts/region-ha-g2/fixture
+```
+**Census:** out of scope (`scripts/`). `TestCensusScopeIsTheRootBinary` must still pass, which confirms the fixture is not a root dependency.
+
+---
+
+## Task 8: T4, `scripts/region-ha-g2/g2-firstserve-stop.sh`
+
+**Why.** The G2 card's T4 row and drill 3 need the hang within about a second of the replacement's first backhauled 200. An SSM round trip is too slow (addendum §5 T4). Facts this relies on:
+- the agent and edge are one process, `ExecStart=/opt/carlos/carlos agent` (`internal/host/units/carlos-edge.service:19`);
+- app stdout reaches that unit's journal (`loglistener.go:76`).
+
+**What to build.** A root bash one-shot: `--fixture HOST [--stamp /run/g2-firstserve.stamp] [--timeout 3600]`.
+1. Start-up refusals: refuse unless uid is 0, `carlos-edge` is active, and the stamp file does not exist.
+2. Follow `journalctl -u carlos-edge -f -n0 -o cat` and match the fixed string `g2fixture status=200 host=<HOST> ` (Task 7's constant) with `grep -F --line-buffered -m1`.
+3. On the first match:
+ - read `MainPID` with `systemctl show -p MainPID --value carlos-edge`;
+ - refuse if it is 0 or 1, or if `/proc/<pid>/exe` is not `/opt/carlos/` plus something;
+ - `kill -STOP <pid>`;
+ - write the UTC time (`date -u +%FT%T.%NZ`) and the pid to the stamp with `set -o noclobber`.
+4. Then poll `/proc/<pid>/stat` once a second until the state is no longer `T` or the pid is gone. Then exit.
+5. `trap` on EXIT, INT and TERM: kill the `journalctl` child and `rm -f -- "$0"`. On timeout without a match, exit, remove itself and write no stamp.
+6. In the header, the delivery: `systemd-run --unit=g2-firstserve --collect /run/g2-firstserve.sh --fixture <host>`, so it outlives the SSM session. Record the sha256 in the window log.
+
+**Refusals that must hold.**
+- It never restarts, kills or terminates anything. The only signal it sends is `-STOP`, once, to the verified `carlos-edge` MainPID.
+- No `systemctl restart`, `stop` or `kill`; no `kill -9`, `-KILL` or `-TERM` (aside from its own `journalctl` child); no `aws`, `CompleteLifecycleAction` or `ABANDON`.
+- A second run while the stamp exists refuses.
+
+**User-facing strings.** The start line, the match line, the refusal lines and the exit line. One copy pass.
+
+**Tests (offline).** `scripts/region_ha_g2_firstserve_test.py` runs the script with a shim `PATH`:
+- `journalctl` emits lines from a file;
+- `systemctl` returns a fake pid, which points at a stub process the test starts;
+- `kill` is a shim that records its arguments.
+
+The stub process path replaces `/proc` through a `PROC_ROOT` variable that defaults to `/proc`. Root is faked through an overridable `ID_CMD`.
+
+Cases:
+- a non-matching host's 200 and a matching host's 503 do not trigger;
+- a matching 200 sends exactly `-STOP <pid>` once and writes the stamp;
+- the state leaving `T` exits and removes the script copy;
+- a timeout gives no stamp and the script removed;
+- an existing stamp refuses;
+- MainPID 0 refuses;
+- the forbidden-command grep over the script text;
+- the match string equals Task 7's constant (read from `main.go`).
+
+Failing first: match `status=200` without the host; the non-matching-host test must fail.
+
+**Run.**
+```
+bash -n scripts/region-ha-g2/g2-firstserve-stop.sh
+python3 -m unittest scripts/region_ha_g2_firstserve_test.py
+```
+shellcheck is not installed. Report it. Rehearsing once on the root runner is window work, not build work.
+
+---
+
diff --git a/infra/modules/region-host/group_alarms.tf b/infra/modules/region-host/group_alarms.tf
index f2c0967ea..d793b3243 100644
--- a/infra/modules/region-host/group_alarms.tf
+++ b/infra/modules/region-host/group_alarms.tf
@@ -125,6 +125,24 @@ resource "aws_cloudwatch_metric_alarm" "group_clock_missing" {
dimensions = { AutoScalingGroupName = aws_autoscaling_group.group[0].name }
}
+resource "aws_cloudwatch_metric_alarm" "group_suspect_holder" {
+ count = var.mode == "group" ? 1 : 0
+ alarm_name = "${var.name}-group-suspect-holder"
+ alarm_description = "A group member has refused a host for over 10 minutes because the lease belongs to an instance that is not confirmed terminated. Read the group's ha_suspect_holder lines, then terminate that instance in its group."
+ namespace = "Carlos/Host"
+ metric_name = "SuspectHolderHosts"
+ statistic = "Maximum"
+ period = 60
+ evaluation_periods = 1
+ datapoints_to_alarm = 1
+ threshold = 0
+ comparison_operator = "GreaterThanThreshold"
+ treat_missing_data = "notBreaching"
+ alarm_actions = local.group_alarm_actions
+ ok_actions = local.group_alarm_actions
+ dimensions = { AutoScalingGroupName = aws_autoscaling_group.group[0].name }
+}
+
resource "aws_cloudwatch_event_rule" "group_launch_failed" {
count = var.mode == "group" ? 1 : 0
name = "${var.name}-launch-failed"
diff --git a/infra/modules/region-host/tests/group_alarms.tftest.hcl b/infra/modules/region-host/tests/group_alarms.tftest.hcl
index d302d8339..f2f3eb2a6 100644
--- a/infra/modules/region-host/tests/group_alarms.tftest.hcl
+++ b/infra/modules/region-host/tests/group_alarms.tftest.hcl
@@ -62,7 +62,7 @@ override_resource {
run "termination_alarm_default_off" {
command = plan
assert {
- condition = length(aws_ssm_parameter.group_ingress) == 0 && length(aws_sns_topic_policy.group_launch_failed) == 0 && length(aws_cloudwatch_metric_alarm.termination_queue_age) == 0 && length(aws_cloudwatch_metric_alarm.group_capacity) == 0 && length(aws_cloudwatch_metric_alarm.group_memory) == 0 && length(aws_cloudwatch_metric_alarm.group_clock) == 0 && length(aws_cloudwatch_metric_alarm.group_clock_missing) == 0 && length(aws_cloudwatch_event_rule.group_launch_failed) == 0
+ condition = length(aws_ssm_parameter.group_ingress) == 0 && length(aws_sns_topic_policy.group_launch_failed) == 0 && length(aws_cloudwatch_metric_alarm.termination_queue_age) == 0 && length(aws_cloudwatch_metric_alarm.group_capacity) == 0 && length(aws_cloudwatch_metric_alarm.group_memory) == 0 && length(aws_cloudwatch_metric_alarm.group_clock) == 0 && length(aws_cloudwatch_metric_alarm.group_clock_missing) == 0 && length(aws_cloudwatch_metric_alarm.group_suspect_holder) == 0 && length(aws_cloudwatch_event_rule.group_launch_failed) == 0
error_message = "fixed plans must not gain a termination queue alarm by default"
}
}
@@ -219,6 +219,10 @@ run "group_alarm_producers" {
condition = alltrue([for a in [aws_cloudwatch_metric_alarm.group_capacity[0], aws_cloudwatch_metric_alarm.group_memory[0], aws_cloudwatch_metric_alarm.group_clock[0], aws_cloudwatch_metric_alarm.group_clock_missing[0]] : a.treat_missing_data == "breaching" && a.alarm_actions == toset([aws_sns_topic.alerts[0].arn]) && a.ok_actions == a.alarm_actions])
error_message = "missing group data must breach and notify the regional topic"
}
+ assert {
+ condition = aws_cloudwatch_metric_alarm.group_suspect_holder[0].treat_missing_data == "notBreaching" && aws_cloudwatch_metric_alarm.group_suspect_holder[0].alarm_actions == toset([aws_sns_topic.alerts[0].arn]) && aws_cloudwatch_metric_alarm.group_suspect_holder[0].ok_actions == aws_cloudwatch_metric_alarm.group_suspect_holder[0].alarm_actions
+ error_message = "suspect-holder missing data or actions changed"
+ }
assert {
condition = aws_cloudwatch_metric_alarm.group_capacity[0].threshold == 0 && aws_cloudwatch_metric_alarm.group_capacity[0].comparison_operator == "LessThanThreshold" && aws_cloudwatch_metric_alarm.group_capacity[0].evaluation_periods == 1 && aws_cloudwatch_metric_alarm.group_capacity[0].datapoints_to_alarm == 1 && one([for q in aws_cloudwatch_metric_alarm.group_capacity[0].metric_query : q.expression if q.id == "deficit"]) == "IF(FILL(desired, -1) < 0, -1, FILL(inservice, -1) - desired)" && alltrue([for q in aws_cloudwatch_metric_alarm.group_capacity[0].metric_query : length(q.metric) == 0 ? true : q.metric[0].period == 60 && q.metric[0].namespace == "AWS/AutoScaling" && q.metric[0].dimensions == tomap({ AutoScalingGroupName = aws_autoscaling_group.group[0].name })])
error_message = "capacity uses actual desired membership including approved Standby"
@@ -227,12 +231,16 @@ run "group_alarm_producers" {
condition = aws_cloudwatch_metric_alarm.group_memory[0].metric_name == "MemAvailablePercent" && aws_cloudwatch_metric_alarm.group_memory[0].statistic == "Minimum" && aws_cloudwatch_metric_alarm.group_memory[0].period == 60 && aws_cloudwatch_metric_alarm.group_memory[0].threshold == 15 && aws_cloudwatch_metric_alarm.group_memory[0].evaluation_periods == 3 && aws_cloudwatch_metric_alarm.group_memory[0].datapoints_to_alarm == 3 && aws_cloudwatch_metric_alarm.group_memory[0].comparison_operator == "LessThanThreshold"
error_message = "one low-memory member must breach for three consecutive minutes"
}
+ assert {
+ condition = aws_cloudwatch_metric_alarm.group_suspect_holder[0].metric_name == "SuspectHolderHosts" && aws_cloudwatch_metric_alarm.group_suspect_holder[0].statistic == "Maximum" && aws_cloudwatch_metric_alarm.group_suspect_holder[0].period == 60 && aws_cloudwatch_metric_alarm.group_suspect_holder[0].evaluation_periods == 1 && aws_cloudwatch_metric_alarm.group_suspect_holder[0].datapoints_to_alarm == 1 && aws_cloudwatch_metric_alarm.group_suspect_holder[0].threshold == 0 && aws_cloudwatch_metric_alarm.group_suspect_holder[0].comparison_operator == "GreaterThanThreshold"
+ error_message = "suspect-holder alarm contract changed"
+ }
assert {
condition = aws_cloudwatch_metric_alarm.group_clock[0].metric_name == "ClockOffsetSeconds" && aws_cloudwatch_metric_alarm.group_clock[0].statistic == "Maximum" && aws_cloudwatch_metric_alarm.group_clock[0].period == 60 && aws_cloudwatch_metric_alarm.group_clock[0].threshold == 1 && aws_cloudwatch_metric_alarm.group_clock[0].evaluation_periods == 1 && aws_cloudwatch_metric_alarm.group_clock[0].datapoints_to_alarm == 1 && aws_cloudwatch_metric_alarm.group_clock[0].comparison_operator == "GreaterThanThreshold" && aws_cloudwatch_metric_alarm.group_clock_missing[0].metric_name == "ClockSamplePresent" && aws_cloudwatch_metric_alarm.group_clock_missing[0].statistic == "Minimum" && aws_cloudwatch_metric_alarm.group_clock_missing[0].threshold == 1
error_message = "unknown clock is not a zero offset"
}
assert {
- condition = one([for q in aws_cloudwatch_metric_alarm.group_capacity[0].metric_query : q.metric[0].metric_name if q.id == "inservice"]) == "GroupInServiceInstances" && one([for q in aws_cloudwatch_metric_alarm.group_capacity[0].metric_query : q.metric[0].metric_name if q.id == "desired"]) == "GroupDesiredCapacity" && alltrue([for a in [aws_cloudwatch_metric_alarm.group_memory[0], aws_cloudwatch_metric_alarm.group_clock[0], aws_cloudwatch_metric_alarm.group_clock_missing[0]] : a.namespace == "Carlos/Host" && a.dimensions == tomap({ AutoScalingGroupName = aws_autoscaling_group.group[0].name })])
+ condition = one([for q in aws_cloudwatch_metric_alarm.group_capacity[0].metric_query : q.metric[0].metric_name if q.id == "inservice"]) == "GroupInServiceInstances" && one([for q in aws_cloudwatch_metric_alarm.group_capacity[0].metric_query : q.metric[0].metric_name if q.id == "desired"]) == "GroupDesiredCapacity" && alltrue([for a in [aws_cloudwatch_metric_alarm.group_memory[0], aws_cloudwatch_metric_alarm.group_clock[0], aws_cloudwatch_metric_alarm.group_clock_missing[0], aws_cloudwatch_metric_alarm.group_suspect_holder[0]] : a.namespace == "Carlos/Host" && a.dimensions == tomap({ AutoScalingGroupName = aws_autoscaling_group.group[0].name })])
error_message = "alarm dimensions and metric names must match the actual producers"
}
assert {
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go
index a43a2ec6e..0cdd3873e 100644
--- a/internal/activator/backend_exec.go
+++ b/internal/activator/backend_exec.go
@@ -393,13 +393,14 @@ type ExecBackend struct {
// TerminationProofs replaces live-only takeover when the departure controller
// installs its verified identity resolver and shared durable proof cache.
TerminationProofs *lease.TerminationProofAdapter
- // Page sends finalizer proof refusals through the host paging sinks. Nil disables paging.
+ // Page sends proof refusals through the host paging sinks. Nil disables paging.
Page func(ctx context.Context, level, subject, body string) error
// takeover is the takeover proof's log throttle (hatakeover.go).
takeover takeoverState
// sameBox is the same-box recovery's state (hasamebox.go): the hosts
// this process has acquired (acquiredHere).
- sameBox sameBoxState
+ sameBox sameBoxState
+ suspectHolders suspectHolderState
// haWakes is each host's last Acquire classification (hawake.go).
haWakes haWakes
// entryFiles is the Service's lookup of an awake entry's files
diff --git a/internal/activator/hasamebox.go b/internal/activator/hasamebox.go
index fbb69bb99..2fa1050ec 100644
--- a/internal/activator/hasamebox.go
+++ b/internal/activator/hasamebox.go
@@ -10,6 +10,7 @@ import (
"time"
"github.com/carlosframework/platform/internal/cgroup"
+ "github.com/carlosframework/platform/internal/lease"
"github.com/carlosframework/platform/internal/registry"
)
@@ -69,6 +70,7 @@ func (b *ExecBackend) sameBoxEmpty(ctx context.Context, rt registry.Route) func(
return func() (bool, error) {
if err := b.sameBoxProven(rt); err != nil {
b.sameBox.alarm(rt.Host, err)
+ b.note(rt.Host, lease.CurrentSelf().IID, true, b.suspectHolders.clock())
return false, err
}
log.Printf("activator: %s: same-box recovery: the startup sweep proved every unit stopped and the host's slice reads empty", rt.Host)
@@ -167,4 +169,7 @@ func (s *sameBoxState) alarm(host string, why error) {
// markAcquiredHere records that this process acquired host (any acquire,
// HA or legacy). Nothing removes it: see sameBoxEmpty, 3.
-func markAcquiredHere(b *ExecBackend, host string) { b.sameBox.markAcquired(host) }
+func markAcquiredHere(b *ExecBackend, host string) {
+ b.sameBox.markAcquired(host)
+ b.suspectHolders.clear(host)
+}
diff --git a/internal/activator/hasuspectholder.go b/internal/activator/hasuspectholder.go
new file mode 100644
index 000000000..162d18b40
--- /dev/null
+++ b/internal/activator/hasuspectholder.go
@@ -0,0 +1,135 @@
+package activator
+
+import (
+ "context"
+ "fmt"
+ "log"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/alerting"
+ "github.com/carlosframework/platform/internal/lease"
+)
+
+const suspectHolderAfter = 10 * time.Minute
+const suspectHolderFresh = 5 * time.Minute
+
+type suspectHolder struct {
+ first, last time.Time
+ ownerIID string
+ crossed bool
+}
+
+type suspectHolderState struct {
+ mu sync.Mutex
+ hosts map[string]suspectHolder
+ paged map[string]time.Time
+ now func() time.Time
+}
+
+func (s *suspectHolderState) clock() time.Time {
+ if s.now != nil {
+ return s.now()
+ }
+ return time.Now()
+}
+
+func (s *suspectHolderState) clear(host string) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ delete(s.hosts, host)
+}
+
+func (b *ExecBackend) note(host, ownerIID string, sameBox bool, now time.Time) {
+ if ownerIID == "" {
+ return
+ }
+ s := &b.suspectHolders
+ s.mu.Lock()
+ if s.hosts == nil {
+ s.hosts = make(map[string]suspectHolder)
+ }
+ // Expire idle entries while using only observations already made by wakes.
+ for h, entry := range s.hosts {
+ if now.Sub(entry.last) >= 2*lease.LeaseTTL {
+ delete(s.hosts, h)
+ }
+ }
+ for iid, last := range s.paged {
+ if now.Sub(last) >= time.Hour {
+ delete(s.paged, iid)
+ }
+ }
+ entry, seen := s.hosts[host]
+ if !seen || entry.ownerIID != ownerIID {
+ entry = suspectHolder{first: now, ownerIID: ownerIID}
+ }
+ entry.last = now
+ eligible := now.Sub(entry.first) >= suspectHolderAfter
+ crossing := eligible && !entry.crossed
+ entry.crossed = entry.crossed || crossing
+ s.hosts[host] = entry
+ var hosts []string
+ if eligible && b.Page != nil {
+ if _, already := s.paged[ownerIID]; !already {
+ if s.paged == nil {
+ s.paged = make(map[string]time.Time)
+ }
+ s.paged[ownerIID] = now
+ for h, candidate := range s.hosts {
+ if candidate.ownerIID == ownerIID && now.Sub(candidate.first) >= suspectHolderAfter && now.Sub(candidate.last) < suspectHolderFresh {
+ hosts = append(hosts, h)
+ }
+ }
+ }
+ }
+ s.mu.Unlock()
+
+ if crossing {
+ if sameBox {
+ log.Printf(suspectHolderSameBoxLog, host)
+ } else {
+ log.Printf(suspectHolderLog, host, ownerIID)
+ }
+ }
+ if len(hosts) == 0 {
+ return
+ }
+ sort.Strings(hosts)
+ listed := strings.Join(hosts[:min(10, len(hosts))], ", ")
+ if len(hosts) > 10 {
+ listed += fmt.Sprintf(" and %d more", len(hosts)-10)
+ }
+ subject, body := fmt.Sprintf(suspectHolderSubject, ownerIID), fmt.Sprintf(suspectHolderBody, ownerIID, listed)
+ if sameBox {
+ subject, body = fmt.Sprintf(suspectHolderSameBoxSubject, ownerIID), fmt.Sprintf(suspectHolderSameBoxBody, listed)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ if err := b.Page(ctx, alerting.LevelWarning, subject, body); err != nil {
+ log.Printf("ha_suspect_holder iid=%s page failed: %v", ownerIID, err)
+ }
+}
+
+// SuspectHolderHosts counts sustained refusals observed in the last five minutes.
+func (b *ExecBackend) SuspectHolderHosts(now time.Time) int {
+ s := &b.suspectHolders
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ n := 0
+ for _, entry := range s.hosts {
+ if now.Sub(entry.first) >= suspectHolderAfter && now.Sub(entry.last) < suspectHolderFresh {
+ n++
+ }
+ }
+ return n
+}
+
+const suspectHolderLog = "activator: ALERT %s: the host has been refused for over 10 minutes. Its lease belongs to instance %s, which is not confirmed terminated. (ha_suspect_holder)"
+const suspectHolderSameBoxLog = "activator: ALERT %s: the host has been refused for over 10 minutes. This box could not prove its earlier processes for it have stopped. (ha_suspect_holder_same_box)"
+const suspectHolderSubject = "Instance %s is holding hosts it does not serve."
+const suspectHolderBody = "Instance %s let its leases expire and is not confirmed terminated. These hosts have been down for over 10 minutes: %s. If the instance is in an Auto Scaling group, terminate it in its group. The hosts then move to a surviving box. If it is a fixed box, check its storage access and its agent first. This page repeats every hour while the hosts stay down. (ha_suspect_holder)"
+const suspectHolderSameBoxSubject = "Box %s cannot recover hosts after a restart."
+const suspectHolderSameBoxBody = "This box could not prove that its earlier processes for these hosts have stopped: %s. No other box may take them, so they have been down for over 10 minutes. If the box is in an Auto Scaling group, terminate it in its group. If it is a fixed box, check the agent's startup sweep and cgroup delegation. This page repeats every hour while the hosts stay down. (ha_suspect_holder_same_box)"
diff --git a/internal/activator/hasuspectholder_test.go b/internal/activator/hasuspectholder_test.go
new file mode 100644
index 000000000..1d871f68b
--- /dev/null
+++ b/internal/activator/hasuspectholder_test.go
@@ -0,0 +1,362 @@
+package activator
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/alerting"
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+type suspectTestPage struct{ subject, body string }
+type suspectTestPages struct {
+ mu sync.Mutex
+ pages []suspectTestPage
+}
+
+func (p *suspectTestPages) wire(t *testing.T, b *ExecBackend) {
+ t.Helper()
+ b.Page = func(ctx context.Context, level, subject, body string) error {
+ if ctx.Err() != nil {
+ t.Errorf("spent page context: %v", ctx.Err())
+ }
+ deadline, ok := ctx.Deadline()
+ if !ok || time.Until(deadline) <= 0 || time.Until(deadline) > 5*time.Second {
+ t.Errorf("page deadline: %v, %v", deadline, ok)
+ }
+ if level != alerting.LevelWarning {
+ t.Errorf("page level: %s", level)
+ }
+ // A page sink may read the metric; the tracker must release its lock first.
+ b.SuspectHolderHosts(time.Now())
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ p.pages = append(p.pages, suspectTestPage{subject, body})
+ return nil
+ }
+}
+func (p *suspectTestPages) snapshot() []suspectTestPage {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ return append([]suspectTestPage(nil), p.pages...)
+}
+func suspectRefuse(t *testing.T, b *ExecBackend, rt registry.Route) {
+ t.Helper()
+ _, err := b.Acquire(context.Background(), rt)
+ var refused *errLeaseRefused
+ if !errors.As(err, &refused) {
+ t.Fatalf("expected refused acquire, got %v", err)
+ }
+ if lockWrites(t, b, rt) != 0 {
+ t.Fatal("refused acquire wrote a lock")
+ }
+}
+
+func TestSuspectHolderThresholdAndHourly(t *testing.T) {
+ logs := captureLog(t)
+ b, rt, _ := takeoverBackend(t, time.Now().Add(-time.Minute), &terminatedOracle{})
+ now := time.Now()
+ start := now
+ b.suspectHolders.now = func() time.Time { return now }
+ var pages suspectTestPages
+ pages.wire(t, b)
+ suspectRefuse(t, b, rt)
+ now = start.Add(9*time.Minute + 59*time.Second)
+ suspectRefuse(t, b, rt)
+ if got := len(pages.snapshot()); got != 0 {
+ t.Fatalf("pages before 10 minutes=%d", got)
+ }
+ if n := b.SuspectHolderHosts(now); n != 0 {
+ t.Fatalf("early count=%d", n)
+ }
+ now = start.Add(10 * time.Minute)
+ suspectRefuse(t, b, rt)
+ if got := pages.snapshot(); len(got) != 1 || got[0].subject != "Instance i-b is holding hosts it does not serve." {
+ t.Fatalf("crossing pages=%+v", got)
+ }
+ if n := b.SuspectHolderHosts(now); n != 1 {
+ t.Fatalf("crossing count=%d", n)
+ }
+ if n := b.SuspectHolderHosts(now.Add(5*time.Minute - time.Nanosecond)); n != 1 {
+ t.Fatalf("fresh count=%d", n)
+ }
+ if n := b.SuspectHolderHosts(now.Add(5 * time.Minute)); n != 0 {
+ t.Fatalf("stale count=%d", n)
+ }
+ for _, d := range []time.Duration{20 * time.Minute, 40 * time.Minute, 60 * time.Minute, 70*time.Minute - time.Nanosecond} {
+ now = start.Add(d)
+ suspectRefuse(t, b, rt)
+ }
+ if got := len(pages.snapshot()); got != 1 {
+ t.Fatalf("pages within hour=%d", got)
+ }
+ now = start.Add(70 * time.Minute)
+ suspectRefuse(t, b, rt)
+ if got := len(pages.snapshot()); got != 2 {
+ t.Fatalf("hourly pages=%d", got)
+ }
+ if n := strings.Count(logs.String(), "(ha_suspect_holder)"); n != 1 {
+ t.Fatalf("crossing logs=%d", n)
+ }
+}
+
+func TestSuspectHolderGroupingAndLimit(t *testing.T) {
+ b := &ExecBackend{}
+ now := time.Now()
+ start := now
+ b.suspectHolders.now = func() time.Time { return now }
+ var pages suspectTestPages
+ pages.wire(t, b)
+ report := func(host, owner string) {
+ b.reportTakeover(context.Background(), registry.Route{Host: host}, owner, false, nil)
+ }
+ for i := 11; i >= 0; i-- {
+ report(fmt.Sprintf("host-%02d.example.com", i), "i-b")
+ }
+ now = start.Add(9 * time.Minute)
+ for i := 0; i < 12; i++ {
+ report(fmt.Sprintf("host-%02d.example.com", i), "i-b")
+ }
+ now = start.Add(10 * time.Minute)
+ report("host-00.example.com", "i-b")
+ got := pages.snapshot()
+ want := []string{}
+ for i := 0; i < 10; i++ {
+ want = append(want, fmt.Sprintf("host-%02d.example.com", i))
+ }
+ if len(got) != 1 || !strings.Contains(got[0].body, strings.Join(want, ", ")+" and 2 more") || strings.Contains(got[0].body, "host-10") {
+ t.Fatalf("group page=%+v", got)
+ }
+ report("other.example.com", "i-c")
+ now = now.Add(10 * time.Minute)
+ report("other.example.com", "i-c")
+ if got := pages.snapshot(); len(got) != 2 || !strings.Contains(got[1].subject, "i-c") {
+ t.Fatalf("owner pages=%+v", got)
+ }
+}
+
+func TestSuspectHolderRecoveryClears(t *testing.T) {
+ for _, mode := range []string{"terminated", "same-box"} {
+ t.Run(mode, func(t *testing.T) {
+ oracle := &terminatedOracle{yes: map[string]bool{}}
+ b, rt, _ := takeoverBackend(t, time.Now().Add(-time.Minute), oracle)
+ now := time.Now()
+ b.suspectHolders.now = func() time.Time { return now }
+ var pages suspectTestPages
+ pages.wire(t, b)
+ suspectRefuse(t, b, rt)
+ now = now.Add(10 * time.Minute)
+ suspectRefuse(t, b, rt)
+ switch mode {
+ case "terminated":
+ oracle.yes["i-b"] = true
+ case "same-box":
+ putLockFor(t, b, rt, leaseBody(t, hafresh.OwnerFor(lease.CurrentSelf(), 7, true), time.Now().Add(-time.Minute)))
+ sameBoxReady(b)
+ }
+ l, err := b.Acquire(context.Background(), rt)
+ if err != nil {
+ t.Fatal(err)
+ }
+ releaseHALease(t, l)
+ if n := b.SuspectHolderHosts(now); n != 0 {
+ t.Fatalf("successful acquire retained %d suspects", n)
+ }
+ b.reportTakeover(context.Background(), rt, "i-c", false, nil)
+ now = now.Add(9*time.Minute + 59*time.Second)
+ b.reportTakeover(context.Background(), rt, "i-c", false, nil)
+ if got := len(pages.snapshot()); got != 1 {
+ t.Fatalf("new owner paged early: %d", got)
+ }
+ })
+ }
+}
+
+func TestSuspectHolderResetOwnerAndGap(t *testing.T) {
+ for _, changeOwner := range []bool{false, true} {
+ t.Run(fmt.Sprint(changeOwner), func(t *testing.T) {
+ b := &ExecBackend{}
+ now := time.Now()
+ start := now
+ b.suspectHolders.now = func() time.Time { return now }
+ var pages suspectTestPages
+ pages.wire(t, b)
+ rt := registry.Route{Host: "host.example.com"}
+ b.reportTakeover(context.Background(), rt, "i-b", false, nil)
+ owner := "i-b"
+ now = start.Add(30 * time.Minute)
+ if changeOwner {
+ owner = "i-c"
+ now = start.Add(9 * time.Minute)
+ }
+ b.reportTakeover(context.Background(), rt, owner, false, nil)
+ now = now.Add(9*time.Minute + 59*time.Second)
+ b.reportTakeover(context.Background(), rt, owner, false, nil)
+ if len(pages.snapshot()) != 0 {
+ t.Fatal("reset clock paged early")
+ }
+ now = now.Add(time.Second)
+ b.reportTakeover(context.Background(), rt, owner, false, nil)
+ if len(pages.snapshot()) != 1 {
+ t.Fatal("reset clock failed to page")
+ }
+ })
+ }
+}
+
+func TestSuspectHolderFinalizerExcludedAndConfirmedClear(t *testing.T) {
+ b := &ExecBackend{}
+ now := time.Now()
+ b.suspectHolders.now = func() time.Time { return now }
+ var pages suspectTestPages
+ pages.wire(t, b)
+ rt := registry.Route{Host: "host.example.com"}
+ ctx := context.WithValue(context.Background(), adoptionCauseKey{}, "b")
+ b.reportTakeover(ctx, rt, "i-b", false, nil)
+ now = now.Add(10 * time.Minute)
+ b.reportTakeover(ctx, rt, "i-b", false, nil)
+ if got := pages.snapshot(); len(got) != 1 || strings.Contains(got[0].body, "ha_suspect_holder") {
+ t.Fatalf("finalizer pages=%+v", got)
+ }
+ if b.SuspectHolderHosts(now) != 0 {
+ t.Fatal("finalizer tracked as suspect")
+ }
+ b.reportTakeover(context.Background(), rt, "i-b", false, nil)
+ now = now.Add(10 * time.Minute)
+ b.reportTakeover(context.Background(), rt, "i-b", false, nil)
+ if b.SuspectHolderHosts(now) != 1 {
+ t.Fatal("visitor not tracked")
+ }
+ b.reportTakeover(ctx, rt, "i-b", true, nil)
+ if b.SuspectHolderHosts(now) != 0 {
+ t.Fatal("confirmed termination not cleared")
+ }
+}
+
+func TestSuspectHolderSameBox(t *testing.T) {
+ logs := captureLog(t)
+ b, rt := haBackend(t, "host.example.com")
+ b.StartupSwept = func() bool { return false }
+ now := time.Now()
+ b.suspectHolders.now = func() time.Time { return now }
+ var pages suspectTestPages
+ pages.wire(t, b)
+ before := len(haFixOf(b).fx.Requests())
+ for _, d := range []time.Duration{0, 10 * time.Minute} {
+ now = now.Add(d)
+ if ok, err := b.sameBoxEmpty(context.Background(), rt)(); ok || err == nil {
+ t.Fatal("same-box refusal changed")
+ }
+ }
+ if got := pages.snapshot(); len(got) != 1 || got[0].subject != "Box i-a cannot recover hosts after a restart." || !strings.Contains(got[0].body, "ha_suspect_holder_same_box") {
+ t.Fatalf("same-box pages=%+v", got)
+ }
+ if len(haFixOf(b).fx.Requests()) != before || lockWrites(t, b, rt) != 0 {
+ t.Fatal("same-box tracking added storage requests")
+ }
+ if strings.Count(logs.String(), "(ha_suspect_holder_same_box)") != 1 {
+ t.Fatalf("same-box log: %s", logs)
+ }
+}
+
+func TestSuspectHolderConcurrentSpentContext(t *testing.T) {
+ b := &ExecBackend{}
+ now := time.Now()
+ b.suspectHolders.now = func() time.Time { return now }
+ var pages suspectTestPages
+ pages.wire(t, b)
+ rt := registry.Route{Host: "host.example.com"}
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ b.reportTakeover(ctx, rt, "i-b", false, context.Canceled)
+ now = now.Add(10 * time.Minute)
+ var wg sync.WaitGroup
+ for range 20 {
+ wg.Go(func() { b.reportTakeover(ctx, rt, "i-b", false, context.Canceled); b.SuspectHolderHosts(now) })
+ }
+ wg.Wait()
+ if got := len(pages.snapshot()); got != 1 {
+ t.Fatalf("concurrent pages=%d", got)
+ }
+}
+
+func TestSuspectHolderNilPageStillCounts(t *testing.T) {
+ b := &ExecBackend{}
+ now := time.Now()
+ b.suspectHolders.now = func() time.Time { return now }
+ rt := registry.Route{Host: "host.example.com"}
+ b.reportTakeover(context.Background(), rt, "i-b", false, nil)
+ now = now.Add(10 * time.Minute)
+ b.reportTakeover(context.Background(), rt, "i-b", false, nil)
+ if b.SuspectHolderHosts(now) != 1 {
+ t.Fatal("nil page lost suspect")
+ }
+}
+
+func TestSuspectHolderAcquireBetweenRefusals(t *testing.T) {
+ b, rt, _ := takeoverBackend(t, time.Now().Add(-time.Minute), &terminatedOracle{})
+ now := time.Now()
+ start := now
+ b.suspectHolders.now = func() time.Time { return now }
+ var pages suspectTestPages
+ pages.wire(t, b)
+ suspectRefuse(t, b, rt)
+ now = start.Add(5 * time.Minute)
+ putLockFor(t, b, rt, leaseBody(t, hafresh.OwnerFor(lease.CurrentSelf(), 7, true), time.Now().Add(-time.Minute)))
+ sameBoxReady(b)
+ l, err := b.Acquire(context.Background(), rt)
+ if err != nil {
+ t.Fatal(err)
+ }
+ releaseHALease(t, l)
+ putLockFor(t, b, rt, leaseBody(t, heldByB, time.Now().Add(-time.Minute)))
+ writes := lockWrites(t, b, rt)
+ for _, d := range []time.Duration{5 * time.Minute, 10 * time.Minute} {
+ now = start.Add(d)
+ if _, err := b.Acquire(context.Background(), rt); err == nil {
+ t.Fatal("foreign owner was acquired")
+ }
+ }
+ if len(pages.snapshot()) != 0 {
+ t.Fatal("acquire between refusals did not reset clock")
+ }
+ now = start.Add(15 * time.Minute)
+ if _, err := b.Acquire(context.Background(), rt); err == nil {
+ t.Fatal("foreign owner was acquired")
+ }
+ if len(pages.snapshot()) != 1 {
+ t.Fatal("new refusal period did not page")
+ }
+ if lockWrites(t, b, rt) != writes {
+ t.Fatal("later refusals wrote a lock")
+ }
+}
+
+func TestSuspectHolderPageListsOnlySustainedRecentRefusals(t *testing.T) {
+ b := &ExecBackend{}
+ now := time.Now()
+ start := now
+ b.suspectHolders.now = func() time.Time { return now }
+ var pages suspectTestPages
+ pages.wire(t, b)
+ report := func(host string) {
+ b.reportTakeover(context.Background(), registry.Route{Host: host}, "i-b", false, nil)
+ }
+ report("stale.example.com")
+ report("active.example.com")
+ now = start.Add(9 * time.Minute)
+ report("young.example.com")
+ now = start.Add(10 * time.Minute)
+ report("active.example.com")
+ got := pages.snapshot()
+ if len(got) != 1 || !strings.Contains(got[0].body, "active.example.com") || strings.Contains(got[0].body, "stale.example.com") || strings.Contains(got[0].body, "young.example.com") {
+ t.Fatalf("page hosts=%+v", got)
+ }
+}
diff --git a/internal/activator/hatakeover.go b/internal/activator/hatakeover.go
index 9659d1403..2077e3197 100644
--- a/internal/activator/hatakeover.go
+++ b/internal/activator/hatakeover.go
@@ -49,6 +49,9 @@ func (b *ExecBackend) reportTakeover(ctx context.Context, rt registry.Route, iid
err = termfence.ErrTerminationProof
}
b.takeover.alarm(rt.Host, iid, cause, err)
+ if cause == "visitor" {
+ b.note(rt.Host, iid, false, b.suspectHolders.clock())
+ }
if finalizer && b.Page != nil && b.takeover.claimPage(rt.Host, time.Now()) {
if ref == "" {
ref = iid
@@ -64,6 +67,7 @@ func (b *ExecBackend) reportTakeover(ctx context.Context, rt registry.Route, iid
}
return
}
+ b.suspectHolders.clear(rt.Host)
if cause == "departure-finalize" {
log.Printf("ha_takeover host=%s iid=%s cause=departure-finalize confirmed=%t error=%t", rt.Host, iid, gone, err != nil)
return
diff --git a/internal/groupadmission/observation.go b/internal/groupadmission/observation.go
index 37d44cdc8..bf87ca7c4 100644
--- a/internal/groupadmission/observation.go
+++ b/internal/groupadmission/observation.go
@@ -6,5 +6,6 @@ type Observation struct {
At time.Time
Deployment, Region string
Admitted bool
+ SuspectHolderHosts int
ClockOffset *time.Duration
}
diff --git a/internal/host/agent.go b/internal/host/agent.go
index d0f3d3ecf..c19058384 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -548,6 +548,9 @@ func runAgent(args []string, buildClaims ClaimFactory) {
// terminated and whose lease expired asks EC2 through one oracle.
confirmer := haOwnerConfirmer()
eb.OwnerTerminated = confirmer.Terminated
+ eb.Page = PageOperator
+ processSuspectHolders.Store(eb)
+ defer processSuspectHolders.CompareAndSwap(eb, nil)
if fs, err := newProductionFilesStore(agentCtx, cfg.Bucket, cfg.Region); err != nil {
log.Printf("agent: region HA: files store: %v (every HA restore that needs it fails)", err)
} else {
diff --git a/internal/host/group_metrics.go b/internal/host/group_metrics.go
index ff5ce9e30..2897a549e 100644
--- a/internal/host/group_metrics.go
+++ b/internal/host/group_metrics.go
@@ -8,19 +8,33 @@ import (
"os/exec"
"strconv"
"strings"
+ "sync/atomic"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/cloudwatch/types"
+ "github.com/carlosframework/platform/internal/activator"
"github.com/carlosframework/platform/internal/groupadmission"
)
+var processSuspectHolders atomic.Pointer[activator.ExecBackend]
+
+func suspectsFrom(p *atomic.Pointer[activator.ExecBackend]) func(time.Time) int {
+ return func(now time.Time) int {
+ if backend := p.Load(); backend != nil {
+ return backend.SuspectHolderHosts(now)
+ }
+ return 0
+ }
+}
+
type admissionMetrics struct {
admitted func() bool
deployment, region string
group string
state *groupadmission.State
clock func(context.Context) (time.Duration, error)
+ suspects func(time.Time) int
}
func admissionMetricsFromEnv(getenv func(string) string, a *fixedAdmission, readRegion func(string, string) (roleRegionConfig, error), clock func(context.Context) (time.Duration, error)) *admissionMetrics {
@@ -44,6 +58,7 @@ func admissionMetricsFromEnv(getenv func(string) string, a *fixedAdmission, read
if m.group == "" {
return nil
}
+ m.suspects = suspectsFrom(&processSuspectHolders)
}
return m
}
@@ -53,6 +68,9 @@ func (m *admissionMetrics) observe(ctx context.Context, now time.Time) (groupadm
if m.admitted != nil {
o.Admitted = m.admitted()
}
+ if m.suspects != nil {
+ o.SuspectHolderHosts = m.suspects(now)
+ }
offset, err := m.clock(ctx)
if err == nil {
o.ClockOffset = &offset
@@ -178,5 +196,6 @@ func groupMetricData(o groupadmission.Observation, group, iid string, memory flo
if o.ClockOffset != nil {
data = append(data, datum("ClockOffsetSeconds", o.ClockOffset.Seconds(), types.StandardUnitSeconds, dims), datum("ClockOffsetSeconds", o.ClockOffset.Seconds(), types.StandardUnitSeconds, member))
}
+ data = append(data, datum("SuspectHolderHosts", float64(o.SuspectHolderHosts), types.StandardUnitCount, dims))
return data
}
diff --git a/internal/host/group_metrics_test.go b/internal/host/group_metrics_test.go
index de9543510..c1d8d0660 100644
--- a/internal/host/group_metrics_test.go
+++ b/internal/host/group_metrics_test.go
@@ -123,6 +123,9 @@ func TestAdmissionMetricFlagshipUnchanged(t *testing.T) {
}
return parseRoleRegionConfig([]byte(`{"v":1,"region_code":"ie","placement":"ie"}`), placement)
}, func(context.Context) (time.Duration, error) { calls++; return 1250 * time.Millisecond, clockErr })
+ if w.admission != nil {
+ w.admission.suspects = func(time.Time) int { return 2 }
+ }
now := time.Unix(1793745600, 0)
for step := 0; step < 3; step++ {
if enabled && step == 1 {
@@ -244,6 +247,7 @@ func testGroupMetricsBatch(t *testing.T) {
if m == nil {
t.Fatal("group metrics were not armed")
}
+ m.suspects = func(time.Time) int { return 2 }
put := &fakePutter{}
w := memwatch{admission: m, put: put, instanceID: "i-group", mem: func() (*int64, *int64) { a, b := int64(1000), int64(140); return &a, &b }, pressure: func() (string, error) { return "some avg60=7.5", nil }, logf: func(string, ...any) {}}
now := time.Unix(1793745600, 0)
@@ -288,6 +292,7 @@ func testGroupMetricsBatch(t *testing.T) {
"MemAvailablePercent:AutoScalingGroupName=carlos-dev-uk-group": memory,
"Admitted:AutoScalingGroupName=carlos-dev-uk-group": admitted,
"ClockSamplePresent:AutoScalingGroupName=carlos-dev-uk-group": 1,
+ "SuspectHolderHosts:AutoScalingGroupName=carlos-dev-uk-group": 2,
"ClockSamplePresent:AutoScalingGroupName=carlos-dev-uk-group,InstanceId=i-group": 1,
}
if step == 2 {
@@ -312,7 +317,7 @@ func TestGroupAlarmProducers(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- for _, name := range []string{`"group_capacity"`, `"group_memory"`, `"group_clock"`, `"group_clock_missing"`, `"group_launch_failed"`} {
+ for _, name := range []string{`"group_capacity"`, `"group_memory"`, `"group_clock"`, `"group_clock_missing"`, `"group_suspect_holder"`, `"group_launch_failed"`} {
if !strings.Contains(string(b), name) {
t.Errorf("missing producer-backed alarm %s", name)
}
@@ -377,3 +382,50 @@ func TestGroupMemberDiagnosticEvidence(t *testing.T) {
}
}
}
+
+func TestGroupMetricSuspectHolder(t *testing.T) {
+ now := time.Unix(1793745600, 0)
+ offset := time.Second
+ for _, clock := range []*time.Duration{nil, &offset} {
+ o := groupadmission.Observation{At: now, Admitted: true, ClockOffset: clock, SuspectHolderHosts: 2}
+ got := groupMetricData(o, "test-group", "i-test", 25)
+ wantCount := 5
+ if clock != nil {
+ wantCount += 2
+ }
+ if len(got) != wantCount {
+ t.Fatalf("got %d datums, want %d", len(got), wantCount)
+ }
+ want := types.MetricDatum{MetricName: aws.String("SuspectHolderHosts"), Value: aws.Float64(2), Unit: types.StandardUnitCount, Timestamp: aws.Time(now), Dimensions: []types.Dimension{{Name: aws.String("AutoScalingGroupName"), Value: aws.String("test-group")}}}
+ if !reflect.DeepEqual(got[len(got)-1], want) {
+ t.Fatalf("suspect datum = %+v", got[len(got)-1])
+ }
+ fixed := admissionMetricData(o)
+ o.SuspectHolderHosts = 0
+ if !reflect.DeepEqual(fixed, admissionMetricData(o)) {
+ t.Fatal("suspects changed fixed-box datums")
+ }
+ }
+}
+
+func TestAdmissionMetricSuspectObservation(t *testing.T) {
+ now := time.Unix(1793745600, 0)
+ clockErr := errors.New("clock unavailable")
+ m := &admissionMetrics{state: &groupadmission.State{}, clock: func(context.Context) (time.Duration, error) { return 0, clockErr }}
+ o, err := m.observe(t.Context(), now)
+ if o.SuspectHolderHosts != 0 || !errors.Is(err, clockErr) {
+ t.Fatalf("nil suspects: %+v %v", o, err)
+ }
+ calls := 0
+ m.suspects = func(at time.Time) int {
+ calls++
+ if !at.Equal(now) {
+ t.Fatalf("suspect time = %v", at)
+ }
+ return 2
+ }
+ o, err = m.observe(t.Context(), now)
+ if o.SuspectHolderHosts != 2 || calls != 1 || !errors.Is(err, clockErr) {
+ t.Fatalf("suspects: %+v calls=%d err=%v", o, calls, err)
+ }
+}
diff --git a/internal/host/suspects_test.go b/internal/host/suspects_test.go
new file mode 100644
index 000000000..1e8e396bd
--- /dev/null
+++ b/internal/host/suspects_test.go
@@ -0,0 +1,144 @@
+package host
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "testing/synctest"
+ "time"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/groupadmission"
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+func withSuspectMetricBackend(t *testing.T, check func(*testing.T, *activator.ExecBackend, time.Time)) {
+ t.Helper()
+ const host = "shop.example.com"
+ body, err := json.Marshal(hafresh.Lock{Generation: 9, Owner: "box/v1;ref=b;iid=i-b;pid=7;ha=1", ExpiresAt: time.Unix(0, 0).UTC()})
+ if err != nil {
+ t.Fatal(err)
+ }
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Connection", "close")
+ if r.Method != http.MethodGet || r.URL.Path != "/locks/"+activator.HibernatePrefix("", host)+"/lock.json" {
+ t.Errorf("unexpected lease request: %s %s", r.Method, r.URL.Path)
+ http.Error(w, "unexpected lease request", http.StatusBadRequest)
+ return
+ }
+ w.Header().Set("ETag", `"held-by-b"`)
+ _, _ = w.Write(body)
+ }))
+ t.Cleanup(srv.Close)
+ for k, v := range map[string]string{
+ "AWS_ACCESS_KEY_ID": "test-key", "AWS_SECRET_ACCESS_KEY": "test-secret", "AWS_SESSION_TOKEN": "", "AWS_PROFILE": "",
+ "AWS_EC2_METADATA_DISABLED": "true", "AWS_CONFIG_FILE": "/nonexistent", "AWS_SHARED_CREDENTIALS_FILE": "/nonexistent",
+ "CARLOS_S3_ENDPOINT": srv.URL,
+ } {
+ t.Setenv(k, v)
+ }
+ t.Cleanup(lease.ProcessStateForTest())
+ lease.SetSelf(hafresh.Self{Ref: "a", IID: "i-a", Account: "111122223333", Region: "eu-west-1"})
+ if err := lease.SetObligationDir(t.TempDir()); err != nil {
+ t.Fatal(err)
+ }
+ root := t.TempDir()
+ synctest.Test(t, func(t *testing.T) {
+ proofs := 0
+ b := &activator.ExecBackend{
+ Cfg: activator.Config{Bucket: "locks", Region: "eu-west-1"},
+ DataDir: filepath.Join(root, "data"), RunDirOverride: filepath.Join(root, "run"),
+ Control: instancectl.NewClient(filepath.Join(root, "unused-control.sock")),
+ OwnerTerminated: func(_ context.Context, iid string) (bool, error) {
+ if iid != "i-b" {
+ t.Fatalf("termination proof for %q, want i-b", iid)
+ }
+ proofs++
+ return false, nil
+ },
+ }
+ rt := registry.Route{Host: host, Kind: "instance", HA: true, Provisioned: true, Hibernate: true,
+ DBPath: provision.NestedDBPath(b.DataDir, host),
+ Socket: filepath.Join(b.RunDirOverride, "instances", provision.InstanceID(host), "app.sock")}
+ refuse := func() {
+ t.Helper()
+ if held, err := b.Acquire(t.Context(), rt); held != nil || err == nil || !strings.Contains(err.Error(), hafresh.ReasonOtherExpired) {
+ t.Fatalf("expected expired-holder refusal, got lease=%v err=%v", held, err)
+ }
+ }
+ refuse()
+ time.Sleep(11 * time.Minute)
+ refuse()
+ if proofs != 2 {
+ t.Fatalf("termination proof calls=%d, want 2", proofs)
+ }
+ check(t, b, time.Now())
+ })
+}
+
+func TestSuspectsFrom(t *testing.T) {
+ withSuspectMetricBackend(t, func(t *testing.T, b *activator.ExecBackend, now time.Time) {
+ var p atomic.Pointer[activator.ExecBackend]
+ count := suspectsFrom(&p)
+ if got := count(now); got != 0 {
+ t.Fatalf("nil backend: count=%d, want 0", got)
+ }
+ p.Store(b)
+ if got := count(now); got != 1 {
+ t.Fatalf("sustained refusal: count=%d, want 1", got)
+ }
+ if got := count(now.Add(-2 * time.Minute)); got != 0 {
+ t.Fatalf("before ten minutes: count=%d, want 0", got)
+ }
+ if got := count(now.Add(5 * time.Minute)); got != 0 {
+ t.Fatalf("stale refusal: count=%d, want 0", got)
+ }
+ p.Store(&activator.ExecBackend{})
+ if got := count(now); got != 0 {
+ t.Fatalf("replacement backend: count=%d, want 0", got)
+ }
+ p.Store(nil)
+ if got := count(now); got != 0 {
+ t.Fatalf("cleared backend: count=%d, want 0", got)
+ }
+ })
+}
+
+func TestGroupMetricSuspectWiring(t *testing.T) {
+ previous := processSuspectHolders.Swap(nil)
+ t.Cleanup(func() { processSuspectHolders.Store(previous) })
+ withSuspectMetricBackend(t, func(t *testing.T, b *activator.ExecBackend, now time.Time) {
+ env := map[string]string{"CARLOS_GROUP_ADMISSION": "1", "CARLOS_DEPLOYMENT_BUCKET": "dev-platform"}
+ construct := func(a *fixedAdmission) *admissionMetrics {
+ return admissionMetricsFromEnv(func(k string) string { return env[k] }, a,
+ func(string, string) (roleRegionConfig, error) { return roleRegionConfig{RegionCode: "ie"}, nil },
+ func(context.Context) (time.Duration, error) { return 0, nil })
+ }
+ m := construct(&fixedAdmission{group: true, launch: &groupadmission.Launch{Group: "carlos-dev-ie-group"}})
+ if m == nil || m.suspects == nil {
+ t.Fatal("group admission metrics have no suspect-holder callback")
+ }
+ for _, step := range []struct {
+ backend *activator.ExecBackend
+ want int
+ }{{nil, 0}, {b, 1}, {nil, 0}} {
+ processSuspectHolders.Store(step.backend)
+ o, err := m.observe(t.Context(), now)
+ if err != nil || o.SuspectHolderHosts != step.want {
+ t.Fatalf("process backend=%p: count=%d, want %d; err=%v", step.backend, o.SuspectHolderHosts, step.want, err)
+ }
+ }
+ if fixed := construct(&fixedAdmission{}); fixed == nil || fixed.suspects != nil {
+ t.Fatal("fixed-box admission metrics gained a suspect-holder callback")
+ }
+ })
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index c60237de8..2b6a09fb9 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -97,3 +97,4 @@ plan14-root-reads-hosts-floor-release.tsv 1daafee8030f9d370adf5541b5e87313523073
plan14-root-reads-region-ha-p3b2.tsv 1b5ef39b210f3c7db69e589da8a467ac4d4a4f218e1d97fb4706cd277a27eae1
plan14-root-reads-region-ha-p1b3b-s.tsv 05f08edeb46837a18f1abca302ad21d8c7782edef8af00cc4082f5ed4ea35ad6
plan14-root-reads-region-ha-g2-t8.tsv 05f08edeb46837a18f1abca302ad21d8c7782edef8af00cc4082f5ed4ea35ad6
+plan14-root-reads-region-ha-g2-t3.tsv 6462853d58331c23d0b2f9ee3b52ccec5198b061d864cc97ba6e7b931017f02a
diff --git a/internal/provision/testdata/plan14-root-reads-region-ha-g2-t3.tsv b/internal/provision/testdata/plan14-root-reads-region-ha-g2-t3.tsv
new file mode 100644
index 000000000..f40d7472c
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-region-ha-g2-t3.tsv
@@ -0,0 +1,16 @@
+# Census overlay region-ha-g2-t3, written by census-propose (#369). census-ruling-region-ha-g2-t3, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-region-ha-g2-t3.md.
+# 3 body, 2 sites, 5 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@legacy 0707799d3c11505f5e8c0f789762ad2baa8a9ec2ad3713f6fe015f8614199f33 infra/modules/region-host/group_alarms.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add default-off termination queue age alarm, using existing queue name and regional SNS topic; no IAM, queue, consumer or instance changes. Copy sweep 1: apply approved variable and alarm descriptions verbatim; no resource, threshold, action or read changes.;rev3=census-ruling-region-ha-p3b;basis=Add group capacity, memory, clock, missing-clock and launch-failure notifications; preserve account-owner SNS rights and scope CloudWatch/EventBridge publishers by source account/ARN. Operator-applied Terraform, no box file read; notifications grant no replacement authority.;rev3=census-ruling-region-ha-g2-t3;basis=T3b: add one group-mode SuspectHolderHosts Maximum alarm, 60 seconds, 1 of 1, threshold greater than zero, missing data notBreaching, existing regional SNS actions and ASG dimension. No replacement, scale, IAM, storage or root runtime authority. file:external@0 687869bbfc0287549a041ba7438a42b7a4793fe917c67ac90664240e30d97e5b
+@legacy 46e395476d197a241d1b41673fcc4b011be6b35a2f6c61b9473dc19aadb38b21 infra/modules/region-host/tests/group_alarms.tftest.hcl external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add plan-only mock queue alarm defaults, thresholds, missing-data and regional notification assertions.;rev3=census-ruling-region-ha-p3b;basis=Mock group metric producers, alarm dimensions/windows/missing data and complete scoped SNS policy; retain fixed alarm expectations. Test-only Terraform input, no root runtime read.;rev3=census-ruling-region-ha-p3b1-fixes;basis=Supply the real-shape group queue URL in the group alarm mock so the launch URL equality guard is exercised. Mock plans only; no runtime reads.;rev3=census-ruling-region-ha-g2-t3;basis=T3b: pin fixed-mode zero count, group shape, regional SNS actions and non-breaching missing data for the new alarm; mock-provider test only, no root runtime read. file:external@0 98fe6ee740066dc092bd1b1f451da4bc78f62862a71292f95ff7c342f4f7ecf1
+@legacy 6adb58ef9090a3b20be51f76c5cd396b38b9bb0d8d29f49c5fb23866c3b5cd26 internal/activator/hasamebox.go ExecBackend.sameBoxEmpty legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: the closure lease.AcquireHA calls as the same-box proof for taking this box's own expired HA lock: true only when sameBoxProven holds, else logs an ALERT at most once a minute and answers false; +registry:Host x2, +whole:Route;rev3=census-ruling-region-ha-g2-t3;basis=T3a: record refused same-box recovery using the existing route Host and lease.CurrentSelf instance id; no new external read; +registry:Host for the tracker call; the emptiness proof and S3-free refusal stay unchanged; pages through the existing sink. registry:Host@194,registry:Host@218,registry:Host@436,whole:Route@157 8bbf73ab3184df6255726461112f7cac215f586dccb63d44fca3b4a124889844
+@legacy dd2a33ff52dc6e169bffab22d1936900551eac1602986f51016c36bbf99a6364 internal/activator/hatakeover.go ExecBackend.reportTakeover legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=Final fix P2-1: report all refused proof results through the per-host alarm and distinguish visitor from departure-finalize. No reads or authority.;rev3=census-ruling-region-ha-followups;basis=Page only departure-finalize proof refusals through the injected host sink, at warning level and once per host per hour. Send on a detached five-second context and log send failures. Read the existing route Host for page throttling, body and failure logging; no new storage read or takeover authority.;rev3=census-ruling-region-ha-g2-t3;basis=T3a: track visitor refusals and clear a host after confirmed termination; no new external read; reads only the existing route Host (+registry:Host x2) and the classified owner instance id; pages through the existing sink; departure-finalize keeps its existing immediate hourly page. registry:Host@1060,registry:Host@1132,registry:Host@1267,registry:Host@1419,registry:Host@347,registry:Host@409,registry:Host@516,registry:Host@957 5fa4f65f910711b5e84a5c56a9c580d470be2139285dac2357271379b3e951ff
+infra/modules/region-host/group_alarms.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add default-off termination queue age alarm, using existing queue name and regional SNS topic; no IAM, queue, consumer or instance changes. Copy sweep 1: apply approved variable and alarm descriptions verbatim; no resource, threshold, action or read changes.;rev3=census-ruling-region-ha-p3b;basis=Add group capacity, memory, clock, missing-clock and launch-failure notifications; preserve account-owner SNS rights and scope CloudWatch/EventBridge publishers by source account/ARN. Operator-applied Terraform, no box file read; notifications grant no replacement authority.;rev3=census-ruling-region-ha-g2-t3;basis=T3b: add one group-mode SuspectHolderHosts Maximum alarm, 60 seconds, 1 of 1, threshold greater than zero, missing data notBreaching, existing regional SNS actions and ASG dimension. No replacement, scale, IAM, storage or root runtime authority. file:external@0 687869bbfc0287549a041ba7438a42b7a4793fe917c67ac90664240e30d97e5b
+infra/modules/region-host/tests/group_alarms.tftest.hcl external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add plan-only mock queue alarm defaults, thresholds, missing-data and regional notification assertions.;rev3=census-ruling-region-ha-p3b;basis=Mock group metric producers, alarm dimensions/windows/missing data and complete scoped SNS policy; retain fixed alarm expectations. Test-only Terraform input, no root runtime read.;rev3=census-ruling-region-ha-p3b1-fixes;basis=Supply the real-shape group queue URL in the group alarm mock so the launch URL equality guard is exercised. Mock plans only; no runtime reads.;rev3=census-ruling-region-ha-g2-t3;basis=T3b: pin fixed-mode zero count, group shape, regional SNS actions and non-breaching missing data for the new alarm; mock-provider test only, no root runtime read. file:external@0 98fe6ee740066dc092bd1b1f451da4bc78f62862a71292f95ff7c342f4f7ecf1
+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. file:Exec@19132,file:Open@1707,file:Statfs@49879,registry:App@12731,registry:Host@45961,whole:Route@12723,whole:Route@45163,whole:Route@46084,whole:Route@46146 b70e365f871ad4d885149a6c48c9e23ae67183c79a310b34fed1ec6c1e708a9f
+internal/activator/hasamebox.go ExecBackend.sameBoxEmpty legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: the closure lease.AcquireHA calls as the same-box proof for taking this box's own expired HA lock: true only when sameBoxProven holds, else logs an ALERT at most once a minute and answers false; +registry:Host x2, +whole:Route;rev3=census-ruling-region-ha-g2-t3;basis=T3a: record refused same-box recovery using the existing route Host and lease.CurrentSelf instance id; no new external read; +registry:Host for the tracker call; the emptiness proof and S3-free refusal stay unchanged; pages through the existing sink. registry:Host@194,registry:Host@218,registry:Host@436,whole:Route@157 8bbf73ab3184df6255726461112f7cac215f586dccb63d44fca3b4a124889844
+internal/activator/hatakeover.go ExecBackend.reportTakeover legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=Final fix P2-1: report all refused proof results through the per-host alarm and distinguish visitor from departure-finalize. No reads or authority.;rev3=census-ruling-region-ha-followups;basis=Page only departure-finalize proof refusals through the injected host sink, at warning level and once per host per hour. Send on a detached five-second context and log send failures. Read the existing route Host for page throttling, body and failure logging; no new storage read or takeover authority.;rev3=census-ruling-region-ha-g2-t3;basis=T3a: track visitor refusals and clear a host after confirmed termination; no new external read; reads only the existing route Host (+registry:Host x2) and the classified owner instance id; pages through the existing sink; departure-finalize keeps its existing immediate hourly page. registry:Host@1060,registry:Host@1132,registry:Host@1267,registry:Host@1419,registry:Host@347,registry:Host@409,registry:Host@516,registry:Host@957 5fa4f65f910711b5e84a5c56a9c580d470be2139285dac2357271379b3e951ff
+@coverage infra/modules/region-host 8c583fcc89c58b01bb7882af57610c8fd4f64ddaf2e4852b5612e91bf42f121f
+@coverage infra/modules/region-host/tests 7687949dcfad73275ff3f61fc8127565623e3f1960b97de47032f71f9ce8f882
+@coverage internal/activator 021afc30fe767e12688922f73153b146f6a5d16a1cd1e99a09a3f1ac68ddb880
+@coverage internal/groupadmission 4ecaa423b61a9f15ad8d5ca20f11b35a04568604d64a80239bbbdf0a12dd68e5
+@coverage internal/host 4dcf112d71bfc86fc73e71952adc8ba7ca7d8fc3d3842795e6adb1616ce7e422
diff --git a/scripts/check-region-group-plan.py b/scripts/check-region-group-plan.py
index 9b8b893f0..a4ee8b437 100755
--- a/scripts/check-region-group-plan.py
+++ b/scripts/check-region-group-plan.py
@@ -62,6 +62,7 @@ GROUP_DISPOSABLE = {
('aws_cloudwatch_metric_alarm', 'group_capacity'), ('aws_cloudwatch_metric_alarm', 'group_memory'),
('aws_cloudwatch_metric_alarm', 'group_clock'),
('aws_cloudwatch_metric_alarm', 'group_clock_missing'),
+ ('aws_cloudwatch_metric_alarm', 'group_suspect_holder'),
('aws_cloudwatch_event_rule', 'group_launch_failed'),
('aws_cloudwatch_event_target', 'group_launch_failed'),
('aws_sns_topic_policy', 'group_launch_failed')}
diff --git a/scripts/check_region_group_plan_test.py b/scripts/check_region_group_plan_test.py
index 8613e2d60..bfff772b9 100644
--- a/scripts/check_region_group_plan_test.py
+++ b/scripts/check_region_group_plan_test.py
@@ -568,6 +568,19 @@ class GroupModuleTests(unittest.TestCase):
self.gate(creation, 0)
self.gate(document, 0, cleanup=group_manifest(document, creation))
+ def test_suspect_holder_alarm_cleanup_manifest(self):
+ for name, expected in [('group_suspect_holder', 0), ('group_unlisted', 1)]:
+ with self.subTest(name=name):
+ document = self.fixture('tofu-1.12-group-partial-destroy.json')
+ creation = self.fixture('tofu-1.12-group-create.json')
+ address = GROUP + 'aws_cloudwatch_metric_alarm.' + name + '[0]'
+ values = {'alarm_name': 'test-group-suspect-holder'}
+ document['resource_changes'].append(resource(address, 'aws_cloudwatch_metric_alarm',
+ name, values, None, actions=['delete']))
+ creation['resource_changes'].append(resource(address, 'aws_cloudwatch_metric_alarm',
+ name, None, values, actions=['create']))
+ self.gate(document, expected, cleanup=group_manifest(document, creation, [address]))
+
def test_full_destroy_needs_manifest_for_group(self):
document = self.fixture('tofu-1.12-group-full-destroy.json')
creation = self.fixture('tofu-1.12-group-create.json')