Merge origin/main into edge-ppv2 (region HA unclean release)
Brings in ab4d773b and b126ea52 (region HA unclean-release work and its census overlays). The census chain keeps main's lines; edge-ppv2 stays last.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
28 files changed,
+918
−74
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 −4internal/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 −0internal/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
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 5df1643b4..576c6dc51 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). |
| @@ -438,7 +445,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. | |
| @@ -488,6 +496,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 | |
| @@ -535,7 +544,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/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 de9abf1d5..a2218e37c 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) { |
| @@ -444,6 +449,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 0ed3af44f..ab980e73b 100644 |
| --- a/internal/lease/release.go |
| +++ b/internal/lease/release.go |
| @@ -114,12 +114,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") |
| @@ -149,7 +158,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 |
| @@ -160,7 +171,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) |
| } |
| @@ -219,9 +231,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) { |
| r.finMu.Lock() |
| defer r.finMu.Unlock() |
| @@ -263,8 +284,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 |
| @@ -279,8 +304,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) |
| } |
| @@ -288,7 +314,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 { |
| @@ -301,7 +328,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 b34759317..57beb13fe 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -197,4 +197,6 @@ 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-ha-unclean-marker-waits.tsv 821598970e60a776d4a62138d5adbfa393cd30bc1ec1f266d290e5b6d4e12c42 |
| +plan14-root-reads-ha-unclean-files-only.tsv bc138ce5435f3ab37f6adff46656eea1c20f48168c569550fe94e390c69ba309 |
| plan14-root-reads-edge-ppv2.tsv 9e75b87ca921122444bc0ddfd58869f118ff31e0dc5c6f4bf6835df35a5ed231 |
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() |
| } |