region HA: an unsettled release marker waits a lease term
Containment for the wake-race review's P1 (Paul, 2026-11-12). An HA release whose replica finalization failed (a final sync that timed out, a store torn down without one) may have an upload in flight that S3 applies after the marker, into the prefix and TXID range the successor writes next: the late object replaces the successor's and history diverges silently. DecideAcquire took every release marker at once. Markers now record settled: the finalization succeeded, or nothing replicated under the lease (Held releases, the acquire's late-ack cleanup, adoption). An unsettled marker is held, for every box, until its At plus the lease term (hafresh.MarkerOpensAt), the margin N-HA9 gives a dead owner's writes; At is stamped after the finalization, so every request was sent before it. Clean and settled markers open at once: the drain's fast handover is unchanged. Old markers read as unsettled. Adoption defers on an unsettled marker the same way. The held answer carries the opening time (Decision.Until), so the edge's Retry-After names it. The finalize comment no longer claims no replica write can follow the marker. Spec rev 6.7 (§5.2, §9.4, §9.8, §9.9). Tests: the decision table, settled markers taken at once (clean, never replicated, good Close, files-only unclean), an unsettled marker held then taken, adoption cases, and the late-write witness adapted to HA (from 8e8a00a0): B is held, A's late write lands inside the term, B continues after it and never rewrites A's keys. The sim models settled.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
16 files changed,
+581
−66
docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md+13 −4internal/activator/haadopt.go+7 −0internal/activator/haadopt_test.go+17 −4internal/hafresh/acquire.go+33 −20internal/hafresh/acquire_test.go+89 −9internal/hafresh/lock.go+23 −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+34 −10internal/lease/termination_proof_test.go+1 −1internal/lease/unclean_marker_test.go+337 −0internal/sim/regionha/actions_test.go+10 −9internal/sim/regionha/duties_model_test.go+1 −1
CI failed — run details
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..62463885f 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.7** (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,7 @@ 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 whose replica finalization failed no longer allows immediate takeover. Its marker is *unsettled*, and every box waits a lease term from the marker's time (§5.2, §9.4, §9.8). Built on branch `ha-unclean-marker-waits`; storage generations, the fix, are designed separately (`2026-11-12-region-ha-storage-generations-design.md`). |
| 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 +191,11 @@ 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 also records `settled: true` when the releasing holder has no replica write outstanding: its finalization (the final sync and the store's close) succeeded, or nothing replicated under the lease at all (a failed wake before replication, an acquire's late-acknowledgement cleanup, an adoption). A clean marker is always settled; an unclean one is settled when only the files publish fell short. |
| + - An **unsettled** marker means a final sync that failed or timed out, or a store torn down without one. An upload it sent may still be applied by S3 after the marker (Litestream's close cancels a request without proving S3 did not receive it), 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 an unsettled 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. A clean or settled marker opens at once, as before: the drain's fast handover (§25) is unchanged. |
| + - A marker written before the field reads as unsettled. A mixed fleet keeps the old behaviour on boxes that have not rolled. |
| - 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 +443,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 or settled | Conditional PUT, with `If-Match`. | |
| +| A release marker, unsettled (§5.2, rev 6.7) | 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 +494,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 unsettled release (§5.2, rev 6.7) | no box takes the host until 15 minutes after the marker: a final sync that timed out 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 +542,9 @@ 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; if the replica's finalization is what failed, the marker is |
| +unsettled and the host 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/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..5e4befb7f 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,83 @@ 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{}}, |
| + } { |
| + 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..495783673 100644 |
| --- a/internal/hafresh/lock.go |
| +++ b/internal/hafresh/lock.go |
| @@ -13,6 +13,14 @@ 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 has no replica write outstanding: its |
| +// finalization (the final sync and the store's close) succeeded, or |
| +// nothing replicated under the lease at all. A clean marker is always |
| +// settled. An unsettled one may have an upload in flight that S3 can |
| +// still apply after the marker, into the prefix the successor writes, so |
| +// DecideAcquire holds it for a lease term from At (MarkerOpensAt). |
| +// Markers written before the field read as unsettled. |
| type Marker struct { |
| V int `json:"v"` |
| Box string `json:"box"` |
| @@ -22,6 +30,21 @@ type Marker struct { |
| FilesGen string `json:"files_gen"` |
| At time.Time `json:"at"` |
| Clean bool `json:"clean"` |
| + Settled bool `json:"settled,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 or settled; |
| +// 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.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..384950f84 100644 |
| --- a/internal/lease/release.go |
| +++ b/internal/lease/release.go |
| @@ -114,12 +114,22 @@ 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 no replica write of the handle can still be in flight |
| +// (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.At = 1, txid, "", false, settled, 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 +159,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 |
| @@ -161,6 +173,7 @@ func (h *Held) ReleaseMarker(ctx context.Context, m hafresh.Marker) error { |
| lease := h.rn.stop() |
| m = withBase(h.base, m) |
| m.Clean = false |
| + m.Settled = !h.wroteReplica() |
| return releaseWithMarker(ctx, h.leaser, h.region, lease, m) |
| } |
| @@ -219,9 +232,17 @@ 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 |
| +// unsettled (hafresh.Marker.Settled), and the successor waits a lease |
| +// term (hafresh.DecideAcquire). One that succeeds can still have |
| +// cancelled a monitor pass; a clean marker carries that 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,7 +284,8 @@ 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 |
| +// only if m says so and the finalization succeeded. It is settled exactly |
| +// when the finalization succeeded, whatever m says. A failure is a |
| // persisted *ObligationError. |
| func (r *Replicator) ReleaseMarker(ctx context.Context, m hafresh.Marker) error { |
| if !r.ha { |
| @@ -279,6 +301,7 @@ 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 = err == nil |
| if err != nil { |
| m.Clean = false |
| } |
| @@ -288,7 +311,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, settled when the finalization succeeded. |
| +// A second release is a no-op. |
| func (r *Replicator) closeHA(ctx context.Context) error { |
| r.mu.Lock() |
| if r.released { |
| @@ -297,11 +321,11 @@ func (r *Replicator) closeHA(ctx context.Context) error { |
| } |
| r.released = true |
| r.mu.Unlock() |
| - txid, _ := r.finalize(ctx, true, false) |
| + txid, ferr := r.finalize(ctx, true, false) |
| 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, ferr == nil))) |
| } |
| 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..05b341f4f |
| --- /dev/null |
| +++ b/internal/lease/unclean_marker_test.go |
| @@ -0,0 +1,337 @@ |
| +package lease_test |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "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 every settled release's fast |
| +// handover alone: a clean marker (held requests' drain depends on it), a |
| +// release that never replicated, a Close whose finalization succeeded and |
| +// an unclean release over a good final sync (an incomplete files publish) |
| +// are all taken at once, under an hour-long lease. |
| +func TestSettledMarkersAreTakenAtOnce(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) |
| + } |
| + if err := r.ReleaseMarker(ctx, hafresh.Marker{V: 1, TXID: txid, FilesGen: "1:aa", Clean: true}); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, |
| + "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) |
| + } |
| + }, |
| + "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) |
| + } |
| + }, |
| + "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, Clean: false}); 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.Settled || m.At.IsZero() { |
| + t.Fatalf("marker %+v: want 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) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// 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/sim/regionha/actions_test.go b/internal/sim/regionha/actions_test.go| index c294f0dab..2f71c2d2c 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, true, 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.Settled = 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 when nothing replicated or the final sync |
| +// succeeded (hafresh.Marker.Settled), as every caller here is. |
| +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, true, 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 |
| } |