hafresh: generations locks open at once on proof (fast)
Storage generations slice 4 (spec §5.3), behind CARLOS_HA_GENERATIONS=fast. Proofs.GenerationsFast, wired from the switch on every HA wake, changes three rows of DecideAcquire, and only for a generations lock: an unsettled release marker is taken at once (no rev 6.7 wait); an unexpired owner of another box is taken on the termination proof (N-HA9's expiry clause goes, the proof stays); an unexpired owner of this box on the emptiness proof. A missing, false or failed proof leaves the owner held until its expiry. Every other row, and every non-generations lock, keeps today's table. Witnesses through the real take: B takes A's unsettled generations marker at once, and an unexpired terminated holder's lock on the proof alone; A's held upload lands afterwards in A's generation, and B's restore, a ResolveReplicaAt inside B's tenure, B's compaction and a restore through head.json never see it. The ordinary-lock witness now runs with the flag set and still waits. The regionha model passes the flag; it is inert there until generations locks are modelled (Task 11).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
10 files changed,
+683
−12
internal/activator/hagenerations_test.go+33 −0internal/activator/hatakeover.go+4 −1internal/activator/hawake.go+6 −2internal/hafresh/acquire.go+48 −5internal/hafresh/acquire_test.go+169 −0internal/lease/gentakeover_test.go+362 −0internal/lease/termination_proof.go+2 −1internal/lease/unclean_marker_test.go+53 −1internal/sim/regionha/actions_test.go+4 −1internal/sim/regionha/duties_model_test.go+2 −1
diff --git a/internal/activator/hagenerations_test.go b/internal/activator/hagenerations_test.go| index 6556eca53..c258d5b56 100644 |
| --- a/internal/activator/hagenerations_test.go |
| +++ b/internal/activator/hagenerations_test.go |
| @@ -759,6 +759,39 @@ func TestGenerationsSwitchParse(t *testing.T) { |
| } |
| } |
| +// The wake hands the acquire table the switch's `fast` (slice 4) and the |
| +// take its `on`: unset or anything else is neither, "on" only the |
| +// generations take, "fast" both. |
| +func TestHAWakeProofsCarryTheFastSwitch(t *testing.T) { |
| + for _, c := range []struct { |
| + env string |
| + on, fast bool |
| + }{{"", false, false}, {"on", true, false}, {"fast", true, true}} { |
| + t.Run("switch="+c.env, func(t *testing.T) { |
| + t.Setenv("CARLOS_HA_GENERATIONS", c.env) |
| + s := haService(t, "shop.example.com") |
| + old := acquireHALease |
| + t.Cleanup(func() { acquireHALease = old }) |
| + calls := 0 |
| + acquireHALease = func(ctx context.Context, bucket, prefix, region string, base hafresh.Marker, p hafresh.Proofs, opts lease.AcquireOptions) (*lease.Held, error) { |
| + calls++ |
| + if p.GenerationsFast != c.fast || opts.GenerationsOn != c.on { |
| + t.Errorf("acquire with GenerationsFast %v, GenerationsOn %v; want %v, %v", p.GenerationsFast, opts.GenerationsOn, c.fast, c.on) |
| + } |
| + return old(ctx, bucket, prefix, region, base, p, opts) |
| + } |
| + e, err := s.wakeForTest(context.Background()) |
| + if err != nil { |
| + t.Fatalf("wake: %v", err) |
| + } |
| + if calls == 0 { |
| + t.Fatal("the wake did not go through the HA acquire") |
| + } |
| + s.stopForTest(e) |
| + }) |
| + } |
| +} |
| + |
| // A truncated replica (Task 5 fix round 1): the clean marker records a |
| // TXID above the newest L0 the replica holds. Every wake refuses it |
| // (clean_marker_above_l0), the second as the first, also after the agent |
diff --git a/internal/activator/hatakeover.go b/internal/activator/hatakeover.go| index fca98fef8..c406d543e 100644 |
| --- a/internal/activator/hatakeover.go |
| +++ b/internal/activator/hatakeover.go |
| @@ -19,7 +19,10 @@ import ( |
| // that box's instance is confirmed terminated: hafresh.DecideAcquire asks |
| // hafresh.Proofs.OwnerTerminated, which is ownerTerminated, only for an |
| // expired lock of another box's non-empty instance id, so an unexpired |
| -// lock is held without asking (N-HA9). The answer is EC2's, in this box's |
| +// lock is held without asking (N-HA9). With the switch's `fast` (storage |
| +// generations slice 4) it also asks for an unexpired generations lock, |
| +// and takes it on the proof; a refused proof leaves that lock held until |
| +// its expiry rather than refusing the wake. The answer is EC2's, in this box's |
| // own account and region (termfence.Confirmer): a stopped, running or |
| // unknown instance, another account or region, or a describe that failed, |
| // refuses the wake and nothing is written. The host then stays down until |
diff --git a/internal/activator/hawake.go b/internal/activator/hawake.go| index 655e3b67c..ccfb03906 100644 |
| --- a/internal/activator/hawake.go |
| +++ b/internal/activator/hawake.go |
| @@ -455,8 +455,12 @@ func (b *ExecBackend) acquireClassified(ctx context.Context, rt registry.Route) |
| // The switch, read once for this wake: on, the take writes a |
| // generations lock over any lock; off, only over a generations lock |
| // (the mode is sticky). Either way the Restore takes a generation on a |
| - // generations lock. |
| - on, _ := generationsSwitch(haGetenv) |
| + // generations lock. fast (slice 4) lets the acquire table take a |
| + // generations lock without the marker wait or the owner's expiry, on |
| + // the same proofs (hafresh.DecideAcquire); any other lock is decided |
| + // as without it. |
| + on, fast := generationsSwitch(haGetenv) |
| + proofs.GenerationsFast = fast |
| opts := lease.AcquireOptions{GenerationsOn: on} |
| var held *lease.Held |
| if duty, ok := ctx.Value(dutyContextKey{}).(dutyRestriction); ok { |
diff --git a/internal/hafresh/acquire.go b/internal/hafresh/acquire.go| index cf4e8e195..2e2846a17 100644 |
| --- a/internal/hafresh/acquire.go |
| +++ b/internal/hafresh/acquire.go |
| @@ -49,6 +49,10 @@ type Proofs struct { |
| OwnerTerminated func(iid string) (bool, error) |
| // ObserveRefusal receives the classified view after an acquire round refuses. |
| ObserveRefusal func(View, Decision) |
| + // GenerationsFast is the box switch's `fast` (CARLOS_HA_GENERATIONS, |
| + // storage generations spec §5.3, slice 4). It changes the table only |
| + // for a generations lock (View.Generations): see DecideAcquire. |
| + GenerationsFast bool |
| } |
| // Refusal reasons, matched by callers and tests. |
| @@ -91,6 +95,25 @@ 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. |
| +// |
| +// With p.GenerationsFast (the switch's `fast`) and a generations lock |
| +// (View.Generations), three rows change (spec §5.3, slice 4). Every take |
| +// of such a lock starts its own generation, so a late write of an earlier |
| +// holder lands in that holder's generation, which the successor has |
| +// copied from and no longer reads as current; the waits that kept such a |
| +// write out of the successor's history have nothing left to guard: |
| +// |
| +// - an unsettled release marker is taken at once (no rev 6.7 wait); |
| +// - an unexpired owner of another box's non-empty instance id is taken |
| +// when the cloud confirms that instance terminated (N-HA9's expiry |
| +// clause goes; the proof stays); |
| +// - an unexpired owner of this box's non-empty instance id is taken |
| +// with the same-box emptiness proof (the proof stays). |
| +// |
| +// A missing, false or failed proof leaves an unexpired owner held until |
| +// its expiry, as without the flag. Every other row, and every row of a |
| +// lock that is not a generations lock, is the table above, whatever the |
| +// flag says. |
| func DecideAcquire(v View, self Self, now time.Time, term time.Duration, p Proofs) Decision { |
| if p.LocalEligible == nil || !p.LocalEligible() { |
| return Decision{Action: ActRefuse, Reason: ReasonPoolIneligible} |
| @@ -104,8 +127,9 @@ func DecideAcquire(v View, self Self, now time.Time, term time.Duration, p Proof |
| if !v.HAOn() { |
| return Decision{Action: ActRefuse, Reason: ReasonLeftoverLock} |
| } |
| + fast := p.GenerationsFast && v.Generations() |
| if m := v.Lock.Release; m != nil { |
| - if opens := MarkerOpensAt(*m, term); !opens.IsZero() && !now.After(opens) { |
| + if opens := MarkerOpensAt(*m, term); !fast && !opens.IsZero() && !now.After(opens) { |
| return Decision{Action: ActHeld, Reason: v.Lock.Owner, Until: opens} |
| } |
| return Decision{Action: ActTake, Reason: ReasonMarker} |
| @@ -116,14 +140,31 @@ func DecideAcquire(v View, self Self, now time.Time, term time.Duration, p Proof |
| return Decision{Action: ActRefuse, Reason: ReasonBadMarker} |
| } |
| if !now.After(v.Lock.ExpiresAt) { |
| + if fast && o.IID != "" { |
| + var d Decision |
| + if o.IID != self.IID { |
| + d = decideOtherBox(o, p) |
| + } else { |
| + d = decideSameBox(p) |
| + } |
| + if d.Action == ActTake { |
| + return d |
| + } |
| + } |
| return Decision{Action: ActHeld, Reason: v.Lock.Owner, Until: v.Lock.ExpiresAt} |
| } |
| if o.IID == "" { |
| return Decision{Action: ActRefuse, Reason: ReasonOtherExpired} |
| } |
| if o.IID != self.IID { |
| - return decideOtherExpired(o, p) |
| + return decideOtherBox(o, p) |
| } |
| + return decideSameBox(p) |
| +} |
| + |
| +// decideSameBox is the row for a lock of this box's non-empty instance |
| +// id: taken only on the emptiness proof. |
| +func decideSameBox(p Proofs) Decision { |
| if p.SameBoxEmpty == nil { |
| return Decision{Action: ActRefuse, Reason: ReasonSameBoxUnsure} |
| } |
| @@ -137,9 +178,11 @@ func DecideAcquire(v View, self Self, now time.Time, term time.Duration, p Proof |
| 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 { |
| +// decideOtherBox is the row for a lock of another box's non-empty |
| +// instance id: taken only on the termination proof. The refusal reasons |
| +// name an expired lease, the only one refused (an unexpired owner whose |
| +// proof fails is held instead). |
| +func decideOtherBox(o Owner, p Proofs) Decision { |
| if p.OwnerTerminated == nil { |
| return Decision{Action: ActRefuse, Reason: ReasonOtherExpired} |
| } |
diff --git a/internal/hafresh/acquire_test.go b/internal/hafresh/acquire_test.go| index 3f5c8d637..a8fea047e 100644 |
| --- a/internal/hafresh/acquire_test.go |
| +++ b/internal/hafresh/acquire_test.go |
| @@ -338,3 +338,172 @@ func TestDecideAcquireRefusesUnknownField(t *testing.T) { |
| t.Fatalf("ineligible box: %+v", d) |
| } |
| } |
| + |
| +// Slice 4 (storage generations spec §5.3), behind the box switch's |
| +// `fast`: with every take in its own generation, a late write of an |
| +// earlier holder lands in that holder's generation, so a generations lock |
| +// drops the rev 6.7 wait and N-HA9's expiry clause. Only when |
| +// Proofs.GenerationsFast is set and the lock is a generations lock: an |
| +// unsettled marker opens at once; an unexpired owner of another box is |
| +// taken on the termination proof alone; an unexpired owner of this box on |
| +// the emptiness proof alone. A failed or missing proof leaves the owner |
| +// held until its expiry, as today. The same views without the flag, and |
| +// ordinary views with it, decide as today. |
| +func TestDecideAcquireFastRows(t *testing.T) { |
| + now := time.Unix(1_800_000_000, 0) |
| + const term = 15 * time.Minute |
| + const gen = "g-00000000000000000009" |
| + self := Self{Ref: "a", IID: "i-a"} |
| + live, exp := now.Add(time.Minute), now.Add(-time.Minute) |
| + other, mine := OwnerFor(Self{Ref: "b", IID: "i-b"}, 9, true), OwnerFor(self, 9, true) |
| + noIIDOther := OwnerFor(Self{Ref: "c"}, 9, true) |
| + proofs := func(term, empty func() (bool, error)) Proofs { |
| + p := Proofs{LocalEligible: func() bool { return true }} |
| + if term != nil { |
| + p.OwnerTerminated = func(string) (bool, error) { return term() } |
| + } |
| + if empty != nil { |
| + p.SameBoxEmpty = empty |
| + } |
| + return p |
| + } |
| + yes := func() (bool, error) { return true, nil } |
| + nope := func() (bool, error) { return false, nil } |
| + broken := func() (bool, error) { return true, errors.New("unreadable") } |
| + both := proofs(yes, yes) |
| + marker := func(m Marker, gen bool) View { |
| + m.Gen = gen |
| + return View{Lock: Lock{ExpiresAt: markerExpiry, Owner: MarkerOwner(m), Release: &m}} |
| + } |
| + unsettled := Marker{V: 1, Box: "b", IID: "i-b", Lifetime: "L1", TXID: 7, At: now} |
| + ownUnsettled := Marker{V: 1, Box: "a", IID: "i-a", Lifetime: "L1", TXID: 7, At: now.Add(-time.Minute)} |
| + held := func(owner string, expires time.Time, gen string) View { |
| + return View{Lock: Lock{Generation: 9, ExpiresAt: expires, Owner: owner, GenName: gen}} |
| + } |
| + type want struct { |
| + action Action |
| + reason string |
| + until time.Time |
| + } |
| + type row struct { |
| + name string |
| + v View |
| + p Proofs |
| + fast want // with the flag, on the generations lock v |
| + slow want // without the flag, or on v without generations |
| + } |
| + heldBy := func(owner string, until time.Time) want { return want{ActHeld, owner, until} } |
| + for _, c := range []row{ |
| + // The three new rows. |
| + {"unsettled marker", marker(unsettled, true), both, |
| + want{ActTake, ReasonMarker, time.Time{}}, heldBy(MarkerOwner(unsettled), now.Add(term))}, |
| + {"unsettled marker, this box's own", marker(ownUnsettled, true), both, |
| + want{ActTake, ReasonMarker, time.Time{}}, heldBy(MarkerOwner(ownUnsettled), now.Add(term-time.Minute))}, |
| + {"unexpired other box, terminated", held(other, live, gen), both, |
| + want{ActTake, ReasonTerminated, time.Time{}}, heldBy(other, live)}, |
| + {"unexpired same box, proven empty", held(mine, live, gen), both, |
| + want{ActTake, ReasonSameBox, time.Time{}}, heldBy(mine, live)}, |
| + // No proof, no take: the owner is held until its expiry. |
| + {"unexpired other box, not terminated", held(other, live, gen), proofs(nope, yes), heldBy(other, live), heldBy(other, live)}, |
| + {"unexpired other box, proof failed", held(other, live, gen), proofs(broken, yes), heldBy(other, live), heldBy(other, live)}, |
| + {"unexpired other box, no proof wired", held(other, live, gen), proofs(nil, yes), heldBy(other, live), heldBy(other, live)}, |
| + {"unexpired iid-less owner", held(noIIDOther, live, gen), both, heldBy(noIIDOther, live), heldBy(noIIDOther, live)}, |
| + {"unexpired same box, not empty", held(mine, live, gen), proofs(yes, nope), heldBy(mine, live), heldBy(mine, live)}, |
| + {"unexpired same box, proof failed", held(mine, live, gen), proofs(yes, broken), heldBy(mine, live), heldBy(mine, live)}, |
| + {"unexpired same box, no proof wired", held(mine, live, gen), proofs(yes, nil), heldBy(mine, live), heldBy(mine, live)}, |
| + // Everything else keeps today's row. |
| + {"settled marker", marker(Marker{V: 1, Box: "b", IID: "i-b", At: now, Settled: true}, true), both, |
| + want{ActTake, ReasonMarker, time.Time{}}, want{ActTake, ReasonMarker, time.Time{}}}, |
| + {"expired other box, terminated", held(other, exp, gen), both, |
| + want{ActTake, ReasonTerminated, time.Time{}}, want{ActTake, ReasonTerminated, time.Time{}}}, |
| + {"expired other box, not terminated", held(other, exp, gen), proofs(nope, yes), |
| + want{ActRefuse, ReasonOtherExpired, time.Time{}}, want{ActRefuse, ReasonOtherExpired, time.Time{}}}, |
| + {"expired same box, no proof", held(mine, exp, gen), proofs(yes, nil), |
| + want{ActRefuse, ReasonSameBoxUnsure, time.Time{}}, want{ActRefuse, ReasonSameBoxUnsure, time.Time{}}}, |
| + {"expired iid-less owner", held(noIIDOther, exp, gen), both, |
| + want{ActRefuse, ReasonOtherExpired, time.Time{}}, want{ActRefuse, ReasonOtherExpired, time.Time{}}}, |
| + {"marker owner without its record", held("released/v1;ref=b;iid=i-b", live, gen), both, |
| + want{ActRefuse, ReasonBadMarker, time.Time{}}, want{ActRefuse, ReasonBadMarker, time.Time{}}}, |
| + } { |
| + if !c.v.Generations() { |
| + t.Fatalf("%s: fixture is not a generations lock", c.name) |
| + } |
| + // An ordinary lock: the same view with its generations fields off. |
| + plain := c.v |
| + plain.Lock.GenName = "" |
| + if plain.Lock.Release != nil { |
| + m := *plain.Lock.Release |
| + m.Gen = false |
| + plain.Lock.Release = &m |
| + plain.Lock.Owner = MarkerOwner(m) |
| + } |
| + if plain.Generations() { |
| + t.Fatalf("%s: fixture's ordinary twin is a generations lock", c.name) |
| + } |
| + for _, k := range []struct { |
| + label string |
| + v View |
| + fast bool |
| + want want |
| + }{ |
| + {"generations, fast", c.v, true, c.fast}, |
| + {"generations, not fast", c.v, false, c.slow}, |
| + {"ordinary, fast", plain, true, c.slow}, |
| + {"ordinary, not fast", plain, false, c.slow}, |
| + } { |
| + if k.want.action == ActHeld && k.v.Lock.Release != nil { |
| + k.want.reason = k.v.Lock.Owner // a marker is held by its own owner string |
| + } |
| + p := c.p |
| + p.GenerationsFast = k.fast |
| + d := DecideAcquire(k.v, self, now, term, p) |
| + if d.Action != k.want.action || d.Reason != k.want.reason || !d.Until.Equal(k.want.until) { |
| + t.Errorf("%s (%s): %+v, want %v %q until %v", c.name, k.label, d, k.want.action, k.want.reason, k.want.until) |
| + } |
| + } |
| + } |
| + // The rows before them still come first: pool eligibility, and a |
| + // carlos_ field this binary does not know. |
| + v := held(other, live, gen) |
| + v.Unknown = []string{"carlos_future"} |
| + if d := DecideAcquire(v, self, now, term, Proofs{GenerationsFast: true}); d.Reason != ReasonPoolIneligible { |
| + t.Fatalf("ineligible box: %+v", d) |
| + } |
| + if d := DecideAcquire(v, self, now, term, Proofs{LocalEligible: func() bool { return true }, GenerationsFast: true, OwnerTerminated: func(string) (bool, error) { return true, nil }}); d.Reason != ReasonUnknownField { |
| + t.Fatalf("unknown field: %+v", d) |
| + } |
| +} |
| + |
| +// Under `fast`, each proof is asked only about the generations lock it |
| +// can speak to, expired or not; an ordinary lock is asked as today. |
| +func TestDecideAcquireFastProofScope(t *testing.T) { |
| + now := time.Unix(1_800_000_000, 0) |
| + const gen = "g-00000000000000000009" |
| + self := Self{Ref: "a", IID: "i-a"} |
| + live := now.Add(time.Minute) |
| + b, mine := OwnerFor(Self{Ref: "b", IID: "i-b"}, 9, true), OwnerFor(self, 9, true) |
| + noIID := OwnerFor(Self{Ref: "c"}, 9, true) |
| + for _, c := range []struct { |
| + name string |
| + lock Lock |
| + wantTerm []string |
| + wantSameBox int |
| + }{ |
| + {"unexpired other, generations", Lock{ExpiresAt: live, Owner: b, GenName: gen}, []string{"i-b"}, 0}, |
| + {"unexpired mine, generations", Lock{ExpiresAt: live, Owner: mine, GenName: gen}, nil, 1}, |
| + {"unexpired iid-less owner, generations", Lock{ExpiresAt: live, Owner: noIID, GenName: gen}, nil, 0}, |
| + {"unexpired other, ordinary", Lock{ExpiresAt: live, Owner: b}, nil, 0}, |
| + {"unexpired mine, ordinary", Lock{ExpiresAt: live, Owner: mine}, nil, 0}, |
| + } { |
| + var term []string |
| + same := 0 |
| + p := Proofs{LocalEligible: func() bool { return true }, GenerationsFast: true, |
| + 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, 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) |
| + } |
| + } |
| +} |
diff --git a/internal/lease/gentakeover_test.go b/internal/lease/gentakeover_test.go| new file mode 100644 |
| index 000000000..dcc60014f |
| --- /dev/null |
| +++ b/internal/lease/gentakeover_test.go |
| @@ -0,0 +1,362 @@ |
| +package lease_test |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "path/filepath" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/replicagen" |
| +) |
| + |
| +// Slice 4 of storage generations (spec 2026-11-12 §5.3, §12 first two |
| +// items), behind the switch's `fast` (hafresh.Proofs.GenerationsFast): a |
| +// generations lock is taken without the waits that kept an earlier |
| +// holder's late write out of the successor's history, because that write |
| +// now lands in the earlier holder's own generation. |
| + |
| +// lateWrites is a genFixture's partition of one holder: while it is on, |
| +// every write under that holder's generation prefix that reaches the |
| +// server is read in full, as S3 would have received it, and held |
| +// unapplied until heal. lock.json and head.json are never under it, and |
| +// neither is anything the successor writes, so the partition can stay on |
| +// until the late write lands. |
| +type lateWrites struct { |
| + partitioned atomic.Bool |
| + prefix atomic.Pointer[string] |
| + healed chan struct{} |
| + heal func() |
| + applied sync.WaitGroup |
| + mu sync.Mutex |
| + keys []string |
| + status []int |
| +} |
| + |
| +func newLateWrites(t *testing.T, fx *genFixture) *lateWrites { |
| + lw := &lateWrites{healed: make(chan struct{})} |
| + lw.heal = sync.OnceFunc(func() { close(lw.healed) }) |
| + t.Cleanup(lw.heal) |
| + fx.setHook(func(r *http.Request, keys []string) func(int) { |
| + if !lw.partitioned.Load() || r.Method == http.MethodGet || r.Method == http.MethodHead || isControlKey(keys) || !lw.under(keys) { |
| + return nil |
| + } |
| + lw.applied.Add(1) |
| + lw.mu.Lock() |
| + lw.keys = append(lw.keys, keys...) |
| + lw.mu.Unlock() |
| + <-lw.healed |
| + return func(status int) { |
| + lw.mu.Lock() |
| + lw.status = append(lw.status, status) |
| + lw.mu.Unlock() |
| + lw.applied.Done() |
| + } |
| + }) |
| + return lw |
| +} |
| + |
| +// partition holds every later write under prefix. |
| +func (lw *lateWrites) partition(prefix string) { |
| + lw.prefix.Store(&prefix) |
| + lw.partitioned.Store(true) |
| +} |
| + |
| +func (lw *lateWrites) under(keys []string) bool { |
| + p := lw.prefix.Load() |
| + return p != nil && slices.ContainsFunc(keys, func(k string) bool { return strings.HasPrefix(k, *p) }) |
| +} |
| + |
| +func (lw *lateWrites) heldKeys() []string { |
| + lw.mu.Lock() |
| + defer lw.mu.Unlock() |
| + return append([]string(nil), lw.keys...) |
| +} |
| + |
| +// land heals the partition and waits until the server has applied every |
| +// held write; each must land (2xx), or the witness proves nothing. |
| +func (lw *lateWrites) land(t *testing.T) { |
| + t.Helper() |
| + lw.heal() |
| + lw.applied.Wait() |
| + lw.mu.Lock() |
| + statuses := append([]int(nil), lw.status...) |
| + lw.mu.Unlock() |
| + if len(statuses) == 0 { |
| + t.Fatal("fixture: no held request of A's was applied") |
| + } |
| + for i, st := range statuses { |
| + if st < 200 || st > 299 { |
| + t.Fatalf("fixture: held request %d of A's answered %d, want 2xx (the late write must land)", i, st) |
| + } |
| + } |
| +} |
| + |
| +// genHolderA is box a's first wake into its own empty generation, rows |
| +// 0-9 replicated (P confirmed). It returns the replicator, the database |
| +// path and A's generation. |
| +func genHolderA(t *testing.T, fx *genFixture, ttl time.Duration) (*lease.Replicator, string, string) { |
| + t.Helper() |
| + fx.setPhase("a") |
| + 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 := fx.acquire(t, ttl) |
| + aTake, err := aHeld.StartGeneration(ctx, fx.st, fx.vs, lease.TakeOptions{First: true, Self: selfA, Lifetime: "L1"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := aTake.Switch(ctx); 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) |
| + } |
| + return a, aPath, replicagen.Name(aHeld.LockGeneration()) |
| +} |
| + |
| +// acquireB is box b's HA acquire of the fixture's lock with p, whatever |
| +// its answer. |
| +func acquireB(fx *genFixture, ttl time.Duration, p hafresh.Proofs) (*lease.Held, error) { |
| + return lease.AcquireHAOptsForTest(ctx, fx.bucket, fx.loc, fx.region, hafresh.Marker{V: 1, Lifetime: "L1"}, p, ttl, genOn) |
| +} |
| + |
| +// requireHeldNothingWritten asserts that box b's acquire with p is held |
| +// until want and wrote nothing. |
| +func requireHeldNothingWritten(t *testing.T, fx *genFixture, ttl time.Duration, p hafresh.Proofs, want time.Time, what string) { |
| + t.Helper() |
| + before := len(fx.keys("", false)) |
| + _, err := acquireB(fx, ttl, p) |
| + var he *lease.HeldError |
| + if !errors.As(err, &he) || !he.ExpiresAt.Equal(want) { |
| + t.Fatalf("%s: %v, want held until %v", what, err, want) |
| + } |
| + if after := fx.keys("", false); len(after) != before { |
| + t.Fatalf("%s: a held answer wrote %v", what, after[before:]) |
| + } |
| +} |
| + |
| +// successorOverLateWrite is the successor's part of both witnesses. B |
| +// (holding bHeld, taken while A's write is still held at the proxy) |
| +// starts its generation, restores from it, switches head.json, replicates |
| +// and writes "b-only". Then A's held write lands, afterLand stops what is |
| +// left of A, and B's compaction runs after it. Neither B's restore, a point-in-time resolution inside B's |
| +// tenure, B's compaction nor a restore through head.json sees "a-only"; |
| +// none of B's objects is replaced; every key A sent is under A's |
| +// generation. |
| +func successorOverLateWrite(t *testing.T, fx *genFixture, lw *lateWrites, bHeld *lease.Held, aGen string, afterLand func()) { |
| + t.Helper() |
| + bucket, prefix, region := fx.bucket, fx.loc, fx.region |
| + fx.setPhase("b") |
| + bGen := replicagen.Name(bHeld.LockGeneration()) |
| + if bGen == aGen { |
| + t.Fatalf("B's generation %s is A's", bGen) |
| + } |
| + bPath := filepath.Join(t.TempDir(), "w.example.com.db") |
| + bTake, err := bHeld.StartGeneration(ctx, fx.st, fx.vs, lease.TakeOptions{Self: selfB, Lifetime: "L2"}) |
| + if err != nil { |
| + t.Fatalf("B's take: %v", err) |
| + } |
| + if bTake.Generation != bGen || bTake.Predecessor != aGen { |
| + t.Fatalf("B's take: generation %s from %s, want %s from %s", bTake.Generation, bTake.Predecessor, bGen, aGen) |
| + } |
| + if ok, err := lease.RestoreTake(ctx, bPath, bTake); err != nil || !ok { |
| + t.Fatalf("B restore: %v %v", ok, err) |
| + } |
| + if n := witnessCount(t, bPath, `body = 'a-only'`); n != 0 { |
| + t.Fatalf("B's restore holds A's unanswered write (%d)", n) |
| + } |
| + if err := bTake.Switch(ctx); err != nil { |
| + t.Fatalf("B's switch: %v", err) |
| + } |
| + b, err := bHeld.Replicate(ctx, bPath, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := b.SyncAndWait(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + // B's store runs one compaction and snapshot pass at Open (retried a |
| + // second later while the database is not ready). Let it finish before |
| + // B's row, so the row lives only in B's L0 until the compaction below. |
| + time.Sleep(1500 * time.Millisecond) |
| + witnessExec(t, bPath, `INSERT INTO t (body) VALUES ('b-only')`) |
| + if err := b.SyncAndWait(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + // Everything B wrote, as it stands before the late write lands. The |
| + // recorder files a request by the phase it arrived in, and A's monitor |
| + // can send another held upload after B's phase began: a key under A's |
| + // generation is A's held request, never B's. |
| + aPrefix := replicagen.Prefix(prefix, aGen) |
| + bBodies := map[string][]byte{} |
| + for _, k := range fx.keys("b", true) { |
| + switch { |
| + case isControlKey([]string{k}): |
| + case strings.HasPrefix(k, aPrefix): |
| + if !slices.Contains(lw.heldKeys(), k) { |
| + t.Errorf("B wrote %s, under A's generation", k) |
| + } |
| + default: |
| + body, _ := fx.m.Current(bucket, k) |
| + bBodies[k] = body |
| + } |
| + } |
| + if len(bBodies) == 0 { |
| + t.Fatal("fixture: B wrote no replica object") |
| + } |
| + |
| + // A's write lands, after B's take and B's own writes. |
| + fx.setPhase("late") |
| + lw.land(t) |
| + afterLand() |
| + t.Logf("A's held writes, applied after B's take: %v", lw.heldKeys()) |
| + for _, k := range append(fx.keys("a", false), fx.keys("late", false)...) { |
| + if !isControlKey([]string{k}) && !strings.HasPrefix(k, aPrefix) { |
| + t.Errorf("A sent %s, outside its generation %s", k, aGen) |
| + } |
| + } |
| + for k, before := range bBodies { |
| + if after, _ := fx.m.Current(bucket, k); !bytes.Equal(after, before) { |
| + t.Errorf("A's late write replaced the successor's %s", k) |
| + } |
| + } |
| + |
| + // B's compaction, after the late write: it reads and writes B's |
| + // generation only. |
| + fx.setPhase("b-compact") |
| + if err := lease.CompactForTest(b, 1); err != nil { |
| + t.Fatalf("B's compaction: %v", err) |
| + } |
| + compacted := fx.keys("b-compact", true) |
| + if !slices.ContainsFunc(compacted, func(k string) bool { return strings.HasPrefix(k, replicagen.Prefix(prefix, bGen)+"0001/") }) { |
| + t.Fatalf("fixture: B's compaction wrote no L1 file: %v", compacted) |
| + } |
| + for _, k := range compacted { |
| + if !strings.HasPrefix(k, replicagen.Prefix(prefix, bGen)) { |
| + t.Errorf("B's compaction wrote %s, outside its generation %s", k, bGen) |
| + } |
| + } |
| + if err := b.Close(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + // A point-in-time read inside B's tenure binds B's generation and |
| + // holds B's row, not A's. |
| + h, _, found, err := lease.ReadHead(ctx, fx.st, prefix) |
| + if err != nil || !found || h.Generation != bGen { |
| + t.Fatalf("head.json %+v found %v (%v), want %s", h, found, err, bGen) |
| + } |
| + inB := time.Now() |
| + if !inB.After(h.CreatedBy.At) { |
| + t.Fatalf("fixture: %s is not inside B's tenure (from %s)", inB, h.CreatedBy.At) |
| + } |
| + r, err := lease.ResolveReplicaAt(ctx, bucket, prefix, region, inB) |
| + if err != nil || r.Generation != bGen { |
| + t.Fatalf("at %s resolved %q, %v; want B's %s", inB, r.Generation, err, bGen) |
| + } |
| + if got := restoreAt(t, r, inB); slices.Contains(got, "a-only") || !slices.Contains(got, "b-only") { |
| + t.Errorf("a read inside B's tenure restored %v: want b-only and no a-only", got) |
| + } |
| + // A's write is readable, but only from A's own generation. |
| + if aRead, err := lease.BindReplica(ctx, bucket, prefix, region, aGen); err != nil { |
| + t.Fatal(err) |
| + } else if got := restoreAt(t, aRead, time.Time{}); !slices.Contains(got, "a-only") { |
| + t.Errorf("A's generation restored %v: the late write did not land there", got) |
| + } |
| + |
| + // The restore through head.json: B's history, B's compaction included. |
| + 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 the late write: %v %v", ok, err) |
| + } |
| + for where, want := range map[string]int{`body = 'b-only'`: 1, `body = 'a-only'`: 0, `body LIKE 'row-%'`: 10} { |
| + if got := witnessCount(t, cPath, where); got != want { |
| + t.Errorf("restore after the late write: %s %d, want %d", where, got, want) |
| + } |
| + } |
| +} |
| + |
| +// Crash takeover on the termination proof alone (§12, second item). A |
| +// holds a generations lock with an hour left on it and dies with an |
| +// upload in flight: the request reached the server and is held there |
| +// unapplied (a partition, a slow proxy), and A does nothing more. Without `fast`, or with it but |
| +// no confirmed termination, B is held until A's expiry and writes |
| +// nothing. With `fast` and EC2 confirming A terminated, B takes at once, |
| +// into its own generation; A's upload landing a minute later lands in |
| +// A's generation and nowhere B reads. |
| +func TestTerminatedHolderTakenOnProofAlone(t *testing.T) { |
| + const ttl = time.Hour // A's lock is unexpired for the whole test |
| + haBox(t) |
| + fx := newGenFixture(t) |
| + lw := newLateWrites(t, fx) |
| + a, aPath, aGen := genHolderA(t, fx, ttl) |
| + |
| + // A's next transaction's upload reaches the server unanswered, and A |
| + // dies: no release, no marker, the lock still A's. (An HA Abandon |
| + // stops the renewer first, and the writer then refuses to send; a |
| + // sync left in flight is the crash with a request outstanding.) |
| + lw.partition(replicagen.Prefix(fx.loc, aGen)) |
| + witnessExec(t, aPath, `INSERT INTO t (body) VALUES ('a-only')`) |
| + synced := make(chan error, 1) |
| + go func() { synced <- a.SyncAndWait(ctx) }() |
| + for deadline := time.Now().Add(10 * time.Second); len(lw.heldKeys()) == 0; time.Sleep(20 * time.Millisecond) { |
| + if time.Now().After(deadline) { |
| + t.Fatal("fixture: no write of A's reached the server") |
| + } |
| + } |
| + v := fx.lockView(t) |
| + if v.Lock.Release != nil || v.Lock.GenName != aGen || !v.Lock.ExpiresAt.After(time.Now().Add(ttl/2)) { |
| + t.Fatalf("A's lock %+v: want held, unexpired, generation %s", v.Lock, aGen) |
| + } |
| + |
| + boxB() |
| + fx.setPhase("b-held") |
| + var asked []string |
| + terminated := func(iid string) (bool, error) { asked = append(asked, iid); return iid == "i-a", nil } |
| + running := func(string) (bool, error) { return false, nil } |
| + eligible := func() bool { return true } |
| + requireHeldNothingWritten(t, fx, ttl, hafresh.Proofs{LocalEligible: eligible, OwnerTerminated: terminated}, v.Lock.ExpiresAt, "B without fast") |
| + if len(asked) != 0 { |
| + t.Fatalf("without fast the termination proof was asked about an unexpired lock: %v", asked) |
| + } |
| + requireHeldNothingWritten(t, fx, ttl, hafresh.Proofs{LocalEligible: eligible, OwnerTerminated: running, GenerationsFast: true}, v.Lock.ExpiresAt, "B with fast, A not terminated") |
| + requireHeldNothingWritten(t, fx, ttl, hafresh.Proofs{LocalEligible: eligible, GenerationsFast: true}, v.Lock.ExpiresAt, "B with fast, no proof wired") |
| + |
| + bHeld, err := acquireB(fx, ttl, hafresh.Proofs{LocalEligible: eligible, OwnerTerminated: terminated, GenerationsFast: true}) |
| + if err != nil { |
| + t.Fatalf("B with fast, A terminated: %v", err) |
| + } |
| + if strings.Join(asked, ",") != "i-a" { |
| + t.Fatalf("termination proof asked about %v, want [i-a]", asked) |
| + } |
| + if !time.Now().Before(v.Lock.ExpiresAt) { |
| + t.Fatal("fixture: A's lock expired before B's take") |
| + } |
| + successorOverLateWrite(t, fx, lw, bHeld, aGen, func() { |
| + // The upload landed; what is left of A goes, with no further sync. |
| + select { |
| + case <-synced: |
| + case <-time.After(30 * time.Second): |
| + t.Fatal("fixture: A's sync never returned after the heal") |
| + } |
| + done, cancel := context.WithCancel(ctx) |
| + cancel() |
| + a.Abandon(done) |
| + }) |
| +} |
diff --git a/internal/lease/termination_proof.go b/internal/lease/termination_proof.go| index b90426cc0..5185049ca 100644 |
| --- a/internal/lease/termination_proof.go |
| +++ b/internal/lease/termination_proof.go |
| @@ -34,7 +34,8 @@ func bindTerminationProof(ctx context.Context, client *s3.Client, bucket, prefix |
| return p |
| } |
| // The closure belongs to this classification round. DecideAcquire invokes it |
| - // only for an expired foreign owner. A CAS retry gets a fresh closure. |
| + // only for a foreign owner: an expired one, or, under the switch's `fast`, |
| + // an unexpired generations lock's. A CAS retry gets a fresh closure. |
| fallback := p.OwnerTerminated |
| p.OwnerTerminated = func(iid string) (gone bool, result error) { |
| defer func() { |
diff --git a/internal/lease/unclean_marker_test.go b/internal/lease/unclean_marker_test.go| index 8ebbc57d5..6f01fe94a 100644 |
| --- a/internal/lease/unclean_marker_test.go |
| +++ b/internal/lease/unclean_marker_test.go |
| @@ -22,6 +22,7 @@ import ( |
| "github.com/carlosframework/platform/internal/lease" |
| "github.com/carlosframework/platform/internal/lease/leasetest" |
| locktest "github.com/carlosframework/platform/internal/lease/locktest" |
| + "github.com/carlosframework/platform/internal/replicagen" |
| ) |
| // boxB makes this process box b, the successor in these tests. |
| @@ -212,6 +213,10 @@ func TestUnsettledMarkerIsHeldForALeaseTerm(t *testing.T) { |
| // 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. |
| +// |
| +// The lock here is an ordinary one (no generations), so B waits even with |
| +// the switch's `fast` set: the slice-4 rows are for generations locks |
| +// only (TestUnsettledGenMarkerTakenAtOnce). |
| func TestUnsettledMarkerKeepsALateWriteOutOfTheSuccessorsHistory(t *testing.T) { |
| const ( |
| bucket = "data" |
| @@ -264,7 +269,7 @@ func TestUnsettledMarkerKeepsALateWriteOutOfTheSuccessorsHistory(t *testing.T) { |
| 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 }} |
| + eligible := hafresh.Proofs{LocalEligible: func() bool { return true }, GenerationsFast: true} |
| acquire := func() (*lease.Held, error) { |
| return lease.AcquireHATTL(ctx, bucket, prefix, region, hafresh.Marker{V: 1, Lifetime: "L1"}, eligible, ttl) |
| } |
| @@ -370,6 +375,53 @@ func TestUnsettledMarkerKeepsALateWriteOutOfTheSuccessorsHistory(t *testing.T) { |
| } |
| } |
| +// The same late write over a generations lock, with the switch's `fast` |
| +// (spec 2026-11-12 §5.3, §12 first item): no wait. A's final sync times |
| +// out with its upload at the server, unanswered, and its unclean marker |
| +// goes through. Without `fast` B is held until the marker opens, as |
| +// today. With it B takes at once, into a new generation copied from A's |
| +// at P; A's held upload lands afterwards, in A's generation. B's restore, |
| +// a resolution inside B's tenure, B's compaction and a restore through |
| +// head.json never see "a-only". |
| +func TestUnsettledGenMarkerTakenAtOnce(t *testing.T) { |
| + const ttl = time.Hour // the wait without fast would outlast the test |
| + haBox(t) |
| + fx := newGenFixture(t) |
| + lw := newLateWrites(t, fx) |
| + a, aPath, aGen := genHolderA(t, fx, ttl) |
| + |
| + // 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). |
| + lw.partition(replicagen.Prefix(fx.loc, aGen)) |
| + witnessExec(t, aPath, `INSERT INTO t (body) VALUES ('a-only')`) |
| + closeCtx, cancel := context.WithTimeout(ctx, time.Second) |
| + _ = a.Close(closeCtx) |
| + cancel() |
| + if len(lw.heldKeys()) == 0 { |
| + t.Fatal("fixture: no write of A's reached the server") |
| + } |
| + v := fx.lockView(t) |
| + m := v.Lock.Release |
| + if m == nil || !m.Gen || m.Clean || m.Settled || m.Finalized || m.At.IsZero() { |
| + t.Fatalf("A's marker %+v: want a generations marker, unclean and unsettled, with its time", m) |
| + } |
| + |
| + boxB() |
| + fx.setPhase("b-held") |
| + eligible := func() bool { return true } |
| + requireHeldNothingWritten(t, fx, ttl, hafresh.Proofs{LocalEligible: eligible}, m.At.Add(ttl), "B without fast") |
| + |
| + bHeld, err := acquireB(fx, ttl, hafresh.Proofs{LocalEligible: eligible, GenerationsFast: true}) |
| + if err != nil { |
| + t.Fatalf("B with fast: %v", err) |
| + } |
| + if !time.Now().Before(m.At.Add(ttl)) { |
| + t.Fatal("fixture: A's marker opened before B's take") |
| + } |
| + successorOverLateWrite(t, fx, lw, bHeld, aGen, func() {}) |
| +} |
| + |
| func witnessExec(t *testing.T, path string, qs ...string) { |
| t.Helper() |
| db, err := sql.Open("sqlite", path) |
diff --git a/internal/sim/regionha/actions_test.go b/internal/sim/regionha/actions_test.go| index ab522e429..fc8ac3f26 100644 |
| --- a/internal/sim/regionha/actions_test.go |
| +++ b/internal/sim/regionha/actions_test.go |
| @@ -49,7 +49,10 @@ func (w *world) decideAcquire(b *box, h string, v hafresh.View) hafresh.Decision |
| } |
| } |
| } |
| - d := hafresh.DecideAcquire(v, b.Self, w.now(), ttlTicks*tick, hafresh.Proofs{LocalEligible: func() bool { return true }, SameBoxEmpty: proof, OwnerTerminated: w.ownerTerminated}) |
| + // GenerationsFast is the switch's `fast`; it changes the table only for |
| + // a generations lock, which this model does not write yet (Task 11 |
| + // models generations), so it decides nothing here today. |
| + d := hafresh.DecideAcquire(v, b.Self, w.now(), ttlTicks*tick, hafresh.Proofs{LocalEligible: func() bool { return true }, SameBoxEmpty: proof, OwnerTerminated: w.ownerTerminated, GenerationsFast: true}) |
| if !on("expiry-authorizes") && d.Action == hafresh.ActRefuse && d.Reason == hafresh.ReasonOtherExpired { |
| d = hafresh.Decision{Action: hafresh.ActTake, Reason: "expired"} |
| } |
diff --git a/internal/sim/regionha/duties_model_test.go b/internal/sim/regionha/duties_model_test.go| index d2a451856..8893ee149 100644 |
| --- a/internal/sim/regionha/duties_model_test.go |
| +++ b/internal/sim/regionha/duties_model_test.go |
| @@ -323,7 +323,8 @@ func (d *dutyWorld) adopt(b *dutyBox, s *dutyScan, hi int) bool { |
| if !on("take-before-expiry") || !on("proof-before-expiry") { |
| now = v.Lock.ExpiresAt.Add(time.Nanosecond) |
| } |
| - p := hafresh.Proofs{LocalEligible: func() bool { return true }, OwnerTerminated: func(iid string) (bool, error) { |
| + // GenerationsFast: inert until the model writes generations locks (Task 11). |
| + p := hafresh.Proofs{LocalEligible: func() bool { return true }, GenerationsFast: true, OwnerTerminated: func(iid string) (bool, error) { |
| if !b.proofs[s.dead] { |
| d.proofReads++ |
| if !d.storeDown && d.proofs[s.dead] { |