Merge remote-tracking branch 'origin/main' into g6-fence
# Conflicts: # internal/provision/testdata/plan14-root-reads-chain.tsv
33 files changed,
+1,576
−75
docs/superpowers/notes/census-proposal-ha-unclean-files-only.md+19 −0docs/superpowers/notes/census-proposal-ha-unclean-marker-waits.md+19 −0docs/superpowers/reviews/ASTRA-BRIEF-ha-unclean-containment.md+55 −0docs/superpowers/reviews/ASTRA-FINDINGS-ha-unclean-containment-R1.md+45 −0docs/superpowers/reviews/ASTRA-FINDINGS-ha-unclean-files-only.md+17 −0docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md+14 −4docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md+383 −0docs/superpowers/specs/ASTRA-FINDINGS-edge-ppv2-R1.md+75 −0docs/superpowers/specs/ASTRA-FINDINGS-edge-ppv2-R2.md+52 −0docs/superpowers/specs/ASTRA-FINDINGS-edge-ppv2-R3.md+69 −0docs/superpowers/specs/CODEX-REVIEW-BRIEF-edge-ppv2.md+79 −0internal/activator/haadopt.go+7 −0internal/activator/haadopt_test.go+17 −4internal/activator/hadrainmove_linux_test.go+60 −0internal/activator/harelease.go+6 −1internal/activator/harelease_test.go+9 −3internal/hafresh/acquire.go+33 −20internal/hafresh/acquire_test.go+90 −9internal/hafresh/lock.go+38 −0internal/hafresh/pools_test.go+1 −1internal/host/haplacement_budget_test.go+2 −2internal/lease/ha.go+5 −3internal/lease/ha_observe_test.go+1 −1internal/lease/lease.go+7 −1internal/lease/release.go+39 −12internal/lease/termination_proof_test.go+1 −1internal/lease/unclean_marker_test.go+399 −0internal/provision/testdata/plan14-root-reads-chain.tsv+2 −1internal/provision/testdata/plan14-root-reads-ha-unclean-files-only.tsv+7 −0internal/provision/testdata/plan14-root-reads-ha-unclean-marker-waits.tsv+7 −0internal/sim/regionha/actions_test.go+10 −9internal/sim/regionha/duties_model_test.go+1 −1internal/sim/regionha/witness_test.go+7 −2
Intent
Attributed to this commit: 21.9 g CO₂e (2,761,548 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on g6-fence, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/docs/superpowers/notes/census-proposal-ha-unclean-files-only.md b/docs/superpowers/notes/census-proposal-ha-unclean-files-only.md| new file mode 100644 |
| index 000000000..f904b9d4f |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-ha-unclean-files-only.md |
| @@ -0,0 +1,19 @@ |
| +# Census approval: ha-unclean-files-only |
| + |
| +Ruling `census-ruling-ha-unclean-files-only`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `internal/activator/harelease.go` `Service.releaseHAClean` | body | unchanged (7) | Sets the marker field finalized from the errors of Final and Finish it already computes, before the record and marker writes it already makes. No new read, write or path. | |
| + |
| +Envelopes re-pinned: `internal/activator`, `internal/hafresh`, `internal/lease`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
| + |
| +Recorded dispositions, which each change must still satisfy: |
| + |
| +- `internal/activator/harelease.go` `Service.releaseHAClean`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: an HA entry's release, in order: host slice read empty through haHostEmpty (else errHostSliceUnproven and nothing written; the same check, moved into that helper by final fix F1), stop and join the files publisher, its final publish (2 min budget), the replica's final sync (Finish, 30 s), the local release record, then the release marker PUT (10 s), clean only when the final publish was complete and the sync and record succeeded; a failed PUT is a persisted lease obligation; +registry:Host, +whole:Route x4;rev3=census-ruling-region-ha-p1b3b-t;basis=Record advisory local-release basis only after ReleaseMarker succeeds. Add a whole-route argument to local duty bookkeeping; release order and lease authority unchanged.;rev3=census-ruling-region-ha-g2-fixes;basis=Latch unexpected lease loss before release and mark intentional release so ErrSpent alone is not treated as loss; no new read.;rev3=census-ruling-region-ha-graceful-terminate-t2;basis=Cap Final, Finish and marker contexts by the shutdown deadline and reserves; keep calls synchronous and stop proof unchanged; record successful marker completion under the service mutex. No read added.;rev3=census-ruling-region-ha-held-build;basis=region HA held-requests Task 5: records the written marker's clean flag on the entry (haReleaseClean) beside haReleased, for the drain report; no read added;rev3=census-ruling-held-move-speed;basis=reads the entry's drainRelease flag under a.mu; for the drain's release calls the replica's FinishSnapshot (final sync, then a litestream snapshot at the final position, before the store's close; the snapshot reader pipe is closed on every outcome) instead of Finish, and logs a snapshot failure naming rt.Host (+registry:Host, the supplied route); marker order, budgets and clean rule unchanged; no new read;rev3=census-ruling-retry-after-503;basis=records four time.Now stamps and logs per-phase durations (files, sync, record, marker) on the existing marker log line; order, budgets and clean rule unchanged; no read added |
| + |
| +Seal: `821598970e60a776d4a62138d5adbfa393cd30bc1ec1f266d290e5b6d4e12c42` → `bc138ce5435f3ab37f6adff46656eea1c20f48168c569550fe94e390c69ba309`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-ha-unclean-files-only.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/notes/census-proposal-ha-unclean-marker-waits.md b/docs/superpowers/notes/census-proposal-ha-unclean-marker-waits.md| new file mode 100644 |
| index 000000000..e8472c262 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-ha-unclean-marker-waits.md |
| @@ -0,0 +1,19 @@ |
| +# Census approval: ha-unclean-marker-waits |
| + |
| +Ruling `census-ruling-ha-unclean-marker-waits`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `internal/activator/haadopt.go` `Service.AdoptHost` | body | unchanged (85) | Defers adoption, before any import, while the observed lock is an unclean release marker that is not settled and younger than a lease term (hafresh.MarkerOpensAt). No new read: it inspects the lock view the unit already read. Only adds a refusal. | |
| + |
| +Envelopes re-pinned: `internal/activator`, `internal/hafresh`, `internal/lease`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
| + |
| +Recorded dispositions, which each change must still satisfy: |
| + |
| +- `internal/activator/haadopt.go` `Service.AdoptHost`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=Serialize through the existing host operation state. Read local route/revision/receipt plus configured lock/manifest/wake objects; use only restricted ordinary acquire, exact guarded restore, ordinary unclean release and verified readback for adoption. No process launch, local-copy reuse or secret access. B3: pass the optional shared durable termination proof adapter into the existing restricted finalizer acquire. The adapter validates the exact classified peer and current host lifetime, uses the acquire data-bucket client, and cannot bypass expiry or CAS. No new read in this unit. B4: A first scanner import may reuse its staging lock observation; the ordinary acquire still rereads and compares the exact ETag/generation and expiry. Existing receipt replay keeps its fresh read. No new read path or takeover authority.;rev3=census-ruling-region-ha-followups;basis=Attach a per-acquire termination proof observer to finalizer acquisitions so refusals retain alarms; avoid duplicate fallback observations. The observer receives the existing route and departure ref for paging; no new storage read or takeover authority.;rev3=census-ruling-region-ha-g2-fixes;basis=Require local pool eligibility at entry and in HA acquisition proofs; supplied route only; termination, lifetime and emptiness checks remain. |
| + |
| +Seal: `55d66980f8db645c762b56e20b5eabba09d8e1f2ab79de5e089ff087ad677bc3` → `821598970e60a776d4a62138d5adbfa393cd30bc1ec1f266d290e5b6d4e12c42`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-ha-unclean-marker-waits.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/reviews/ASTRA-BRIEF-ha-unclean-containment.md b/docs/superpowers/reviews/ASTRA-BRIEF-ha-unclean-containment.md| new file mode 100644 |
| index 000000000..66fe78579 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/ASTRA-BRIEF-ha-unclean-containment.md |
| @@ -0,0 +1,55 @@ |
| +# Astra review brief: region HA containment, unsettled release markers wait a lease term |
| + |
| +Repo worktree: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/ha-unclean, branch |
| +ha-unclean-marker-waits, commit 08aed1c1 on origin/main ae1b8cca. Review `git diff ae1b8cca..08aed1c1`. |
| +Code and spec reading only: no edits, no pushes. If you build or test, leave GOCACHE unset. One round. |
| + |
| +## Background |
| +Your own wake-race review (~/.cache/ha-flakes/wake-race/FINDINGS.md, P1 B) found that an unclean HA |
| +release lets a successor take the lock at once, restore to P, and write its own L0 [P+1..P+1] into the |
| +shared prefix, while the old holder's timed-out upload of the same key can still be applied by S3 and |
| +replace it. Paul ruled (2026-11-12): containment now, storage generations later (designed separately, |
| +not in scope here). The containment brief: "an UNCLEAN release marker no longer allows immediate |
| +takeover. Successor waits until the lock's expiry exactly like the expired-owner rows; clean markers |
| +unchanged (held requests' fast handover depends on them)." |
| + |
| +## What the commit does (verify it; do not trust it) |
| +- hafresh.Marker gains `settled` (omitempty). Settled = no replica write outstanding: the replicator's |
| + finalization (final sync + store close) succeeded, or nothing replicated under the lease. |
| +- hafresh.DecideAcquire takes a lease term. Clean or settled marker: take. Unsettled: ActHeld (reason the |
| + marker owner, Decision.Until = At + term) until now > At + term, then take. No termination proof for |
| + markers. A marker with zero At is treated as open (every production marker has At; many test fixtures |
| + lack it). The author chose At + term over recording the lease's ExpiresAt: At is stamped after |
| + finalize, so it bounds every send time, and it does not depend on renewer health. |
| +- Writers: Replicator.ReleaseMarker (settled = finalize err nil), closeHA (same), Held.Release and |
| + Held.ReleaseMarker (settled unless the handle built a store: new Held.stored set in newStore), the |
| + acquire's late-ack cleanup (settled). activator.releaseHAClean goes through Replicator.ReleaseMarker. |
| +- AcquireHA's HeldError.ExpiresAt is Decision.Until (Retry-After). Adoption (haadopt.go) defers on an |
| + unsettled marker before importing. Spec rev 6.7 (§5.2, §9.4, §9.8, §9.9). The sim models settled. |
| +- Tests: internal/hafresh/acquire_test.go (table, JSON), internal/lease/unclean_marker_test.go (settled |
| + paths taken at once; unsettled held then taken; the HA late-write witness), activator haadopt cases. |
| + |
| +## Questions, in order |
| +A. Does the rule close the containment's intent: no successor (any box, same box included, adoption |
| + included) creates a new history in the shared prefix while a write the old holder sent before its |
| + marker could still land, up to the N-HA9 margin? Walk every marker writer and every acquire path |
| + (AcquireHA, AcquireHAForDuty, adoption, the drain's take, haplacement/forwarding, legacy readers that |
| + read markers as free). Is any path still taking an unsettled marker early, or marking settled when a |
| + write may be in flight (e.g. Store.Close's cancelled monitor passes on a "successful" finalize; a |
| + failed Replicate; Checkpoint; files and wake-state publishes under the lease)? |
| +B. Is At + term the right bound vs the lease's ExpiresAt or the S3 object's Last-Modified? Clock skew, |
| + a marker obligation retried much later (owed.go, RetryPending: is At the time of the first attempt?), |
| + a far-future At, zero At. |
| +C. Availability: what newly waits 15 minutes in normal operation? Which unclean releases are settled |
| + (files incomplete, failed wakes) and which are not? Is ActHeld with the marker owner handled sanely |
| + by callers (errLeaseHeld, haforward's holder header, held requests §25, the coordinator, the suspect- |
| + holder observer, wakefaillog)? Retry storms? |
| +D. Mixed fleet and rollout: old binaries ignore `settled`; new binaries read old markers as unsettled. |
| + Anything that strands a host or loops? |
| +E. G6's write fence deliberately produces unclean releases (a fence trips, the holder stops). How do the |
| + two combine: time to recover after a fence trips, and is anything worse than "15 minutes down"? |
| +F. Tests: do they witness the rule (would a regression be caught)? Anything important untested? |
| + |
| +## Output |
| +Findings with P1 / P2 / P3 severities and file:line citations. Answer A-F in order, each with a short |
| +verdict line first. Be concise. |
diff --git a/docs/superpowers/reviews/ASTRA-FINDINGS-ha-unclean-containment-R1.md b/docs/superpowers/reviews/ASTRA-FINDINGS-ha-unclean-containment-R1.md| new file mode 100644 |
| index 000000000..df612f323 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/ASTRA-FINDINGS-ha-unclean-containment-R1.md |
| @@ -0,0 +1,45 @@ |
| +Static review of `ae1b8cca..08aed1c1`: **one P1 and one P2**. No files changed; no tests run. |
| + |
| +**A. P1 — successful finalization does not prove `settled`.** |
| + |
| +**Fault family: completion of the previous holder’s storage requests.** `ReleaseMarker` sets `Settled = err == nil`, and `closeHA` does the equivalent. However, Litestream’s `Store.Close` cancels background requests, joins their goroutines, and returns database-close errors—not the outstanding requests’ server-side outcomes. An unclean release can therefore carry `settled:true` while a cancelled snapshot, compaction or retention request can still land. The successor immediately acquires and starts using the same prefix. This bypasses the requested containment even within the lease-term margin. See [release.go:304](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/ha-unclean/internal/lease/release.go:304), [release.go:328](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/ha-unclean/internal/lease/release.go:328), and [Litestream store.go:236](/home/paulca/go/pkg/mod/github.com/benbjohnson/litestream@v0.5.14/store.go:236). |
| + |
| +**Fix:** preserve the explicitly required clean-marker exception, but make replicated **unclean** releases wait unless completion is actually established. A successful final sync alone cannot grant that exception. |
| + |
| +For markers correctly classified as unsettled, the acquisition paths are sound: ordinary acquire, duty acquire, same-box recovery and drain take share the decision table; adoption also checks before importing. Placement and forwarding supply routing advice, not acquisition authority. Current legacy acquisition refuses HA markers. Failed `Replicate` and `Checkpoint` releases conservatively remain unsettled. |
| + |
| +Files and wake state need a distinction: object uploads use immutable keys and manifest publication uses compare-and-swap, so they do not share the unconditional L0 overwrite mechanism. Nevertheless, a timed-out files publication can remain outstanding despite successful replica finalization; `settled` does not establish completion of all lease-scoped writes. See [publisher.go:199](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/ha-unclean/internal/hostfiles/publisher.go:199) and [publisher.go:342](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/ha-unclean/internal/hostfiles/publisher.go:342). |
| + |
| +**B. Verdict — `At + term` is a reasonable mitigation under the existing clock assumptions.** |
| + |
| +Production callers stamp `At` after finalization. Unlike the previous lease expiry, it therefore leaves a whole nominal term after the last possible send. Obligation retries preserve the original body and timestamp; a delayed retry should not restart that interval. See [release.go:58](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/ha-unclean/internal/lease/release.go:58) and [owed.go:284](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/ha-unclean/internal/lease/owed.go:284). |
| + |
| +This remains a clock-dependent margin, not a completion guarantee. Allowed opposing clock offsets can shorten it by roughly four seconds. A far-future `At` extends the outage without a cap; zero `At` explicitly bypasses the wait. Existing production writers supply timestamps, but missing timestamps should ideally fail closed rather than receive a production exception for test fixtures. See [lock.go:43](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/ha-unclean/internal/hafresh/lock.go:43). |
| + |
| +**C. P2 — clean releases now prevent pool withdrawal from completing.** |
| + |
| +**Fault family: agreement between local and remote release evidence.** `releaseHAClean` writes the local record with `Settled == false`; `Replicator.ReleaseMarker` changes its private copy to `true`. Pool withdrawal compares the complete markers, finds them different, then rejects the fallback because the remote marker still names this box. A normally sleeping host can consequently remain pending indefinitely unless another owner acquires it. See [harelease.go:223](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/ha-unclean/internal/activator/harelease.go:223), [release.go:304](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/ha-unclean/internal/lease/release.go:304), and [poolwithdrawal.go:190](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/ha-unclean/internal/activator/poolwithdrawal.go:190). |
| + |
| +**Fix:** construct consistent release evidence before writing either record, or explicitly define which fields withdrawal compares. Add a real-release-to-withdrawal regression test. |
| + |
| +The intended new waits cover failed finalizations, abandonment, and releases after building a store—including successful checkpoints. Pre-replication failed wakes and adoption remain immediate. Files-only failures remain immediate under the current implementation. |
| + |
| +`HeldError` carries the correct deadline. Marker owners fail `ParseOwner`, so forwarding reports no holder rather than redirecting to the releaser. Resident pacing uses the deadline. Background duties, however, only persist `NotBefore` for owner locks, and lease-loss recovery retries every ten seconds: these continue probing during the wait. See [haduties.go:315](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/ha-unclean/internal/activator/haduties.go:315). |
| + |
| +**D. Verdict — compatible encoding, incomplete containment during rollout.** |
| + |
| +Old binaries still take these markers immediately. New binaries wait on old unclean markers with timestamps; old clean markers remain immediate. The added field does not itself create an acquisition loop, but containment cannot be claimed fleet-wide until every possible acquirer is upgraded. `expires_at` remains 1970, so expiry-only readers also receive no protection. See [lock.go:76](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/ha-unclean/internal/hafresh/lock.go:76). |
| + |
| +**E. Verdict — recovery is not bounded by “15 minutes down.”** |
| + |
| +If G6 stops the holder and finalization fails, recovery waits until **15 minutes after `At`**, then still needs acquisition and restore. Stopping and finalization precede that timestamp. If the marker cannot be published, the existing expired-owner rules apply; another box still needs termination proof. Conversely, merely setting `Clean=false` does **not** guarantee a wait because of A. |
| + |
| +G6’s implementation is outside this reviewed commit; these are the integration conditions it must satisfy. |
| + |
| +**F. Verdict — the new tests witness the failed-final-sync case, but miss the exemptions.** |
| + |
| +The delayed-write test checks immediate refusal, lets the old write land inside the term, then verifies restored successor data. Removing the wait would fail it. See [unclean_marker_test.go:250](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/ha-unclean/internal/lease/unclean_marker_test.go:250). |
| + |
| +Missing coverage: successful finalization with an outstanding monitor request; real clean release followed by pool withdrawal; failed `Replicate`/checkpoint releases; delayed obligation replay preserving the deadline; and uncertain files/wake publication. |
| + |
| +**NOT READY — P1 A remains; P2 C also needs correction.** |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/ASTRA-FINDINGS-ha-unclean-files-only.md b/docs/superpowers/reviews/ASTRA-FINDINGS-ha-unclean-files-only.md| new file mode 100644 |
| index 000000000..f3473b81b |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/ASTRA-FINDINGS-ha-unclean-files-only.md |
| @@ -0,0 +1,17 @@ |
| +**P1: none found.** |
| + |
| +- **P2 — missing test for the files-error boundary.** [hadrainmove_linux_test.go:32](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/ha-files/internal/activator/hadrainmove_linux_test.go:32) covers incomplete-tree success, but no activator test proves a failed final object/manifest PUT leaves `Finalized=false` and blocks acquisition. Removing `ferr == nil` at [harelease.go:229](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/ha-files/internal/activator/harelease.go:229) would escape the added coverage. Add that negative case, including a timed-out publication. |
| + |
| +- **P3 — “none is outstanding” overstates the guarantee.** [Design:199](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/ha-files/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md:199). After an uncertain earlier PUT, refresh can read the old manifest; `Final` can then succeed through `Commit`’s no-op at [publisher.go:327](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/ha-files/internal/hostfiles/publisher.go:327). Earlier requests can remain outstanding. Clean releases share this exposure; describe equivalence rather than completion. |
| + |
| +- **P3 — other APIs preserve caller-supplied `Finalized`.** [release.go:174](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/ha-files/internal/lease/release.go:174) clears `Clean` but not `Finalized` on `Held.ReleaseMarker`; `uncleanMarker` also preserves it from `base`. A checkpointed handle supplied `Finalized:true` bypasses the wait. **No current production caller supplies it through these paths.** Clear it defensively and test that case. |
| + |
| +**A:** The current production path has the same storage exposure as a clean release, under Paul’s accepted exception. Publisher shutdown joins both passes; files, wake state and sealed escrow use immutable objects plus conditional manifest publication. I found no additional outstanding-write hazard unique to finalized-but-unclean releases. |
| + |
| +**B:** Successful local records still match remote markers: `Finalized` is set before recording, and replica finalization returns its cached result. Unclean or failed-record releases remain ineligible for pool withdrawal. |
| + |
| +**C:** Positive acquisition and abandonment coverage is useful; the files-error boundary needs the P2 test. |
| + |
| +Static review only; no edits or tests run. |
| + |
| +**READY AFTER FIXES** — address P2 within this round; P3s are follow-ups. |
| \ No newline at end of file |
diff --git a/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md b/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md| index 4f993ba5c..c8fcf5799 100644 |
| --- a/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md |
| +++ b/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md |
| @@ -1,6 +1,6 @@ |
| # Region HA without claims: N-box regions behind a load balancer |
| -Design, 2026-10-26, **rev 6.6** (§25 held requests during a planned handover, 2026-11-08, APPROVED by Paul 2026-11-08 ~22:15Z as r4 (§25.15); Astra rounds 1-3 spent, no fourth round; rev 6.5 added §7.5 DR-5): rev 6 APPROVED by Paul on 2026-10-26, plus his ruling N-HA7 the same day (a scope ruling, not a redesign: §2.1, §8.4, §13, §19). Astra rounds 1 to 3 are complete, and the review budget is spent (AGENTS.md, stopping rules). Branch `design-region-ha-no-claims`, cut from `origin/main` at ddf3b929. Nothing here is built. |
| +Design, 2026-10-26, **rev 6.8** (rev 6.8: finalized files-only releases open at once; rev 6.7: the unsettled-marker wait, Paul's containment ruling 2026-11-12; §25 held requests during a planned handover, 2026-11-08, APPROVED by Paul 2026-11-08 ~22:15Z as r4 (§25.15); Astra rounds 1-3 spent, no fourth round; rev 6.5 added §7.5 DR-5): rev 6 APPROVED by Paul on 2026-10-26, plus his ruling N-HA7 the same day (a scope ruling, not a redesign: §2.1, §8.4, §13, §19). Astra rounds 1 to 3 are complete, and the review budget is spent (AGENTS.md, stopping rules). Branch `design-region-ha-no-claims`, cut from `origin/main` at ddf3b929. Nothing here is built. |
| This spec supersedes every claim-dependent part of "Region HA, spec 2: two-box regions" (`2026-10-15-region-ha-two-box-regions-design.md`, rev 21, cited **S2 §n**) and of spec 1 (`2026-10-04-region-ha-box-placement-design.md`, cited **S1 §n**). §16 lists what it reuses from S2, plan 2a (6834659c) and plan 2b (b1118925), and the removals this series owns. Line citations are to this worktree unless they name a module path. |
| @@ -14,6 +14,8 @@ This spec supersedes every claim-dependent part of "Region HA, spec 2: two-box r |
| - **Rev 6.4** records T1/DR-4 planned termination: shutdown ordering, release budgets and the real-terminate witness (§9.9, 2026-11-08). |
| - **Rev 6.5** records DR-5: a departure finishes when no surviving box serves a departed box's pool, and departures finish within 3 minutes of proof (§7.5, 2026-11-08). |
| - **Rev 6.6** adds §25: a planned member replacement (terminate, roll, resize, scale-in) holds requests for a few seconds instead of answering 503. Unplanned deaths are unchanged. Not built; Paul approves before any build. |
| +- **Rev 6.7** (2026-11-12, Paul's containment ruling in the HA session, after the wake-race review's P1): an unclean release after replication no longer allows immediate takeover. Its marker is not *settled*, and every box waits a lease term from the marker's time (§5.2, §9.4, §9.8, §9.9). Built on branch `ha-unclean-marker-waits`; storage generations, the fix, are designed separately (`2026-11-12-region-ha-storage-generations-design.md`). |
| +- **Rev 6.8** (2026-11-12, follow-up): an unclean release whose replica finalization and files commit both succeeded (only the tree was incomplete, or the local record failed) is *finalized* and opens at once (§5.2): files cannot collide like L0, and its exposure is a clean marker's. |
| Under stopping rule 2, the families I2, I3 and I4 drew findings two rounds running. I2 and I4 are now stated as invariants, enforced in one place and checked by the simulation (§3.1). I3 drew a P1 in all three rounds, so rev 6 cuts its transfer protocol and restates I3 over the scan alone. |
| @@ -190,7 +192,12 @@ So old binaries and non-HA boxes see a marker as a released lease. |
| - **Expiry never discharges the obligation.** It ends only on success, or on a 412 (someone else has the lease now). |
| - Until then the host stays unacquirable by other boxes, which is safe. |
| - **What `clean` means** (astra-1.4 r2). The marker is `clean: true` only if the final sync succeeded and the final files publish was complete: no entry skipped or unreadable (`internal/hostfiles/sync.go:126-175`). |
| - - Otherwise it is written with `clean: false`. Another box may then acquire, nobody keeps a local copy, and writes or files that did not reach S3 are lost. |
| + - Otherwise it is written with `clean: false`. Nobody keeps a local copy, and writes or files that did not reach S3 are lost. |
| +- **What `settled` means** (rev 6.7, 2026-11-12). The marker records `settled: true` only when the releasing holder never replicated under the lease: a failed wake before replication, an acquire's late-acknowledgement cleanup, an adoption. A holder that replicated never writes it, even after a final sync that succeeded: Litestream's store close cancels its monitors' compaction, snapshot and retention requests without proving S3 did not receive them (Astra containment review R1 P1). |
| + - An unclean marker that is not settled may have an upload in flight that S3 applies after the marker, into the very prefix and TXID range the successor writes next. That is the wake-race review's P1: the late object replaces the successor's, and history diverges silently. |
| + - So such a marker opens only a lease term (`LeaseTTL`, 15 minutes) after its `at`, for every box, the releaser's own included (§9.4). `at` is written after the finalization returns, so every request the holder sent was sent before it, and each has had at least the margin N-HA9 gives a dead owner's writes. An owed marker keeps its first `at` when it is retried. A clean marker opens at once whatever it says, by Paul's ruling: the drain's fast handover (§25) stays. It carries the same monitor exposure; storage generations close it (`2026-11-12-region-ha-storage-generations-design.md`). |
| + - **Finalized** (rev 6.8, 2026-11-12). An unclean marker also records `finalized: true` when the release's replica finalization and its final files commit both succeeded, so that it is unclean only for a local reason: a files tree that could not be published completely (a file over the size limit, an unreadable or non-regular entry), or a release record that could not be written. Its storage exposure is then exactly a clean marker's, and it opens at once like one. Files cannot collide the way an L0 can: each object is written create-only under `objects/<seq>-<sha256>`, and the manifest moves only by compare-and-swap, so a late files write either fails its condition or makes the successor's next commit fail loudly (`ErrSuperseded`). A finalized release's exposure is therefore the same as a clean release's, not none: an earlier uncertain manifest PUT can still be outstanding after a final commit that had nothing new to write, exactly as in a clean release (Astra files-only review P3). A host whose files are never complete therefore keeps the drain's fast handover. Only `releaseHAClean` sets `finalized`; every other release path clears it. |
| + - A marker written before the field reads as not settled. Old binaries ignore the field and still take every marker at once, so the containment holds only once every box of a pool runs it. |
| - A host whose last marker is not clean is not ready for retirement (§13). |
| - If S3 is unreachable, no marker is written. The lease stays held until it expires, and then only this box may take it again (§9.4). |
| @@ -440,7 +447,8 @@ On an HA box, the lease package's acquire reads first: one GET of `lock.json` wi |
| | Lock state | Action | |
| |---|---| |
| | Absent | Create, with `If-None-Match: *`. | |
| -| A release marker, clean or not | Conditional PUT, with `If-Match`. | |
| +| A release marker, clean, settled or finalized | Conditional PUT, with `If-Match`. | |
| +| A release marker, unclean, neither settled nor finalized (§5.2, rev 6.7, 6.8) | Held, naming the marker, until its `at` plus the lease term; then a conditional PUT. No termination proof applies: the releaser usually lives, and a proof would not stop a request S3 already has. | |
| | Held and unexpired | A held answer naming the owner (§6.2). | |
| | Expired, owner is this box's instance id | Conditional PUT, only with the emptiness proof of §9.6. Otherwise refused. | |
| | Expired, owner confirmed terminated (§9.2, N-HA9) | Conditional PUT: the takeover. A terminated owner's unexpired lock is held until it expires, because a write the dead process already sent can still land. | |
| @@ -490,6 +498,7 @@ These are estimates; dev measures each one (§21). |
| | First request: acquire, describe, takeover, restore | about a second, plus the restore | the same | |
| | **Total, request-driven instances** | **about 1 to 3 min** | **about 2 to 5 min** | |
| | Until storage fencing (N-HA9) | takeover also waits for the lease to expire, so the totals above are up to about 15 minutes after the last renewal | the same | |
| +| After an unclean release that replicated and was not finalized (§5.2, rev 6.7 and 6.8) | no box takes the host until 15 minutes after the marker: a release whose final sync or files commit failed costs that host a lease term | the same | |
| | Always-on workers, ticks, due wakes | one sweep (30 s or less) after confirmation; backoffs cancelled | the same | |
| | Worst case, event lost | the next request's dial failure confirms at once; with no requests, view ageing (15 min) | the same | |
| @@ -537,7 +546,8 @@ marker guarantee. |
| The single-writer rule holds on timeout too: no marker until every host |
| writer is proven stopped, the publisher is joined, and `Final` and `Finish` |
| have returned. Bounded completion with a durability error can produce an |
| -unclean marker. A stuck finalizer produces no marker; takeover still needs |
| +unclean marker, and the host then waits a lease term before any box takes |
| +it (§5.2, rev 6.7). A stuck finalizer produces no marker; takeover still needs |
| lease expiry plus owner termination proof (§9.4 unchanged). A deadline is |
| never proof that storage writes have stopped. |
diff --git a/docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md b/docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md| new file mode 100644 |
| index 000000000..afa7bb1d5 |
| --- /dev/null |
| +++ b/docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md |
| @@ -0,0 +1,383 @@ |
| +# PROXY protocol v2 on the region HA load balancers |
| + |
| +Design, 2026-11-12, **rev 5** (Astra rounds 1 to 3 applied, §12, §13 and §15. Round 3, the last, was NOT READY with one P1 in F1; its fix, the trust barrier, was **accepted without a fourth round by 8a3d302 on 2026-11-12** (§15). **APPROVED 2026-11-12** for build: Paul approved "PPv2 ... before G6"; no infra or live change without 8a3d302's GO and a #421 window. Earlier: round 2 repeated fault family F1, so under stopping rule 2 the choice went to Paul: **option A, one-way PROXY protocol, decided 2026-11-12** by agent manager 8a3d302 on Paul's standing acceptance of recommendations, Paul informed and free to override; §14). Rev 4 wrote A in; rev 5 applies round 3's P2s and proposes the barrier for its P1 (§4.7, §15). Agent manager 8a3d302 asked for it on 2026-11-12 with Paul's approval: client IP preservation off and PROXY protocol v2 on, on both target groups of each region NLB, before G6 opens the NLBs to customers. Design only; the build is a separate GO. Review budget: at most three Astra rounds (AGENTS.md stopping rules); all three rounds are spent. |
| + |
| +Line citations are to `origin/main` at ae1b8cca. AWS facts quote "Edit target group attributes for your Network Load Balancer" (docs.aws.amazon.com/elasticloadbalancing/latest/network/edit-target-group-attributes.html, read 2026-11-12) unless another page is named. |
| + |
| +## 1. The finding |
| + |
| +On the v0.34.46 flagship roll (2026-11-11), four requests through the US NLB died in the TCP connect: the SYN was never answered for 30 s, and no edge saw the connection (`~/.cache/lost-post/REPORT.md`). The best fit is a limit AWS documents ("Intermittent TCP connection establishment failure", NLB troubleshooting page): with client IP preservation on and cross-zone on, one client IP and source port can reach the same target through two NLB addresses, and the target sees one 4-tuple for two connections. A NAT that keeps source ports (docs-t1's, many office routers, some carrier NATs) makes this happen to ordinary clients. The user sees a connect that hangs 20 to 30 s. |
| + |
| +The 2026-11-12 drain experiment (`~/.cache/drain-syn/REPORT.md`) cleared the W6 drain and the NLB's handling of target changes, and left this limit as the open issue. It found PAWS counters on every target (PAWSEstab 10,716 on leo, 97,318 on sophie), which is what colliding 4-tuples produce. |
| + |
| +AWS lists four mitigations: more targets (lowers the odds), clients changing ports (not ours to change), cross-zone off, or client IP preservation off with the client address read from PROXY protocol v2. Cross-zone off is ruled out: the group spec needs it (2026-10-15 §A1-1; `group.tf` refuses an NLB without it) and US 1a has one target. |
| + |
| +Today on both NLBs (read 2026-11-12, `~/.cache/ppv2/aws/`): |
| + |
| +| | dev IE (`carlos-dev-ie-nlb`) | flagship US (`carlos-flagship-us-nlb`) | |
| +|---|---|---| |
| +| Targets in both TGs | leo, sophie (fixed), 2 members | adi (fixed), 2 members | |
| +| Node private addresses | 172.31.29.110 (1a), 172.31.11.189 (1c) | 172.31.3.3 (1a), 172.31.17.119 (1c) | |
| +| `preserve_client_ip` / `proxy_protocol_v2` | true / false on both TGs | true / false on both TGs | |
| +| Health checks | HTTP :80 `/.carlos/lb-health`, both TGs | same | |
| +| Peak new flows, 14 days | 1,203 a minute, NLB-wide | 198 a minute | |
| + |
| +## 2. What changes, in one paragraph |
| + |
| +Each target group stops preserving the client address and sends a PROXY protocol v2 header instead. The target then sees every NLB connection coming from one of the NLB's own private addresses, on a source port the NLB chose, so two client connections can never share a 4-tuple at the target. The edge learns the client address from the header. It reads a header as identity only on connections whose socket peer is one of its region NLB's private addresses, listed in a new host-env key; it rewrites the connection's remote address to the header's source before net/http sees it, so every reader of `r.RemoteAddr` downstream (rate limits, protection, geo, records, analytics, `X-Forwarded-For`) sees the client exactly as today. A header from any other peer is consumed and ignored. A trusted connection without a client address may only answer the health check. The cutover flips one attribute on one target group per step, through states where every target handles every new connection correctly, each forward step proven converged on every NLB node before the next. PROXY protocol is one-way: once on, it never goes off, so the one unsafe state (preservation off with PROXY protocol off) is never a step. The tooling refuses it, an alarm detects it for the whole armed lifetime, and a root barrier takes identity away from every connection it could have touched (§4.7). The price is stated in §7.3: once a target group has PROXY protocol on, no edge older than this release can run behind it again. |
| + |
| +## 3. Guarantee and invariant |
| + |
| +**The trust invariant.** A node address grants trust to the first header on a connection only because the NLB writes that header. That holds only while the target group has PROXY protocol on. With preservation off and PROXY protocol off (S3, §6.2) the node address still arrives as the peer, the NLB writes nothing, and a client's own header would be read as the NLB's: any client could choose its address, and that address reaches limits and the signed `X-Forwarded-For` (`homemap.go:1684-1718`, `forwardproof.go:44-51`). So **S3 is a security state, not a degraded one**. It is kept out by making PROXY protocol one-way: the only moves are S0 to S1, S1 to S2 and S2 to S1 (§6.2), none of which can pass through S3 however the NLB nodes disagree mid-change, and the step tooling refuses every other move (§6.3). S3 then needs someone to turn PROXY protocol off outside the tooling. That is detected for the whole armed lifetime, not only in a window, by the edge's trust-violation metric and its alarm (§4.5): in S3 every client that sends no header of its own is refused, so the metric is loud. The incident (§6.5) raises a trust barrier on every target, which closes trusted connections and keeps any later or half-parsed one from carrying an identity (§4.7), and then restores preservation. |
| + |
| +**Fixed:** with preservation off, two client connections through the NLB never share a 4-tuple at a target: the NLB allocates the source address and port toward each target, so the documented collision cannot happen. Hairpin connections through the NLB work too (AWS: "you can also prevent this type of connection error by disabling client IP preservation"), which removes the A21 limit (region HA spec 2026-10-26 §12.4). |
| + |
| +**Kept:** every request that reaches an edge through the NLB carries the same client address in `r.RemoteAddr` as it does today, in every state the cutover passes through (§6.2). Requests that do not come through the NLB (fixed boxes' own EIPs, cross-region backhaul to a member's public address, hop-signed forwards between boxes, the door, hairpin, tunnels) are unchanged, except that on an armed box the edge reads their first bytes before net/http does (§4.3). |
| + |
| +**Zero downtime is the target and is measured** (§10), as in W6. AWS states that preservation changes "take effect only for new TCP connections" and states nothing for PROXY protocol. The design assumes both apply only to new connections, because a header can only be the first bytes of a connection; the dev witness tests the assumption with connections held open across every step (§10 row 3) before the flagship relies on it. |
| + |
| +**Not covered:** |
| +- A target running an edge older than the release that carries this (vN) while its TG has PROXY protocol on. It answers the header with 400 or a TLS error, fails its health checks and leaves the target group: one lost target, not an outage, unless every target is old, when the NLB fails open to all of them. Refused up front by a box-side guard and by the release and roll checks: §7.3. |
| +- Real client addresses inside the NLB's own TCP layer (NLB logs, flow logs): unchanged, off. |
| + |
| +## 4. Edge parsing |
| + |
| +### 4.1 Which listeners |
| + |
| +The public `:80` and `:443` listeners bound in `Serve` (`internal/edge/edge.go:5295-5310`), on a box whose host.env carries `CARLOS_INGRESS_PROXY_SOURCES` (§4.2). Both, because both TGs flip and both TGs' health checks land on `:80` (`HealthCheckPort 80` on the `:443` TG today). The dev-mode single listener (`edge.go:5124-5139`), the door, the backhaul port, devbox listeners and the relay are never wrapped. |
| + |
| +A box without the key runs exactly today's listeners: no wrapper, no peek. That keeps every box that is not an NLB target (annie, Tito's boxes, self-hosters) out of the change, and it is the dormancy switch. |
| + |
| +The wrapper goes outermost, after `ConfigureGroupHairpin` (`edge.go:5303-5310`), so that `hairpinListener.Accept` (`internal/edge/hairpin.go:66-82`) still classifies the raw socket and never blocks on a header. `hairpinConnContext` (`hairpin.go:84-92`) unwraps the new connection type before its type assertion (one `NetConn()`-style accessor, the same shape as `tls.Conn.NetConn`), and a test pins that a hairpin connection through the wrapped listener keeps its normalisation (`normalizeHairpin`, `hairpin.go:93-110`). |
| + |
| +### 4.2 The trust rule |
| + |
| +`CARLOS_INGRESS_PROXY_SOURCES` is a comma-separated list of 1 to 16 IPv4 addresses: the region NLB's node private addresses, one per enabled zone (two today). It is a new `Optional` host-env key (`internal/hostenv/hostenv.go:75`), validated at write and seed like `CARLOS_INGRESS_TARGET_GROUPS` (`hostenv.go:255-282`): each entry a private (RFC 1918) IPv4 address, no duplicates. The edge reads it once at start; a change takes an edge restart (drained on fixed boxes by W6, on members by the group roll). |
| + |
| +A connection is **trusted** when its socket peer address (the kernel's, before any rewrite) is in the list. Nothing else makes it trusted: not the destination, not a header, not the VPC CIDR. The VPC CIDR is not enough because target security groups admit 443 from the VPC (`infra/modules/region-host/group.tf:150-156`) and tenant code runs on boxes in that VPC; a tenant could otherwise send a header from a box's private address and choose its client address, which reaches other tenants' apps as `X-Forwarded-For`. VPC source/destination checks stop a box sending from an NLB node's address. |
| + |
| +Trust is also conditional on the NLB writing the first header (§3): the list says who may speak, the target group attribute says that it does. The edge cannot check the second half, so §6 owns it. |
| + |
| +Where the addresses come from: tofu reads the NLB's network interfaces and outputs their private addresses (§8.1). They are fixed for the NLB's life and change only if a zone is added to the NLB; §4.5's `ignored_private` counter catches a list that is out of date. |
| + |
| +### 4.3 Reading the header |
| + |
| +The wrapper's `Accept` returns at once; nothing is read on the accept goroutine. Each wrapped connection owns a parse state: pending, then exactly one of `proxied` (header source), `no-client` (LOCAL, UNSPEC or no header on a trusted connection), `plain` (untrusted), or failed (closed). The state resolves once, on the connection's own goroutine, at the first of `Read` or `RemoteAddr`. |
| + |
| +net/http calls `RemoteAddr` first thing in `conn.serve` (`$GOROOT/src/net/http/server.go:1908`, Go 1.26.10), before any deadline or read of its own, and `tls.Conn.RemoteAddr` delegates to the wrapped connection (`crypto/tls/conn.go:136`). So the state is resolved before net/http or TLS read a byte, and before any handler runs. `ConnContext` runs earlier, on the accept goroutine (`server.go:3474-3476`): it stores a pointer to the connection's parse state in the context and reads nothing. Handlers read the resolved state through that pointer; a handler that finds it pending is a bug, and a test pins that it cannot happen through `Serve` and `ServeTLS` (HTTP/1.1 and HTTP/2). `ConnState` hooks and the existing `ConnContext` hooks (hairpin, `connDrain.serve` at `internal/edge/hadrainconns.go:152-165`) must not call `RemoteAddr`; a test pins that a silent trusted connection does not delay the accept of the next one. |
| + |
| +Untrusted connection: `RemoteAddr` answers the socket peer at once. On the first `Read`, the wrapper reads up to 12 bytes, stopping at the first byte that differs from the PPv2 signature (`\r\n\r\n\0\r\nQUIT\n`). HTTP and TLS both differ at byte 0, so this is one read. A mismatch replays the bytes read to the caller. A full signature means a header: §4.4. |
| + |
| +Trusted connection: the first `RemoteAddr` or `Read` reads the same way, under a read deadline of 10 s from accept (the listeners' `ReadHeaderTimeout`, `internal/edge/ingressdrain.go:92-93`), then clears that deadline. The design does not depend on whether the NLB sends the header at connect or with the client's first bytes ("prepends a proxy protocol header to the TCP data"). A timeout closes the connection. |
| + |
| +`Close` never waits for the parse: it closes the socket without taking the parse lock, which fails a pending read at once. So `Server.Shutdown` (which closes `StateNew` connections older than 5 s, `server.go:3227-3230`) and W6's `CloseIngress` (`ingressdrain.go:121`) end a connection still waiting for its header as they end one waiting for request headers today. Tests cover a silent and a partial header through both. |
| + |
| +v1 (text) headers are never parsed: the NLB sends only v2. A client that sends `PROXY TCP4 ...` gets today's 400. |
| + |
| +### 4.4 What each header does |
| + |
| +| Peer | First bytes | Parse state and result | |
| +|---|---|---| |
| +| trusted | PPv2, command PROXY, family INET or INET6, a usable source (below) | `proxied`: remote address = header source address and port | |
| +| trusted | PPv2, command LOCAL, or PROXY with family UNSPEC | `no-client`: remote address = socket peer; health check only (§4.6). AWS health checks carry this: "the client connection information is not sent" | |
| +| trusted | no PPv2 signature | `no-client`, as above. Before step A (§6.2) this is every health check; after it, only S3 produces it | |
| +| trusted | PPv2, malformed or over the limits | connection closed | |
| +| untrusted | PPv2, well formed | `plain`: header consumed and ignored; remote address = socket peer. Needed in S1 (§6.2), where the peer is the client itself | |
| +| untrusted | PPv2, malformed | connection closed | |
| +| untrusted | anything else | `plain`, unchanged | |
| + |
| +Limits and checks: version nibble 2; command LOCAL or PROXY; family and protocol INET/STREAM, INET6/STREAM or UNSPEC; the declared length at least the address block (12 bytes for INET, 36 for INET6) and at most 512 bytes in total, TLVs included. TLVs are skipped unread (AWS sends `PP2_TYPE_AWS` 0xEA only for PrivateLink). A usable source is a unicast address that is not loopback, unspecified, link-local or multicast; anything else closes the connection (a real NLB cannot send it). Exactly one header is consumed. AWS: the NLB "does not discard or overwrite ... any incoming proxy protocol headers sent by the client", so in S1 and S2 a client's own header after the NLB's reaches net/http as payload and fails as today. The forgery probe (§6.4) relies on this. |
| + |
| +The header's destination address and port are not used. |
| + |
| +### 4.5 Counters |
| + |
| +Per listener and, for trusted connections, per node address, since start: `proxied`, `no_client`, `no_client_refused` (§4.6), `ignored` (untrusted header consumed), `ignored_private` (untrusted header from a private address: almost certainly an NLB node missing from the key), `marker_trusted` (§6.4), `malformed`, `timeout`. One journal line at start (`edge: proxy protocol: armed on :80 and :443, trusting 172.31.29.110,172.31.11.189`), and one throttled line every minute while armed, naming every counter. `no_client_refused` and `ignored_private` above zero also log once a minute at warning level with the peer address. The cutover reads these lines over SSM (§6.4). |
| + |
| +**The trust-violation metric, for the whole armed lifetime.** `no_client_refused` plus `marker_trusted` is the S3 signal: in S3 every client that sends no header of its own lands in `no_client_refused` (§4.6), which on a serving target group is nearly every client, and the forgery probe's marker lands in `marker_trusted`. The agent publishes the per-minute increase of that sum as `IngressProxyTrustViolations` in the `Carlos/Host` namespace, with the `Deployment` and `Region` dimensions the clock and admission metrics already use (`internal/host/memwatch.go:53-90`, `ingress/alarms.tf:49-90`), on every armed box with `CARLOS_HOST_METRICS=cloudwatch`. The agent runs the edge in-process (`internal/host/ingressdrain.go:87-88` holds it) and reads the counters directly. One alarm in the ingress module (§8.1) fires on Maximum > 0 for one minute, missing data not breaching (unarmed boxes publish nothing). The armed prerequisite (§6.1) includes `CARLOS_HOST_METRICS=cloudwatch` on every target. |
| + |
| +### 4.6 A trusted connection without a client address answers the health check only |
| + |
| +A `no-client` connection has an NLB node as its socket peer and no client to key limits on, and outside the health check it exists only in S3 (§4.4). So a request on it is served only when it is a `GET` or `HEAD` of `/.carlos/lb-health` on `:80`, and then the outer wrapper calls `lbHealthAnswer` (`internal/edge/lbhealth.go:34-48`) directly, never entering the ordinary handler chain: in that chain `redirectDemoRequest` runs before the health branch (`internal/edge/edge.go:3788-3799`, `demo.go:94`), so a demo `Host` would otherwise escape. If `lbHealthAnswer` declines (region HA off), the answer is 503. Every other request on such a connection, on either listener, is answered `503` with `Connection: close`, before any routing, rate limit, analytics or forwarding, and counted `no_client_refused`. The check is one wrapper around each public server's handler that reads the parse state (§4.3). Tests cover ordinary, demo and unknown `Host` values. |
| + |
| +So no request ever reaches a client-address reader without a client address: `clientIP(r)` (`internal/edge/analytics.go:100-115`) always answers a real client, nothing is forwarded with a node address in `X-Forwarded-For`, and analytics never sees an empty address (`internal/analytics/meter.go:68`, `:191` would otherwise hash it into one shared visitor). |
| + |
| +In S3, ordinary clients (no header of their own) are refused loudly by this rule. A client that sends its own header is still believed; only §6 prevents that. |
| + |
| +### 4.7 The trust barrier (rev 5, accepted 2026-11-12; replaces rev 4's one-shot `close-trusted`, see §15) |
| + |
| +A root command on the box, `carlos system edge trust-barrier`, raises a barrier in the edge. While it is up, a trusted connection's header grants no identity: **every** connection from a node address, whether open, still parsing its header, or accepted later, is treated as `no-client` (§4.6) once its state resolves, so it can answer the health check and nothing else. Raising the barrier sets it before it closes anything: first the flag, then it closes every open connection from a node address, pending ones included. The wrapper tracks trusted connections from accept, not from parse, for this. A connection that finishes a forged header after the flag is up is still `no-client`; a node still in S3 that sends new connections meets the same rule. Health checks keep passing, so targets stay in service, and in S0 or S1 every client connection is untrusted and served as normal. |
| + |
| +The barrier is written to a file in the agent's state directory and read at edge start, so a restart does not lower it. Only `carlos system edge trust-resume` lowers it, run after the target group is verified back in S1 or S2 by the marker probe (§6.4). The step script refuses a forward step while any target's barrier is up. The commands are root CLI verbs that reach the agent the way W6's and §25's verbs do: a child that drops to the agent's user and calls the drain socket (`internal/host/hadrain_call.go`, `hadrain_socket_linux.go:23`, which admits only the agent's UID). The agent holds the edge in-process (`internal/host/ingressdrain.go:87-88`). Each reports how many connections it closed and the barrier state; the state also goes in the §4.5 journal line. |
| + |
| +## 5. Client IP everywhere it is used |
| + |
| +Every reader derives the client from `r.RemoteAddr`, directly or through `clientIP(r)`; none reads the socket. The wrapper changes the connection's `RemoteAddr`, net/http copies it into `r.RemoteAddr` (`server.go:1908`, and `:2152`/`:4002` for HTTP/2), so no reader changes. |
| + |
| +| Reader | Where | With PPv2 | |
| +|---|---|---| |
| +| Per-client rate limit | `ratelimit.go:133` | client, as today | |
| +| Protection tiers: probe-burst cooling and trip | `guard.go:161`, `:316` | client | |
| +| Backhaul fair share | `edge.go:4554-4561` | client | |
| +| Geo headers | `geoipheaders.go:41` | client; door, hop and tunnel branches unchanged | |
| +| Request records | `reqrecords.go:46` | client | |
| +| Analytics visitor hash and pace | `analytics.go:100-115`, `:154`; `internal/analytics/meter.go:191` | client | |
| +| `X-Forwarded-For` and its proof to apps and holders | `homemap.go:1684-1718` (`SetXForwarded` reads `r.RemoteAddr`), `forwardproof.go:44-51` | client, signed as today | |
| +| Gate attempt limiter | `gate.go:260-268` | client | |
| +| Journal lines naming a peer | `burst_notice.go:603`, `hadrain.go:282`, net/http's TLS handshake error (`server.go:1953`) | client | |
| +| Asset catch record | `assetcatch.go:676` | client | |
| +| Hairpin normalisation | `hairpin.go:93-110` | unchanged (hairpin peers are never trusted) | |
| +| Door, devbox front, tunnel hub log | `door.go:126`, `devboxfront.go:44`, `tunnel.go:329` | not on a wrapped path, or not via the NLB | |
| +| Console readers (`authcli.go:574`, `cliplace.go`, `demo_api_origin.go:38`, `stepup.go:499`) | console on annie | annie is not an NLB target; they read what the local edge forwards | |
| + |
| +Hop-verified requests between boxes keep taking the client from the signed `X-Forwarded-For` (`analytics.go:101-108`); the sending edge now fills it from the header-derived address, and never from a `no-client` connection (§4.6). |
| + |
| +## 6. Cutover |
| + |
| +### 6.1 Prerequisites, per NLB |
| + |
| +In this order: |
| +1. **vN on every target in both TGs.** Fixed boxes rolled. Members replaced through the group roll onto a launch template naming vN. |
| +2. **The bootstrap object at vN or later.** Members run the separately seeded bootstrap binary (`group-init.sh.tftpl:200-215`) for `host-env write` (`:332`), and it refuses a key outside its compiled allowlist (`internal/hostenv/group.go:112`). So the region's `boot/bootstrap-object` and `boot/bootstrap-sha256` name a vN build, checked from SSM and the object's hash, **before** the key is published. |
| +3. **The key.** `CARLOS_INGRESS_PROXY_SOURCES` equal to the module output (§8.1): in the region's host-env parameters, then a group roll so every member is launched with it (members write host.env only at launch, `hostenv.go:144-150`), and in each fixed box's host.env with a drained restart, as W6 delivered `CARLOS_INGRESS_TARGET_GROUPS`. Each target's journal shows the §4.5 armed line with exactly the module's addresses. |
| +4. **The group module at vN**, whose precondition accepts the new states (§8.2). A group plan with the old module would refuse once the TGs change. |
| +5. **Metrics and alarm.** `CARLOS_HOST_METRICS=cloudwatch` on every target; the module's `proxy_trust_alarm` input set, both alarms applied, in OK, and notification delivery seen (§4.5, §8.1, §8.3). |
| + |
| +Arming changes nothing on the wire: until step A80 no connection carries a header, and trusted peers are only health checks, which §4.6 serves. |
| + |
| +**Before A80 everything can still be unwound** in reverse: the key removed from the parameters and the fixed boxes, then the bootstrap object or any target may go below vN. A bootstrap below vN with the key still published stops every new member at boot. **After A80 nothing below vN comes back** (§7.3). |
| + |
| +### 6.2 States and steps |
| + |
| +Two attributes per TG, four combinations. The steps visit only S0, S1 and S2, and PPv2 is one-way: S1 never goes back to S0. |
| + |
| +| State | preserve | PPv2 | Socket peer at target | First header | Edge result | |
| +|---|---|---|---|---|---| |
| +| S0 today | on | off | client | none, or the client's | untrusted; a client header ignored | |
| +| S1 | on | on | client | NLB's, source = client | untrusted, header ignored, peer = client: same address | |
| +| S2 target | off | on | NLB node | NLB's | trusted, header source = client | |
| +| S3 **forbidden** | off | off | NLB node | none, or the client's | trusted: a client header is believed (§3) | |
| + |
| +In S1 the edge must ignore, not trust, the header, because the peer is the client and is not in the list; §4.4 does that. While one attribute propagates, nodes can disagree, so new connections are in one of the two states on either side of the step; every edge handles both of each allowed pair. The allowed moves are S0 to S1 and S1 to S2 forward, and S2 to S1 back. None of them changes PPv2 while preservation is off, so no node can be in S3 at any point of any of them, converged or not. That is why S2 to S1 needs no convergence proof and the probe's inability to tell S1 from S2 (round 2) no longer matters. The moves that could touch S3 (S0 to S2 and S2 to S0 in one go, and S1 to S0 after a reverse B that may not have reached every node) are refused. |
| + |
| +Steps, per NLB, each a targeted tofu apply of one attribute on one TG (0 add / 1 change / 0 destroy): |
| +1. **A80:** PPv2 on, `:80` TG (S0 to S1). |
| +2. **A443:** PPv2 on, `:443` TG. |
| +3. **B80:** preservation off, `:80` TG (S1 to S2). |
| +4. **B443:** preservation off, `:443` TG. |
| + |
| +`:80` goes first in each pair because it carries only ACME challenges, redirects and health checks. Each step starts only when the previous step's convergence evidence (§6.4) is in. |
| + |
| +### 6.3 The step tool refuses any move that could pass through S3 |
| + |
| +A card script in each root (`scripts/ppv2-step.sh <tg-port> <attribute> <value>`) is the only way the attributes change: |
| +- it reads the TG's live attributes (`describe-target-group-attributes`) and refuses unless the move is one of S0 to S1, S1 to S2, S2 to S1 for that TG; any change that sets PPv2 off is refused, whatever the state; |
| +- it runs `tofu plan -target` and refuses unless the plan changes exactly that one attribute on that one TG; |
| +- for a forward move, it refuses unless the previous forward step's convergence record (§6.4) exists and passed; S2 to S1 needs none; |
| +- then it applies, and starts the next convergence check. |
| + |
| +The module also refuses S3 as a declared state (§8.1), so an ordinary plan cannot request it. Direct `aws elbv2 modify-target-group-attributes` is allowed in only one direction and only in an abort or incident: preservation **on** (S2 to S1, or S3 to S0), which can never create S3. Tofu is reconciled afterwards with a plan that shows no change. Turning PPv2 off by any route (tofu, CLI, console) is outside every procedure; if it happens, §4.5's alarm fires and §6.5 runs. |
| + |
| +### 6.4 Convergence evidence and the forgery probe |
| + |
| +The probe runs in region (§10), with one process per NLB address and port, each binding source ports from its own range so the probe itself never sends one source port to both addresses. Each process sends, every 2 s, two requests on fresh connections: |
| +- **plain:** a normal request to the echo app, which returns the `X-Forwarded-For` it received; |
| +- **marker:** a PPv2 header claiming source 192.0.2.1 (TEST-NET-1), then the same request. |
| + |
| +What each state answers, per NLB address. On `:443` the request goes to the echo app. On `:80` it is a `GET` for the echo app's host with redirects not followed, so the expected answer is today's `302` to HTTPS (`internal/edge/edge.go:3840`), not 200: |
| + |
| +| State on that node | plain `:443` | marker `:443` | plain `:80` | marker `:80` | |
| +|---|---|---|---|---| |
| +| S0 | 200, probe's address | 200, probe's address (client header ignored, §4.4) | 302 | 302 | |
| +| S1 | 200, probe's address | fails: the NLB's header is first, the marker is payload (TLS error) | 302 | fails: 400 | |
| +| S2 | 200, probe's address | fails, the same way | 302 | fails: 400 | |
| +| S3 | 503, refused (§4.6) | connection closed by the edge; `marker_trusted` counts it | 503 | the same | |
| + |
| +The edge catches the forged marker itself: a trusted `proxied` header whose source is in 192.0.2.0/24 (TEST-NET-1, never a real client) closes the connection before any response and increments `marker_trusted`, logged at warning level. So the probe never sees a forged echo; `marker_trusted` above zero means S3 on that target's port. (A marker that fails in S1 or S2 fails with an answer, 400 or a TLS alert; a marker closed in S3 gets none. The probe records which, but the counter is the verdict.) |
| + |
| +Convergence of a step, per TG port, needs all of: |
| +- after A: the marker fails on **both** NLB addresses for 30 consecutive attempts (60 s); plain stays at its port's answer on both addresses (`:443`: 200 with the probe's address; `:80`: 302, not followed); |
| +- after B: the same, plus every target's counters show `proxied` rising from **both** node addresses and `no_client_refused` at 0; |
| +- all the time: `malformed`, `timeout`, `ignored_private` and `marker_trusted` at 0. |
| + |
| +**Transition gates and maintenance rows are separate.** From the start of an attribute step until its convergence record is written, every target is healthy in both TGs (`describe-target-health` every 10 s) and no drain, restart or group roll runs. Maintenance rows (§10 rows 5 and 6) run only between steps: during one, the named target may be `unhealthy.draining` or deregistered, every other target stays healthy, and the plain probe stays at 0 errors. The all-healthy gate is back before the next attribute step starts. |
| + |
| +The script writes the record (times, counts, per-address results) that the next step requires. |
| + |
| +**Any `marker_trusted` or any `no_client_refused` is S3 on some node: §6.5 at once.** The probe runs for the whole window, not only between steps; outside windows the alarm (§4.5) carries the watch. |
| + |
| +### 6.5 Rollback and the S3 incident |
| + |
| +**Rollback ends at S1.** B443 then B80 back, each preservation **on**, by the step script or, in an abort, the direct command. S1 is today's client addresses through the NLB and today's collision behaviour, which is everything a rollback needs to restore; the edge stays armed and keeps ignoring the NLB's header as in S1. A80 and A443 are never reversed (§6.2, §7.3). No convergence proof is needed for S2 to S1, because every node is in S1 or S2 throughout and neither trusts a client header. |
| + |
| +**S3 incident** (the alarm, any `marker_trusted`, or any `no_client_refused`): |
| +1. `carlos system edge trust-barrier` (§4.7) on every target in that TG, over SSM on all of them at once. From that moment no connection from a node address carries an identity, open, pending or new, and the forged ones are closed. Health checks keep passing. |
| +2. Preservation **on** for the affected TG with the direct command (§6.3). New client connections become untrusted (S0 or S1) and are served normally behind the barrier. |
| +3. Find who turned PPv2 off. Verify the TG is in S1 with the marker probe on both addresses, then `trust-resume` on every target, then go forward with the step script (S1 to S2) in a window. |
| +4. Report to 8a3d302 with the alarm, the counters and the barrier's close counts. |
| + |
| +### 6.6 Order across NLBs |
| + |
| +Dev IE first, in a dev #421 window after vN is on dev. Flagship US after the dev witness passes every row, in a flagship window with the lock posted on #421 (region HA live window rules), before G6 opens the US NLB to customers. Not in the same window as a release roll or a group roll, except the group roll that §6.1 calls for. |
| + |
| +## 7. Interactions |
| + |
| +### 7.1 Fixed boxes in the target groups and W6 |
| + |
| +leo, sophie and adi carry NLB traffic and their own EIP traffic on the same listeners. NLB connections come from the node addresses (trusted); EIP connections come from clients (untrusted, unchanged). W6's drain reads TG health and fails `/.carlos/lb-health` on purpose (`lbhealth.go:34-48`); health checks reach that handler as `no-client` or, before step A, without a header, so the drain is unchanged. The W6 witness rows (drained restarts with 0 errors) rerun in S2 (§10). |
| + |
| +### 7.2 Health checks |
| + |
| +Both TGs check `:80` `/.carlos/lb-health`. After A80 or A443, that TG's checks carry a LOCAL header from trusted peers. Between A80 and A443, `:80` sees both kinds at once, per connection. Admission gating (`lbhealth.go:38-46`) is unchanged. |
| + |
| +### 7.3 The cost: no release below vN on an NLB target, ever again |
| + |
| +**Once A80 is done on a region's NLB, no carlos build older than vN can run on any target of that NLB again.** PPv2 is one-way (§6.2), and an edge below vN answers the NLB's header with a 400 or a TLS error, fails its health checks and drops out (all of them at once is an outage). So for those boxes a platform release rollback below vN is off the table. Rollbacks stay possible to any build at or above vN, which all parse; a bad release after vN is rolled back to the previous good one as today, as long as that one is vN or later, or fixed forward. Boxes that are not NLB targets (annie, the AU and UK boxes, Tito's, self-hosters) are not affected. |
| + |
| +Today that means: dev leo, sophie and the IE members from dev's A80; flagship adi and the US members from flagship's A80. The list grows with every region that gets an HA group. |
| + |
| +**Refused up front on the box.** One guard, in the code that activates a carlos binary on a box (`carlos system apply` and `rollback`, and `install-channel` in member boot, `group-init.sh.tftpl:332`): a box whose host.env carries `CARLOS_INGRESS_PROXY_SOURCES` refuses to activate a binary that does not report the `ingress-proxy-v2` feature. The check runs the staged binary's `carlos version --json` (vN adds a `features` list; an older binary has none, so it is refused) and leaves the running binary in place. On a fixed box the update or rollback fails with the reason; a member launched from a template below vN fails its boot, which the group's launch hook and the HA capacity alarms already report. The key is the trigger, not the TG state, so the guard also holds before A80; unwinding before A80 removes the key first (§6.1). |
| + |
| +**What the release recipe must check** (written into the recipe by the build plan): |
| +- Before promoting any build to a channel pointer (canary or stable) of a deployment, read `proxy_protocol_v2.enabled` on every region NLB target group of that deployment (`aws elbv2 describe-target-group-attributes`, read-only). If any is `true`, the build must be vN or later. Re-promoting an old build as a quick rollback is refused; cut forward instead. |
| +- The same check before changing a region's bootstrap object or re-pinning a group launch template. |
| +- The recipe's state line records, per deployment, "PPv2 on since <date>: floor vN". |
| + |
| +**What the roll card must check:** |
| +- Pre-roll: the same read per region; for each region with PPv2 on, the card lists its NLB targets and states "rollback below vN is off the table on these boxes; rollback target is <previous build ≥ vN> or forward fix". |
| +- The card's rollback section names that target build explicitly, never "the previous release" unchecked. |
| +- Post-roll: every NLB target shows the §4.5 armed line with the module's addresses, and the trust-violation alarm is OK. |
| + |
| +Members launched while PPv2 is on must come from a launch template naming vN or later, with a vN bootstrap object and the key in the region's parameters (§6.1). |
| + |
| +### 7.4 Hairpin (A21) |
| + |
| +Members redirect their own traffic to the NLB addresses to the local edge (§12.4 of the HA spec, `hairpin.go`). That stays: it is correct in every state, and it saves a round trip. With preservation off, hairpin through the NLB would work, so the redirect becomes optional; retiring it is a separate simplification, not part of this change. |
| + |
| +### 7.5 Capacity |
| + |
| +AWS: with preservation off, about 55,000 connections a minute to each target IP and port. Peak is 1,203 new flows a minute NLB-wide on dev and 198 on the flagship (14 days to 2026-11-12). The NLB alarms gain `PortAllocationErrorCount` (§8.1). |
| + |
| +### 7.6 Security groups |
| + |
| +Unchanged. Targets already admit 80 and 443 from the NLB's security group (`group.tf:134-143`); the NLB's egress already covers the VPC CIDRs on both ports (`ingress/main.tf:51-63`). Health checks already come from the node addresses. |
| + |
| +## 8. Tofu |
| + |
| +### 8.1 This repo, `infra/modules/region-host/ingress` (rides vN) |
| + |
| +- `aws_lb_target_group.target` (`ingress/main.tf:97-126`): `preserve_client_ip` and `proxy_protocol_v2` from two map variables keyed by port (`{ "80" = ..., "443" = ... }`), defaults `true` and `false`, so a root can flip one TG at a time and re-pinning to vN plans no TG change. A validation refuses any port with preservation off and PPv2 off (S3). |
| +- Output `proxy_protocol_sources`: the node private addresses, sorted. One singular `data "aws_network_interface"` per zone in `var.zones` (keys known at plan time), filtered on `description = "ELB ${aws_lb.nlb.arn_suffix}"` and that zone's `subnet-id`, each yielding exactly one interface and its `private_ip`. (The plural `aws_network_interfaces` returns only IDs.) |
| +- A new input, `proxy_trust_alarm = object({ deployment = string, region = string, topic_arn = string })`, default null, separate from `regional_metrics` (`ingress/variables.tf:68`) so that setting it does not also switch on the clock and admission alarms. A precondition on the target groups refuses any port with PPv2 on while it is null: no TG gets PPv2 without its alarm. |
| +- Alarm `<name>-proxy-trust` on `Carlos/Host` `IngressProxyTrustViolations` (§4.5), dimensions `Deployment` and `Region` from that input, Maximum > 0 for one 60 s period, `treat_missing_data = "notBreaching"`, actions and OK actions on its `topic_arn`. |
| +- Alarm `<name>-port-allocation` on `AWS/NetworkELB` `PortAllocationErrorCount`, Sum > 0 over 5 minutes, on the same topic. Both alarms exist only when the input is set. |
| + |
| +### 8.2 This repo, `infra/modules/region-host/group.tf` (rides vN) |
| + |
| +The existing-target-group precondition (`group.tf:182-187`) requires `preserve_client_ip == "true"`. It changes to accept S0, S1 and S2 and refuse S3 per TG: `tg.preserve_client_ip == "true" || tg.proxy_protocol_v2`. The error message names both attributes. Other checks stay. |
| + |
| +### 8.3 Roots |
| + |
| +Neither root sets `regional_metrics` on the ingress module today (pinfra `dev/region-ha-ingress.tf:24` has it commented out with no topic; carloku-infrastructure `region-ha-us.tf:5` has a topic and no `regional_metrics`), so the trust alarm cannot ride it; that is why it has its own input. Each root sets `proxy_trust_alarm` with its deployment bucket and region code (the `Carlos/Host` dimensions its boxes publish) and a confirmed topic: on the flagship, the topic the module already uses; on dev, the region HA alert topic the dev root already publishes to (the plan quotes its ARN). The re-pin to vN then plans **2 to add** (the two alarms), 0 to change, 0 to destroy. Delivery is verified on the card with one test datapoint and the notification seen (§10 row 11). |
| + |
| +- **dev, platform-infrastructure:** re-pin `dev/region-ha-ingress.tf` (with `proxy_trust_alarm`) and `dev/region-ha-group.tf` to vN; bootstrap object to vN; `CARLOS_INGRESS_PROXY_SOURCES` into `/carlos/dev/ie/` and into leo's and sophie's host.env; group roll; then the four steps through `scripts/ppv2-step.sh`. |
| +- **flagship, carloku-infrastructure:** push vN to the GitHub mirror, bump `?ref=` on `region-ha-us.tf` and `region-ha-us-group.tf`, the same sequence with adi. |
| + |
| +First-of-kind applies need 8a3d302's GO; later NLBs' identical steps fall under the standing approval for counted applies when the plan and the step script's record match the card exactly. |
| + |
| +## 9. Tests |
| + |
| +- `internal/proxyproto` (new, about 250 lines, no dependency): table tests for every row of §4.4 and every limit; byte-at-a-time and split reads; a 12-byte prefix that diverges at each position; timeout; exactly one header consumed, a second left as payload; a v1 header passed through; `Close` during a pending read returns at once. |
| +- Listener: a real `http.Server` behind the wrapper, plain and TLS (HTTP/1.1 and HTTP/2), with a trusted and an untrusted dialler (a test hook supplying the peer), asserting `r.RemoteAddr` and the parse state seen by the handler; a silent trusted connection does not delay a second connection's accept; `ConnContext` and `ConnState` hooks never block; `Shutdown` and `CloseIngress` end silent and partial-header connections within their bounds. |
| +- Production wiring (house rule, production-wired witnesses): the listener stack built the way `Serve` builds it (`publicServers`, `ConfigureGroupHairpin`, the wrapper, the §4.6 handler wrapper), with a header-carrying request reaching the rate limiter and `X-Forwarded-For` with the header's address, a hairpin connection keeping its normalisation, a `no-client` health check answered and a `no-client` request for an app refused with 503 before routing. |
| +- hostenv: the key's validation (private IPv4, 1-16, no duplicates), in both `Assemble` and the group `write` path. |
| +- Tofu: `ingress` tests for the defaults (S0), each per-port step, the S3 refusal and the output with one interface per zone; `group.tf` test for the precondition in all four states. |
| +- The step script: a dry-run mode tested against recorded `describe-target-group-attributes` outputs for every allowed and refused move, PPv2 off refused from every state. |
| +- The trust barrier (§4.7), **two mandatory race tests the plan must carry by name**: (a) a trusted connection that is mid-header when the barrier is raised and completes a valid PROXY header afterwards resolves to `no-client` and can answer only the health check; (b) a trusted connection accepted after the barrier is raised, with a valid header, likewise. Also: raised, it closes open and pending trusted connections and leaves `plain` ones; a partial header completed after it is raised resolves to `no-client`; a trusted connection accepted after it answers only the health check; it survives an edge restart; only `trust-resume` lowers it; it is reachable only through the drain socket's caller path. |
| +- The activation guard (§7.3): with the key set, a staged binary without the `ingress-proxy-v2` feature (including one with no `version --json`) is refused by `apply`, `rollback` and `install-channel`, and the running binary stays; without the key, nothing changes. |
| +- The trust-violation metric: the agent publishes the per-minute increase of `no_client_refused` plus `marker_trusted`, and nothing on an unarmed box. |
| +- `go vet` and cross-builds (darwin, windows) for the new package. |
| + |
| +## 10. Witness |
| + |
| +**Probe:** in region, as the drain experiment recommends: a throwaway t4g.nano (or the root runner) in the NLB's VPC public subnet, running §6.4's processes on both NLB addresses and both ports. **Echo:** an app on the HA pool that returns the `X-Forwarded-For` it received (the plan names it; a 20-line app if none exists). |
| + |
| +Dev rows, all in one window: |
| +1. Prerequisites (§6.1) shown from command output: versions, bootstrap object hash, armed lines, key equal to the module output. |
| +2. Each step A80 to B443 through the step script, with its convergence record; record how long after each apply the marker starts failing on each address, which measures propagation. |
| +3. **Held connections across steps.** Before each step, open and keep open through both NLB addresses: an HTTP/1.1 keep-alive connection sending a request every 5 s, an HTTP/2 connection doing the same, and an SSE stream. Each must keep working, with the echo showing the probe's address, through the step and the next 2 minutes. Any failure stops the window: the new-connections-only assumption (§3) is wrong. |
| +4. In S2: the echo shows the probe's public address; a rate-limit burst from the probe is limited and a request from a second address is not; a request to an app whose holder is another box arrives with the probe's address in the signed `X-Forwarded-For`. |
| +5. In S2: 4 W6 drained restarts (2 leo, 2 sophie) under the probe, 0 errors. |
| +6. In S2: one group roll replacing a member, under the probe, 0 errors, the new member armed from the vN bootstrap. |
| +7. In S2: from a member, `curl` an NLB public address (hairpin redirect, unchanged path), 200. |
| +8. **Collision row:** from one host, 200 pairs of connections with the same source port to both NLB addresses (the lost-post repro), in S0 and then S2. In S2, target-side `ss` shows the pairs as distinct 4-tuples from the node addresses. S0 is expected to pass too (the repro never failed); the row shows the mechanism, not a before and after. |
| +9. **Rollback drill:** B443 then B80 back to S1 through the script, under the probe and the held connections, 0 errors; then forward to S2 again with convergence records. |
| +10. **Refusals, dry:** the step script refuses S0 to S2, S2 to S0 and S1 to S0 against the live TG, and the module refuses an S3 plan. S3 itself is never entered. |
| +11. **Containment and alarm, safely:** with the TG back in S1 (row 9), raise the barrier on one target: its health checks keep passing, the probe's plain requests keep answering (in S1 they are untrusted), the barrier survives one drained edge restart, then `trust-resume`. The races (a pending header completed after the barrier, a trusted accept after it) are covered by §9's tests, since only the NLB can open a trusted connection. Separately, publish one test datapoint and see the trust alarm fire, notify (the message received) and return to OK. |
| +12. **The activation guard:** on one armed fixed box, `carlos system apply` of a build below vN is refused with the reason and the box keeps serving. |
| + |
| +Flagship rows: 1, 2, 3 (one held connection of each kind), 4 (echo and burst), 5 (2 adi restarts), 8 in S2 only, 11 (the alarm datapoint only). |
| + |
| +## 11. Decisions (8a3d302, 2026-11-12) |
| + |
| +1. **Hairpin redirect (§7.4):** kept; retiring it is a later, separate change. |
| +2. **Direct rollback command (§6.3):** allowed for preservation **on** only, in an abort or S3 incident, reconciled by a no-change tofu plan after. |
| +3. **S3 containment (§6.5):** a root action on every target replaced rev 3's drained restarts and member roll; rev 5 proposes the barrier form of it (§4.7, §15). |
| +4. **When:** build after this is approved; dev window on the first dev roll after vN; flagship before G6. The dormant code's switch-on date is that dev window. |
| + |
| +## 12. Astra round 1 and where it went |
| + |
| +`docs/superpowers/specs/ASTRA-FINDINGS-edge-ppv2-R1.md`, NOT READY: one P1, six P2s. |
| + |
| +| Finding | Fault family | Disposition | |
| +|---|---|---| |
| +| P1: in S3 a client's own header is trusted, so S3 is forgery, not "limits off" | F1: client bytes becoming trusted identity | Accepted. §3 states the invariant; §6.2-§6.4 make S3 unreachable by the step script and detect it with the marker probe; §6.5 incident; §4.6 no longer claims S3 is bounded. | |
| +| P2: client unknown turns into a node address after forwarding | F2: missing identity across a hop | Accepted by removing client unknown: a `no-client` connection answers only the health check (§4.6), so nothing is forwarded without a client. | |
| +| P2: analytics hashes an empty address into one visitor | F2 | Resolved by the same change: no request reaches analytics without a client (§4.6). | |
| +| P2: the context mark needs a deferred-state contract | connection metadata without blocking | Accepted: §4.3 parse state, pointer in `ConnContext`, resolved on the serving goroutine, `Close` never waits; tests in §9. | |
| +| P2: the witness does not prove the cutover claims | rollout claims beyond evidence | Accepted: §3 states the assumption; §6.4 convergence per address and port gates each step; §10 row 3 holds connections across steps. | |
| +| P2: `aws_network_interfaces` has no private addresses | infra discovery | Accepted: singular lookups per zone (§8.1). | |
| +| P2: the member bootstrap binary refuses the new key | bootstrap compatibility | Accepted: §6.1 step 2 and the unwinding order. | |
| + |
| +## 13. Astra round 2 and where it went |
| + |
| +`docs/superpowers/specs/ASTRA-FINDINGS-edge-ppv2-R2.md`, NOT READY. Round 1 dispositions: R1.2, R1.3, R1.4, R1.6, R1.7 resolved; R1.1 (F1) and R1.5 partly. |
| + |
| +| Finding | Fault family | Disposition | |
| +|---|---|---| |
| +| P1: S3 still reachable on rollback and not bounded. S1 and S2 answer the probe identically, so S2 to S1 cannot be proven converged before PPv2 goes off; S3 drift after the window has no detector (forged requests count as `proxied`); the incident's serial drained restarts keep forged connections serving and can fail | **F1, second round running** | **Not fixed: stopping rule 2. Options in §14.** | |
| +| P2: the probe table is wrong for `:80` (302 redirect, not echo) | rollout evidence | Fixed in rev 3: per-port table with redirects not followed; the edge's own `marker_trusted` counter covers `:80` (§6.4). | |
| +| P2: "every target healthy all the time" contradicts the drain and roll rows | rollout evidence | Fixed in rev 3: transition gates and maintenance rows separated (§6.4). | |
| + |
| +## 14. Fault family F1: the decision |
| + |
| +**Decided 2026-11-12: A**, by agent manager 8a3d302 on Paul's standing acceptance of recommendations on this work (Paul informed, free to override). Rev 4 writes it in: §6.2 (allowed moves), §6.3 (the step script refuses PPv2 off from every state; the refusal sits in the script, not the module, because the module cannot read the live attribute of a target group it manages), §6.5 (rollback ends at S1; incident), §4.5 (metric and alarm), §4.7 (close-trusted), §7.3 (the cost, the activation guard, the release recipe and roll card checks). The options as put to Paul: |
| + |
| +F1 is "client bytes becoming trusted identity". It lives in one AWS state the edge cannot see, S3, and in the transitions next to it. Round 1 found S3 unguarded; rev 2 guarded the forward path and added a probe; round 2 found the reverse path (S2 to S1 to S0) unprovable with that probe, no detector outside the window, and an incident that cannot close forged connections promptly. Stopping rule 2 says not to write a third fix in the same family. The choices: |
| + |
| +**A. Cut: PROXY protocol is one-way (recommended).** Once a TG reaches S1, PPv2 never goes off again. Rollback ends at S1 (preservation back on, PPv2 on, the edge ignoring the header as in S1 today): that restores today's client addresses and today's collision behaviour, which is the whole of what a rollback needs. S1 to S0 and S2 to S0 are refused by the step script and removed from every card; the module refuses PPv2 off on a TG whose live attribute is on. Every unprovable transition is gone, since the only remaining moves are S0 to S1 (forward, proven by the marker), S1 to S2 (forward, proven by the marker plus per-node `proxied`) and S2 to S1 (reverse, safe whether converged or not: S1 and S2 both trust only the NLB's own header). S3 then needs someone to turn PPv2 off outside the tooling. Two small additions, still F1 but enforcing in one place rather than patching: the edge publishes `no_client_refused` and `marker_trusted` through the existing host metrics path (`CARLOS_HOST_METRICS`, `internal/host/memwatch.go:77`) with one alarm on either above zero (S3 turns every header-less client into a 503, so it is loud), and an edge control action that closes every trusted connection at once, without a drain, for the incident. Cost: an edge older than vN can never again run on an NLB target; that is already true from step A80 on. |
| + |
| +**B. Refuse up front with evidence.** Keep S1 to S0, gated on target-side evidence that preservation is back on every node: with the probe dialling both addresses every 2 s, `proxied` from each node address stays at 0 on every target for 5 minutes (in S2 every data connection from a node is `proxied`, so silence from both nodes means both preserve). Plus the alarm and the close-all action from A. This is a third fix in F1, which the stopping rule asks Paul to approve explicitly, and it keeps a transition whose safety rests on reading counters correctly under time pressure. |
| + |
| +**C. Stop the work.** Keep preservation on. Clients behind port-preserving NAT keep the rare 20-30 s connect hang on HA-pool names (§1). G6 opens with the known limit. |
| + |
| +Recommendation was **A**: it removes the unprovable transition rather than proving it, and costs nothing a rollback needs. Astra round 3 reviews rev 4, as the last round. |
| + |
| +## 15. Astra round 3 (the last) and the open P1 |
| + |
| +`docs/superpowers/specs/ASTRA-FINDINGS-edge-ppv2-R3.md`, NOT READY. Round 2 dispositions: R2.1 (F1) partly (one-way PPv2 removed the unsafe rollback; containment still leaks), R2.2 partly, R2.3 resolved. Astra recommends no further round. |
| + |
| +| Finding | Fault family | Disposition | |
| +|---|---|---| |
| +| P1: rev 4's one-shot `close-trusted` misses a connection still parsing its header (it completes a forged header afterwards) and connections a node still in S3 opens after the action | **F1, third round** | **Open; fix proposed in rev 5 §4.7 (the trust barrier), needs 8a3d302's go.** | |
| +| P2: the convergence gate demanded 200 on `:80`; the S3 marker row contradicted the edge's own close | rollout evidence | Fixed: per-port expectations (302 not followed on `:80`), S3 marker row is "closed, `marker_trusted`" (§6.4). | |
| +| P2: neither root sets `regional_metrics`, so the trust alarm would not exist; setting it would also switch on clock and admission alarms | detection config | Fixed: own input `proxy_trust_alarm`, required before any TG gets PPv2, both roots set it, delivery checked (§8.1, §8.3). | |
| +| P2: a `no-client` health request with a demo `Host` would hit `redirectDemoRequest` before the health branch | health-only boundary | Fixed: the wrapper calls `lbHealthAnswer` directly (§4.6). | |
| +| P3: the drain socket admits the agent's UID, not root | description | Fixed in §4.7's text. | |
| + |
| +**The P1 and its proposed fix.** Both races share one cause, which Astra names: containment had no barrier covering every trusted peer, only a sweep of the ones already parsed. Rev 5 replaces the sweep with a barrier that is state, not an action: while it is up, a trusted connection's header grants no identity, whenever it was accepted and whenever its header completes; the flag is set before the sweep, so nothing slips between them; it persists across restarts; only an explicit resume after the marker probe shows S1 lowers it. That is Astra's own suggested direction ("refusing trusted application traffic during containment"), and it costs nothing in S0 or S1, where no client traffic is trusted. It does not touch the one-way decision. |
| + |
| +**Decided 2026-11-12: option 1**, by 8a3d302: the barrier is accepted as state without another spec round; the build's whole-branch Astra review covers it, and the two race tests in §9 are mandatory in the plan. The choices as put: |
| +1. **Accept rev 5's barrier without another round** (recommended). The change is one flag checked at one point (the parse state's resolution) plus its persistence and two verbs; §9 tests the two races directly, and the build's whole-branch review covers it. |
| +2. **A fourth Astra round on §4.7 only**, scoped to the barrier. |
| +3. **Cut containment back to "stop public ingress"** in an S3 incident (deregister or drain every target), Astra's other suggestion: simpler to state, but an outage for every HA-pool app until the TG is verified, where the barrier keeps serving. |
diff --git a/docs/superpowers/specs/ASTRA-FINDINGS-edge-ppv2-R1.md b/docs/superpowers/specs/ASTRA-FINDINGS-edge-ppv2-R1.md| new file mode 100644 |
| index 000000000..6c55c6d08 |
| --- /dev/null |
| +++ b/docs/superpowers/specs/ASTRA-FINDINGS-edge-ppv2-R1.md |
| @@ -0,0 +1,75 @@ |
| +Reviewed commit `5eae4ea7569451db267f2a15541edece108e5107` against `origin/main` at `ae1b8cca` and the installed Go 1.26.10 sources. No files changed, subagents spawned, test suites run, or AWS calls made. |
| + |
| +1. **P1 — S3 allows client-address forgery, not just disabled limits (§§4.2, 4.4, 6.3).** |
| + |
| + The fallback described at [design:161](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md:161) is unsafe. In S3, the NLB supplies its trusted socket address but supplies no header. A client can send a valid PPv2 header followed by TLS; [design:73](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md:73) then accepts the client’s chosen address. AWS documents the NLB source address when preservation is disabled and that TCP payload, including client-supplied proxy headers, is retained. [https://docs.aws.amazon.com/elasticloadbalancing/latest/network/edit-target-group-attributes.html](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/edit-target-group-attributes.html) |
| + |
| + That forged address reaches limits and becomes edge-signed forwarding identity through [homemap.go:1685](/home/paulca/amadan.net/carlos/platform-ppv2/internal/edge/homemap.go:1685) and [forwardproof.go:51](/home/paulca/amadan.net/carlos/platform-ppv2/internal/edge/forwardproof.go:51). The design also gives affected connections no maximum lifetime. |
| + |
| + **Fix:** remove the claim that §4.6 safely bounds S3. Make “the NLB prepends its own header whenever its source address grants trust” an explicit operational invariant. Specify transition verification and an S3 incident procedure that blocks affected traffic and closes existing connections before recovery. Add a forgery witness; merely refusing headerless application requests does not reject a forged, well-formed header. |
| + |
| + **Fault family:** client-controlled bytes becoming trusted client identity. |
| + |
| +2. **P2 — “Client unknown” becomes a known NLB address after forwarding (§§4.6, 5).** |
| + |
| + [Design:91–96](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md:91) keeps the NLB address in `r.RemoteAddr` and outbound `X-Forwarded-For`, while storing unknown status only in local context. On another edge, [analytics.go:101](/home/paulca/amadan.net/carlos/platform-ppv2/internal/edge/analytics.go:101) takes the last forwarded address on a verified hop. [ratelimit.go:133](/home/paulca/amadan.net/carlos/platform-ppv2/internal/edge/ratelimit.go:133) and [guard.go:161](/home/paulca/amadan.net/carlos/platform-ppv2/internal/edge/guard.go:161) then treat that node address as a client. |
| + |
| + **Failure scenario:** unknown-client requests forwarded to a holder share one rate-limit and probe-burst bucket per NLB node—the aggregation §4.6 intends to prevent. |
| + |
| + **Fix:** either restrict unknown-client handling to health checks and refuse application traffic, or carry authenticated unknown status across forwarding and consume it before client-address readers. Add a two-edge witness. |
| + |
| + **Fault family:** loss of client-identity status across a trusted hop. |
| + |
| +3. **P2 — Analytics does not treat an empty address as “no client” (§4.6).** |
| + |
| + The claim at [design:94](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md:94) stops at the observation’s string field. [meter.go:191](/home/paulca/amadan.net/carlos/platform-ppv2/internal/analytics/meter.go:191) still hashes that field, and [meter.go:68](/home/paulca/amadan.net/carlos/platform-ppv2/internal/analytics/meter.go:68) accepts an empty IP. The hash feeds visitor counting and the pace detector. |
| + |
| + **Failure scenario:** unrelated unknown clients with the same user agent collapse into one visitor. Their combined requests can trigger the 20-page pace threshold at [pace.go:19](/home/paulca/amadan.net/carlos/platform-ppv2/internal/analytics/pace.go:19), misclassifying subsequent pageviews as bot traffic. |
| + |
| + **Fix:** specify and test analytics behavior for missing client identity, including skipping visitor deduplication and pace classification while retaining applicable aggregate counts. |
| + |
| + **Fault family:** missing identity becoming a shared analytics identity. |
| + |
| +4. **P2 — The unknown-client context mark needs a deferred-state contract (§§4.3, 4.6).** |
| + |
| + [Design:91](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md:91) says `ConnContext` sets the mark, but header parsing happens later. Go invokes `ConnContext` before launching the connection goroutine at [server.go:3474](/home/paulca/.local/go-dist/src/net/http/server.go:3474); that goroutine first calls `RemoteAddr` at [server.go:1908](/home/paulca/.local/go-dist/src/net/http/server.go:1908). |
| + |
| + **Failure scenario:** a snapshot taken in `ConnContext` cannot distinguish PROXY from LOCAL or absent headers. Parsing there instead blocks acceptance, contrary to §4.3. |
| + |
| + **Fix:** explicitly put a reference to connection-owned parse state in context without reading the connection. Resolve it once on the serving goroutine and expose the completed status to handlers. Require `Close` to interrupt pending parsing without waiting for its lock, and test silent/partial headers through `Shutdown` and `CloseIngress`. |
| + |
| + **Fault family:** connection metadata becoming available without blocking acceptance or shutdown. |
| + |
| +5. **P2 — The witness does not establish the stated cutover guarantees (§§3, 6.2, 10).** |
| + |
| + [Design:35](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md:35) says the design does not depend on PPv2 changes affecting only new connections; [design:143](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md:143) explicitly assumes that behavior. The parser consumes exactly one initial header. The probe at [design:229](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md:229) exercises one NLB address and does not require connections spanning attribute changes. |
| + |
| + **Failure scenario:** the witness passes while an unprobed node, port, or established connection behaves differently. Fixed watch periods and aggregate counter increases do not establish convergence on every node. |
| + |
| + **Fix:** state the assumption honestly and gate rollout on a dev witness covering both NLB addresses and ports, fresh connections, and persistent HTTP/1.1, HTTP/2 and streaming connections across forward and reverse changes. Define the evidence required before proceeding to the next attribute change; retain zero downtime as a measured result. |
| + |
| + **Fault family:** rollout guarantees exceeding transition evidence. |
| + |
| +6. **P2 — The ENI data source does not provide private addresses (§8.1).** |
| + |
| + [Design:202](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md:202) names `aws_network_interfaces` as the source of node private addresses. Its schema exposes interface IDs and tags, not private addresses; its read function stores only IDs (`vpc_network_interfaces_data_source.go:27–35,65–70`). [https://raw.githubusercontent.com/hashicorp/terraform-provider-aws/main/internal/service/ec2/vpc_network_interfaces_data_source.go](https://raw.githubusercontent.com/hashicorp/terraform-provider-aws/main/internal/service/ec2/vpc_network_interfaces_data_source.go) |
| + |
| + **Failure scenario:** implementing the stated lookup alone cannot produce `proxy_protocol_sources`. |
| + |
| + **Fix:** specify the singular `aws_network_interface` lookups that obtain `private_ip`. Prefer stable zone-keyed lookups filtered by NLB description and subnet, enforcing one interface per expected zone; this also avoids an initial-create `for_each` based on unknown interface IDs. |
| + |
| + **Fault family:** infrastructure discovery producing a complete trust list. |
| + |
| +7. **P2 — Host-env prerequisites omit the independently selected bootstrap binary (§§6.1, 8.3).** |
| + |
| + Naming vN in the launch template does not update the binary that initially reads host-env. [group-init.sh.tftpl:208](/home/paulca/amadan.net/carlos/platform-ppv2/infra/modules/region-host/group-init.sh.tftpl:208) fetches and verifies the independently seeded bootstrap object; [group-init.sh.tftpl:332](/home/paulca/amadan.net/carlos/platform-ppv2/infra/modules/region-host/group-init.sh.tftpl:332) runs that binary’s `host-env write` before installation. [group.go:112](/home/paulca/amadan.net/carlos/platform-ppv2/internal/hostenv/group.go:112) rejects keys outside its compiled allowlist. |
| + |
| + **Failure scenario:** the new parameter exists and the launch template names vN, but an older bootstrap rejects `CARLOS_INGRESS_PROXY_SOURCES`; replacement members never reach installation or health. |
| + |
| + **Fix:** explicitly require updating and verifying the bootstrap object/version/hash to a build accepting the key before publishing it. Include bootstrap compatibility in rollback instructions while the parameter remains present. |
| + |
| + **Fault family:** bootstrap/configuration compatibility during member replacement. |
| + |
| +No P3 findings. |
| + |
| +**NOT READY** |
| \ No newline at end of file |
diff --git a/docs/superpowers/specs/ASTRA-FINDINGS-edge-ppv2-R2.md b/docs/superpowers/specs/ASTRA-FINDINGS-edge-ppv2-R2.md| new file mode 100644 |
| index 000000000..d20b54fd9 |
| --- /dev/null |
| +++ b/docs/superpowers/specs/ASTRA-FINDINGS-edge-ppv2-R2.md |
| @@ -0,0 +1,52 @@ |
| +- **R1.1 P1 — S3 forgery: partly resolved.** The invariant is explicit, but rollback verification, detection coverage and incident containment remain incomplete. |
| +- **R1.2 P2 — Unknown identity across forwarding: resolved.** §4.6 refuses application requests before forwarding. |
| +- **R1.3 P2 — Empty analytics identity: resolved.** Those requests no longer reach analytics. |
| +- **R1.4 P2 — Deferred connection metadata: resolved.** The connection-owned state, nonblocking context hook and interruptible `Close` address the finding. |
| +- **R1.5 P2 — Cutover witness: partly resolved.** Persistent connections are covered, but the port-80 probe and drain-window conditions remain wrong. |
| +- **R1.6 P2 — ENI discovery: resolved.** Singular, zone-keyed interface lookups provide `private_ip`. |
| +- **R1.7 P2 — Bootstrap compatibility: resolved.** The bootstrap prerequisite and rollback ordering now cover the allowlist. |
| + |
| +1. **P1 — S3 is still neither excluded by the rollback procedure nor reliably bounded (§§3, 6.3–6.5).** |
| + |
| + **Evidence:** The convergence predicates at [design:187](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md:187) omit reverse B, although [design:199](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md:199) requires it before reverse A. S1 and S2 have identical plain/marker answers. Rising `proxied` counters establish S2 activity; they do not establish that preservation has returned on every node. |
| + |
| + **Failure scenario:** During rollback, one node still uses preservation-off when PPv2-off reaches it. That node enters S3 despite each requested move changing only one attribute. The prescribed probes cannot certify the preceding S2→S1 transition. A client-supplied address then becomes signed forwarding identity through [homemap.go:1685](/home/paulca/amadan.net/carlos/platform-ppv2/internal/edge/homemap.go:1685) and [forwardproof.go:51](/home/paulca/amadan.net/carlos/platform-ppv2/internal/edge/forwardproof.go:51). |
| + |
| + Detection and recovery do not close this gap: |
| + |
| + - The probe runs only during the window ([design:195](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md:195)). Later S3 drift has no specified forgery detector. Forged requests increment `proxied`, not `no_client_refused`; [design:95](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md:95) supplies journal output without an alarm. Thus S3 can occur without the promised detection. |
| + - The incident procedure restores preservation, then performs serial graceful restarts ([design:202](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md:202)). Existing forged connections remain usable. W6 explicitly keeps serving before closing ingress ([ingressdrain.go:370](/home/paulca/amadan.net/carlos/platform-ppv2/internal/host/ingressdrain.go:370)); member drains can stop with failure ([depart.go:321](/home/paulca/amadan.net/carlos/platform-ppv2/internal/grouproll/depart.go:321)). There is no incident-wide quarantine or closure deadline independent of successful maintenance. |
| + |
| + AWS confirms that preservation changes affect only new TCP connections. [https://docs.aws.amazon.com/elasticloadbalancing/latest/network/edit-target-group-attributes.html](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/edit-target-group-attributes.html) |
| + |
| + **Concrete fix:** Refuse PPv2-off rollback until fresh, correlated observations establish preserved socket peers on every node; the existing echo/marker pair cannot supply this evidence. Specify detection for the entire armed lifetime, and an incident action that blocks affected traffic and closes potentially forged connections before recovery, even when a normal roll fails. |
| + |
| + **Fault family:** **F1 — client-controlled bytes becoming trusted identity**, carried forward from round 1. |
| + |
| +2. **P2 — The per-state probe table is wrong for port 80 (§§6.4, 10).** |
| + |
| + **Evidence:** [Design:174](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md:174) requires an echo-app response on both ports. Production port 80 instead redirects routable application requests to HTTPS at [edge.go:3840](/home/paulca/amadan.net/carlos/platform-ppv2/internal/edge/edge.go:3840). |
| + |
| + **Failure scenario:** On port 80, ordinary requests in S0–S2 return a redirect, not `200` with an address. The S0 marker also redirects; an accepted S3 marker redirects without exposing its forged address. Following that redirect creates a separate TLS connection and loses the original marker identity. Literal enforcement therefore prevents the witness from passing; following redirects does not establish the claimed port-80 result. |
| + |
| + **Concrete fix:** Define separate port-80 expectations with redirects disabled. Obtain port-80 identity and parse-state evidence through correlated target observations, or explicitly design a suitable diagnostic endpoint. Keep the echo-app table for port 443. |
| + |
| + **Fault family:** **Rollout guarantees exceeding transition evidence**, carried forward from R1.5. |
| + |
| +3. **P2 — “Every target healthy all the time” contradicts the required drain witnesses (§§6.4, 10).** |
| + |
| + **Evidence:** [Design:191](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md:191) requires every target healthy throughout the window. [Design:276](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md:276) requires drained restarts and a member replacement during that window. W6 deliberately fails health before withdrawing a target ([ingressdrain.go:385](/home/paulca/amadan.net/carlos/platform-ppv2/internal/host/ingressdrain.go:385)). |
| + |
| + **Failure scenario:** A correctly functioning drain violates the probe’s pass condition and aborts the witness. |
| + |
| + **Concrete fix:** Separate attribute-transition gates from maintenance-witness gates. During a named drain, permit only that target’s expected withdrawal while requiring healthy alternatives and successful traffic probes; restore the all-healthy gate before further attribute changes. |
| + |
| + **Fault family:** **Rollout guarantees exceeding transition evidence**, carried forward from R1.5. |
| + |
| +No P3 findings. |
| + |
| +F1 has recurred in rounds 1 and 2, so stopping rule 2 applies. The choices are to refuse the unsafe rollback up front, cut mixed-state rollback, or enforce the invariant in one place with a guard test or simulation. I recommend the refusal until adequate transition evidence exists. |
| + |
| +Reviewed commit `9d1be70aafe46ce56d3b68adb3a70c55620a3b73` against the named `ae1b8cca` code and installed Go 1.26.10 sources. No files changed, subagents spawned, test suites run or AWS calls made. |
| + |
| +**NOT READY** |
| \ No newline at end of file |
diff --git a/docs/superpowers/specs/ASTRA-FINDINGS-edge-ppv2-R3.md b/docs/superpowers/specs/ASTRA-FINDINGS-edge-ppv2-R3.md| new file mode 100644 |
| index 000000000..d0d2c9f97 |
| --- /dev/null |
| +++ b/docs/superpowers/specs/ASTRA-FINDINGS-edge-ppv2-R3.md |
| @@ -0,0 +1,69 @@ |
| +- **R2.1 P1 — S3 exclusion and containment: partly resolved.** One-way PPv2 removes the unsafe rollback transition. The new close action still permits forged connections to survive containment. |
| +- **R2.2 P2 — Port-80 probe: partly resolved.** The response table distinguishes ports, but the convergence gate still requires an impossible port-80 response. |
| +- **R2.3 P2 — Health gates versus maintenance: resolved.** §6.4 separates transition gates from named maintenance withdrawals. |
| + |
| +1. **P1 — `close-trusted` does not close every potentially forged connection (§§4.7, 6.5).** |
| + |
| + **Evidence:** [Design:109](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md:109) registers connections only when parsing resolves, closes only `proxied` and `no-client`, and explicitly continues accepting connections. [Design:212](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md:212) restores preservation and immediately runs this one-shot close. |
| + |
| + **Failure scenarios:** |
| + |
| + - An attacker opens an S3 connection and sends a partial header. It remains `pending` during `close-trusted`, so the action misses it. The attacker completes a forged header within the ten-second deadline afterward. The connection becomes `proxied` and can serve requests indefinitely. Restoring preservation does not change an existing connection’s peer. |
| + - While preservation-on propagates, a node still in S3 accepts another connection after that target’s close action. Nothing prevents it from establishing another forged identity. |
| + |
| + The resulting address feeds forwarding at [homemap.go:1685](/home/paulca/amadan.net/carlos/platform-ppv2/internal/edge/homemap.go:1685) and is signed at [forwardproof.go:51](/home/paulca/amadan.net/carlos/platform-ppv2/internal/edge/forwardproof.go:51). AWS confirms preservation changes affect only new connections. [https://docs.aws.amazon.com/elasticloadbalancing/latest/network/edit-target-group-attributes.html](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/edit-target-group-attributes.html) |
| + |
| + **Concrete fix:** Track trusted socket peers from acceptance, including pending parsers. Make containment establish a persistent refusal barrier before closing that population, covering concurrent accepts and parse completion. Keep it until explicitly verified recovery; alternatively, stop public ingress during containment. Add witnesses for a partial header spanning the action and a new connection from a node still in S3. |
| + |
| + **Fault family:** **F1 — client-controlled bytes becoming trusted identity.** |
| + |
| +2. **P2 — The convergence gate still cannot pass on port 80 (§6.4).** |
| + |
| + **Evidence:** [Design:197](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md:197) requires plain responses to remain `200` with the probe’s address, per target-group port; the next line inherits that requirement. Port 80 returns `302` at [edge.go:3840](/home/paulca/amadan.net/carlos/platform-ppv2/internal/edge/edge.go:3840), as the revised table correctly states. |
| + |
| + The S3 marker row also contradicts the new detector: [design:192](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md:192) predicts an echo or redirect, while line 194 closes that marker connection before either response. |
| + |
| + **Failure scenario:** A correctly functioning A80 step cannot obtain its convergence record. A probe implementing the S3 table also expects responses the marker detector prevents. |
| + |
| + **Concrete fix:** Make convergence explicitly require `302`, without following redirects, on port 80 and `200` plus identity on port 443. Change the S3 marker expectations to connection closure plus `marker_trusted`. |
| + |
| + **Fault family:** **Rollout guarantees exceeding transition evidence**, carried from R2.2. |
| + |
| +3. **P2 — The root changes omit inputs needed to create and notify the trust alarm (§8).** |
| + |
| + **Evidence:** [Design:270](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md:270) gates the alarm on `regional_metrics`; [variables.tf:68](/home/paulca/amadan.net/carlos/platform-ppv2/infra/modules/region-host/ingress/variables.tf:68) defaults that input to null. The checked roots omit it: |
| + |
| + - `platform-infrastructure@a314594d`, `dev/region-ha-ingress.tf:24`: assignment remains commented out; the module also has no alarm topic. |
| + - `carloku-infrastructure@afa6ed16`, `region-ha-us.tf:5`: module supplies a topic but no `regional_metrics`. |
| + |
| + **Failure scenario:** The repins described at [design:278](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md:278) create no trust alarm. Enabling the shared input also enables the existing clock and admission alarms, so the stated “one new alarm” plan is inaccurate. |
| + |
| + **Concrete fix:** Specify the dimensions and notification topic in both roots, account for all resulting alarms, and verify notification delivery. Alternatively, give the mandatory trust alarm its own explicit configuration. |
| + |
| + **Fault family:** **Required detection omitted by infrastructure configuration.** |
| + |
| +4. **P2 — The health-only exception relies on incorrect handler ordering (§4.6).** |
| + |
| + **Evidence:** [Design:101](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md:101) says `lbHealthAnswer` already answers first. In fact, [edge.go:3788](/home/paulca/amadan.net/carlos/platform-ppv2/internal/edge/edge.go:3788) calls `redirectDemoRequest` before the health handler. That function selects an upstream at [demo.go:94](/home/paulca/amadan.net/carlos/platform-ppv2/internal/edge/demo.go:94) and can return a demo response. |
| + |
| + **Failure scenario:** A `no-client` request matching the permitted health method and path, but carrying a demo Host, passes the proposed exception and reaches host routing or a demo response instead of the health answer. |
| + |
| + **Concrete fix:** Have the outer wrapper dispatch permitted `no-client` health requests directly to `lbHealthAnswer`, without entering the ordinary handler chain. Test ordinary, demo and unknown Host values. |
| + |
| + **Fault family:** **Identity-free connections escaping the health-only boundary.** |
| + |
| +5. **P3 — The existing drain socket is not root-only (§4.7).** |
| + |
| + **Evidence:** [hadrain_socket_linux.go:23](/home/paulca/amadan.net/carlos/platform-ppv2/internal/host/hadrain_socket_linux.go:23) admits the agent’s UID; root verbs use a child that drops to that UID. |
| + |
| + **Failure scenario:** A direct root caller is rejected, while another process running as the agent can call the socket. This differs from [design:109](/home/paulca/amadan.net/carlos/platform-ppv2/docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md:109). |
| + |
| + **Concrete fix:** Describe the root command and service-UID socket separately, preserving the existing caller mechanism. |
| + |
| + **Fault family:** **Control-interface authority description.** Follow-up only. |
| + |
| +The sole outstanding P1 remains F1; both containment races share the absence of a barrier covering all trusted socket peers. Refusing trusted application traffic during containment, or cutting continued public serving during the incident, removes those races without reversing the accepted one-way PPv2 decision. This exhausts round 3; I do not recommend another review round. |
| + |
| +Reviewed `b06da7a081ac3e881300e438d0d91ecdda715bc4` against the named `ae1b8cca` code and installed Go 1.26.10 sources. No files changed, subagents spawned, test suites run or AWS calls made. |
| + |
| +**NOT READY** |
| \ No newline at end of file |
diff --git a/docs/superpowers/specs/CODEX-REVIEW-BRIEF-edge-ppv2.md b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-edge-ppv2.md| new file mode 100644 |
| index 000000000..2535ae184 |
| --- /dev/null |
| +++ b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-edge-ppv2.md |
| @@ -0,0 +1,79 @@ |
| +# Review brief: PROXY protocol v2 on the region HA NLBs (spec), round 3 of 3 (the last) |
| + |
| +Repo carlos/platform, branch `design-edge-ppv2`, the commit named in your prompt. |
| +Under review: `docs/superpowers/specs/2026-11-12-edge-proxy-protocol-design.md`. |
| +Authorities (merged on main): `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md` (§12), |
| +`docs/superpowers/specs/2026-10-15-region-ha-two-box-regions-design.md`, |
| +`docs/superpowers/specs/2026-11-10-fixed-edge-ingress-drain-design.md` (W6). Code at `origin/main` ae1b8cca. |
| + |
| +You are an independent reviewer. Read the document, then the code it names, and check every claim against that code. |
| +Background evidence (read only if useful): `~/.cache/lost-post/REPORT.md`, `~/.cache/drain-syn/REPORT.md`, |
| +live NLB attributes in `~/.cache/ppv2/aws/`. |
| + |
| +## Fixed: do not re-argue |
| + |
| +- Paul approved the direction: client IP preservation off plus PROXY protocol v2 on both TGs of each region NLB, |
| + edge parses on :80 and :443 trusting only the NLB's private addresses. Cross-zone off is NOT an option. |
| +- Design only; no infra change is part of this review. |
| +- Decided after round 2 under stopping rule 2 (spec §14, §11): option A, PROXY protocol is one-way |
| + (rollback ends at S1, PPv2 never goes off); keep the A21 hairpin redirect; direct aws rollback only for |
| + preservation ON; timing as in §11. The cost (no build below vN on an NLB target after A80) is accepted. |
| + Report only mechanisms that fail to honour these, not the choices themselves. |
| + |
| +## What to check |
| + |
| +1. The trust rule (§4.2): can any party other than the NLB get a header trusted? Tenants on boxes in the VPC, |
| + cross-region backhaul to members' public 443, fixed boxes' EIPs, hairpin, health checks. |
| +2. The cutover states (§6.2): is every new connection handled correctly in S0, S1 and S2 and across each |
| + single-attribute step, including propagation where nodes disagree? Is S3 really unreachable or bounded? |
| + Is the S1 "ignore untrusted header" rule safe? |
| +3. Blocking (§4.3): does anything on net/http's accept goroutine (ConnContext, ConnState, hairpin Accept, |
| + connDrain) call RemoteAddr or Read on a wrapped connection? Check Go 1.26 net/http and crypto/tls. |
| + Interaction with Server.Shutdown / W6 CloseIngress for connections still reading a header. |
| +4. §5: is any client-address reader missing, or one that reads the socket rather than r.RemoteAddr? |
| +5. §4.6 (rev 2): a trusted connection without a client address answers only the health check. Can any other |
| + request on it reach routing, limits, analytics or forwarding? |
| +6. Tofu (§8): attribute names and in-place updates in the AWS provider; the group.tf precondition change; |
| + the ENI data source; ordering against the pinned module refs in the two roots. |
| +7. Host-env delivery (§6.1): do members and fixed boxes really get the key the way the spec says? |
| +8. Witness (§10): does it prove the fix and the zero-downtime claim as far as the spec claims? |
| + |
| +## Round 3 |
| + |
| +Earlier rounds: round 1 `docs/superpowers/specs/ASTRA-FINDINGS-edge-ppv2-R1.md` (NOT READY: P1 F1, six P2s), |
| +round 2 `docs/superpowers/specs/ASTRA-FINDINGS-edge-ppv2-R2.md` (NOT READY: P1 F1 again, two P2s). The spec's |
| +§12-§14 give each disposition. |
| + |
| +First give one line per P1 and P2 from round 2: resolved, partly, or not. Carry every unresolved or partly |
| +resolved finding forward, then add new findings. The verdict covers everything outstanding. |
| + |
| +Rev 4 answers F1 with option A: allowed moves S0->S1, S1->S2, S2->S1 only (§6.2, §6.3); the trust-violation |
| +metric and alarm for the whole armed lifetime (§4.5, §8.1); `close-trusted` containment (§4.7, §6.5); and the |
| +cost section with a box-side activation guard and release/roll checks (§7.3). Check in particular: can any |
| +allowed move, mid-propagation, put a node in S3? Is the alarm's signal real in S3? Does close-trusted close |
| +every connection that could carry a forged identity? Does the activation guard cover every way a binary |
| +reaches a target (apply, rollback, install-channel at member boot, channel pointers)? |
| + |
| +This is round 3. A NOT READY must also say whether the P1s share one cause, and whether refusing the case up |
| +front or cutting the feature would remove them. |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, would not compile, a test fails, or it would not work. Blocks merge. |
| +- **P2**: wrong or missing. Fixed without reopening this review. |
| +- **P3**: clarity or polish. Goes on a follow-up list; never a reason for another round. |
| + |
| +A P1 states its failure scenario and the evidence (file:line). Do not raise a P2 to P1 to keep the review open. |
| + |
| +## Output |
| + |
| +Findings ranked P1, P2, P3. Each gives the section, the problem, the evidence (file:line, verified), the failure |
| +scenario, a concrete fix and the invariant or trust boundary it breaks (its fault family). End with exactly one |
| +verdict: |
| + |
| +- **READY**: no P1 and no P2. |
| +- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another round. |
| +- **NOT READY**: one or more P1s, listed. |
| + |
| +Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test |
| +suites. Do not make any AWS call that changes anything. |
diff --git a/internal/activator/haadopt.go b/internal/activator/haadopt.go| index 2790e9169..d3d717299 100644 |
| --- a/internal/activator/haadopt.go |
| +++ b/internal/activator/haadopt.go |
| @@ -269,6 +269,13 @@ func (a *Service) AdoptHost(ctx context.Context, rt registry.Route, req Adoption |
| if view.Lock.Release == nil && !a.now().After(view.Lock.ExpiresAt) { |
| return Deferred, nil |
| } |
| + // An unsettled marker opens a lease term after its write (the acquire |
| + // would answer held until then). |
| + if m := view.Lock.Release; m != nil { |
| + if opens := hafresh.MarkerOpensAt(*m, lease.LeaseTTL); !opens.IsZero() && !a.now().After(opens) { |
| + return Deferred, nil |
| + } |
| + } |
| var staged []registry.HAWakeImport |
| if !exists { |
| s, err := b.adoptionWake(ctx, rt.Host) |
diff --git a/internal/activator/haadopt_test.go b/internal/activator/haadopt_test.go| index 54bde7cfd..6dc77357b 100644 |
| --- a/internal/activator/haadopt_test.go |
| +++ b/internal/activator/haadopt_test.go |
| @@ -50,7 +50,7 @@ func publishAdoptWake(t *testing.T, s *haSvc, ws hostfiles.WakeState) { |
| } |
| } |
| func TestHAAdoptAuthority(t *testing.T) { |
| - for _, kind := range []string{"unclean", "clean", "held", "expiry equality", "expired", "marker failure", "marker 412"} { |
| + for _, kind := range []string{"unclean", "clean", "held", "expiry equality", "expired", "marker failure", "marker 412", "unsettled", "unsettled, a term past"} { |
| t.Run(kind, func(t *testing.T) { |
| s, req := haAdoptionFixture(t) |
| ctx := context.Background() |
| @@ -68,6 +68,18 @@ func TestHAAdoptAuthority(t *testing.T) { |
| body, _ := json.Marshal(hafresh.Lock{Generation: 5, Owner: heldByB, ExpiresAt: expiry}) |
| putLockFor(t, s.b, s.rt, body) |
| s.b.OwnerTerminated = func(context.Context, string) (bool, error) { return true, nil } |
| + case "unsettled", "unsettled, a term past": |
| + // The departed box's finalization failed: a write of its |
| + // may still land, so adoption waits a lease term from At. |
| + at := time.Now().UTC() |
| + if kind != "unsettled" { |
| + at = at.Add(-lease.LeaseTTL - time.Minute) |
| + } |
| + body, err := hafresh.MarkerBody(5, hafresh.Marker{V: 1, Box: "b", IID: "i-b", Lifetime: req.Lifetime, At: at}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + putLockFor(t, s.b, s.rt, body) |
| case "marker failure": |
| s.fx.FailNextMatching("PUT", 503, func(k string, b []byte) bool { return strings.Contains(string(b), "carlos_release") }) |
| case "marker 412": |
| @@ -80,7 +92,7 @@ func TestHAAdoptAuthority(t *testing.T) { |
| } |
| start := len(s.fx.Requests()) |
| got, err := s.a.AdoptHost(ctx, s.rt, req) |
| - denied := kind == "held" || kind == "expiry equality" || strings.HasPrefix(kind, "marker ") |
| + denied := kind == "held" || kind == "expiry equality" || kind == "unsettled" || strings.HasPrefix(kind, "marker ") |
| if denied { |
| if got != Deferred { |
| t.Fatalf("refusal %v %v", got, err) |
| @@ -105,7 +117,8 @@ func TestHAAdoptAuthority(t *testing.T) { |
| t.Fatalf("adopt %v %v", got, err) |
| } |
| v, e := lease.ReadLock(ctx, s.b.Cfg.Bucket, s.b.Cfg.hibernatePrefix(s.rt.Host), s.b.Cfg.Region) |
| - if e != nil || v.Lock.Release == nil || v.Lock.Release.Box != "a" || v.Lock.Release.Clean || v.Lock.Release.Lifetime != req.Lifetime { |
| + // The adopter replicated nothing: its own marker is settled. |
| + if e != nil || v.Lock.Release == nil || v.Lock.Release.Box != "a" || v.Lock.Release.Clean || !v.Lock.Release.Settled || v.Lock.Release.Lifetime != req.Lifetime { |
| t.Fatalf("marker %+v %v", v, e) |
| } |
| d, ok, e := s.b.Registry.HADuty(s.rt.Host, req.Lifetime) |
| @@ -387,7 +400,7 @@ func TestHAAdoptSuperseded(t *testing.T) { |
| func haAdoptMarker(t *testing.T, ref, iid, life string, generation int64, clean bool) []byte { |
| t.Helper() |
| - body, err := hafresh.MarkerBody(generation, hafresh.Marker{V: 1, Box: ref, IID: iid, Lifetime: life, At: time.Now().UTC(), Clean: clean}) |
| + body, err := hafresh.MarkerBody(generation, hafresh.Marker{V: 1, Box: ref, IID: iid, Lifetime: life, At: time.Now().UTC(), Clean: clean, Settled: true}) |
| if err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/activator/hadrainmove_linux_test.go b/internal/activator/hadrainmove_linux_test.go| index 108e90d0f..96f50c8e2 100644 |
| --- a/internal/activator/hadrainmove_linux_test.go |
| +++ b/internal/activator/hadrainmove_linux_test.go |
| @@ -4,10 +4,16 @@ package activator |
| import ( |
| "context" |
| + "errors" |
| "path/filepath" |
| "syscall" |
| "testing" |
| "time" |
| + |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/hostfiles" |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/release" |
| ) |
| // Files Final incomplete: the marker is unclean, and the drain stop says |
| @@ -24,4 +30,58 @@ func TestDrainStopFilesFinalIncomplete(t *testing.T) { |
| if err != nil || !rel.Marker || rel.Clean { |
| t.Fatalf("drain stop: %+v %v, want an unclean marker", rel, err) |
| } |
| + // Only the tree was incomplete: the files commit and the replica's |
| + // finalization succeeded, so the marker is finalized and opens at once. |
| + if m := s.lockView(t).Lock.Release; m == nil || m.Clean || !m.Finalized || !hafresh.MarkerOpensAt(*m, lease.LeaseTTL).IsZero() { |
| + t.Fatalf("files-only unclean marker %+v: want finalized, open at once", m) |
| + } |
| +} |
| + |
| +// filesCommitFails fails every manifest PUT once armed: refused (nothing |
| +// applied) or lost (applied, the reply lost: a timed-out publication). |
| +type filesCommitFails struct { |
| + release.Store |
| + manifest string |
| + mode string // "", "refused" or "lost" |
| +} |
| + |
| +func (s *filesCommitFails) Put(ctx context.Context, key string, body []byte, match string) (string, error) { |
| + if key != s.manifest || s.mode == "" { |
| + return s.Store.Put(ctx, key, body, match) |
| + } |
| + if s.mode == "lost" { |
| + if _, err := s.Store.Put(ctx, key, body, match); err != nil { |
| + return "", err |
| + } |
| + return "", errors.New("applied manifest PUT, reply lost") |
| + } |
| + return "", errors.New("manifest PUT refused") |
| +} |
| + |
| +// The files-error boundary of finalized (Astra files-only review P2): a |
| +// final files commit that fails or whose outcome is unknown leaves the |
| +// marker unclean and NOT finalized, so it waits a lease term. |
| +func TestDrainStopFilesCommitFailureNotFinalized(t *testing.T) { |
| + for _, mode := range []string{"refused", "lost"} { |
| + t.Run(mode, func(t *testing.T) { |
| + s := haService(t, "shop.example.com") |
| + store := &filesCommitFails{Store: s.b.FilesStore, manifest: hostfiles.ManifestKey(s.b.filesPrefix(s.rt.Host))} |
| + s.b.FilesStore = store |
| + if _, err := s.wakeForTest(context.Background()); err != nil { |
| + t.Fatalf("wake: %v\nroot was asked:\n%s", err, s.ctl.joined()) |
| + } |
| + writeFiles(t, s.b, s.rt, map[string]string{"a.txt": "changed after the wake"}) |
| + store.mode = mode |
| + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) |
| + defer cancel() |
| + rel, _ := s.a.DrainStop(ctx, s.rt.Host) |
| + if !rel.Marker || rel.Clean { |
| + t.Fatalf("drain stop: %+v, want an unclean marker", rel) |
| + } |
| + m := s.lockView(t).Lock.Release |
| + if m == nil || m.Clean || m.Finalized || hafresh.MarkerOpensAt(*m, lease.LeaseTTL).IsZero() { |
| + t.Fatalf("marker %+v: want unclean, not finalized, held a lease term", m) |
| + } |
| + }) |
| + } |
| } |
diff --git a/internal/activator/harelease.go b/internal/activator/harelease.go| index 90178f966..c2f1fb8b0 100644 |
| --- a/internal/activator/harelease.go |
| +++ b/internal/activator/harelease.go |
| @@ -167,7 +167,8 @@ func haEntryRep(e *actEntry) (haRep, bool) { |
| // close, so the successor restores one file (§25.4 step 3.3). A |
| // snapshot that fails is logged and changes nothing else; |
| // 5. ReleaseMarker, clean only when Final was complete, Finish succeeded |
| -// and the record was written. |
| +// and the record was written; finalized when Final's commit and Finish |
| +// succeeded (it then opens at once even if unclean). |
| // |
| // Any other error is returned for the log: the marker was still written, |
| // or, if its PUT failed, lease has persisted the obligation |
| @@ -222,6 +223,10 @@ func (a *Service) releaseHAClean(ctx context.Context, e *actEntry) error { |
| m := hb.haReleaseBase(rt) |
| m.TXID, m.FilesGen, m.At = txid, gen, time.Now().UTC() |
| m.Clean = complete && ferr == nil && finErr == nil |
| + // Finalized (hafresh.Marker.Finalized): the files commit and the |
| + // replica finalization both succeeded, so an incomplete tree or a |
| + // failed record leaves the marker unclean but opening at once. |
| + m.Finalized = ferr == nil && finErr == nil |
| rerr := hb.writeHARecord(rt, m, files) |
| if rerr != nil { |
| // Without the record nothing could keep on this copy: the marker |
diff --git a/internal/activator/harelease_test.go b/internal/activator/harelease_test.go| index 31b006482..87e95ea4d 100644 |
| --- a/internal/activator/harelease_test.go |
| +++ b/internal/activator/harelease_test.go |
| @@ -559,11 +559,17 @@ func TestReapedWakeObligationSurvivesRestart(t *testing.T) { |
| if n := len(lease.PendingObligations()); n != 1 { |
| t.Fatalf("the reaper's obligation was dropped: %d pending", n) |
| } |
| - if _, err := s2.b.Acquire(context.Background(), s2.rt); err != nil { |
| - t.Fatal(err) |
| + // The acquire settles the owed marker first. The reaped wake had |
| + // replicated, so its unclean marker is not settled and holds every box |
| + // for a lease term (region HA rev 6.7): the acquire is held, naming the |
| + // marker, and writes nothing more. |
| + _, err := s2.b.Acquire(context.Background(), s2.rt) |
| + var held *errLeaseHeld |
| + if !errors.As(err, &held) || !strings.HasPrefix(held.holder, hafresh.MarkerOwnerPrefix) || held.retryAfter < lease.LeaseTTL-time.Minute { |
| + t.Fatalf("acquire after the owed unclean marker: %v", err) |
| } |
| w := lockWriteLogOf(s) |
| - if len(w) < 2 || !isMarker(w[len(w)-2]) || !isHAHeld(w[len(w)-1], s2.b.self()) || len(lease.PendingObligations()) != 0 { |
| + if len(w) < 1 || !isMarker(w[len(w)-1]) || len(lease.PendingObligations()) != 0 { |
| t.Fatalf("writes %d, pending %d", len(w), len(lease.PendingObligations())) |
| } |
| } |
diff --git a/internal/hafresh/acquire.go b/internal/hafresh/acquire.go| index 5f1a0cdb9..2cf9c6b99 100644 |
| --- a/internal/hafresh/acquire.go |
| +++ b/internal/hafresh/acquire.go |
| @@ -27,10 +27,13 @@ func (a Action) String() string { |
| } |
| // Decision is DecideAcquire's answer. Reason is "absent", "release |
| -// marker", the holder's owner for ActHeld, or the refusal. |
| +// marker", the holder's owner for ActHeld, or the refusal. Until is, for |
| +// ActHeld only, when the lock frees: the owner's expiry, or an unsettled |
| +// marker's opening (MarkerOpensAt). |
| type Decision struct { |
| Action Action |
| Reason string |
| + Until time.Time |
| } |
| // Proofs are the facts DecideAcquire cannot read from the lock. |
| @@ -61,11 +64,18 @@ const ( |
| ReasonTerminated = "holder terminated" |
| ) |
| -// DecideAcquire is the HA acquire's one table (I1), for HA hosts only: |
| +// DecideAcquire is the HA acquire's one table (I1), for HA hosts only. |
| +// term is the lease term (lease.LeaseTTL in production): |
| // |
| // - absent: create (the caller still proves the prefix empty); |
| // - present, not HA-format: refuse, a leftover lock; |
| -// - a release marker, clean or not: take; |
| +// - a clean or settled release marker: take; |
| +// - an unsettled release marker: held until its At plus term, then take |
| +// (MarkerOpensAt). Its holder may have an upload in flight, and the |
| +// successor writes the same prefix: the wait is the margin N-HA9 |
| +// gives a dead owner's writes. No termination proof applies: the |
| +// releaser is usually alive, and a proof would not stop a request S3 |
| +// already has; |
| // - an unexpired HA owner: held, by that owner; |
| // - expired, owned by this box's non-empty instance id: take only with |
| // the same-box emptiness proof, else refuse; |
| @@ -74,58 +84,61 @@ const ( |
| // Expiry alone never hands an HA lock to another box, and a |
| // terminated owner's lock is not taken before it expires (N-HA9); |
| // - expired, owned by a box with no instance id: refuse. |
| -func DecideAcquire(v View, self Self, now time.Time, p Proofs) Decision { |
| +func DecideAcquire(v View, self Self, now time.Time, term time.Duration, p Proofs) Decision { |
| if p.LocalEligible == nil || !p.LocalEligible() { |
| - return Decision{ActRefuse, ReasonPoolIneligible} |
| + return Decision{Action: ActRefuse, Reason: ReasonPoolIneligible} |
| } |
| if v.Absent { |
| - return Decision{ActCreate, ReasonAbsent} |
| + return Decision{Action: ActCreate, Reason: ReasonAbsent} |
| } |
| if !v.HAOn() { |
| - return Decision{ActRefuse, ReasonLeftoverLock} |
| + return Decision{Action: ActRefuse, Reason: ReasonLeftoverLock} |
| } |
| - if v.Lock.Release != nil { |
| - return Decision{ActTake, ReasonMarker} |
| + if m := v.Lock.Release; m != nil { |
| + if opens := MarkerOpensAt(*m, term); !opens.IsZero() && !now.After(opens) { |
| + return Decision{Action: ActHeld, Reason: v.Lock.Owner, Until: opens} |
| + } |
| + return Decision{Action: ActTake, Reason: ReasonMarker} |
| } |
| o, ok := ParseOwner(v.Lock.Owner) |
| if !ok { |
| // HA-format by its marker owner, but without the marker record. |
| - return Decision{ActRefuse, ReasonBadMarker} |
| + return Decision{Action: ActRefuse, Reason: ReasonBadMarker} |
| } |
| if !now.After(v.Lock.ExpiresAt) { |
| - return Decision{ActHeld, v.Lock.Owner} |
| + return Decision{Action: ActHeld, Reason: v.Lock.Owner, Until: v.Lock.ExpiresAt} |
| } |
| if o.IID == "" { |
| - return Decision{ActRefuse, ReasonOtherExpired} |
| + return Decision{Action: ActRefuse, Reason: ReasonOtherExpired} |
| } |
| if o.IID != self.IID { |
| return decideOtherExpired(o, p) |
| } |
| if p.SameBoxEmpty == nil { |
| - return Decision{ActRefuse, ReasonSameBoxUnsure} |
| + return Decision{Action: ActRefuse, Reason: ReasonSameBoxUnsure} |
| } |
| empty, err := p.SameBoxEmpty() |
| if err != nil { |
| - return Decision{ActRefuse, ReasonSameBoxUnsure + ": " + err.Error()} |
| + return Decision{Action: ActRefuse, Reason: ReasonSameBoxUnsure + ": " + err.Error()} |
| } |
| if !empty { |
| - return Decision{ActRefuse, ReasonSameBoxUnsure} |
| + return Decision{Action: ActRefuse, Reason: ReasonSameBoxUnsure} |
| } |
| - return Decision{ActTake, ReasonSameBox} |
| + return Decision{Action: ActTake, Reason: ReasonSameBox} |
| } |
| // decideOtherExpired is the row for an expired lock of another box's |
| // non-empty instance id. |
| func decideOtherExpired(o Owner, p Proofs) Decision { |
| if p.OwnerTerminated == nil { |
| - return Decision{ActRefuse, ReasonOtherExpired} |
| + return Decision{Action: ActRefuse, Reason: ReasonOtherExpired} |
| } |
| gone, err := p.OwnerTerminated(o.IID) |
| if err != nil { |
| - return Decision{ActRefuse, ReasonOtherExpired + ": " + err.Error()} |
| + return Decision{Action: ActRefuse, Reason: ReasonOtherExpired + ": " + err.Error()} |
| } |
| if !gone { |
| - return Decision{ActRefuse, ReasonOtherExpired} |
| + return Decision{Action: ActRefuse, Reason: ReasonOtherExpired} |
| } |
| - return Decision{ActTake, ReasonTerminated} |
| + return Decision{Action: ActTake, Reason: ReasonTerminated} |
| } |
diff --git a/internal/hafresh/acquire_test.go b/internal/hafresh/acquire_test.go| index f0460db10..dabc21bb9 100644 |
| --- a/internal/hafresh/acquire_test.go |
| +++ b/internal/hafresh/acquire_test.go |
| @@ -26,7 +26,7 @@ func TestDecideAcquireTable(t *testing.T) { |
| }{ |
| {View{Absent: true}, Proofs{LocalEligible: func() bool { return true }}, ActCreate}, |
| {View{Lock: Lock{ExpiresAt: exp, Owner: "ip-10-0-0-1:77"}}, Proofs{LocalEligible: func() bool { return true }}, ActRefuse}, |
| - {View{Lock: Lock{Owner: "released/v1;ref=b;iid=i-b", Release: &Marker{Box: "b"}}}, Proofs{LocalEligible: func() bool { return true }}, ActTake}, |
| + {View{Lock: Lock{Owner: "released/v1;ref=b;iid=i-b", Release: &Marker{Box: "b", Settled: true}}}, Proofs{LocalEligible: func() bool { return true }}, ActTake}, |
| {View{Lock: Lock{ExpiresAt: now.Add(time.Minute), Owner: other}}, Proofs{LocalEligible: func() bool { return true }}, ActHeld}, |
| {View{Lock: Lock{ExpiresAt: exp, Owner: other}}, yes, ActRefuse}, |
| {View{Lock: Lock{ExpiresAt: exp, Owner: mine}}, Proofs{LocalEligible: func() bool { return true }}, ActRefuse}, |
| @@ -48,7 +48,7 @@ func TestDecideAcquireTable(t *testing.T) { |
| {View{Lock: Lock{ExpiresAt: exp, Owner: other}}, terminatedErr, ActRefuse}, |
| {View{Lock: Lock{ExpiresAt: exp, Owner: noIIDOther}}, terminated, ActRefuse}, |
| } { |
| - if got := DecideAcquire(c.v, self, now, c.p).Action; got != c.want { |
| + if got := DecideAcquire(c.v, self, now, 15*time.Minute, c.p).Action; got != c.want { |
| t.Errorf("case %d: %v, want %v", i, got, c.want) |
| } |
| } |
| @@ -65,17 +65,17 @@ func TestDecideAcquireTable(t *testing.T) { |
| {View{Lock: Lock{ExpiresAt: exp, Owner: other}}, terminated, ReasonTerminated}, |
| {View{Lock: Lock{ExpiresAt: exp, Owner: mine}}, yes, ReasonSameBox}, |
| } { |
| - if got := DecideAcquire(c.v, self, now, c.p).Reason; got != c.want { |
| + if got := DecideAcquire(c.v, self, now, 15*time.Minute, c.p).Reason; got != c.want { |
| t.Errorf("reason %q, want %q", got, c.want) |
| } |
| } |
| - if got := DecideAcquire(View{Lock: Lock{ExpiresAt: exp, Owner: other}}, self, now, terminatedErr).Reason; !strings.HasPrefix(got, ReasonOtherExpired+": ") { |
| + if got := DecideAcquire(View{Lock: Lock{ExpiresAt: exp, Owner: other}}, self, now, 15*time.Minute, terminatedErr).Reason; !strings.HasPrefix(got, ReasonOtherExpired+": ") { |
| t.Fatalf("terminated-proof error reason %q", got) |
| } |
| // A box whose instance id is still unknown never proves itself the |
| // owner of an expired lock, even one with no iid either. |
| noIID := OwnerFor(Self{Ref: "a"}, 9, true) |
| - if d := DecideAcquire(View{Lock: Lock{ExpiresAt: exp, Owner: noIID}}, Self{Ref: "a"}, now, yes); d.Action != ActRefuse { |
| + if d := DecideAcquire(View{Lock: Lock{ExpiresAt: exp, Owner: noIID}}, Self{Ref: "a"}, now, 15*time.Minute, yes); d.Action != ActRefuse { |
| t.Fatalf("no iid: %+v", d) |
| } |
| } |
| @@ -84,11 +84,11 @@ func TestDecideAcquireReasons(t *testing.T) { |
| now := time.Unix(1_800_000_000, 0) |
| self := Self{Ref: "a", IID: "i-a"} |
| v := View{Lock: Lock{ExpiresAt: now.Add(-time.Minute), Owner: OwnerFor(Self{Ref: "b", IID: "i-b"}, 9, true)}} |
| - d := DecideAcquire(v, self, now, Proofs{LocalEligible: func() bool { return true }, OwnerTerminated: func(string) (bool, error) { return true, nil }}) |
| + d := DecideAcquire(v, self, now, 15*time.Minute, Proofs{LocalEligible: func() bool { return true }, OwnerTerminated: func(string) (bool, error) { return true, nil }}) |
| if d.Action != ActTake || d.Reason != ReasonTerminated { |
| t.Fatalf("terminated take: %+v", d) |
| } |
| - d = DecideAcquire(v, self, now, Proofs{LocalEligible: func() bool { return true }, OwnerTerminated: func(string) (bool, error) { return false, errors.New("throttled") }}) |
| + d = DecideAcquire(v, self, now, 15*time.Minute, Proofs{LocalEligible: func() bool { return true }, OwnerTerminated: func(string) (bool, error) { return false, errors.New("throttled") }}) |
| if d.Action != ActRefuse || d.Reason != ReasonOtherExpired+": throttled" { |
| t.Fatalf("proof error: %+v", d) |
| } |
| @@ -119,7 +119,7 @@ func TestDecideAcquireProofScope(t *testing.T) { |
| SameBoxEmpty: func() (bool, error) { same++; return true, nil }, |
| OwnerTerminated: func(iid string) (bool, error) { term = append(term, iid); return true, nil }, |
| } |
| - DecideAcquire(View{Lock: c.lock}, self, now, p) |
| + DecideAcquire(View{Lock: c.lock}, self, now, 15*time.Minute, p) |
| if strings.Join(term, ",") != strings.Join(c.wantTerm, ",") || same != c.wantSameBox { |
| t.Errorf("%s: OwnerTerminated calls %v, SameBoxEmpty calls %d; want %v, %d", c.name, term, same, c.wantTerm, c.wantSameBox) |
| } |
| @@ -131,7 +131,7 @@ func TestDecideAcquireProofScope(t *testing.T) { |
| func TestDecideAcquireStoppedOwnerIsNotTaken(t *testing.T) { |
| now := time.Unix(1_800_000_000, 0) |
| v := View{Lock: Lock{ExpiresAt: now.Add(-time.Minute), Owner: OwnerFor(Self{Ref: "b", IID: "i-b"}, 9, true)}} |
| - d := DecideAcquire(v, Self{Ref: "a", IID: "i-a"}, now, Proofs{LocalEligible: func() bool { return true }, OwnerTerminated: func(string) (bool, error) { return false, nil }}) |
| + d := DecideAcquire(v, Self{Ref: "a", IID: "i-a"}, now, 15*time.Minute, Proofs{LocalEligible: func() bool { return true }, OwnerTerminated: func(string) (bool, error) { return false, nil }}) |
| if d.Action != ActRefuse || d.Reason != ReasonOtherExpired { |
| t.Fatalf("%+v", d) |
| } |
| @@ -192,3 +192,84 @@ func TestDecodeLockAndHAOn(t *testing.T) { |
| t.Fatal("an absent lock is HA-format") |
| } |
| } |
| + |
| +// The containment of the unclean-release late write (2026-11-12): a clean |
| +// or settled marker is taken at once; an unsettled one is held until its |
| +// At plus the lease term, equality held, then taken; one with no At (none |
| +// is written) is open. No proof is asked for a marker, the same box's |
| +// included. |
| +func TestDecideAcquireUnsettledMarkerWaitsALeaseTerm(t *testing.T) { |
| + now := time.Unix(1_800_000_000, 0) |
| + const term = 15 * time.Minute |
| + self := Self{Ref: "a", IID: "i-a"} |
| + p := Proofs{LocalEligible: func() bool { return true }, |
| + SameBoxEmpty: func() (bool, error) { t.Error("emptiness proof asked for a marker"); return true, nil }, |
| + OwnerTerminated: func(string) (bool, error) { t.Error("termination proof asked for a marker"); return true, nil }} |
| + view := func(m Marker) View { |
| + return View{Lock: Lock{ExpiresAt: markerExpiry, Owner: MarkerOwner(m), Release: &m}} |
| + } |
| + other := Marker{V: 1, Box: "b", IID: "i-b", Lifetime: "L1", TXID: 7} |
| + mine := Marker{V: 1, Box: "a", IID: "i-a", Lifetime: "L1", TXID: 7} |
| + at := func(m Marker, t time.Time, clean, settled bool) Marker { |
| + m.At, m.Clean, m.Settled = t, clean, settled |
| + return m |
| + } |
| + for _, c := range []struct { |
| + name string |
| + m Marker |
| + action Action |
| + reason string |
| + until time.Time |
| + }{ |
| + {"clean, just written", at(other, now, true, true), ActTake, ReasonMarker, time.Time{}}, |
| + {"clean, settled not recorded", at(other, now, true, false), ActTake, ReasonMarker, time.Time{}}, |
| + {"unclean, settled", at(other, now, false, true), ActTake, ReasonMarker, time.Time{}}, |
| + {"unsettled, just written", at(other, now, false, false), ActHeld, MarkerOwner(other), now.Add(term)}, |
| + {"unsettled, a second short", at(other, now.Add(-term+time.Second), false, false), ActHeld, MarkerOwner(other), now.Add(time.Second)}, |
| + {"unsettled, equality", at(other, now.Add(-term), false, false), ActHeld, MarkerOwner(other), now}, |
| + {"unsettled, a term past", at(other, now.Add(-term-time.Nanosecond), false, false), ActTake, ReasonMarker, time.Time{}}, |
| + {"unsettled, this box's own", at(mine, now.Add(-time.Minute), false, false), ActHeld, MarkerOwner(mine), now.Add(term - time.Minute)}, |
| + {"unsettled, no At", at(other, time.Time{}, false, false), ActTake, ReasonMarker, time.Time{}}, |
| + {"settled, no At", at(other, time.Time{}, false, true), ActTake, ReasonMarker, time.Time{}}, |
| + {"unclean, finalized (files only)", func() Marker { m := at(other, now, false, false); m.Finalized = true; return m }(), ActTake, ReasonMarker, time.Time{}}, |
| + } { |
| + d := DecideAcquire(view(c.m), self, now, term, p) |
| + if d.Action != c.action || d.Reason != c.reason || !d.Until.Equal(c.until) { |
| + t.Errorf("%s: %+v, want %v %q until %v", c.name, d, c.action, c.reason, c.until) |
| + } |
| + } |
| + // An unexpired owner's held answer carries its expiry. |
| + exp := now.Add(time.Minute) |
| + if d := DecideAcquire(View{Lock: Lock{ExpiresAt: exp, Owner: OwnerFor(Self{Ref: "b", IID: "i-b"}, 9, true)}}, self, now, term, p); d.Action != ActHeld || !d.Until.Equal(exp) { |
| + t.Fatalf("owner held: %+v", d) |
| + } |
| +} |
| + |
| +// A marker written before the field reads as unsettled, and the field |
| +// round-trips; a settled false is left out of the body. |
| +func TestMarkerSettledField(t *testing.T) { |
| + old := []byte(`{"generation":3,"expires_at":"1970-01-01T00:00:00Z","owner":"released/v1;ref=b;iid=i-b","carlos_release":{"v":1,"box":"b","iid":"i-b","lifetime":"L1","txid":9,"files_gen":"","at":"2026-11-12T10:00:00Z","clean":false}}`) |
| + v, err := DecodeLock(old, "e1") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if v.Lock.Release.Settled { |
| + t.Fatal("an old marker read as settled") |
| + } |
| + if opens := MarkerOpensAt(*v.Lock.Release, time.Minute); !opens.Equal(time.Date(2026, 11, 12, 10, 1, 0, 0, time.UTC)) { |
| + t.Fatalf("old marker opens %v", opens) |
| + } |
| + for _, settled := range []bool{false, true} { |
| + body, err := MarkerBody(3, Marker{V: 1, Box: "b", At: time.Unix(1, 0).UTC(), Settled: settled}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := strings.Contains(string(body), `"settled"`); got != settled { |
| + t.Fatalf("settled %v: body %s", settled, body) |
| + } |
| + v, err := DecodeLock(body, "e") |
| + if err != nil || v.Lock.Release.Settled != settled { |
| + t.Fatalf("settled %v: %+v %v", settled, v, err) |
| + } |
| + } |
| +} |
diff --git a/internal/hafresh/lock.go b/internal/hafresh/lock.go| index 261381e51..2cc57624d 100644 |
| --- a/internal/hafresh/lock.go |
| +++ b/internal/hafresh/lock.go |
| @@ -13,6 +13,19 @@ import ( |
| // generation, and whether that release was clean (the final sync |
| // succeeded and the files tree was complete). Only a clean marker can let |
| // a box keep its local copy; every other release writes Clean false. |
| +// |
| +// Settled says the releasing holder never replicated under the lease (a |
| +// failed wake before replication, an acquire's late-acknowledgement |
| +// cleanup, an adoption): no replica request of its can be in flight. A |
| +// holder that did replicate never writes it, even after a final sync |
| +// that succeeded: litestream's store close cancels its monitors' requests |
| +// (compaction, snapshot, retention) without proof that S3 did not get |
| +// them. An unclean marker that is not settled may therefore have a write |
| +// in flight into the prefix the successor writes, so DecideAcquire holds |
| +// it for a lease term from At (MarkerOpensAt). A clean marker opens at |
| +// once whatever it says (Paul, 2026-11-12: the drain's fast handover |
| +// stays); storage generations close that exposure. Markers written before |
| +// the field read as not settled. |
| type Marker struct { |
| V int `json:"v"` |
| Box string `json:"box"` |
| @@ -22,6 +35,31 @@ type Marker struct { |
| FilesGen string `json:"files_gen"` |
| At time.Time `json:"at"` |
| Clean bool `json:"clean"` |
| + Settled bool `json:"settled,omitempty"` |
| + // Finalized says the release's replica finalization (final sync and |
| + // store close) and its final files commit both succeeded: the marker is |
| + // unclean only for a reason that left no storage write outstanding (a |
| + // files tree that could not be published completely, a local release |
| + // record that could not be written). Its storage exposure is then a |
| + // clean marker's, and it opens at once like one (2026-11-12 follow-up: |
| + // files objects are create-only and the manifest moves by CAS, so a |
| + // files-only release cannot collide the way an L0 can). |
| + Finalized bool `json:"finalized,omitempty"` |
| +} |
| + |
| +// MarkerOpensAt is when m lets another holder take the lock, for a lease |
| +// term of term: at once (the zero time) when m is clean, settled or |
| +// finalized; |
| +// otherwise At plus term, the same margin an expired lock gives a write |
| +// its dead owner already sent (N-HA9). At is written after the holder's |
| +// finalization, so every replica request it sent was sent before At. |
| +// Every marker the lease package writes carries an At (releaseWithMarker |
| +// stamps it); one without reads as written at the zero time, long open. |
| +func MarkerOpensAt(m Marker, term time.Duration) time.Time { |
| + if m.Clean || m.Settled || m.Finalized || m.At.IsZero() { |
| + return time.Time{} |
| + } |
| + return m.At.Add(term) |
| } |
| // Lock is lock.json as region HA reads it: litestream's lease fields, plus |
diff --git a/internal/hafresh/pools_test.go b/internal/hafresh/pools_test.go| index 505c327c0..368fa0a0f 100644 |
| --- a/internal/hafresh/pools_test.go |
| +++ b/internal/hafresh/pools_test.go |
| @@ -21,7 +21,7 @@ func TestAcquireHAPoolEligibility(t *testing.T) { |
| p := Proofs{SameBoxEmpty: func() (bool, error) { t.Error("emptiness proof called"); return true, nil }, OwnerTerminated: func(string) (bool, error) { t.Error("termination proof called"); return true, nil }} |
| for _, eligible := range []func() bool{nil, func() bool { return false }} { |
| p.LocalEligible = eligible |
| - d := DecideAcquire(v, me, now, p) |
| + d := DecideAcquire(v, me, now, 15*time.Minute, p) |
| if d.Action != ActRefuse || d.Reason != "ha_pool_ineligible" { |
| t.Fatalf("decision %+v", d) |
| } |
diff --git a/internal/host/haplacement_budget_test.go b/internal/host/haplacement_budget_test.go| index 79cc38b95..b90a4a552 100644 |
| --- a/internal/host/haplacement_budget_test.go |
| +++ b/internal/host/haplacement_budget_test.go |
| @@ -330,10 +330,10 @@ func testColdPlacementExpiryEquality(t *testing.T) { |
| now := time.Now() |
| self := hafresh.Self{Ref: "leo", IID: "i-leo", Account: "111122223333", Region: "eu-west-1"} |
| view := hafresh.View{Lock: hafresh.Lock{Generation: 1, Owner: hafresh.OwnerFor(self, 123, true), ExpiresAt: now}} |
| - if d := hafresh.DecideAcquire(view, self, now, hafresh.Proofs{LocalEligible: func() bool { return true }, SameBoxEmpty: func() (bool, error) { t.Error("equality requested proof"); return true, nil }}); d.Action != hafresh.ActHeld { |
| + if d := hafresh.DecideAcquire(view, self, now, 15*time.Minute, hafresh.Proofs{LocalEligible: func() bool { return true }, SameBoxEmpty: func() (bool, error) { t.Error("equality requested proof"); return true, nil }}); d.Action != hafresh.ActHeld { |
| t.Fatal("equality was not held", d) |
| } |
| - if d := hafresh.DecideAcquire(view, self, now.Add(time.Nanosecond), hafresh.Proofs{LocalEligible: func() bool { return true }}); d.Action != hafresh.ActRefuse { |
| + if d := hafresh.DecideAcquire(view, self, now.Add(time.Nanosecond), 15*time.Minute, hafresh.Proofs{LocalEligible: func() bool { return true }}); d.Action != hafresh.ActRefuse { |
| t.Fatal("missing proof did not refuse", d) |
| } |
| } |
diff --git a/internal/lease/ha.go b/internal/lease/ha.go| index f27722f16..7d5fe8a29 100644 |
| --- a/internal/lease/ha.go |
| +++ b/internal/lease/ha.go |
| @@ -118,7 +118,7 @@ func acquireHARestricted(ctx context.Context, bucket, prefix, region string, bas |
| } |
| } |
| proofs := bindTerminationProof(ctx, client, bucket, loc, region, base, me, v, p) |
| - d := hafresh.DecideAcquire(v, me, time.Now(), proofs) |
| + d := hafresh.DecideAcquire(v, me, time.Now(), ttl, proofs) |
| won = d |
| if p.ObserveRefusal != nil && (d.Action == hafresh.ActRefuse || d.Action == hafresh.ActHeld) { |
| p.ObserveRefusal(v, d) |
| @@ -136,7 +136,8 @@ func acquireHARestricted(ctx context.Context, bucket, prefix, region string, bas |
| case hafresh.ActTake: |
| return nil |
| case hafresh.ActHeld: |
| - return &HeldError{Owner: v.Lock.Owner, ExpiresAt: v.Lock.ExpiresAt, Generation: v.Lock.Generation} |
| + // Until: the owner's expiry, or an unsettled marker's opening. |
| + return &HeldError{Owner: v.Lock.Owner, ExpiresAt: d.Until, Generation: v.Lock.Generation} |
| default: |
| return &RefusedError{Reason: d.Reason} |
| } |
| @@ -158,7 +159,8 @@ func acquireHARestricted(ctx context.Context, bucket, prefix, region string, bas |
| cur := rn.stop() |
| relCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| defer cancel() |
| - return nil, errors.Join(fmt.Errorf("acquire HA lease: %w", err), releaseWithMarker(relCtx, leaser, region, cur, uncleanMarker(base, 0))) |
| + // Nothing replicated under it: the marker is settled. |
| + return nil, errors.Join(fmt.Errorf("acquire HA lease: %w", err), releaseWithMarker(relCtx, leaser, region, cur, uncleanMarker(base, 0, true))) |
| } |
| log.Printf("lease: %s: HA lease acquired in %s (%s)", prefix, time.Since(began).Round(time.Millisecond), takeWord(won, view)) |
| return &Held{leaser: leaser, region: region, rn: rn, ha: true, view: view, base: base}, nil |
diff --git a/internal/lease/ha_observe_test.go b/internal/lease/ha_observe_test.go| index 547c45ae1..3afb1eb03 100644 |
| --- a/internal/lease/ha_observe_test.go |
| +++ b/internal/lease/ha_observe_test.go |
| @@ -25,7 +25,7 @@ func TestAcquireHAObserveRefusal(t *testing.T) { |
| want.Reason = hafresh.ReasonSameBoxUnsure |
| case "held": |
| expiry = time.Now().Add(time.Hour).Truncate(time.Second) |
| - want = hafresh.Decision{Action: hafresh.ActHeld, Reason: owner} |
| + want = hafresh.Decision{Action: hafresh.ActHeld, Reason: owner, Until: expiry.UTC()} |
| case "legacy": |
| owner = "old:123" |
| want.Reason = hafresh.ReasonLeftoverLock |
diff --git a/internal/lease/lease.go b/internal/lease/lease.go| index 53a8298cb..2aae06f51 100644 |
| --- a/internal/lease/lease.go |
| +++ b/internal/lease/lease.go |
| @@ -167,6 +167,11 @@ type Held struct { |
| // the moves checkpoint): its store starts no compaction, snapshot or L0 |
| // retention monitor. Guarded by mu. |
| oneShot bool |
| + // stored is set once this handle has built a litestream store |
| + // (Replicate, Checkpoint), successful or not: from then on a replica |
| + // write it sent may still be in flight, so its own releases write |
| + // markers that are not settled. Guarded by mu. |
| + stored bool |
| } |
| // Acquire claims the single-writer lease at s3://bucket/prefix/lock.json |
| @@ -328,7 +333,7 @@ func (h *Held) Release(ctx context.Context) error { |
| return nil |
| } |
| if h.ha { |
| - return releaseWithMarker(ctx, h.leaser, h.region, lease, uncleanMarker(h.base, 0)) |
| + return releaseWithMarker(ctx, h.leaser, h.region, lease, uncleanMarker(h.base, 0, !h.wroteReplica())) |
| } |
| err := h.leaser.ReleaseLease(ctx, lease) |
| if err != nil && !releaseSettled(err) { |
| @@ -458,6 +463,7 @@ func (h *Held) newStore(dbPath string, syncInterval time.Duration) (*litestream. |
| db.SetMetaPath(filepath.Join(filepath.Dir(dbPath), ".activator-"+filepath.Base(dbPath)+"-litestream")) |
| db.MonitorInterval = dbMonitorInterval |
| h.mu.Lock() |
| + h.stored = true |
| if h.monitor > 0 { |
| db.MonitorInterval = h.monitor |
| } |
diff --git a/internal/lease/release.go b/internal/lease/release.go| index 9341c89d0..05436b0bb 100644 |
| --- a/internal/lease/release.go |
| +++ b/internal/lease/release.go |
| @@ -120,12 +120,21 @@ func conditionFailed(err error) bool { |
| // uncleanMarker is the marker every release but the clean one writes: the |
| // handle's base (box, instance id, lifetime), Clean false, at txid. |
| -func uncleanMarker(base hafresh.Marker, txid uint64) hafresh.Marker { |
| +// settled says the handle never replicated (hafresh.Marker.Settled). |
| +func uncleanMarker(base hafresh.Marker, txid uint64, settled bool) hafresh.Marker { |
| m := base |
| - m.V, m.TXID, m.FilesGen, m.Clean, m.At = 1, txid, "", false, time.Now().UTC() |
| + m.V, m.TXID, m.FilesGen, m.Clean, m.Settled, m.Finalized, m.At = 1, txid, "", false, settled, false, time.Now().UTC() |
| return m |
| } |
| +// wroteReplica reports whether h has built a litestream store, so that a |
| +// replica write it sent may still be in flight (Held.stored). |
| +func (h *Held) wroteReplica() bool { |
| + h.mu.Lock() |
| + defer h.mu.Unlock() |
| + return h.stored |
| +} |
| + |
| // ErrNotHA refuses a marker release on a legacy handle. |
| var ErrNotHA = errors.New("lease: not an HA lease") |
| @@ -155,7 +164,9 @@ func (h *Held) SetMonitorInterval(d time.Duration) { |
| // ReleaseMarker releases an HA lease that never replicated, through the |
| // marker, and spends the handle. Nothing was synced under this handle, so |
| -// the marker is never clean, whatever m says. |
| +// the marker is never clean, whatever m says. It is settled unless the |
| +// handle built a store (a failed Replicate, a Checkpoint): only then can a |
| +// replica write of its own still be in flight. |
| func (h *Held) ReleaseMarker(ctx context.Context, m hafresh.Marker) error { |
| if !h.ha { |
| return ErrNotHA |
| @@ -166,7 +177,8 @@ func (h *Held) ReleaseMarker(ctx context.Context, m hafresh.Marker) error { |
| defer h.finish(true, nil) |
| lease := h.rn.stop() |
| m = withBase(h.base, m) |
| - m.Clean = false |
| + m.Clean, m.Finalized = false, false |
| + m.Settled = !h.wroteReplica() |
| return releaseWithMarker(ctx, h.leaser, h.region, lease, m) |
| } |
| @@ -225,9 +237,18 @@ var finalSyncHook = func() {} |
| // finalize is the HA replicator's one finalization, serialized and |
| // cached: the forced sync (when sync is set) and the store's close, under |
| // finMu. Every release calls it before it writes the marker, and waits |
| -// for one already running, so no replica write can follow the marker. |
| -// Once it has run, nothing syncs again: later calls, SyncAndWait |
| -// included, get its answer or ErrSpent. |
| +// for one already running, so no replica request is *sent* after the |
| +// marker. That is not a completion barrier: a request the close cancelled |
| +// (a timed-out final sync's upload, a compaction, snapshot or retention |
| +// pass of the store's monitors) got no answer, and S3 can still apply it |
| +// after the marker. A finalization that fails therefore leaves the marker |
| +// unclean, and one that succeeds can still have cancelled a monitor |
| +// pass: no marker of a replicator is ever settled |
| +// (hafresh.Marker.Settled), so after an unclean one the successor waits a |
| +// lease term (hafresh.DecideAcquire). A clean marker carries the monitor |
| +// exposure too, until storage generations close it (N-HA9). Once it has |
| +// run, nothing syncs again: later calls, SyncAndWait included, get its |
| +// answer or ErrSpent. |
| func (r *Replicator) finalize(ctx context.Context, sync, snapshot bool) (uint64, error) { |
| ctx = withFinalization(ctx) // the fence gate lets these replica calls through |
| r.finMu.Lock() |
| @@ -271,8 +292,12 @@ func (r *Replicator) finalize(ctx context.Context, sync, snapshot bool) (uint64, |
| // ReleaseMarker writes m as the release marker and spends the replicator. |
| // It finalizes first (waiting for a Finish already running) if Finish has |
| // not run. The TXID is always the finalization's, and a marker is clean |
| -// only if m says so and the finalization succeeded. A failure is a |
| -// persisted *ObligationError. |
| +// only if m says so and the finalization succeeded. It is never settled, |
| +// whatever m says (hafresh.Marker.Settled), and finalized only if m says |
| +// so (the caller's files commit succeeded) and the finalization did too |
| +// (hafresh.Marker.Finalized). Otherwise the marker written |
| +// is m: pool withdrawal compares it with the local release record built |
| +// from the same m. A failure is a persisted *ObligationError. |
| func (r *Replicator) ReleaseMarker(ctx context.Context, m hafresh.Marker) error { |
| if !r.ha { |
| return ErrNotHA |
| @@ -287,8 +312,9 @@ func (r *Replicator) ReleaseMarker(ctx context.Context, m hafresh.Marker) error |
| txid, err := r.finalize(ctx, true, false) |
| m = withBase(r.base, m) |
| m.TXID = txid |
| + m.Settled = false |
| if err != nil { |
| - m.Clean = false |
| + m.Clean, m.Finalized = false, false |
| } |
| return releaseWithMarker(ctx, r.leaser, r.region, r.rn.stop(), m) |
| } |
| @@ -296,7 +322,8 @@ func (r *Replicator) ReleaseMarker(ctx context.Context, m hafresh.Marker) error |
| // closeHA is Close for an HA replicator: the shared finalization (as |
| // Close syncs: the forced sync initializes the DB, the store's close is |
| // the sync that counts), then the unclean marker at the replica's |
| -// position, on its own budget. A second release is a no-op. |
| +// position, on its own budget, never settled. A second release is a |
| +// no-op. |
| func (r *Replicator) closeHA(ctx context.Context) error { |
| r.mu.Lock() |
| if r.released { |
| @@ -309,7 +336,7 @@ func (r *Replicator) closeHA(ctx context.Context) error { |
| lease := r.rn.stop() |
| relCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| defer cancel() |
| - return errors.Join(r.storeCloseErr(), releaseWithMarker(relCtx, r.leaser, r.region, lease, uncleanMarker(r.base, txid))) |
| + return errors.Join(r.storeCloseErr(), releaseWithMarker(relCtx, r.leaser, r.region, lease, uncleanMarker(r.base, txid, false))) |
| } |
| func (r *Replicator) storeCloseErr() error { |
diff --git a/internal/lease/termination_proof_test.go b/internal/lease/termination_proof_test.go| index 8a96d7344..346ad9d84 100644 |
| --- a/internal/lease/termination_proof_test.go |
| +++ b/internal/lease/termination_proof_test.go |
| @@ -154,7 +154,7 @@ func TestTerminationProofAcquireOnly(t *testing.T) { |
| t.Fatal(err) |
| } |
| bound := bindTerminationProof(ctx, client, fx.Bucket, "instances/shop", region, hafresh.Marker{Lifetime: "life"}, me, v, p) |
| - if d := hafresh.DecideAcquire(v, me, at, bound); d.Action != hafresh.ActHeld { |
| + if d := hafresh.DecideAcquire(v, me, at, LeaseTTL, bound); d.Action != hafresh.ActHeld { |
| t.Fatal(d) |
| } |
| } else { |
diff --git a/internal/lease/unclean_marker_test.go b/internal/lease/unclean_marker_test.go| new file mode 100644 |
| index 000000000..8ebbc57d5 |
| --- /dev/null |
| +++ b/internal/lease/unclean_marker_test.go |
| @@ -0,0 +1,399 @@ |
| +package lease_test |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + lsfile "github.com/benbjohnson/litestream/file" |
| + |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/lease/leasetest" |
| + locktest "github.com/carlosframework/platform/internal/lease/locktest" |
| +) |
| + |
| +// boxB makes this process box b, the successor in these tests. |
| +func boxB() { |
| + lease.SetSelf(hafresh.Self{Ref: "b", IID: "i-b", Account: "111122223333", Region: "eu-west-1"}) |
| +} |
| + |
| +func acquireAsB(fx *locktest.LockFixture, prefix string, ttl time.Duration) (*lease.Held, error) { |
| + return lease.AcquireHATTL(ctx, fx.Bucket, prefix, "", hafresh.Marker{V: 1, Lifetime: "L1"}, hafresh.Proofs{LocalEligible: func() bool { return true }}, ttl) |
| +} |
| + |
| +// The containment (2026-11-12) leaves the fast handovers alone: a clean |
| +// marker (held requests' drain depends on it) and a release that never |
| +// replicated are taken at once, under an hour-long lease. The clean |
| +// marker written is exactly the one the caller passed (with the |
| +// finalization's TXID): pool withdrawal compares it with the local release |
| +// record built from the same marker. |
| +func TestCleanAndNeverReplicatedMarkersAreTakenAtOnce(t *testing.T) { |
| + const ttl = time.Hour |
| + for name, release := range map[string]func(t *testing.T, fx *locktest.LockFixture, prefix string){ |
| + "clean": func(t *testing.T, fx *locktest.LockFixture, prefix string) { |
| + r := haReplicatorTTL(t, fx, prefix, ttl) |
| + txid, err := r.Finish(ctx) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + m := hafresh.Marker{V: 1, Box: "a", IID: "i-a", Lifetime: "L1", TXID: txid, FilesGen: "1:aa", At: time.Now().UTC().Truncate(time.Second), Clean: true} |
| + if err := r.ReleaseMarker(ctx, m); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := lockView(t, fx, prefix).Lock.Release; got == nil || *got != m { |
| + t.Fatalf("the clean marker written %+v, not the one passed %+v", got, m) |
| + } |
| + }, |
| + "never replicated": func(t *testing.T, fx *locktest.LockFixture, prefix string) { |
| + if err := haHeldTTL(t, fx, prefix, ttl).Release(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, |
| + "never replicated, through the marker": func(t *testing.T, fx *locktest.LockFixture, prefix string) { |
| + if err := haHeldTTL(t, fx, prefix, ttl).ReleaseMarker(ctx, hafresh.Marker{V: 1}); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, |
| + "unclean, finalized (files only)": func(t *testing.T, fx *locktest.LockFixture, prefix string) { |
| + r := haReplicatorTTL(t, fx, prefix, ttl) |
| + if _, err := r.Finish(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := r.ReleaseMarker(ctx, hafresh.Marker{V: 1, Finalized: true}); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + haBox(t) |
| + fx := locktest.NewLockFixture(t) |
| + release(t, fx, "instances/h") |
| + m := lockView(t, fx, "instances/h").Lock.Release |
| + if m == nil || !(m.Clean || m.Settled || m.Finalized) || m.At.IsZero() { |
| + t.Fatalf("marker %+v: want clean or settled, with its time", m) |
| + } |
| + boxB() |
| + h, err := acquireAsB(fx, "instances/h", ttl) |
| + if err != nil { |
| + t.Fatalf("successor: %v", err) |
| + } |
| + if err := h.Release(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// Every unclean release of a handle that built a store is held a lease |
| +// term from its At, whether or not its final sync succeeded: the store's |
| +// close cancels monitor requests without proof S3 did not get them (Astra |
| +// containment R1 P1). That includes a files-only unclean release, a Close |
| +// after a good finalization, an abandoned replicator, and a checkpoint's |
| +// handle. |
| +func TestReplicatedUncleanMarkersAreNotSettled(t *testing.T) { |
| + const ttl = time.Hour |
| + for name, release := range map[string]func(t *testing.T, fx *locktest.LockFixture, prefix string){ |
| + "unclean over a good final sync": func(t *testing.T, fx *locktest.LockFixture, prefix string) { |
| + r := haReplicatorTTL(t, fx, prefix, ttl) |
| + if _, err := r.Finish(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := r.ReleaseMarker(ctx, hafresh.Marker{V: 1, Settled: true}); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, |
| + "closed after a good finalization": func(t *testing.T, fx *locktest.LockFixture, prefix string) { |
| + if err := haReplicatorTTL(t, fx, prefix, ttl).Close(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, |
| + "abandoned, claiming clean and finalized": func(t *testing.T, fx *locktest.LockFixture, prefix string) { |
| + r := haReplicatorTTL(t, fx, prefix, ttl) |
| + r.Abandon(ctx) |
| + if err := r.ReleaseMarker(ctx, hafresh.Marker{V: 1, Clean: true, Finalized: true}); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, |
| + "checkpointed handle, claiming finalized": func(t *testing.T, fx *locktest.LockFixture, prefix string) { |
| + h := haHeldTTL(t, fx, prefix, ttl) |
| + lease.SetReplicaClientForTest(h, lsfile.NewReplicaClient(t.TempDir())) |
| + if _, err := h.Checkpoint(ctx, tempDB(t)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := h.ReleaseMarker(ctx, hafresh.Marker{V: 1, Finalized: true}); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + haBox(t) |
| + fx := locktest.NewLockFixture(t) |
| + release(t, fx, "instances/h") |
| + v := lockView(t, fx, "instances/h") |
| + m := v.Lock.Release |
| + if m == nil || m.Clean || m.Settled || m.Finalized || m.At.IsZero() { |
| + t.Fatalf("marker %+v: want unclean, not settled, not finalized, with its time", m) |
| + } |
| + boxB() |
| + _, err := acquireAsB(fx, "instances/h", ttl) |
| + var he *lease.HeldError |
| + if !errors.As(err, &he) || he.Owner != v.Lock.Owner || !he.ExpiresAt.Equal(m.At.Add(ttl)) { |
| + t.Fatalf("successor: %v (want held until %v)", err, m.At.Add(ttl)) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// An unsettled marker (a replicator whose finalization failed) holds every |
| +// box, its own included, until its At plus the lease term: a held answer |
| +// naming the marker and the time it opens, nothing written. Then it is |
| +// taken. |
| +func TestUnsettledMarkerIsHeldForALeaseTerm(t *testing.T) { |
| + const ttl = 2 * time.Second |
| + haBox(t) |
| + fx := locktest.NewLockFixture(t) |
| + r := haReplicatorTTL(t, fx, "instances/h", ttl) |
| + r.Abandon(ctx) // no final sync: the finalization fails |
| + if err := r.ReleaseMarker(ctx, hafresh.Marker{V: 1, Clean: true}); err != nil { |
| + t.Fatal(err) |
| + } |
| + v := lockView(t, fx, "instances/h") |
| + m := v.Lock.Release |
| + if m == nil || m.Clean || m.Settled || m.At.IsZero() { |
| + t.Fatalf("marker %+v: want unclean and unsettled", m) |
| + } |
| + opens := m.At.Add(ttl) |
| + for _, who := range []string{"same box", "another box"} { |
| + if who == "another box" { |
| + boxB() |
| + } |
| + before := len(writes(fx)) |
| + _, err := lease.AcquireHATTL(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1, Lifetime: "L1"}, hafresh.Proofs{LocalEligible: func() bool { return true }}, ttl) |
| + var he *lease.HeldError |
| + if !errors.As(err, &he) || he.Owner != v.Lock.Owner || !he.ExpiresAt.Equal(opens) { |
| + t.Fatalf("%s before the term: %v (want held by %q until %v)", who, err, v.Lock.Owner, opens) |
| + } |
| + if n := len(writes(fx)); n != before { |
| + t.Fatalf("%s: a held answer wrote: %v", who, writes(fx)[before:]) |
| + } |
| + } |
| + time.Sleep(time.Until(opens) + 100*time.Millisecond) |
| + h, err := acquireAsB(fx, "instances/h", ttl) |
| + if err != nil { |
| + t.Fatalf("after the term: %v", err) |
| + } |
| + if err := h.Release(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// The witness of the wake-race review's P1, for region HA (it was |
| +// TestWitnessLateWriteFromAnEarlierHolderKeepsTheSuccessorsHistory on |
| +// branch witness-stale-holder-late-write, legacy leases). Holder A's final |
| +// sync times out with its L0 upload [P+1..P+1] at the server, unanswered; |
| +// its release writes the marker anyway, unclean. Before the containment B |
| +// took that marker at once, restored to P, wrote its own [P+1..P+1] (the |
| +// same key) and A's late request then replaced it. |
| +// |
| +// Now the marker is unsettled: B is held until A's At plus the lease |
| +// term, the margin N-HA9 gives a dead owner's writes. A's request lands |
| +// inside it (the partition heals), B restores it, and B's history |
| +// continues after it: nothing of B's is replaced. A write later than a |
| +// whole lease term is the residual risk storage generations close. |
| +func TestUnsettledMarkerKeepsALateWriteOutOfTheSuccessorsHistory(t *testing.T) { |
| + const ( |
| + bucket = "data" |
| + prefix = "instances/w.example.com" |
| + region = "test-region" |
| + ttl = 3 * time.Second |
| + ) |
| + haBox(t) |
| + store := leasetest.NewVersionedBucket() |
| + store.AddBucket(bucket) |
| + inner, _ := leasetest.NewS3Server(store) |
| + var ( |
| + partitioned atomic.Bool |
| + healed = make(chan struct{}) |
| + held sync.WaitGroup |
| + mu sync.Mutex |
| + heldKeys []string |
| + bPhase atomic.Bool |
| + bKeys = map[string]bool{} |
| + ) |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + key := strings.TrimPrefix(r.URL.Path, "/"+bucket+"/") |
| + if r.Method == http.MethodPut && partitioned.Load() && !strings.HasSuffix(key, "lock.json") { |
| + body, err := io.ReadAll(r.Body) |
| + if err != nil { |
| + return |
| + } |
| + held.Add(1) |
| + defer held.Done() |
| + mu.Lock() |
| + heldKeys = append(heldKeys, key) |
| + mu.Unlock() |
| + <-healed |
| + r.Body = io.NopCloser(bytes.NewReader(body)) |
| + } |
| + if r.Method == http.MethodPut && bPhase.Load() && !strings.HasSuffix(key, "lock.json") { |
| + mu.Lock() |
| + bKeys[key] = true |
| + mu.Unlock() |
| + } |
| + inner.ServeHTTP(w, r) |
| + })) |
| + t.Cleanup(srv.Close) |
| + heal := sync.OnceFunc(func() { close(healed) }) |
| + t.Cleanup(heal) |
| + t.Setenv("AWS_ACCESS_KEY_ID", "test-key") |
| + t.Setenv("AWS_SECRET_ACCESS_KEY", "test-secret") |
| + t.Setenv("AWS_SESSION_TOKEN", "") |
| + t.Setenv("AWS_EC2_METADATA_DISABLED", "true") |
| + t.Setenv("AWS_CONFIG_FILE", filepath.Join(t.TempDir(), "absent")) |
| + t.Setenv("AWS_SHARED_CREDENTIALS_FILE", filepath.Join(t.TempDir(), "absent")) |
| + t.Setenv("CARLOS_S3_ENDPOINT", srv.URL) |
| + eligible := hafresh.Proofs{LocalEligible: func() bool { return true }} |
| + acquire := func() (*lease.Held, error) { |
| + return lease.AcquireHATTL(ctx, bucket, prefix, region, hafresh.Marker{V: 1, Lifetime: "L1"}, eligible, ttl) |
| + } |
| + |
| + // A: rows 0-9 replicated, P confirmed. |
| + aPath := filepath.Join(t.TempDir(), "w.example.com.db") |
| + witnessExec(t, aPath, `PRAGMA journal_mode=WAL`, `CREATE TABLE t (id INTEGER PRIMARY KEY, body TEXT)`) |
| + for i := range 10 { |
| + witnessExec(t, aPath, fmt.Sprintf(`INSERT INTO t (body) VALUES ('row-%d')`, i)) |
| + } |
| + aHeld, err := acquire() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + a, err := aHeld.Replicate(ctx, aPath, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := a.SyncAndWait(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + // A's next transaction reaches the server unanswered; its release's |
| + // final sync times out, and the marker goes through (lock.json is not |
| + // partitioned). |
| + partitioned.Store(true) |
| + witnessExec(t, aPath, `INSERT INTO t (body) VALUES ('a-only')`) |
| + closeCtx, cancel := context.WithTimeout(ctx, time.Second) |
| + _ = a.Close(closeCtx) |
| + cancel() |
| + mu.Lock() |
| + aKeys := append([]string(nil), heldKeys...) |
| + mu.Unlock() |
| + if len(aKeys) == 0 { |
| + t.Fatal("fixture: no write of A's reached the server") |
| + } |
| + body, _ := store.Current(bucket, prefix+"/lock.json") |
| + v, err := hafresh.DecodeLock(body, "") |
| + if err != nil || v.Lock.Release == nil || v.Lock.Release.Clean || v.Lock.Release.Settled { |
| + t.Fatalf("A's marker: %+v %v (want unclean, unsettled)", v.Lock.Release, err) |
| + } |
| + opens := v.Lock.Release.At.Add(ttl) |
| + partitioned.Store(false) |
| + |
| + // B, at once: held until the marker opens, nothing written. |
| + boxB() |
| + _, err = acquire() |
| + var he *lease.HeldError |
| + if !errors.As(err, &he) || !he.ExpiresAt.Equal(opens) { |
| + t.Fatalf("B before the term: %v (want held until %v)", err, opens) |
| + } |
| + |
| + // Inside the term, the server applies what A sent. |
| + heal() |
| + held.Wait() |
| + time.Sleep(time.Until(opens) + 200*time.Millisecond) |
| + |
| + bPhase.Store(true) |
| + bPath := filepath.Join(t.TempDir(), "w.example.com.db") |
| + bHeld, err := acquire() |
| + if err != nil { |
| + t.Fatalf("B after the term: %v", err) |
| + } |
| + if ok, err := lease.Restore(ctx, bPath, bucket, prefix, region); err != nil || !ok { |
| + t.Fatalf("B restore: %v %v", ok, err) |
| + } |
| + // A's write reached S3 before B's restore: B continues after it. |
| + if n := witnessCount(t, bPath, `body = 'a-only'`); n != 1 { |
| + t.Fatalf("B's restore holds a-only %d times, want 1 (A's write landed inside the term)", n) |
| + } |
| + b, err := bHeld.Replicate(ctx, bPath, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := b.SyncAndWait(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + witnessExec(t, bPath, `INSERT INTO t (body) VALUES ('b-only')`) |
| + if err := b.SyncAndWait(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := b.Close(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + // The invariant at the object level: B never wrote a key A had sent, |
| + // so no TXID range has two histories. |
| + mu.Lock() |
| + for _, k := range aKeys { |
| + if bKeys[k] { |
| + t.Errorf("the successor rewrote %s, a key the earlier holder sent", k) |
| + } |
| + } |
| + mu.Unlock() |
| + cPath := filepath.Join(t.TempDir(), "w.example.com.db") |
| + if ok, err := lease.Restore(ctx, cPath, bucket, prefix, region); err != nil || !ok { |
| + t.Fatalf("restore after B: %v %v", ok, err) |
| + } |
| + for where, want := range map[string]int{`body = 'b-only'`: 1, `body = 'a-only'`: 1, `body LIKE 'row-%'`: 10} { |
| + if got := witnessCount(t, cPath, where); got != want { |
| + t.Errorf("restore after B: %s %d, want %d", where, got, want) |
| + } |
| + } |
| +} |
| + |
| +func witnessExec(t *testing.T, path string, qs ...string) { |
| + t.Helper() |
| + db, err := sql.Open("sqlite", path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer db.Close() |
| + for _, q := range qs { |
| + if _, err := db.Exec(q); err != nil { |
| + t.Fatalf("%s: %v", q, err) |
| + } |
| + } |
| +} |
| + |
| +func witnessCount(t *testing.T, path, where string) int { |
| + t.Helper() |
| + db, err := sql.Open("sqlite", path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer db.Close() |
| + var n int |
| + if err := db.QueryRow(`SELECT count(*) FROM t WHERE ` + where).Scan(&n); err != nil { |
| + t.Fatal(err) |
| + } |
| + return n |
| +} |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index d3017d882..0071eacfe 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -197,4 +197,5 @@ plan14-root-reads-stateless-replicas-4-merge-main2.tsv 5889e1513a21733385ef3926d |
| plan14-root-reads-stateless-replicas-4-drill3.tsv d0773df1895af8ab5e402e9caceb90e571ea300eb19fd3b50abb2041783d1d08 |
| plan14-root-reads-stateless-replicas-4-r28.tsv 55d66980f8db645c762b56e20b5eabba09d8e1f2ab79de5e089ff087ad677bc3 |
| plan14-root-reads-stateless-replicas-4-merge-main3.tsv 55d66980f8db645c762b56e20b5eabba09d8e1f2ab79de5e089ff087ad677bc3 |
| -plan14-root-reads-g6-fence.tsv ca2a9b1fc24a51311c8d50febcb8d362f181ed39b64e861e60dc4b849ff30152 |
| +plan14-root-reads-ha-unclean-marker-waits.tsv 821598970e60a776d4a62138d5adbfa393cd30bc1ec1f266d290e5b6d4e12c42 |
| +plan14-root-reads-ha-unclean-files-only.tsv bc138ce5435f3ab37f6adff46656eea1c20f48168c569550fe94e390c69ba309 |
diff --git a/internal/provision/testdata/plan14-root-reads-ha-unclean-files-only.tsv b/internal/provision/testdata/plan14-root-reads-ha-unclean-files-only.tsv| new file mode 100644 |
| index 000000000..b3d983fec |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-ha-unclean-files-only.tsv |
| @@ -0,0 +1,7 @@ |
| +# Census overlay ha-unclean-files-only, written by census-propose (#369). census-ruling-ha-unclean-files-only, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-ha-unclean-files-only.md. |
| +# 1 body, 0 sites, 3 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +@legacy 29acf7650de6bddd49fb9516618950e21be6ad9bf7c143fe989e9b7acbfef166 internal/activator/harelease.go Service.releaseHAClean legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: an HA entry's release, in order: host slice read empty through haHostEmpty (else errHostSliceUnproven and nothing written; the same check, moved into that helper by final fix F1), stop and join the files publisher, its final publish (2 min budget), the replica's final sync (Finish, 30 s), the local release record, then the release marker PUT (10 s), clean only when the final publish was complete and the sync and record succeeded; a failed PUT is a persisted lease obligation; +registry:Host, +whole:Route x4;rev3=census-ruling-region-ha-p1b3b-t;basis=Record advisory local-release basis only after ReleaseMarker succeeds. Add a whole-route argument to local duty bookkeeping; release order and lease authority unchanged.;rev3=census-ruling-region-ha-g2-fixes;basis=Latch unexpected lease loss before release and mark intentional release so ErrSpent alone is not treated as loss; no new read.;rev3=census-ruling-region-ha-graceful-terminate-t2;basis=Cap Final, Finish and marker contexts by the shutdown deadline and reserves; keep calls synchronous and stop proof unchanged; record successful marker completion under the service mutex. No read added.;rev3=census-ruling-region-ha-held-build;basis=region HA held-requests Task 5: records the written marker's clean flag on the entry (haReleaseClean) beside haReleased, for the drain report; no read added;rev3=census-ruling-held-move-speed;basis=reads the entry's drainRelease flag under a.mu; for the drain's release calls the replica's FinishSnapshot (final sync, then a litestream snapshot at the final position, before the store's close; the snapshot reader pipe is closed on every outcome) instead of Finish, and logs a snapshot failure naming rt.Host (+registry:Host, the supplied route); marker order, budgets and clean rule unchanged; no new read;rev3=census-ruling-retry-after-503;basis=records four time.Now stamps and logs per-phase durations (files, sync, record, marker) on the existing marker log line; order, budgets and clean rule unchanged; no read added;rev3=census-ruling-ha-unclean-files-only;basis=Sets the marker field finalized from the errors of Final and Finish it already computes, before the record and marker writes it already makes. No new read, write or path. registry:Host@1584,registry:Host@3029,whole:Route@109,whole:Route@1710,whole:Route@2092,whole:Route@267,whole:Route@2868 e970ef6011466eb62a60a8d4e8468526167873539c08ab955786306f8a5d82d1 |
| +internal/activator/harelease.go Service.releaseHAClean legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: an HA entry's release, in order: host slice read empty through haHostEmpty (else errHostSliceUnproven and nothing written; the same check, moved into that helper by final fix F1), stop and join the files publisher, its final publish (2 min budget), the replica's final sync (Finish, 30 s), the local release record, then the release marker PUT (10 s), clean only when the final publish was complete and the sync and record succeeded; a failed PUT is a persisted lease obligation; +registry:Host, +whole:Route x4;rev3=census-ruling-region-ha-p1b3b-t;basis=Record advisory local-release basis only after ReleaseMarker succeeds. Add a whole-route argument to local duty bookkeeping; release order and lease authority unchanged.;rev3=census-ruling-region-ha-g2-fixes;basis=Latch unexpected lease loss before release and mark intentional release so ErrSpent alone is not treated as loss; no new read.;rev3=census-ruling-region-ha-graceful-terminate-t2;basis=Cap Final, Finish and marker contexts by the shutdown deadline and reserves; keep calls synchronous and stop proof unchanged; record successful marker completion under the service mutex. No read added.;rev3=census-ruling-region-ha-held-build;basis=region HA held-requests Task 5: records the written marker's clean flag on the entry (haReleaseClean) beside haReleased, for the drain report; no read added;rev3=census-ruling-held-move-speed;basis=reads the entry's drainRelease flag under a.mu; for the drain's release calls the replica's FinishSnapshot (final sync, then a litestream snapshot at the final position, before the store's close; the snapshot reader pipe is closed on every outcome) instead of Finish, and logs a snapshot failure naming rt.Host (+registry:Host, the supplied route); marker order, budgets and clean rule unchanged; no new read;rev3=census-ruling-retry-after-503;basis=records four time.Now stamps and logs per-phase durations (files, sync, record, marker) on the existing marker log line; order, budgets and clean rule unchanged; no read added;rev3=census-ruling-ha-unclean-files-only;basis=Sets the marker field finalized from the errors of Final and Finish it already computes, before the record and marker writes it already makes. No new read, write or path. registry:Host@1584,registry:Host@3029,whole:Route@109,whole:Route@1710,whole:Route@2092,whole:Route@267,whole:Route@2868 e970ef6011466eb62a60a8d4e8468526167873539c08ab955786306f8a5d82d1 |
| +@coverage internal/activator d2ae0333e9bb808bd422faca72ad7138851972dcb458416c871fa1500acec76f |
| +@coverage internal/hafresh 6f4c0f2d8f2edbe59fbf08203d7642972c4d9c3e93c9c8e4c2bcfb93b2fd7e66 |
| +@coverage internal/lease 1404400a7f954f5674b3c792faba6038b443382fd4127ce9dd0115a8ae161b5c |
diff --git a/internal/provision/testdata/plan14-root-reads-ha-unclean-marker-waits.tsv b/internal/provision/testdata/plan14-root-reads-ha-unclean-marker-waits.tsv| new file mode 100644 |
| index 000000000..ee24dea39 |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-ha-unclean-marker-waits.tsv |
| @@ -0,0 +1,7 @@ |
| +# Census overlay ha-unclean-marker-waits, written by census-propose (#369). census-ruling-ha-unclean-marker-waits, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-ha-unclean-marker-waits.md. |
| +# 1 body, 0 sites, 3 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +@legacy d75eee0e5e35babd3b520a4d04089f602b85d6a21bd54e6e44d310b2855695ce internal/activator/haadopt.go Service.AdoptHost legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=Serialize through the existing host operation state. Read local route/revision/receipt plus configured lock/manifest/wake objects; use only restricted ordinary acquire, exact guarded restore, ordinary unclean release and verified readback for adoption. No process launch, local-copy reuse or secret access. B3: pass the optional shared durable termination proof adapter into the existing restricted finalizer acquire. The adapter validates the exact classified peer and current host lifetime, uses the acquire data-bucket client, and cannot bypass expiry or CAS. No new read in this unit. B4: A first scanner import may reuse its staging lock observation; the ordinary acquire still rereads and compares the exact ETag/generation and expiry. Existing receipt replay keeps its fresh read. No new read path or takeover authority.;rev3=census-ruling-region-ha-followups;basis=Attach a per-acquire termination proof observer to finalizer acquisitions so refusals retain alarms; avoid duplicate fallback observations. The observer receives the existing route and departure ref for paging; no new storage read or takeover authority.;rev3=census-ruling-region-ha-g2-fixes;basis=Require local pool eligibility at entry and in HA acquisition proofs; supplied route only; termination, lifetime and emptiness checks remain.;rev3=census-ruling-ha-unclean-marker-waits;basis=Defers adoption, before any import, while the observed lock is an unclean release marker that is not settled and younger than a lease term (hafresh.MarkerOpensAt). No new read: it inspects the lock view the unit already read. Only adds a refusal. registry:AcquiredGeneration@2664,registry:AcquiredGeneration@3037,registry:AcquiredGeneration@3815,registry:AcquiredGeneration@4427,registry:AcquiredGeneration@4518,registry:AcquiredGeneration@5157,registry:AcquiredGeneration@5248,registry:DepartureIID@1912,registry:DepartureIID@6033,registry:DepartureRef@1876,registry:DepartureRef@6017,registry:ExpectedPair@8529,registry:Host@1074,registry:Host@1277,registry:Host@1373,registry:Host@1445,registry:Host@1514,registry:Host@1780,registry:Host@2155,registry:Host@2881,registry:Host@3218,registry:Host@3605,registry:Host@5846,registry:Host@6267,registry:Host@6452,registry:Host@7534,registry:Host@8291,registry:Host@8593,registry:Host@9156,registry:Host@976,registry:Lifetime@6069,registry:Lifetime@8498,registry:LockETag@6104,registry:LockGeneration@1948,registry:LockGeneration@6116,registry:Phase@2996,registry:Phase@3013,registry:Phase@3355,registry:Phase@3393,registry:Phase@3449,registry:Phase@4459,registry:Phase@4551,registry:Phase@5101,registry:Phase@5189,registry:Receipt@6093,registry:Revision@3237,registry:Revision@6081,registry:Sequence@3141,registry:Sequence@3161,registry:WakeDigest@3100,registry:WakeDigest@3122,whole:HAAdoption@3254,whole:HAAdoption@6408,whole:HAWakeImport@3083,whole:HAWakeImport@5988,whole:HAWakeImport@6004,whole:HAWakeImport@6012,whole:HAWakeImport@6286,whole:HAWakeImport@8300,whole:HAWakeImport@8602,whole:HAWakeImport@8694,whole:Pair@3231,whole:Pair@6280,whole:Pair@8535,whole:Pair@8555,whole:Route@1004,whole:Route@1243,whole:Route@1286,whole:Route@1293,whole:Route@138,whole:Route@174,whole:Route@2813,whole:Route@308,whole:Route@3515,whole:Route@4828,whole:Route@568,whole:Route@5935,whole:Route@646,whole:Route@7006,whole:Route@7047,whole:Route@7092,whole:Route@7247,whole:Route@7802,whole:Route@838,whole:Route@8387 57e100f7d2bdb0631df62171f72429dce94edeacf7a51b1310a51c78cdd89742 |
| +internal/activator/haadopt.go Service.AdoptHost legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=Serialize through the existing host operation state. Read local route/revision/receipt plus configured lock/manifest/wake objects; use only restricted ordinary acquire, exact guarded restore, ordinary unclean release and verified readback for adoption. No process launch, local-copy reuse or secret access. B3: pass the optional shared durable termination proof adapter into the existing restricted finalizer acquire. The adapter validates the exact classified peer and current host lifetime, uses the acquire data-bucket client, and cannot bypass expiry or CAS. No new read in this unit. B4: A first scanner import may reuse its staging lock observation; the ordinary acquire still rereads and compares the exact ETag/generation and expiry. Existing receipt replay keeps its fresh read. No new read path or takeover authority.;rev3=census-ruling-region-ha-followups;basis=Attach a per-acquire termination proof observer to finalizer acquisitions so refusals retain alarms; avoid duplicate fallback observations. The observer receives the existing route and departure ref for paging; no new storage read or takeover authority.;rev3=census-ruling-region-ha-g2-fixes;basis=Require local pool eligibility at entry and in HA acquisition proofs; supplied route only; termination, lifetime and emptiness checks remain.;rev3=census-ruling-ha-unclean-marker-waits;basis=Defers adoption, before any import, while the observed lock is an unclean release marker that is not settled and younger than a lease term (hafresh.MarkerOpensAt). No new read: it inspects the lock view the unit already read. Only adds a refusal. registry:AcquiredGeneration@2664,registry:AcquiredGeneration@3037,registry:AcquiredGeneration@3815,registry:AcquiredGeneration@4427,registry:AcquiredGeneration@4518,registry:AcquiredGeneration@5157,registry:AcquiredGeneration@5248,registry:DepartureIID@1912,registry:DepartureIID@6033,registry:DepartureRef@1876,registry:DepartureRef@6017,registry:ExpectedPair@8529,registry:Host@1074,registry:Host@1277,registry:Host@1373,registry:Host@1445,registry:Host@1514,registry:Host@1780,registry:Host@2155,registry:Host@2881,registry:Host@3218,registry:Host@3605,registry:Host@5846,registry:Host@6267,registry:Host@6452,registry:Host@7534,registry:Host@8291,registry:Host@8593,registry:Host@9156,registry:Host@976,registry:Lifetime@6069,registry:Lifetime@8498,registry:LockETag@6104,registry:LockGeneration@1948,registry:LockGeneration@6116,registry:Phase@2996,registry:Phase@3013,registry:Phase@3355,registry:Phase@3393,registry:Phase@3449,registry:Phase@4459,registry:Phase@4551,registry:Phase@5101,registry:Phase@5189,registry:Receipt@6093,registry:Revision@3237,registry:Revision@6081,registry:Sequence@3141,registry:Sequence@3161,registry:WakeDigest@3100,registry:WakeDigest@3122,whole:HAAdoption@3254,whole:HAAdoption@6408,whole:HAWakeImport@3083,whole:HAWakeImport@5988,whole:HAWakeImport@6004,whole:HAWakeImport@6012,whole:HAWakeImport@6286,whole:HAWakeImport@8300,whole:HAWakeImport@8602,whole:HAWakeImport@8694,whole:Pair@3231,whole:Pair@6280,whole:Pair@8535,whole:Pair@8555,whole:Route@1004,whole:Route@1243,whole:Route@1286,whole:Route@1293,whole:Route@138,whole:Route@174,whole:Route@2813,whole:Route@308,whole:Route@3515,whole:Route@4828,whole:Route@568,whole:Route@5935,whole:Route@646,whole:Route@7006,whole:Route@7047,whole:Route@7092,whole:Route@7247,whole:Route@7802,whole:Route@838,whole:Route@8387 57e100f7d2bdb0631df62171f72429dce94edeacf7a51b1310a51c78cdd89742 |
| +@coverage internal/activator 5beb4d1544451c8331013ede98a8fa9860ae9fa324c075d61893491771ab2fc5 |
| +@coverage internal/hafresh 511d4b2df62cd0d6ae89c20676b7f603f2062e1607718ee3b63b007226369b25 |
| +@coverage internal/lease 81b4ff457ea4c2fa9b2b964ee523ca70c59850e1a23f68bd2432c658af6ed7f3 |
diff --git a/internal/sim/regionha/actions_test.go b/internal/sim/regionha/actions_test.go| index c294f0dab..ab522e429 100644 |
| --- a/internal/sim/regionha/actions_test.go |
| +++ b/internal/sim/regionha/actions_test.go |
| @@ -49,7 +49,7 @@ func (w *world) decideAcquire(b *box, h string, v hafresh.View) hafresh.Decision |
| } |
| } |
| } |
| - d := hafresh.DecideAcquire(v, b.Self, w.now(), hafresh.Proofs{LocalEligible: func() bool { return true }, SameBoxEmpty: proof, OwnerTerminated: w.ownerTerminated}) |
| + d := hafresh.DecideAcquire(v, b.Self, w.now(), ttlTicks*tick, hafresh.Proofs{LocalEligible: func() bool { return true }, SameBoxEmpty: proof, OwnerTerminated: w.ownerTerminated}) |
| if !on("expiry-authorizes") && d.Action == hafresh.ActRefuse && d.Reason == hafresh.ReasonOtherExpired { |
| d = hafresh.Decision{Action: hafresh.ActTake, Reason: "expired"} |
| } |
| @@ -219,7 +219,7 @@ func (w *world) wake(b *box, h string, o wakeOpts, pre *pending) string { |
| if o.LateAck { |
| // The acquire's own cleanup: the lock is ours, the deadline is not. |
| w.event("late-ack") |
| - w.releaseUnclean(b, h, e, 0, o.MarkerFails) |
| + w.releaseUnclean(b, h, e, 0, true, o.MarkerFails) |
| return "late ack" |
| } |
| l := w.local(b, h) |
| @@ -236,7 +236,7 @@ func (w *world) wake(b *box, h string, o wakeOpts, pre *pending) string { |
| w.setAside(l) |
| if o.RestoreFails { |
| w.event("failed-restore") |
| - w.releaseUnclean(b, h, e, 0, o.MarkerFails) |
| + w.releaseUnclean(b, h, e, 0, true, o.MarkerFails) |
| return "failed restore" |
| } |
| w.restore(l, h) |
| @@ -558,7 +558,7 @@ func (w *world) tryRelease(b *box, h string) { |
| return |
| } |
| w.sync(b, h, false) |
| - w.releaseUnclean(b, h, e, e.Uploaded, o.MarkerFails) |
| + w.releaseUnclean(b, h, e, e.Uploaded, false, o.MarkerFails) |
| return |
| } |
| if on("marker-before-slice-empty") && !w.sliceEmpty(b, h) { |
| @@ -581,7 +581,7 @@ func (w *world) tryRelease(b *box, h string) { |
| gen, complete := w.stopAndFinal(b, h, e, o.FinalIncomplete) |
| txid, synced := w.finish(b, h, e, o.SyncFails) |
| m := base |
| - m.TXID, m.FilesGen, m.Clean = txid, gen, complete && synced |
| + m.TXID, m.FilesGen, m.Clean, m.Finalized = txid, gen, complete && synced, synced |
| w.writeRecord(l, m) |
| w.putMarker(b, h, e, m, o.MarkerFails) |
| delete(b.Entries, h) |
| @@ -669,15 +669,16 @@ func (w *world) putMarker(b *box, h string, e *entry, m hafresh.Marker, fails bo |
| // releaseUnclean is every release but the clean one: the acquire's cleanup |
| // after a late acknowledgement, a failed restore, and Close. The marker is |
| -// unclean, at txid. |
| -func (w *world) releaseUnclean(b *box, h string, e *entry, txid uint64, markerFails bool) { |
| +// unclean, at txid; settled only when nothing replicated under the lease |
| +// (hafresh.Marker.Settled): the late-ack and failed-restore cleanups. |
| +func (w *world) releaseUnclean(b *box, h string, e *entry, txid uint64, settled, markerFails bool) { |
| delete(b.Entries, h) |
| if !on("cleanup-deletes-lock") { |
| w.deleteLock(h, e.ETag) |
| w.logf("box%d: %s: released by deleting the lock", b.ID, h) |
| return |
| } |
| - m := hafresh.Marker{V: 1, Box: b.Self.Ref, IID: b.Self.IID, Lifetime: w.lifetime(h), TXID: txid, At: w.now()} |
| + m := hafresh.Marker{V: 1, Box: b.Self.Ref, IID: b.Self.IID, Lifetime: w.lifetime(h), TXID: txid, At: w.now(), Settled: settled} |
| w.putMarker(b, h, e, m, markerFails) |
| } |
| @@ -701,7 +702,7 @@ func (w *world) closeHA(b *box, h string, markerFails bool, straggler int) { |
| return |
| } |
| w.sync(b, h, false) |
| - w.releaseUnclean(b, h, e, e.Uploaded, markerFails) |
| + w.releaseUnclean(b, h, e, e.Uploaded, false, markerFails) |
| } |
| // legacySleep is the legacy Close: the final sync, then a DELETE of the |
diff --git a/internal/sim/regionha/duties_model_test.go b/internal/sim/regionha/duties_model_test.go| index c57d8fdd8..d2a451856 100644 |
| --- a/internal/sim/regionha/duties_model_test.go |
| +++ b/internal/sim/regionha/duties_model_test.go |
| @@ -345,7 +345,7 @@ func (d *dutyWorld) adopt(b *dutyBox, s *dutyScan, hi int) bool { |
| } |
| return valid && b.proofs[s.dead], nil |
| }} |
| - a := hafresh.DecideAcquire(v, b.self, now, p) |
| + a := hafresh.DecideAcquire(v, b.self, now, lease.LeaseTTL, p) |
| if a.Action != hafresh.ActTake { |
| return false |
| } |
diff --git a/internal/sim/regionha/witness_test.go b/internal/sim/regionha/witness_test.go| index 741d17d32..94f07cd31 100644 |
| --- a/internal/sim/regionha/witness_test.go |
| +++ b/internal/sim/regionha/witness_test.go |
| @@ -398,6 +398,7 @@ func wUncleanMarkerRestores(t *testing.T, w *world) { |
| w.sleepNow(A, sleepOpts{FinalIncomplete: true}) |
| v := w.view(sh) |
| expect(t, "keep-unclean", v.Lock.Release != nil && !v.Lock.Release.Clean, "the release left %s, not an unclean marker", w.lockString(sh)) |
| + w.advance(ttlTicks + 1) // a replicated unclean marker opens a lease term after its release (rev 6.7) |
| restored := w.events["restored"] |
| w.req(A, wakeOpts{}) |
| expect(t, "keep-unclean", w.events["restored"] == restored+1, "A, under its own unclean marker, did not restore") |
| @@ -552,15 +553,19 @@ func wStragglerHoldsRelease(t *testing.T, w *world) { |
| func wFailedWakeStragglerHoldsRelease(t *testing.T, w *world) { |
| A, B, _ := w.abc() |
| - r := w.req(A, wakeOpts{FailAfterRepl: true, Straggler: 5}) |
| + // The straggler outlives a lease term, so the unsettled marker's own |
| + // wait (rev 6.7) is not what keeps B out: the held release is. |
| + r := w.req(A, wakeOpts{FailAfterRepl: true, Straggler: ttlTicks + 5}) |
| if r != "failed after replication" { |
| t.Errorf("setup: %s", r) |
| } |
| + w.advance(ttlTicks + 2) |
| r = w.req(B, wakeOpts{}) |
| expect(t, "failed-wake-before-slice-empty", strings.HasPrefix(r, "refused: held"), "B while A's replacement runs: %s", r) |
| - w.advance(6) |
| + w.advance(4) |
| v := w.view(sh) |
| expect(t, "failed-wake-before-slice-empty", v.Lock.Release != nil && !v.Lock.Release.Clean, "the held release never finished: %s", w.lockString(sh)) |
| + w.advance(ttlTicks + 1) |
| w.checkLiveness() |
| } |