plans: P1b-3b plan rev 1 (duties, departure scan, SQS consumer)
Plan local duty ownership, transactional wake-state adoption, confirmed termination scanning, and one SQS consumer with a start/cancel contract for P3a. Include request budgets, production witnesses, census work, copy deck, and the disposable dev-box drill approval card. Split native-sidecar coverage because main explicitly keeps sidecars legacy. Preserve empty home placement and the inherited review rulings. Planning only; no production code, deployment, or push.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 file changed,
+331
−0
docs/superpowers/plans/2026-11-03-region-ha-p1b3b-duties.md+331 −0
diff --git a/docs/superpowers/plans/2026-11-03-region-ha-p1b3b-duties.md b/docs/superpowers/plans/2026-11-03-region-ha-p1b3b-duties.md| new file mode 100644 |
| index 000000000..e41555c85 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-11-03-region-ha-p1b3b-duties.md |
| @@ -0,0 +1,331 @@ |
| +# Region HA P1b-3b: local duties and departure recovery Implementation Plan — rev 1 |
| + |
| +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. This commission is planning only: no production code, reviewer dispatch, push, release or live drill. Preserve the execution method chosen by the controller. |
| + |
| +**Goal:** Recover a terminated box's durable timers and due wakes without visitor traffic, and expose a truthful termination-consumer start/cancel acknowledgment for P3a. |
| + |
| +**Architecture:** One local duty gate selects work; the existing HA acquire remains the writer gate. One termination consumer per box, request-confirmation notifications and cached view ageing feed a durable local departure journal. One import transaction installs wake state before conditional edges deletion. Drain remains a named integration hook until its producer merges. |
| + |
| +**Tech Stack:** Go 1.26, SQLite registries, `hostfiles` manifests/wake state, conditional S3 leases/deletes, the existing EC2/SQS adapters, and `internal/sim/regionha`. |
| + |
| +**Spec:** `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md`, especially §3.1/I3, §4, §7, §9, §18–21. Parent: `docs/superpowers/plans/2026-11-01-region-ha-p1b3-placement.md`, B1–B5 and Task 5B. Formatting reference: `docs/superpowers/plans/2026-10-29-region-ha-p1b2-forwarding.md`. |
| + |
| +**Base:** amadan `origin/main` **9a064ebeba6fb07ecce97fdf276f8caa00d90c8a**. Every code citation below is at that commit; new files have no invented line numbers. P1a, P1b-1, P1b-2, dead-holder backoff, P1b-3a, P2a and durability 3a are already merged. Read current code rather than the old plans' line numbers. |
| + |
| +**Status:** draft executable termination slice, with a separately gated native-sidecar extension. No review verdict claimed. The P3 document was read with `git show origin/region-ha-p3-group:docs/superpowers/plans/2026-11-01-region-ha-p3-group.md`; its :27 and integration row “Termination-start latch / I3,A1” describe a downstream need, not authority to implement unmerged P3 code. |
| + |
| +## Rulings |
| + |
| +- **N-HA9 / I1:** storage fencing is separate. Confirmed termination never permits taking an unexpired owner lock; equality at expiry remains held under the existing decision. No TTL reduction, early same-box recovery or acceptance of stopped/shutting-down/missing instances. |
| +- **N-HA11:** each enabled box uses one small consumer on its existing EC2 termination queue, 20-second long polls, about 180 receives/hour/box. No new S3 poll. View age is the lost-event fallback. SQS is work distribution when boxes share a queue; receiving a message creates responsibility, not an invitation to discard it because HRW chose another box. |
| +- **N-HA12:** retain the merged 10-second placement-suspect rule and its caller-cancellation correction. Duty suppression is separate from visitor placement; neither changes lease authority. |
| +- **N-HA14:** group boxes roll only through an operator-owned ASG Standby transaction, one at a time. This plan creates no ASG, automatic replacement, drain producer or restart policy. |
| +- **I3 / §7.4:** scan and import is the transfer mechanism. No duty objects, roster, enrollment, claim fence record, published awake set or invented drained flag. |
| +- **N-HA7:** HA classification is a durable host fact. Switching off placement must not route an HA duty through legacy acquire. P1a's explicit legacy-sidecar classification stays until the separate birth-only extension below is approved and implemented. |
| +- **H7:** duplicate ticks during adoption are allowed; losing a durable once-timer, repeatedly probing a live holder, or overwriting a newer registration is not. |
| + |
| +These decisions come from the merged spec/parent plan and `amadan discuss show carlos/platform 421`, read for this revision. The discussion records the 2026-11-03 home-scope failure and the correction on `region-ha-home-placement`; that branch is not an implementation dependency to review against. Rebase after it merges before the dev drill. |
| + |
| +## Scope and slices |
| + |
| +**T — termination recovery, the first merge and P3a dependency.** Tasks B1–B5 form one working slice: local instance duties, atomic import, one consumer and its start acknowledgment, evidence/age fallback, scan-before-delete, simulation and real wiring witnesses. Its visible result is unattended recovery of a synced timer on a born-HA instance. P3a consumes the lifecycle interface only after this implementation is on main. There is no start-only scaffolding merge. |
| + |
| +**S — native-sidecar coverage and full Task 5B acceptance.** Task B6 adds birth-only HA support for native sidecars, then reuses T's gate/importer; Task 5B drills the combined result. This is separate because main deliberately classifies every sidecar as legacy (`internal/activator/hawake.go:74`), `SidecarRecord` has no HA bit (`internal/provision/sidecar.go:71`), and its legacy release cannot supply an HA releaser marker. Merely including sidecar rows in a scan cannot recover an asleep sidecar whose lock was deleted. Changing that behavior touches record creation, classification, lease/restore, secrets and workers. Do not hide it behind a fixture setting `Route.HA=true`. |
| + |
| +T inventories sidecar records and reports unsupported coverage; it never declares them imported or deletes evidence for a departure it cannot cover. T can be activated for a fixed-pair scope whose departing boxes have no native-sidecar duties. The preflight/card must establish that restriction. S needs Paul's birth-only extension decision below; existing sidecars are never silently migrated. This restriction must be carried into P3a's integration/activation card. |
| + |
| +Drain, group admission/latch, role writers, ASG hooks/rolls, hairpin, §6.5 retry, migration, offline moves and imports remain outside both slices. No G1/G2/G3 claim from this plan alone. P3 later owns a separate executable drain integration addendum against merged producers. |
| + |
| +**Switch-on:** Paul is requesting T to unblock P3a and finish the G3 path. Proposed activation is the first dev-only release containing T, on the approved fixed pair, followed by S's disposable-box drill when authorized. If that release/drill slot is not agreed, keep implementation on its branch; no undated dormant merge. Flagship activation remains a later gate. |
| + |
| +## Round history |
| + |
| +| Round | Brief / findings | Verdict | Fault families / disposition | |
| +|---|---|---|---| |
| + |
| +Empty means no review of this document has run, not a reset of inherited history. Parent P1b-3 plan: Opus R1 NOT READY (3 P1, 4 P2, 6 P3), R2 READY AFTER FIXES (0 P1, 2 P2, 6 P3); N-HA12 closed the repeated I4 family, rev 3 final. Its B1–B5/5B decisions are inherited, not reopened. Spec, P1b-1, P1b-2 and dead-holder backoff each spent three rounds and are closed; duty-file transfer was cut after three P1 rounds. |
| + |
| +A reviewer of the newly executable mechanisms must carry those counts and distinguish new findings from settled decisions. Use `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md`. Stop at the first round without P1; apply P2s without another round, retaining census/new-security checks. Two rounds in one invariant/trust-boundary family stop fixes; offer the prescribed refuse/cut/central-invariant choice. A fourth round needs Paul's go. Splitting T/S does not reset review history. No reviewers or subagents run in this planning session. |
| + |
| +## Global Constraints |
| + |
| +- **Home scope, lesson of 2026-11-03:** dev and every home region run with `CARLOS_REGION` unset. It is `provision.Reconcile`'s record scope, not the AWS region. Empty placement is a real scope and matches only empty placement; it is neither unknown nor a wildcard. Dev IE records have `region:""`; `hapair-a1` is in pool `hapair`. Never set `CARLOS_REGION=ie` to make the drill pass: that would remove home records. Test every new comparison with those values. A separate known/present bit represents missing evidence. |
| +- AWS region/account/iid must be proven and non-empty; placement may be empty. Require compatible non-empty data bucket and secrets fingerprint. Keep box reference, iid, record lifetime and registry `Pair` distinct. |
| +- Host universe comes from existing instance **and sidecar** reconciliation, including asleep/hidden hosts. Public edges, the local in-pool registry and `LifetimeIndex` alone are not a complete regional census. Pool equality is a tenancy boundary; do not widen it to finish a scan. |
| +- HA duties use the existing nested acquire → restore → sealed-secrets publication → start path. Import reads only manifest and `wake.json`; it neither restores DB/files/secrets nor starts a process. All publish-before-start and positive-proof reuse rules remain. |
| +- One local import transaction and one duty-selection policy; no claim-mode activation. No dependency on `CARLOS_HOST_CLAIM` or an unmerged role/drain producer. |
| +- Existing view freshness: **15 minutes**, future tolerance **1 minute**; fold tick **30 seconds**, timed publication **5–6 minutes**. The ageing callback runs even when the change index skips the host fold. No new S3 polling loop or request-time membership reads. |
| +- `Confirmer.Terminated` stays shared with acquire: positive cache **24h**, negative/error cache **10s**, one in-flight describe/iid. The old `termfence.Verify` accepts an event; do **not** use it as the new proof path. `FromEvent` is a hint parser only. |
| +- Startup/cancel acknowledgment describes the functioning consumer lifecycle, not queue contents, scan completion, cloud health or permission to take a lease. An empty successful receive counts; failed client construction does not. Runtime S3/SQS blips must not cause automatic replacement. |
| +- Copy is a draft deck for controller → Luna, including error/notice destinations. No product string is approved here. Implementation-plan prose uses writing-pipeline's explicit plan exception; the requested draft deck is not shipped copy. |
| +- Targeted checks use `nice -n 19`, `-run`, `-count=1`; keep `GOCACHE` at its default. Scratch only under `/home/paulca/t/`, remove only owned scratch. Bind local test listeners to `127.0.0.1`. No `sudo`. |
| +- Implementation landing runs the repo build/vet/test/format gate once, plus darwin/amd64, windows/amd64 and linux/arm64 cross-compiles with `CGO_ENABLED=0`; arm64 binary **<64,000,000 bytes**. No full test suite for this plan commit. |
| +- One session per slice, with the stated merge finish line. Three days/three compactions: hand off and stop. At 24h without merge or a stopping-rule trigger, tell Paul and the controller what blocks, the last two rounds and the recommended cut; repeat each 24h. Posting remains subject to the session's communication authorization. |
| + |
| +## Current code and file map |
| + |
| +| Existing seam at 9a064ebe | Work and proposed files | |
| +|---|---| |
| +| `internal/host/agent.go:485,583,915,1313`; `internal/host/hatakeover.go:22,35` | Share the confirmer, arm the controller once before workers/runner, give it the agent lifetime. New `internal/host/hadepartures.go`, `hadepartures_wiring_test.go`. | |
| +| `internal/activator/activator.go:2383,3855,5151,5242,6150`; `internal/activator/hawake.go:74,294,340,738` | Duty eligibility, wake cause, acquisition result and ordinary restore integration. New `haduties.go`, `haadopt.go` and focused tests. | |
| +| `internal/lease/ha.go:59,99,169`; `internal/hafresh/acquire.go:72` | Restriction-only duty predicate on the acquire's existing lock read; preserve the authority decision. No independent pre-acquire probe. | |
| +| `internal/schedule/runner.go:564`; `internal/host/schedule_wiring.go:64,186`; `internal/host/instancekeys.go:75` | Gate before token preparation; preserve escrow read-after-restore and HA backfill exclusion. New duty-runner tests. | |
| +| `internal/host/runs.go:229`; `internal/host/runrelay.go:68`; `internal/host/runexec.go:109` | Gate before either pickup sink and before command start, not only in runexec after a run was already picked. | |
| +| `internal/hostfiles/wake.go:47,84,134`; `internal/hostfiles/manifest.go:64,133`; `internal/activator/hawake.go:593,738` | Reuse validated manifest/LoadWake; replace non-atomic import via new registry transaction, including ordinary wake restore. | |
| +| `internal/registry/timers.go:54,126,321`; `internal/registry/registry.go:1878,3236,3265`; `internal/registry/remote_dispatch.go:143` | New `ha_duties.go`, `ha_departures.go`, tests and remote dispatch parity. Add tables in registry initialization; atomic state/receipt, guarded progress, removal cleanup. | |
| +| `internal/provision/reconcile.go:1068,1230,1304`; `internal/provision/sidecar_reconcile.go:190,451`; `internal/provision/lifetimeindex.go:40` | New `departure_inventory.go`: complete validated regional record snapshot before pool filtering, from existing reads; no extra list. Both record families participate. | |
| +| `internal/edge/homemap.go:265,420,519,1221`; `internal/edge/wakeplacement.go:133` | Retain exact ETags with cached files; export immutable departure observations and 30s callback independent of fold skip. New `hadepartures.go` and tests. Empty home scope fixed in every new predicate. | |
| +| `internal/termfence/confirm.go:112`; `internal/termfence/fence.go:117`; `internal/boxid/record.go:65`; `internal/boxid/verify.go:102` | Confirmation callback after cache publication; signed identity binding without roster. New adapter tests. | |
| +| `internal/release/conditional_delete.go:29,94`; `internal/release/changeindex.go:125,179` | Existing conditional deletion, plus an explicitly acknowledged index completion seam; current automatic bump logs/swallow errors. | |
| +| `infra/modules/region-host/main.tf:835,841,865,890`; `infra/modules/region-host/outputs.tf:41`; `internal/hostenv/hostenv.go:71` | Existing queue/rule/receive-delete-getattributes policy and queue URL output. Add optional queue-URL configuration, no new queue or IAM actions. New `internal/awsterminations/queue.go` and adapter tests; `go.mod`/`go.sum` for SQS SDK if needed. | |
| +| `internal/sim/regionha/{world_test.go,actions_test.go,rules_test.go,invariants_test.go:59,sim_test.go:27,witness_test.go:101,mutate.sh}` | Durable timer/queue model and I6, sharing production pure decisions. | |
| +| `internal/host/haplacement_root_linux_test.go:1` and `haplacement_scenarios_root_linux_test.go` | Follow the existing Linux rootrunner harness; new `hadepartures_root_linux_test.go` executes real import/acquire/delivery paths. | |
| +| `internal/provision/sidecar.go:71`; `sidecar_reconcile.go:131`; `internal/activator/backend_exec.go:3335` | S only: additive birth stamp, sidecar lifetime/reconcile, contained HA worker path; console sidecar create/enable doors and their refusal tests. | |
| + |
| +New provider-neutral protocol/lifecycle types live in `internal/hadeparture/{types.go,consumer.go,consumer_test.go}`. This package imports no AWS SDK; the host orchestrates registry/activator/edge dependencies. AWS conversion lives in `internal/awsterminations`. `termfence` is already AWS-bound, so keep it behind host callbacks rather than importing it into the new core. |
| + |
| +## Protocol decisions and interfaces |
| + |
| +### Scope, evidence and inventory |
| + |
| +Use `hadeparture.Scope{CloudRegion, Placement, DataBucket, SecretsKeyFP string}` plus `Known bool` on the observation containing it. `Placement:""` is valid. A `Box` carries `Ref, InstanceID, Account, RecordSHA256 string` and `Scope`. A `Departure` carries that Box, exact `EdgesKey, EdgesETag string`, `ObservedAt time.Time`, and a stable ID derived from deployment bucket + cloud account/region + ref + iid + record digest. It contains no tenant-supplied path or arbitrary object prefix. |
| + |
| +`provision.DepartureInventory.Snapshot() (generation uint64, records []DepartureHost, complete bool)` returns immutable, validated records from the existing full passes. `DepartureHost` contains canonical account/app/host, kind, placement, pool, lifetime ID, record revision and HA classification. Complete requires both families' successful scans under one reconciled generation; parse/read failures retain the old data but clear completeness. Capture records before the pool filter. Fresh startup without a complete inventory cannot complete a departure. Local route eligibility still uses the normal provision policy. |
| + |
| +The edge exports `DepartureView{Self BoxObservation, Peers []BoxObservation, Complete bool}`; each observation retains source key/ETag and generation. Keep stale files for suspicion; do not filter them out before the age callback. Verify immutable `control/boxes/<ref>.json` once per new ref against existing AWS certificates, expected account/region and the cached published iid. The unsigned record Box field alone cannot bind a reference: require agreement with the scoped edges identity, signed iid and, for group refs, the existing deterministic reference derivation. Duplicate iid/ref assignments are unusable. No enrollment write or claim roster is created. |
| + |
| +For a queue iid absent from a **complete** known deployment view, delete as irrelevant. An uninitialized/partial view is not proof of irrelevance: retain/retry. Wrong event account/region/source/type/state and malformed bodies are rejected without a scan. Validation/read errors are not proof of irrelevance; retain the message and report them. `termfence.FromEvent` does not check terminated by itself; the adapter must. Bound event bodies to 64 KiB; no payload field chooses a bucket, URL, key or AWS region. |
| + |
| +All accepted hints enter `Controller.Enqueue(ctx context.Context, box BoxObservation) error`. Enqueue confirms via the shared `Confirmer.Terminated`, verifies the binding, then durably upserts pending work before returning success. The request path reports a successful confirmation through a callback after the confirmer publishes its result and releases locks; a failed enqueue must remain retryable on subsequent positive-cache hits. Never run a scan while holding a confirmer, edge-fold or activator mutex. |
| + |
| +### The independent start/cancel acknowledgment |
| + |
| +The exported provider-neutral types are in `hadeparture`; `Controller` below is the host orchestration type. Its lifecycle result uses only these types, so P3 needs no queue SDK dependency: |
| + |
| +```go |
| +// In internal/hadeparture: |
| +type Message struct { ID, Receipt string; Body []byte } |
| +type Queue interface { |
| + Receive(context.Context, time.Duration) ([]Message, error) |
| + Delete(context.Context, string) error |
| +} |
| +type Lifecycle interface { |
| + Started() <-chan struct{} |
| + Done() <-chan struct{} |
| + Running() bool |
| + Stop(context.Context) error |
| +} |
| +// In internal/host (Queue/Lifecycle below denote hadeparture types): |
| +// NewController validates dependencies and opens/replays the local journal. |
| +// Start constructs the queue, registers the worker and starts one receive loop. |
| +func (c *Controller) Start(ctx context.Context, |
| + makeQueue func(context.Context) (Queue, error)) (Lifecycle, error) |
| +``` |
| + |
| +`Started` closes once, after journal recovery, handler registration and the first **successful** Receive result, empty included. A first result containing messages must have each message durably recorded as received (or definitively rejected) before startup is acknowledged; confirmation/import may still be pending. Keep a bounded local received-message record keyed by message ID/body digest, without a reusable receipt handle. Failure to persist leaves Started open and the receipt unacknowledged. Queue construction failure returns an error and no started lifecycle. Initialization does not wait for a message, a drained producer, a completed scan, a tenant wake or P3 admission. A receive error before first success leaves Started open and retries with bounded backoff. Start twice on the same controller returns an error, never a second consumer. |
| + |
| +After first start, transient queue/store/describe failures keep the loop alive and the start fact latched. `Running` becomes false synchronously when Stop or parent cancellation begins; Done closes after receiver and scan work have joined. Stop is idempotent, context-bounded, and cannot acknowledge uncommitted work; a timeout reports an unfinished stop. Unexpected terminal exit also clears Running and closes Done. P3 will set its `TerminationStarted` fact only from Started while Running, then close admission before invoking Stop or reacting to Done. This plan adds no P3 import, no `lbhealth.SetHosting` call and no cloud reads to health. |
| + |
| +Use one process-owned cancellation context in `runAgent`; pass it into the new controller and bridge the existing edge shutdown signal to it. Do not copy `context.Background()` from unrelated existing loops. Wiring tests execute the same `armHADepartures` helper called by runAgent. |
| + |
| +### Persistence, import and completion |
| + |
| +Store received-message bodies, pending departures and host receipts in the existing registry DB, not a new disk path or S3 object. Cap one received body at 64 KiB and the active inbox at 1,024 rows; at the cap pause Receive until existing work drains, leaving messages on SQS. Do not evict incomplete work. New tables: |
| + |
| +- `ha_termination_inbox`: message ID/body digest/body, received time and validation state; delete after completion or definite rejection. No receipt handle persists. |
| +- `ha_departures`: departure ID, bound identity/scope/edges revision, verified evidence time, inventory generation, phase, next attempt, last error code. Phases: pending → scanning → imported → edges_deleted → indexed → complete. Receipt handles are ephemeral; never persist them as permanent queue identity. |
| +- `ha_departure_hosts`: departure ID + host + lifetime, lock fingerprint, manifest sequence/wake digest, status (`pending`, `wait_expiry`, `imported`, `superseded`, `unsupported`), retry time. A skipped pool/unknown lifetime/failed read cannot become imported. |
| +- `ha_duties`: host + lifetime, owner basis (`local-holder`, `local-release`, `adopted`), departure ID, wake digest/sequence, registry revision and suppression holder. Host retirement/recreation invalidates entries; historical receipts never authorize a new lifetime. |
| + |
| +`Service.AdoptHost(ctx context.Context, rt registry.Route, req Adoption) (AdoptResult, error)` is the one entry. `Adoption` carries departure identity, expected lifetime/registry Pair, observed lock and local revision. Results are `Imported`, `AlreadyImported`, `Superseded`, or `Deferred`; only the first three can discharge a matching host. Superseded requires a proven newer local owner/committed import or a complete authoritative record retirement, not absence from a stale cache. A changed remote lock alone is not proof this local import completed; classify it from the new view on the next attempt. |
| + |
| +Use existing `hostfiles.Load` and `LoadWake` at the backend's configured `filesPrefix` (`<hibernatePrefix>/files/0/`). Validate manifest version, object origin, digest, wake V/Host, replication class and every timer before writing. No wake entry means no durable wake state; a referenced missing/corrupt wake object is incomplete. A missing whole manifest on a previously held host is reported as ambiguous, not silently installed as an empty timer set. Never read sealed items or instantiate a files publisher for adoption. |
| + |
| +Add `Registry.ImportHAWake(ctx context.Context, host string, expected Pair, state HAWakeImport) (ImportResult, error)`. `HAWakeImport` contains validated timer rows, next_due, replication, lifetime, expected local revision and adoption receipt. In one SQL transaction: compare lifetime/Pair/revision, replace the intended wake state, record adoption and host progress, commit. Reuse the same atomic wake-state primitive from `hostfiles.ImportWake` for ordinary restore. Remote registry methods must preserve the comparison/result/error behavior. |
| + |
| +Advance a per-host local revision transactionally for registration/deletion, timer advancement, next_due consumption, relevant reconcile changes, successful acquire and release. Read the revision before I/O; commit only if unchanged. Serialize wake/adoption in the activator's host operation state without holding `a.mu` over I/O. An acquire begun after a scan invalidates the scan commit; an import begun during wake defers. A repeat receipt returns AlreadyImported without restoring old timer rows. Ordinary restore must not replay an older manifest over delivery progress made after adoption; use the same receipt/digest/revision rules. Keep registration identity and completion tombstones until the corresponding receipt can no longer replay. |
| + |
| +For a terminated **held** lock, import completion waits until the observed expiry has passed, then reads the current lock/manifest in a new attempt. This prevents a last in-flight wake-state publication before expiry from being missed. Waiting is a persisted local deadline, not a lock poll. The later actual duty still acquires normally under N-HA9. A released marker needs matching ref **and iid and lifetime**, whether clean or unclean; cleanliness only controls local-copy reuse. |
| + |
| +### Duty selection |
| + |
| +One pure `DecideDuty(DutyInput) DutyDecision` in `activator/haduties.go`: non-HA retains existing behavior; an owned awake HA entry may act; a local releaser/adopter may attempt its sleeping work; only HRW over compatible serving boxes may attempt an unknown/never-woken host. HRW uses the greatest SHA-256 of `host + "\x00" + ref`, lexical ref tie-break, and **no capacity ranking**. Never use H4's roomiest choice for timer ownership. Missing scope/view defers an unknown starter without dropping rows; known local duty remains eligible subject to local service restrictions and acquire. |
| + |
| +The cached serving projection for duties must support sidecar pool eligibility without using public Hosts entries as a roster. Explicit booting/drain/platform forbids new duty starts; absent role retains fixed-box behavior. P3 will later supply its merged admission predicate. On upgrade/restart with no duty basis yet, allow one discovery attempt at the first due work through the same acquire read: a self-owned release can establish the local basis even when self is not HRW; an absent lock may be taken only by HRW. A peer answer establishes suppression. This is demand-driven discovery, never a new per-host poll, and costs at most one losing GET per box/host until the relevant evidence changes. Non-owners leave younger schedule ticks untouched and advance only occurrences at least **15 minutes** old, guarded by registration/DueAt. Once-timers and imported next_due are not blanket-pruned by this rule. |
| + |
| +Add a restriction-only acquire entry `lease.AcquireHAForDuty(ctx, bucket, prefix, region, base, proofs, allow func(hafresh.View) error)` sharing `classifyAndTake` with AcquireHA. Invoke allow on the existing read on each CAS round; it can refuse, never override `DecideAcquire`. This avoids a second GET and closes the race between a cached duty choice and a peer release. A live peer/another releaser drops local duty eligibility; an exact adoption receipt allows the departed releaser case. Keep the typed refusal private to background work, not a new visitor response. |
| + |
| +Suppression is keyed by host lifetime + holder ref/iid + relevant view/duty generation. A live-holder encounter costs one GET, then zero probes until that holder leaves view or confirmed departure cancels the suppression. An imported dead-holder lock waiting for expiry gets a local not-before deadline; it must not be suppressed forever. Ordinary visitor wakes remain able to acquire and thereby become the local duty owner. Local release saves its duty basis only after the real marker/release result, never before a failed release is settled. |
| + |
| +## S3, SQS and EC2 request budget |
| + |
| +Counts are logical API attempts, including failed CAS; instrument transport retries separately. New SQS/EC2 adapters set SDK max attempts to **1** so their retry loop is the count. S3 keeps existing adapter behavior; report actual wire retries alongside logical counters. G/P/L/D mean S3 GET/PUT/LIST/DELETE. |
| + |
| +Let N be the complete regional scan's host count, A matching/importable hosts and W manifests containing wake state (W≤A). Let U be previously unverified box references, E be event-required edges refresh reads (normally 0), and k be index CAS attempts (1≤k≤4). The current implementation has **four total attempts**, not five, despite §18's “four retries” wording. |
| + |
| +| Path | S3 | SQS / EC2 | |
| +|---|---|---| |
| +| Quiet enabled box, no pending departure; each ordinary duty/age pass with nothing eligible | **0 incremental G/P/L/D** | 1 Receive/20s ≈ **180/h**, **4,320/day**; 0 Delete, 0 Describe | |
| +| Startup, identity cache empty | U G for discovered signed records, one-time; no LIST | At most 1 GetQueueAttributes to validate the configured queue, then receives; no GetQueueUrl | |
| +| One valid termination, successful full scan | **(U+E+N+A+W)G**, 0L/0P before completion | 1 delivering Receive + 1 Delete after complete; 1 Describe on cache miss, 0 on hit | |
| +| Completion, uncontended | **1D + 1G+1P** index | Message deletion above | |
| +| Completion with index conflicts | **1D + kG+kP**, k≤4 | No ack until indexed or a later acknowledged retry | |
| +| Single scan pass | At most **32 lock G + 32 manifest G + 32 wake G = 96G**, plus identity/refresh G and completion if last page | 0 additional receives required by scanner; at most one Describe/iid/10s | |
| +| Held lock still unexpired | 1 lock G in this attempt, 0 manifest/wake G; persist deadline | No repeat describe within negative/positive cache bounds | |
| +| Resume after expiry/error, n remaining/revalidated hosts, a/w imports | **(n+a+w)G**, plus U/E; worst a full formula again | Redelivery adds a Receive and eventually a Delete for its current receipt | |
| +| Duplicate completed event on same durable registry | 0 scan G; completion receipt checked locally | 1 Receive + 1 Delete; evidence cache hit 0 Describe | |
| +| Concurrent scanner on another box | Up to another full formula; no claim that queues broadcast once | Its own receive/redelivery and delete attempts | |
| +| Malformed/wrong-account/known unrelated event | 0 scan S3; unknown identity binding can cost U G | 1 Receive + 1 Delete for definitively irrelevant message; 0 Describe | |
| +| Identity/view/inventory incomplete | No host scan; at most bounded U/E reads on work retry | No Delete; confirmation retry respects cache | |
| +| Delete CAS conflict / ambiguous delete result | Failed 1D; next attempt +1G exact edges key, then repeat only after identity/revision check | No ack from conflict/error | |
| +| Ordinary duty acquire | Existing **1G + 1P** if acquired, plus ordinary restore R; absent lock adds **1L** prefix-empty proof | At most existing confirmation on expired peer | |
| +| Duplicate duty meets live owner/releaser | **1G**, 0P, then **0** until suppression invalidation | No duty-rate describes | |
| +| Gate, HRW, local journal/receipt, inventory projection | **0** | **0** | |
| + |
| +R is unchanged: up to five Litestream LISTs plus extra pages per 1,000 L0 files, object GETs, manifest GET and referenced objects; sealed escrow reads/publication remain on ordinary wake. CAS acquisition retains the existing maximum three classification rounds, so gG+pP+lL with 1≤g≤3, 0≤p,l≤g, and L only for absent-prefix proof. Marker obligations and renewals keep their existing cost. |
| + |
| +N=500, A=W=20 gives **540 GETs = $0.000216** at §18's prices, before evidence, completion and ordinary wake costs. Completion adds $0.0000054 uncontended (DELETE free). A fully populated 32-host pass costs at most $0.0000384 in scan GETs. An identity cache of B references adds at most B successful GETs per process lifetime, with explicit bounded retry attempts for failures. No claim that failed identity reads are free. |
| + |
| +One successful edges deletion causes the existing coalesced fold: per reader `ceil(B/1000)L+B*G`. Existing cap is `120*(ceil(B/1000)+B)` requests/hour/box. Quiet S3 baseline remains §18's **3,300–3,500/hour**, not additional allowance. SQS's ~180/h applies to empty long polls; event bursts/redeliveries add receives. Use MaxNumberOfMessages=1, WaitTimeSeconds=20, VisibilityTimeout=120 on Receive; no ChangeMessageVisibility, SendMessage or new IAM permission. Empty early responses are paced to 20s; errors back off 1,2,4,8,16,30s with bounded jitter, cancelable. Scanner retries run on the existing 30s callback with 30/60/120/300s backoff, one worker and 32 hosts/pass. Receives continue independently of long scans. |
| + |
| +Fixed dev boxes have distinct module IAM names/queues (`platform-infrastructure/dev/region-ie.tf:9`, `region-ie-b.tf:13`); each polls its own authorized existing queue. A future shared group queue distributes messages. Do not point leo at sophie's queue and assume its existing IAM permits that. Queue URL is supplied from `termination_queue_url` into optional `CARLOS_TERMINATION_QUEUE_URL`; URL/account/region validation happens once, with no inferred URL or discovery poll. Missing URL means not started, with a notice; no IAM widening to make configuration work. |
| + |
| +## Review Focus |
| + |
| +1. **Empty home placement and pool mismatch:** Task B3 `TestDepartureHomeScopeAndPools` uses dev-shaped records; an unserved matching host keeps completion false. |
| +2. **Scanner dies after importing one host, before ack:** B4/B5 restart on a different registry and replay through real import; every durable obligation survives and no early delete occurs. |
| +3. **Replay races delivery, registration, ordinary restore or hostname recreation:** B2 transaction/CAS witnesses preserve advanced rows and refuse old lifetimes. |
| +4. **Queue empty, construction fails, or cancellation wins startup:** B3 lifecycle tests establish exactly when Started/Running/Done change; no fake P3 boolean. |
| +5. **Held terminated owner has time left, or final wake publication lands late:** B4 waits the expiry deadline and re-reads before completion; B5 proves zero pre-expiry starts. |
| + |
| +--- |
| + |
| +### Task B1: One local duty gate [T; own review: lease/start authority] |
| + |
| +**Files:** create `internal/activator/haduties.go`, `haduties_test.go`; modify the activator/acquire, schedule, worker boot and run seams in the file map; create `internal/host/haduties_wiring_test.go`. B2 supplies persistent duty state; declare those interfaces first, then integrate before landing T. |
| + |
| +**Interfaces:** `DecideDuty(DutyInput) DutyDecision`; `Service.Duty(ctx context.Context, rt registry.Route) (DutyDecision, error)`; decisions Attempt/Inspect/Defer/AdvanceOldTick; Inspect is the first-duty discovery above and grants no write on its own. Inputs name lifetime, self, owned-awake, local duty basis, suppression and compatible serving refs. Add `Service.WithDuty(ctx context.Context, rt registry.Route, work func(context.Context) error) error` to carry the duty restriction through the existing singleflight wake; foreground callers joining that wake must not inherit a permanent background refusal. `AcquireHAForDuty` is as defined above; no second authority implementation. |
| + |
| +- [ ] **Step 1: Write failing tests.** `TestHADutyOwnerTable` covers awake holder, sleeping releaser/adopter, unknown HRW starter, pre-upgrade releaser with no new duty row, localDenied, missing view, peer release and HA switch-off. `TestHADutyTickAge` asserts 14m59s retained, 15m advanced, guarded registration and once-timer preservation. `TestHADutySuppressLivePeer` asserts one lock GET across 20 sweeps, then retry on view departure/confirmation. `TestHADutyBeforeEveryProducer` drives schedule Tick, due sweep, worker boot/sweep and both run sinks; losing box makes zero token-mint, RunPick or start calls. `TestDutyAcquireRestrictionOnly` checks every acquire state including equality at expiry and three-round CAS reclassification. |
| +- [ ] **Step 2: Run** `nice -n 19 go test ./internal/activator ./internal/lease ./internal/schedule ./internal/host -run 'TestHADuty|TestDutyAcquire' -count=1`; expected failures at the missing gate/observed effects. |
| +- [ ] **Step 3: Implement** the single policy, local suppression/deadlines and restriction callback. Evaluate schedule ownership before Token; ordinary restored token preparation remains in ServeScheduled. A held result leaves younger timers queued, not marked as a failed delivered tick. Gate run pickup before `sinkFor`/`Pickup` and recheck ownership before exec. Preserve co-spawn's holder attachment, WebSocket backhaul, static and housekeeper behavior. Never hold `a.mu` across registry or store calls. |
| +- [ ] **Step 4: Run the same tests**, plus existing schedule/escrow/instance-key tests for changed entry points. Prove no new token/key before restore and no HTTP forwarding of ticks. Test visitor/background wake coalescing and lease loss during delivery. |
| +- [ ] **Step 5: Commit** `ha: gate local duties on their owner`. Task acceptance is all producers wired, not a pure chooser test alone. |
| + |
| +### Task B2: Atomic, replay-safe adoptHost [T; own review: production storage] |
| + |
| +**Files:** new `internal/activator/haadopt.go`, `haadopt_test.go`; new `internal/registry/ha_duties.go`, `ha_departures.go` and tests; modify registry initialization/remote dispatch, timer/next_due mutations, `internal/hostfiles/wake.go`, ordinary restore in `hawake.go`. |
| + |
| +**Interfaces:** AdoptHost/Adoption/AdoptResult and ImportHAWake above. `hostfiles.ImportWake` retains its existing public signature and delegates its three changes to one registry transaction. Registry exposes `HADuty(host, lifetime string) (DutyState, bool, error)` and guarded revision/receipt operations to B1; it does not import activator or hostfiles (convert wire timers at the hostfiles boundary). |
| + |
| +- [ ] **Step 1: Write failing tests.** `TestHAAdoptAtomic` injects failure before each write and COMMIT: all old rows or all imported rows, never mixed; close/reopen DB after each crash point. `TestHAAdoptReplay` imports, delivers/advances a timer, then repeats the same receipt: no resurrection. `TestHAAdoptRaces` registers a same-name new once-timer, consumes next_due, starts a visitor wake, and replaces the route lifetime during manifest I/O. `TestHAAdoptManifestBoundary` covers absent wake entry, absent referenced object, bad digest/origin/V/Host/replication, duplicate timer names and malformed timer kinds/specs. Count zero DB/file-tree/sealed-secret GETs. `TestHAAdoptRemoteParity` runs the transaction through the actual remote registry transport. `TestHAAdoptThenOrdinaryRestore` preserves newer registration/delivery against an older restored wake object. |
| +- [ ] **Step 2: Run** `nice -n 19 go test ./internal/registry ./internal/hostfiles ./internal/activator -run 'TestHAAdopt|TestImportWake' -count=1`; expect the transaction/replay cases to fail against the current three writes. |
| +- [ ] **Step 3: Implement** the journal schema, transaction and per-host revision guards. Validate all input before beginning effects. AdoptHost uses the existing files store/prefix and validates lifetime via the current record/index; no arbitrary prefix parameter. Stage I/O outside locks and commit only against the captured revision. Add cleanup at route retirement, but retain receipt history needed to reject replay. No import writes an instance env file, changes a lease or marks an unproven host locally reusable. |
| +- [ ] **Step 4: Run the same tests**, ordinary wake restore/once-timer tests and the schema/remote round-trip checks. Assert an adopted held host remains unable to start until existing acquire allows it. No golden test that merely mirrors SQL. |
| +- [ ] **Step 5: Commit** `ha: import departure wake state atomically`. |
| + |
| +### Task B3: Evidence, one consumer and independent start acknowledgment [T; own review: termination] |
| + |
| +**Files:** new `internal/hadeparture/*`, `internal/awsterminations/*`, `internal/host/hadepartures.go`; new `internal/provision/departure_inventory.go`; new `internal/edge/hadepartures.go`; modify agent, hatakeover, confirmer, home-map, both reconciles, hostenv allowlist and SDK module files. |
| + |
| +**Interfaces:** Lifecycle/Queue/Start/Enqueue above. `armHADepartures` takes the same confirmer installed at `agent.go:485`, registry, service, stores and immutable view/inventory callbacks; returns controller/lifecycle or a typed initialization error. Edge exposes `WithDepartureTick(func(context.Context, DepartureView))`; invoke after the existing poll on every 30s tick, including skipped/error folds. Controller exposes `Tick(context.Context, DepartureView) error`, used for age suspicion and pending retries. Tick may schedule asynchronous work but never blocks the fold on a full scan. |
| + |
| +- [ ] **Step 1: Write failing tests.** `TestTerminationConsumerLifecycle` covers successful empty receive, client/attributes failure, initial receive failure then recovery, repeated Start, cancel before first success, cancel during Receive/import, bounded Stop and unexpected exit. `TestTerminationEventEvidence` supplies event-only, wrong account/region, stopped/shutting-down/not-found, poisoned ref/iid, duplicate iid, self and invalid signatures; no scan/deletion follows. `TestDepartureHomeScopeAndPools` uses cloud eu-west-1, placement "", hapair-a1/pool hapair, plus shared/cohort1 and foreign-region records. `TestDepartureAgeOnSkippedFold` holds change-index generation constant, advances past 15m, and proves one queued confirmation on the real tick with zero extra S3 membership calls. `TestRequestConfirmationEnqueues` tests cached-positive retries after journal failure. `TestDepartureInventoryComplete` includes hidden sidecars and an out-of-pool record; incomplete family/record scans cannot certify coverage. |
| +- [ ] **Step 2: Run** `nice -n 19 go test ./internal/hadeparture ./internal/awsterminations ./internal/host ./internal/edge ./internal/termfence ./internal/provision -run 'TestTermination|TestDeparture|TestRequestConfirmation' -count=1`; expect missing consumer/callback failures. |
| +- [ ] **Step 3: Implement** the SDK method-value adapter and provider-neutral lifecycle. Receive uses the exact values/bounds in the budget; no queue per departure or visibility extension. Validate configured URL against own cloud identity and attributes; never log receipt handles. Retain existing queue policy. Export inventory completeness before filtering; preserve partial-fold evidence and ETags. On age crossing, failed holder observation or request confirmation, coalesce one journal entry per bound departure. Confirmed evidence cancels duty suppression and records counters without changing N-HA9. |
| +- [ ] **Step 4: Run the same tests**, including method-value binary linking and config disabled/legacy parity. The common arm helper must be called once before service/worker/runner start and stopped by actual agent cancellation; permit one syntactic call/order check only for the uncallable runAgent wrapper, paired with executable helper tests. Test one receiver even when future P3-like lifecycle observation is attached; the observer is only a test consumer of Lifecycle, not a fake drain producer. |
| +- [ ] **Step 5: Commit** `ha: consume termination hints with lifecycle acknowledgment`. |
| + |
| +### Task B4: Complete scan before deletion and queue acknowledgment [T; own review: termination/storage] |
| + |
| +**Files:** extend `internal/host/hadepartures.go`, `internal/registry/ha_departures.go`, importer and their tests; add acknowledged conditional-delete/index seam in `internal/release/conditional_delete.go`/`changeindex.go` with tests. |
| + |
| +**Interfaces:** `Controller.ScanPass(ctx context.Context) (progress bool, err error)` runs one bounded page; `Controller.Complete(ctx context.Context, departureID string) error` performs completion phases. Add `release.DeleteIfMatchIndexed(ctx context.Context, s Store, key, etag string) error` for stores that can acknowledge both operations; unsupported stores refuse. Keep existing DeleteIfMatch semantics for other callers. Use raw delete plus one explicit index bump, not the existing automatic bump plus a second bump. |
| + |
| +- [ ] **Step 1: Write failing tests.** `TestDepartureScanOwnersAndReleasers` scans all records, awake/asleep/sidecar included, matches strict HA owner or marker ref/iid/lifetime, and calls the one importer. `TestDepartureNoEarlyDelete` injects every lock/manifest/object/import/commit failure and verifies edges and receipt remain. `TestDepartureWaitsExpiry` schedules an unexpired dead-owner lock, lands a final wake publication before expiry, and proves final import uses it. `TestDepartureScannerDeath` kills scanner after one import and before each completion phase; a different live registry rescans/redelivers. `TestDepartureDeletionRace` changes the edges ETag/iid, makes Delete succeed with lost response, and fails index bump. `TestDeparturePoolCoverage` cannot complete when a matched host is unserved or a native sidecar is unsupported. `TestDepartureRequestBudget` asserts every budget row, including idle/partial/duplicate and index conflict maxima. |
| +- [ ] **Step 2: Run** `nice -n 19 go test ./internal/host ./internal/registry ./internal/release -run 'TestDeparture' -count=1`; expect incomplete scans currently lack durable ordering. |
| +- [ ] **Step 3: Implement** pending → scanning → imported → edges_deleted → indexed → complete. Iterate a stable complete inventory generation; changed records during the scan invalidate their checkpoints. One lock read per host/attempt; do not select from public edges Hosts. Read errors and malformed old locks stay visibly unresolved when they could conceal duties. Never call an out-of-pool match complete. Preserve the SQS message and edges for redelivery to an eligible box; report a scope with no eligible adopter instead of widening tenancy or discarding work. Shared-queue nonchosen receivers do not ack based on HRW. |
| +- [ ] **Step 4: Implement completion recovery.** Persist full import completion before conditional deletion of the retained revision. On 412 re-read that exact edges key, revalidate the same bound identity, and rescan invalidated work; never delete a replacement box's file. On uncertain response, read back and resume the journal phase. Index failure remains locally pending and unacknowledged; retry the explicit bump, not the scan. Do not fabricate a successful bump from the existing swallowed error. Only after durable completion cancel remaining relevant duty backoffs and Delete the currently received SQS receipt. Delete failure redelivers safely. Known absence alone is never proof that this scanner imported anything. |
| +- [ ] **Step 5: Run the tests**, plus a two-scanner race where one deletes edges while the other is still importing; the latter must use its retained verified departure, not treat missing edges as success. For scanner death before durable whole-scan completion, the original edges revision and unacknowledged message remain the discovery evidence; a fresh process must re-confirm and rescan rather than rely on the lost scanner journal. Record the boundary separately: local durability proves process-restart replay, while the independent-survivor witness proves partial-scan machine loss. Do not label either as proof of arbitrary simultaneous losses after completed transfer. |
| +- [ ] **Step 6: Commit** `ha: finish departure imports before removing evidence`. |
| + |
| +### Task B5: I6, production witnesses, observability and T landing |
| + |
| +**Files:** simulation files in the map; new `internal/host/hadepartures_root_linux_test.go`; counting transport tests; host departure log/metric wiring and `internal/host/metrics_loop.go`; implementation census artifacts only when code exists. |
| + |
| +**Interfaces:** simulation calls production DecideDuty and the production scan-match predicate extracted from B4 (`MatchesDeparture(view hafresh.View, departure Box, lifetime string) bool`). Simulation owns virtual queues/time/crash scheduling; it must not copy either decision table. Host records transfer/confirmation counters and latency into the existing metrics flush, with no new PutMetricData loop. |
| + |
| +- [ ] **Step 1: Write failing I6 tests.** Add durable wake/timer state, registrations, due times, receipt visibility/redelivery, scanner progress and inventory/fold generations to the 2–5-box model. `TestWitnesses` includes held+released departure, scanner death, duplicate import after delivery, lost queue event with no visitors, skipped-index ageing and a timer registered immediately before death whose wake state never synced. After faults stop and a compatible live adopter/store exist, all durable work must eventually deliver within event/age + expiry + bounded scan pages + next runner/sweep; only the final unsynced ~1s timer may be absent. State fairness assumptions; never turn persistent store failure into a false pass. |
| +- [ ] **Step 2: Add mutations.** `skip-departure-scan`, `scan-owners-not-releasers`, `delete-before-import`, `ack-before-import`, `ignore-termination-event`, `skip-age-on-unchanged-index`, `replay-overwrites-delivered-timer`, `duty-ignores-owner`, `take-before-expiry`, `start-before-client`. Each must have a deterministic witness and be caught; no expected-missed exemption for I6. Startup mutation is an executable wiring mutation, not a model-only boolean. |
| +- [ ] **Step 3: Build real witnesses.** `TestHADepartureProductionWiring` runs the actual arm helper, queue adapter boundary, shared confirmer, complete reconcile inventory, importer, runner/sweeper and counted stores. `TestHADepartureRootLifecycle` uses separate survivor processes/registries, real ExecBackend acquire/restore, nested instance control and schedule delivery. Mock only EC2/SQS transport and storage endpoints; do not mock successful acquire, AdoptHost, timer delivery or edges deletion. No visitor request is allowed to rescue a missing trigger. Prove another live registry recovers after partial scanner death. Preserve instance key/token identity and one writer. Run through the approved rootrunner; a skipped privileged test is not PASS. |
| +- [ ] **Step 4: Run once per implementation revision:** `RHASIM_SEEDS=3000 nice -n 19 go test ./internal/sim/regionha -run '^TestRegionHA$' -count=1`; build its test binary under owned `/home/paulca/t/` and run `RHASIM_PAR=1 nice -n 19 internal/sim/regionha/mutate.sh <binary> 3000 <new-rules>`. Record failing mutation seeds and witness names. Use targeted deterministic tests during fixes; no repeated full sweep without a new revision. |
| +- [ ] **Step 5: Wire §20 evidence.** Structured transfer/confirmation logs carry host, lifetime, dead ref/iid, scan ID, result and latency. Metrics carry counts/age/latency without per-host cardinality. Export oldest pending scan and consumer start/error state through the existing status/metrics path. On incomplete recovery, emit C3 once per departure/hour/process; C4 only after durable completion. Queue oldest-message >10m alarm remains part of the scoped infrastructure card, using the existing queue; do not create it from the box. Suspect-holder >10m and existing alarms remain intact. A stopped consumer before startup cannot report healthy start. |
| +- [ ] **Step 6: Obtain accepted copy and complete census**, then run build/vet/format/test once and cross-compiles. Review T's full diff against current amadan main, including all new registry/provision/release/SDK surfaces. Use the bounded review rules; no automatic extra review after P2 fixes. |
| +- [ ] **Step 7: Commit** `ha: prove unattended departure duty recovery`. At implementation time only: push to amadan, describe exact scope/restrictions/tests/review, check green CI at the full tip and squash-land through `amadan branch merge -expect`; read main CI afterward. This planning commission stops at its local commit and never runs those commands. |
| + |
| +### Task B6: Native sidecars born HA [S; needs the decision below; own review] |
| + |
| +**Files:** `internal/provision/sidecar.go`, `sidecar_reconcile.go`, `internal/console/apisidecars.go:223,330,598` and its tests; `internal/activator/hawake.go`, worker acquire/restore/files paths; B1/B2/B4 tests, sidecar record-write inventories and census. No CLI verb is added. |
| + |
| +**Decision proposed:** extend the existing new-record HA stamp to native sidecars created in configured HA regions, with the same empty home-scope resolution as instance creation. Add `HA bool` with `json:"ha,omitempty"` to SidecarRecord; absent remains legacy. Every actual record-creation path (create, enable/auto-create) must stamp/refuse before writes. Existing sidecars and co-spawn children do not change classification. No migration by enabling a box switch. |
| + |
| +**Interfaces:** derive the sidecar lifetime from canonical account/app/synthetic host/CreatedAt; populate the existing lifetime index and sticky route HA bit. `haLegacyRoute` retains legacy behavior for unprovisioned/unstamped sidecars, but stamped, proven native sidecars use the same HA containment/acquire/restore/release/import path as an instance. They remain `IsSidecar()`, socketless and explicitly refused at ingress. Reuse AdoptHost; no sidecar-specific transfer protocol. |
| + |
| +- [ ] **Step 1: Write failing tests** `TestSidecarHABirthOnly` (all create paths, configured home region with record region "", absent stamp remains legacy), `TestSidecarHADutyLifecycle` (real worker acquire, wake-state publish, sleep marker, dead-releaser scan, import, due wake), `TestSidecarHARefusals` (uncontained layout/unknown lifetime/shared secrets unavailable before writes/start), and `TestSidecarNeverAdvertisedOrDialled`. Inherit P2a's supported shape/capacity/move/import refusals rather than bypass them through the sidecar door. |
| +- [ ] **Step 2: Run targeted provision/console/activator/host tests** with `-run 'TestSidecarHA|TestSidecarNever' -count=1`; verify the existing unconditional legacy classification is the failing behavior. |
| +- [ ] **Step 3: Implement the additive birth stamp and contained worker lifecycle.** Check that the worker uses the real files publisher and ~1s WakeItem sync, imports before due delivery and publishes restored/new secrets before launch. Do not settle for setting the route bit. Legacy locks/records remain legacy; an HA-shaped lock under an unstamped unsupported route is refused. Co-spawn remains attached to its parent's acquired lifetime, without a separate duty owner. |
| +- [ ] **Step 4: Extend I6 and the production root witness** with a real standalone sidecar written through the console/provision path. Re-run S's changed-path tests, census and the one per-revision sweep; retain T's history. The full 5B drill cannot pass before this witness. |
| +- [ ] **Step 5: Commit** `ha: preserve duties for native sidecars born HA`; land through the same reviewed amadan gate when S is authorized. If Paul defers S, leave this task unimplemented and keep native-sidecar acceptance explicitly incomplete. |
| + |
| +### Task 5B: Disposable-box dev drill approval card |
| + |
| +**This task prepares a reviewable card before requesting scoped approval.** No live mutation is authorized by this plan. Never terminate sophie-knitting or leo-climbing. A process kill is not EC2 termination evidence. No drain drill until P3's real drained producer and durable completion integration are merged. |
| + |
| +- [ ] **Step 1: Assemble read-only evidence and the exact card.** Private root `/home/paulca/amadan.net/carlos/platform-infrastructure/dev`, current account identity (historical #421 account **640012953448**, reverify), AWS **eu-west-1**, cloud resource IDs, both queue URLs/IAM scopes, exact third-box module/instance/profile/SG/subnet/EBS/EIP resources, and instance type/count/expiry. Name exact app/account/hosts/domains/record and data prefixes. Confirm existing dev records remain `region:""`; hapair-a1/pool hapair is an existing fixture, usable only if included in approval. Verify the merged home-placement fix is in the deployed binary. Do not change `CARLOS_REGION`. |
| +- [ ] **Step 2: Specify effects/cost/cleanup before asking.** One disposable third **fixed** box in pool hapair, exact role/resource changes from a saved whole-root plan and targeted closure, any new module-owned queue/rule/IAM resources explicitly enumerated rather than called “no infra change.” T uses existing queues; provisioning C may create its own module resources. No ASG or NLB needed. List dev-only binary roll, `CARLOS_REGION_HA=1`, each box's own queue URL, console isolation from host.env, permitted restarts, temporary records/timer writes and EC2 termination of **C's exact iid only**. No customer DNS/traffic shift. Produce a currency estimate from the selected instance/storage/IP/queue/metric/alarm prices with a numeric cap and at most **2 hours**; unresolved IDs/cost make the card non-approvable. Name the operator, cleanup owner, expiry and verification commands. S3-loss/negative-evidence tests stay local unless separately added to the card. |
| +- [ ] **Step 3: Ask for one scoped approval** of that concrete account/region/domain/resources/permissions/traffic/cost/duration/cleanup card. T's implementation approval or a prior dev release is not this approval. The production-infrastructure rule in AGENTS.md requires it. No repeated per-call questions within the approved scope. |
| +- [ ] **Step 4: Prepare real duties on C.** Verify exact built binary/revision, identity records, consumer Started, fresh compatible edges, nested/escrow readiness and all intended records on eligible survivors. On C create one held born-HA instance, one cleanly released born-HA instance, synced once-timers and next_due, plus an S-born native sidecar. Use real worker/sleep paths. Read exact manifest/wake digests and record UTC sync acknowledgments; preserve token/key fingerprints without printing secrets. Keep all visitor probes off after setup. T's earlier restricted drill omits sidecar only under an explicit restricted acceptance label, never a full 5B PASS. |
| +- [ ] **Step 5: Terminate C through EC2 and observe unattended recovery.** Log API time, confirmed terminated state, original expiry, queue receipt, scan/import transaction, timer delivery and conditional edges deletion/index/ack. No start before expiry; for held work measure remaining TTL separately from scan/delivery latency. Normal event bound is event/describe latency + remaining lease + `ceil(N/32)*30s` scan allowance + ≤30s delivery sweep plus restore. Do not quote the pre-fencing 1–3m estimate as a guarantee. Reader convergence after acknowledged index is about 30s. |
| +- [ ] **Step 6: Exercise partial scanner death safely.** Local multi-process/root witnesses already prove another-registry recovery. Keep live scope to the disposable third box; use the separate-process rootrunner witness to kill the confirming scanner after one import and resume on another survivor, without adding a fourth live box or terminating sophie/leo. Attach that exact built-revision result to the card and label the fault as local production-path coverage, not a live kill on dev. No production fault flag, fake EC2 proof or drained flag. Queue redelivery/age retry must recover remaining hosts without a visitor. |
| +- [ ] **Step 7: Prove loss bound and cleanup.** Every recorded durable timer/next_due delivered; only an intentionally unsynced final ~1s timer may be lost. H7 duplicate delivery is recorded, not called exactly-once. Compare the built revision's counting-transport budget report; journals cannot prove exact AWS API counts. Remove approved disposable resources and temporary records/prefixes, restore prior config through the release operator, verify sophie/leo instance IDs and `CARLOS_REGION` unchanged, consumers/pair healthy and no scratch/processes left. Keep app logs/evidence specified by the card. Report pass/fail and timings to the controller for #421; no flagship roll or G3 claim. |
| + |
| +## Drain integration hook, deliberately not wired |
| + |
| +Reserve the name `EnqueueDrained` for P3's future verified drain-completion input and a durable completion receipt keyed to its generation. Do not implement an exported `drained bool`, synthetic event or always-true acknowledgment now. The future addendum must define the producer's quiescence proof, HRW scanner choice, invalidation when work changes, acknowledgment delivery and the ordering with publication/deletion. It will call the same AdoptHost and scan engine, not create a second consumer. Consumer Start takes no drain argument and works before that addendum exists. |
| + |
| +## Copy deck for controller → Luna |
| + |
| +Draft source strings only. No Luna invocation or approval claimed. Obtain accepted text before writing product destinations; preserve placeholders and IDs. Structured field names, metric identifiers and internal sentinel errors are not prose, but wrapping them in notices is. Inventory any additional strings discovered during implementation rather than quietly shipping them. |
| + |
| +| ID | Destination | Draft text | Context / constraints | |
| +|---|---|---|---| |
| +| HA3-C3 | `internal/host/hadepartures.go`, recovery warning body | Duties from box %s have not been recovered. The scan will retry. Check the box's wake state before removing its records. | Incomplete scan; append a sanitized cause separately. Never imply it is safe to delete. | |
| +| HA3-C3-subject | Same warning's PageOperator subject | Duties from box %s need attention | Pair with C3, warning, once/departure/hour/process. | |
| +| HA3-C4 | `internal/host/hadepartures.go`, completion notice | Recovered duties for %d instances from box %s. | Only durable completed recovery; count hosts including native sidecars after S. Not proof every timer fired. | |
| +| HA3B-C5 | Consumer startup refusal/status | Termination recovery has not started: %s. | Sanitized reason: missing queue setting, invalid identity, client or journal failure. No receipt, credential or private path. | |
| +| HA3B-C6 | Consumer recovery warning | Termination recovery is retrying after a queue error. | Runtime transient; does not order restart/replacement or clear P3's latched admission. | |
| +| HA3B-C7 | Coverage refusal/status | Duties for instance %s need a box that serves pool %s. Recovery is incomplete. | Operator only; render the empty pool as “shared” without treating it as wildcard. No suggestion to change CARLOS_REGION. | |
| +| HA3B-C8 | Unsupported native-sidecar coverage | Duties for sidecar %s cannot be recovered by this version. Keep the departure records and upgrade before retrying. | T only, or legacy sidecar unsupported by S; must not promise retry alone fixes it. | |
| +| HA3B-C9 | Startup success log | Termination recovery is running. | Emit after genuine Started acknowledgment, never constructor entry. | |
| +| HA3B-C10 | Completion after cancellation | Termination recovery has stopped. Pending recovery will resume on restart. | Emit after Done; do not emit when bounded Stop timed out. | |
| + |
| +S's console refusal copy must reuse accepted P2a wording where semantics match; new sidecar-specific strings require a supplemental deck before code. No new visitor error is needed: existing HA refusal/503 behavior remains. |
| + |
| +## Census and implementation verification |
| + |
| +This Markdown plan is outside the census; generate no overlay now. Execution changes root-binary dependencies `internal/{activator,host,edge,termfence}` and also registry, provision, hostfiles, lease, release, hostenv and new adapter/core packages. Linux amd64/arm64 dependency union, whole-file envelopes and test-source changes all count. “Agent-run” is no exemption; schema and remote-dispatch changes need review. Any module/config delivery change brings its infra/unit envelope too. |
| + |
| +At each implementation slice's final diff: `make census-card`; write tab-separated CLAIMS under owned `/home/paulca/t/`; `make census-propose NAME=region-ha-p1b3b-t CLAIMS=<file>` (S uses its own branch name). Review each unit/envelope against current amadan main, including the new callback's refusal-only property, identity-to-key derivation, local transaction authority, remote registry inputs and conditional delete/index ordering. Run targeted `TestPlan14RootReadCensus|TestCensusScopeIsTheRootBinary|TestPlan14RootInputInventoryCoverage|TestCensusRebaseCarriesDispositions`; check record-write inventories for B6, with no blind digest updates. Independent cross-family reviewer decides every census class and records the tip/verdict on #280; no census unit escalates to Paul. |
| + |
| +The rootrunner witness must run with the built revision, not a stale `CARLOS_BIN`, and record its result/artifact. Shell-out CLI tests use `carlosTestEnv` and scratch cwd. Compile non-Linux tests and the new SDK adapter on Darwin/Windows; run linux/arm64 size check. Once those and the repo gate pass, broaden testing only for a new failure/change. A skipped witness or red package remains a defect. |
| + |
| +## Open questions for Paul and explicit limits |
| + |
| +1. **Native sidecars:** approve S's proposed **birth-only HA sidecar extension**, or defer standalone-sidecar acceptance and keep T/P3a activation restricted to scopes with no such duties? Recommendation: land the useful T slice first, then approve S; do not silently reverse P1a's legacy-sidecar rule. Full §7/5B acceptance requires S or an explicitly revised scope. |
| +2. **Switch-on slot:** reserve the next dev-only T release and restricted unattended-timer drill, then review the fully populated disposable-box card for S/5B. No resource mutation approval is requested by this planning commit. |
| + |
| +The bounded scanner-death acceptance is death before whole-scan completion, as §7.4 and the parent outline specify. Repeated failures after completion while adopted hosts still name an earlier dead releaser need a separate explicit coverage witness before claiming tolerance of that failure sequence; this plan does not quietly substitute local disk durability for surviving machine loss. Pool-restricted receivers cannot complete another pool's duties; unsupported scopes retain evidence and alert. Permanent object loss/EC2 evidence aged out is an operator fault, never guessed termination. Drain acceptance and group-wide liveness wait for their real producers and drills. |
| + |
| +## Self-review record |
| + |
| +Coverage: §7.1–7.3 → B1/B2, with native-sidecar gap made explicit in S/B6; §7.4/I3 → B2/B4/B5; §4 identity/home scope → B3; §9/N-HA9/N-HA11 → B3/B4; §18 → counted event/pass/quiet formulas; §19 → T first visible merge and activation slot; §20 → B5 and card; §21 → I6 mutations and real process witnesses. P3 receives a provider-neutral, independent lifecycle interface with no drain dependency. Review Focus cases have named tests. Code/file citations were read at 9a064ebe. Planning validation is file/citation/format/diff checks only; no full suites, production code, reviewers, push or live drill. |