carlos / platform Public

lease: failed takes keep their TXID bound; tighten the fence mint rule

Astra and Fable task 5 R1.

- hafresh.Marker gains min_txid (inside the record) and TakeBound, the
  higher of a clean marker's TXID and min_txid. StartGeneration raises
  the caller's bound to the acquired marker's. Every release of a
  generations lock whose take never switched (a refusal, a failure
  before planning, a lost race, the acquire's late acknowledgement)
  writes min_txid = that bound, so a truncated replica is refused by
  every later take, after a restart too. Switched releases are as before.
- The HA mint guard reads only a fence placeholder as no manifest:
  version 2, a lock generation, seq 0, no entry, platform item or
  origin; one decoder (baselineManifest) on both paths.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev dac44f05d430a845da16be9273e7c9980ee7943f parent f4a4dbd
11 files changed, +457 −30
  • internal/activator/hagenerations_test.go +68 −2
  • internal/activator/hasecrets.go +40 −21
  • internal/activator/hasecrets_test.go +124 −0
  • internal/activator/hawake.go +4 −2
  • internal/hafresh/generations_test.go +46 −0
  • internal/hafresh/lock.go +20 −0
  • internal/lease/gentake.go +44 −1
  • internal/lease/gentake_test.go +96 −0
  • internal/lease/ha.go +8 −2
  • internal/lease/lease.go +3 −1
  • internal/lease/release.go +4 −1
diff --git a/internal/activator/hagenerations_test.go b/internal/activator/hagenerations_test.go
index c819c71a4..0e3eab7c2 100644
--- a/internal/activator/hagenerations_test.go
+++ b/internal/activator/hagenerations_test.go
@@ -693,6 +693,7 @@ func TestHAWakeHeadMovedRetriesOnce(t *testing.T) {
s, e := haServiceEntry(t, "shop.example.com")
s.insertRows(t, 0, 2)
s.stopForTest(e)
+ cleanTXID := s.lockView(t).Lock.Release.TXID
key := s.headKey()
if c.fence {
key = hostfiles.ManifestKey(s.b.filesPrefix(s.rt.Host))
@@ -716,8 +717,10 @@ func TestHAWakeHeadMovedRetriesOnce(t *testing.T) {
if !errors.Is(err, lease.ErrHeadMoved) {
t.Fatalf("wake: %v, want ErrHeadMoved", err)
}
- if v := s.lockView(t); v.Lock.Release == nil || !v.Lock.Release.Settled {
- t.Fatalf("the failed wake's release %+v", v.Lock)
+ // Two takes failed in a row: the clean marker's bound is carried
+ // through both releases.
+ if v := s.lockView(t); v.Lock.Release == nil || !v.Lock.Release.Settled || v.Lock.Release.MinTXID != cleanTXID || cleanTXID == 0 {
+ t.Fatalf("the failed wake's release %+v, want min_txid %d", v.Lock, cleanTXID)
}
return
}
@@ -754,3 +757,66 @@ func TestGenerationsSwitchParse(t *testing.T) {
}
}
}
+
+// 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
+// restarts (the bound read from the stored marker alone), and after a
+// wake that failed before planning: the release of a take that never
+// switched carries the bound forward as min_txid.
+func TestHAWakeTruncatedReplicaRefusesEveryWake(t *testing.T) {
+ setup := func(t *testing.T) (*haSvc, uint64) {
+ t.Helper()
+ t.Setenv("CARLOS_HA_GENERATIONS", "on")
+ s, e := haServiceEntry(t, "shop.example.com")
+ s.insertRows(t, 0, 3)
+ s.stopForTest(e)
+ v := s.lockView(t)
+ if v.Lock.Release == nil || !v.Lock.Release.Clean || !v.Lock.Release.Gen {
+ t.Fatalf("release %+v", v.Lock.Release)
+ }
+ m := *v.Lock.Release
+ m.TXID += 50 // the replica's newest L0 is 50 short of the marker
+ body, err := hafresh.MarkerBody(v.Lock.Generation, m)
+ if err != nil {
+ t.Fatal(err)
+ }
+ putLockFor(t, s.b, s.rt, body)
+ return s, m.TXID
+ }
+ refused := func(t *testing.T, s *haSvc, want uint64, i int) {
+ t.Helper()
+ _, err := s.wakeForTest(context.Background())
+ var re *errLeaseRefused
+ if !errors.As(err, &re) || !strings.Contains(re.reason, lease.RefuseCleanMarkerAboveL0) {
+ t.Fatalf("wake %d: %v, want clean_marker_above_l0", i, err)
+ }
+ if r := s.lockView(t).Lock.Release; r == nil || r.Clean || !r.Settled || r.MinTXID != want {
+ t.Fatalf("wake %d's release %+v, want min_txid %d", i, r, want)
+ }
+ }
+ t.Run("refused, again, and after a restart", func(t *testing.T) {
+ s, want := setup(t)
+ h, _ := s.head(t)
+ refused(t, s, want, 1)
+ refused(t, s, want, 2)
+ refused(t, s.restart(t), want, 3)
+ if got, _ := s.head(t); got.Generation != h.Generation {
+ t.Fatalf("head moved to %s", got.Generation)
+ }
+ })
+ t.Run("a failure before planning keeps the bound", func(t *testing.T) {
+ s, want := setup(t)
+ key := s.headKey()
+ s.fx.FailNextMatching("GET", 403, func(k string, _ []byte) bool { return k == key })
+ _, err := s.wakeForTest(context.Background())
+ var re *errLeaseRefused
+ if err == nil || errors.As(err, &re) {
+ t.Fatalf("wake with head.json unreadable: %v, want a failure", err)
+ }
+ if r := s.lockView(t).Lock.Release; r == nil || !r.Settled || r.MinTXID != want {
+ t.Fatalf("the failed wake's release %+v, want min_txid %d", r, want)
+ }
+ refused(t, s, want, 2)
+ })
+}
diff --git a/internal/activator/hasecrets.go b/internal/activator/hasecrets.go
index bcac4f039..8f8d2c643 100644
--- a/internal/activator/hasecrets.go
+++ b/internal/activator/hasecrets.go
@@ -237,35 +237,54 @@ func (b *ExecBackend) haPublisherNow(host string) *hostFiles {
}
// haManifestFound reports whether rt's files manifest exists, from the
-// publisher this wake already holds, else by one read. A manifest a
-// storage generations files fence stamped (region HA storage generations
-// §7, hostfiles.FenceManifest) that holds no entry and no platform item
-// is the fence's create over an empty tree: nothing was ever published
-// beside it, so no launch used a secret, and it answers false as no
-// manifest does.
+// publisher this wake already holds, else by one read, both decoded by
+// baselineManifest. One manifest answers false as no manifest does: the
+// placeholder a storage generations files fence creates over an empty
+// tree (fencePlaceholder; region HA storage generations §7,
+// hostfiles.FenceManifest). Its seq is 0, so no publisher ever committed
+// to it (every stage and delete takes a sequence number, and a fence
+// keeps the seq it found), and no launch was ever handed a secret beside
+// it.
+//
+// A writer of the bucket can make a manifest look like that placeholder
+// by overwriting it, and so make the next wake mint a new pair. That is
+// no new power: such a writer is a box of the deployment, which already
+// holds the secrets key and can publish a sealed env of its choosing,
+// and the overwritten manifest stays in the bucket's versions.
func (b *ExecBackend) haManifestFound(ctx context.Context, rt registry.Route) (bool, error) {
+ var base hostfiles.Baseline
if f := b.haPublisherNow(rt.Host); f != nil {
- base := f.pub.Baseline()
- if !base.Found {
- return false, nil
+ base = f.pub.Baseline()
+ } else {
+ if b.FilesStore == nil {
+ return false, errors.New("no files store configured")
}
- var m hostfiles.Manifest
- if err := json.Unmarshal(base.Body, &m); err != nil {
- return false, fmt.Errorf("the wake's files manifest: %w", err)
+ body, etag, err := b.FilesStore.Get(ctx, hostfiles.ManifestKey(b.filesPrefix(rt.Host)))
+ switch {
+ case errors.Is(err, os.ErrNotExist):
+ case err != nil:
+ return false, err
+ default:
+ base = hostfiles.Baseline{Found: true, Body: body, ETag: etag}
}
- return !fencedEmpty(m), nil
}
- if b.FilesStore == nil {
- return false, errors.New("no files store configured")
+ if !base.Found {
+ return false, nil
+ }
+ m, err := baselineManifest(base)
+ if err != nil {
+ return false, err
}
- m, found, err := hostfiles.Load(ctx, b.FilesStore, b.filesPrefix(rt.Host))
- return found && !fencedEmpty(m), err
+ return !fencePlaceholder(m), nil
}
-// fencedEmpty reports a manifest a files fence stamped that holds no
-// entry (live, deleted or skipped) and no platform item.
-func fencedEmpty(m hostfiles.Manifest) bool {
- return m.LockGeneration > 0 && len(m.Entries) == 0 && len(m.Platform) == 0
+// fencePlaceholder reports the manifest a files fence's create writes
+// over an empty tree, and a later fence's re-stamp of it: this binary's
+// version, a lock generation, seq 0, and no entry, platform item or
+// origin.
+func fencePlaceholder(m hostfiles.Manifest) bool {
+ return m.V == hostfiles.ManifestVersion && m.LockGeneration > 0 && m.Seq == 0 &&
+ len(m.Entries) == 0 && len(m.Platform) == 0 && len(m.Origins) == 0
}
// haSecretsReady is the step between an HA host's ensure calls and its
diff --git a/internal/activator/hasecrets_test.go b/internal/activator/hasecrets_test.go
index c06c65808..fd33133eb 100644
--- a/internal/activator/hasecrets_test.go
+++ b/internal/activator/hasecrets_test.go
@@ -538,3 +538,127 @@ func TestHALaunchEnvIsTheAcknowledgedOne(t *testing.T) {
t.Fatalf("the launch was handed %q / %q, not the acknowledged t1 / k1", got["CARLOS_ADMIN_TOKEN"], got[InstanceKeyVar])
}
}
+
+// The HA mint guard and the storage generations files fence (Task 5 fix
+// round 1). A placeholder a fence created over an empty tree (seq 0, no
+// entry, platform item or origin) is no manifest: the mint goes ahead,
+// also after a second take re-stamps it, on the store path and the wake
+// publisher's path alike. Any manifest a publisher ever committed to
+// refuses, fenced or not.
+func TestHAMintGuardFencePlaceholder(t *testing.T) {
+ ctx := context.Background()
+ // verdicts is the guard's answer on the store path, then on the path
+ // of a wake publisher staged on the stored manifest.
+ verdicts := func(t *testing.T, b *ExecBackend, rt registry.Route) [2]error {
+ t.Helper()
+ var out [2]error
+ out[0] = b.haMintGuard(ctx, rt)("CARLOS_ADMIN_TOKEN")
+ pub, err := hostfiles.Open(ctx, b.FilesStore, b.filesPrefix(rt.Host))
+ if err != nil {
+ t.Fatal(err)
+ }
+ b.stageWakeFiles(rt, pub.Baseline())
+ if _, ok := b.wakeFiles(rt.Host); !ok {
+ t.Fatal("no wake publisher staged")
+ }
+ out[1] = b.haMintGuard(ctx, rt)("CARLOS_ADMIN_TOKEN")
+ b.haWakes.takeFiles(rt.Host)
+ return out
+ }
+ fence := func(t *testing.T, b *ExecBackend, rt registry.Route, gen int64) {
+ t.Helper()
+ pub, err := hostfiles.Open(ctx, b.FilesStore, b.filesPrefix(rt.Host))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := hostfiles.FenceManifest(ctx, b.FilesStore, b.filesPrefix(rt.Host), pub.Baseline(), gen); err != nil {
+ t.Fatal(err)
+ }
+ }
+ refuses := func(t *testing.T, v [2]error) {
+ t.Helper()
+ for i, err := range v {
+ if !errors.Is(err, ErrInstanceKeyDeferred) {
+ t.Fatalf("path %d: %v, want ErrInstanceKeyDeferred", i, err)
+ }
+ }
+ }
+
+ t.Run("fence placeholder mints, re-stamped too, then a lost env refuses", func(t *testing.T) {
+ b, rt := haLaunchBackend(t, "shop.example.com")
+ fence(t, b, rt, 3)
+ if v := verdicts(t, b, rt); v[0] != nil || v[1] != nil {
+ t.Fatalf("placeholder: %v", v)
+ }
+ fence(t, b, rt, 4) // a second take, before any publish
+ if v := verdicts(t, b, rt); v[0] != nil || v[1] != nil {
+ t.Fatalf("re-stamped placeholder: %v", v)
+ }
+ if err := b.launchForTest(rt); err != nil {
+ t.Fatalf("first launch over the placeholder: %v", err)
+ }
+ if env := platformEnv(t, b, rt); !strings.Contains(env, "CARLOS_ADMIN_TOKEN=") || !strings.Contains(env, InstanceKeyVar+"=") {
+ t.Fatalf("the minted pair was not published: %q", env)
+ }
+ writeEnv(t, b, rt, "") // the env is lost after the acknowledged publish
+ if err := b.launchForTest(rt); !errors.Is(err, ErrInstanceKeyDeferred) || envFileHas(t, b, rt, "CARLOS_ADMIN_TOKEN") {
+ t.Fatalf("launch after a lost env: %v", err)
+ }
+ fence(t, b, rt, 5)
+ refuses(t, verdicts(t, b, rt))
+ })
+
+ t.Run("a real manifest, fenced, refuses", func(t *testing.T) {
+ b, rt := haLaunchBackend(t, "shop.example.com")
+ publishSealedEnv(t, b, rt, "CARLOS_ADMIN_TOKEN=t1\n"+InstanceKeyVar+"=k1\n")
+ fence(t, b, rt, 6)
+ refuses(t, verdicts(t, b, rt))
+ })
+
+ t.Run("seq above 0 with its platform emptied, fenced, refuses", func(t *testing.T) {
+ b, rt := haLaunchBackend(t, "shop.example.com")
+ pub, err := hostfiles.Open(ctx, b.FilesStore, b.filesPrefix(rt.Host))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := pub.StagePlatform(ctx, "item", []byte("x")); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := pub.Commit(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if err := pub.StagePlatformDelete("item"); err != nil {
+ t.Fatal(err)
+ }
+ if seq, err := pub.Commit(ctx); err != nil || seq == 0 {
+ t.Fatalf("commit %d %v", seq, err)
+ }
+ if m, _, _ := hostfiles.Load(ctx, b.FilesStore, b.filesPrefix(rt.Host)); len(m.Platform) != 0 || len(m.Entries) != 0 || m.Seq == 0 {
+ t.Fatalf("fixture: %+v", m)
+ }
+ fence(t, b, rt, 7)
+ refuses(t, verdicts(t, b, rt))
+ })
+
+ t.Run("an origins-only manifest, fenced, refuses", func(t *testing.T) {
+ b, rt := haLaunchBackend(t, "shop.example.com")
+ pub, err := hostfiles.Open(ctx, b.FilesStore, b.filesPrefix(rt.Host))
+ if err != nil {
+ t.Fatal(err)
+ }
+ pub.SetOrigins([]string{b.filesPrefix(rt.Host)})
+ if seq, err := pub.Commit(ctx); err != nil || seq != 0 {
+ t.Fatalf("commit %d %v", seq, err)
+ }
+ fence(t, b, rt, 8)
+ refuses(t, verdicts(t, b, rt))
+ })
+
+ t.Run("a crafted stamp on a published seq refuses", func(t *testing.T) {
+ b, rt := haLaunchBackend(t, "shop.example.com")
+ if _, err := b.FilesStore.Put(ctx, hostfiles.ManifestKey(b.filesPrefix(rt.Host)), []byte(`{"v":2,"seq":12,"entries":{},"platform":{},"lock_generation":9}`), ""); err != nil {
+ t.Fatal(err)
+ }
+ refuses(t, verdicts(t, b, rt))
+ })
+}
diff --git a/internal/activator/hawake.go b/internal/activator/hawake.go
index 23f840938..943c09049 100644
--- a/internal/activator/hawake.go
+++ b/internal/activator/hawake.go
@@ -733,8 +733,10 @@ func (b *ExecBackend) restoreHAGenerations(ctx context.Context, rt registry.Rout
return false, err
}
opt := lease.TakeOptions{First: first, Self: b.self(), Lifetime: lifetime}
- if m := v.Lock.Release; m != nil && m.Clean {
- opt.CleanTXID = m.TXID
+ if m := v.Lock.Release; m != nil {
+ // A clean marker's TXID, or the bound a failed take before this one
+ // carried forward (min_txid); the lease raises it to the same.
+ opt.CleanTXID = m.TakeBound()
}
var vs lease.VersionedStore
if !first {
diff --git a/internal/hafresh/generations_test.go b/internal/hafresh/generations_test.go
index 813234e31..24ded1bc8 100644
--- a/internal/hafresh/generations_test.go
+++ b/internal/hafresh/generations_test.go
@@ -259,3 +259,49 @@ func TestMarkerSameRecord(t *testing.T) {
t.Fatal("a different record matched")
}
}
+
+// min_txid (storage generations, Task 5 fix round 1): inside the marker
+// record, round-tripped in either format, part of the record SameRecord
+// compares, absent from markers that do not set it, and the take bound is
+// the higher of it and a clean marker's TXID.
+func TestMarkerMinTXID(t *testing.T) {
+ for _, gen := range []bool{false, true} {
+ m := Marker{V: 1, Box: "a", IID: "i-a", Lifetime: "L", Settled: true, MinTXID: 100, Gen: gen}
+ body, err := MarkerBody(7, m)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(string(body), `"min_txid":100`) {
+ t.Fatalf("body %s", body)
+ }
+ if u, err := UnknownFields(body); err != nil || len(u) != 0 {
+ t.Fatalf("unknown top-level fields %v %v", u, err)
+ }
+ v, err := DecodeLock(body, `"e"`)
+ if err != nil || v.Lock.Release == nil || v.Lock.Release.MinTXID != 100 || !v.Lock.Release.SameRecord(m) {
+ t.Fatalf("decoded %+v %v", v.Lock.Release, err)
+ }
+ o := m
+ o.MinTXID = 0
+ if v.Lock.Release.SameRecord(o) {
+ t.Fatal("SameRecord ignores min_txid")
+ }
+ if body, _ := MarkerBody(7, o); strings.Contains(string(body), "min_txid") {
+ t.Fatalf("a marker without min_txid writes it: %s", body)
+ }
+ }
+ for _, c := range []struct {
+ m Marker
+ want uint64
+ }{
+ {Marker{TXID: 90, Clean: true}, 90},
+ {Marker{TXID: 90}, 0},
+ {Marker{MinTXID: 100}, 100},
+ {Marker{TXID: 90, Clean: true, MinTXID: 100}, 100},
+ {Marker{TXID: 120, Clean: true, MinTXID: 100}, 120},
+ } {
+ if got := c.m.TakeBound(); got != c.want {
+ t.Fatalf("%+v: bound %d, want %d", c.m, got, c.want)
+ }
+ }
+}
diff --git a/internal/hafresh/lock.go b/internal/hafresh/lock.go
index e15603b58..b4c78ad7b 100644
--- a/internal/hafresh/lock.go
+++ b/internal/hafresh/lock.go
@@ -46,6 +46,15 @@ type Marker struct {
// files objects are create-only and the manifest moves by CAS, so a
// files-only release cannot collide the way an L0 can).
Finalized bool `json:"finalized,omitempty"`
+ // MinTXID is the lowest TXID a storage generations take from this
+ // marker may start at (TakeBound): written only by the release of a
+ // generations lock whose take never switched head.json (a refusal, a
+ // failure before or during the take, a lost race), so that the bound
+ // that take enforced, its predecessor's clean TXID or an earlier
+ // failed take's MinTXID, outlives the release that replaced that
+ // marker. Additive and inside the record: absent (0) on every other
+ // marker.
+ MinTXID uint64 `json:"min_txid,omitempty"`
// Gen is the marker's format, not part of its record: true for a
// storage-generations host's marker, written with the owner suffix
// ;gen=1 and its record in carlos_release_g instead of carlos_release
@@ -57,6 +66,17 @@ type Marker struct {
Gen bool `json:"-"`
}
+// TakeBound is the TXID a generation take over m must reach (the lease's
+// PlanStart lower bound): the TXID a clean m records, or MinTXID, the
+// bound a failed take carried forward, whichever is higher.
+func (m Marker) TakeBound() uint64 {
+ b := m.MinTXID
+ if m.Clean && m.TXID > b {
+ b = m.TXID
+ }
+ return b
+}
+
// SameRecord reports whether m and o record the same release, whatever
// format each was (or will be) written in: Gen is left out.
func (m Marker) SameRecord(o Marker) bool {
diff --git a/internal/lease/gentake.go b/internal/lease/gentake.go
index 2b27b63d4..164e1e7f6 100644
--- a/internal/lease/gentake.go
+++ b/internal/lease/gentake.go
@@ -66,6 +66,11 @@ type TakeOptions struct {
Self hafresh.Self
// Lifetime is the incarnation created_by names.
Lifetime string
+ // CleanTXID is raised to the bound of the marker the acquire took over
+ // (hafresh.Marker.TakeBound) whatever the caller passes: a released
+ // generations lock whose take never switched carries its bound in
+ // MinTXID, and no take may drop it.
+ //
// HeadRead says Head, HeadETag and HeadFound are head.json as the
// caller already read it (ReadHead), so the take does not read it
// again. Otherwise the take reads it (one GET).
@@ -97,6 +102,10 @@ type Take struct {
Predecessor string
StartTXID uint64
Empty bool
+ // Bound is the lowest TXID the take accepted as its start (PlanStart's
+ // lower bound): until it switches, the handle's releases carry it
+ // forward as the marker's MinTXID.
+ Bound uint64
h *Held
st release.Store
@@ -145,7 +154,10 @@ func (h *Held) StartGeneration(ctx context.Context, st release.Store, vs Version
if err != nil {
return nil, err
}
- t := &Take{Generation: gen, h: h, st: st, loc: loc, reader: reader,
+ if b := h.viewBound(); b > opt.CleanTXID {
+ opt.CleanTXID = b
+ }
+ t := &Take{Generation: gen, Bound: opt.CleanTXID, h: h, st: st, loc: loc, reader: reader,
created: HeadCreator{LockGeneration: h.lockGen, Box: self.Ref, IID: self.IID, Lifetime: opt.Lifetime}}
h.mu.Lock()
@@ -332,6 +344,37 @@ func RestoreTake(ctx context.Context, dbPath string, t *Take) (bool, error) {
return restoreFrom(ctx, t.reader, dbPath, 0)
}
+// viewBound is the take bound of the marker h's acquire took over
+// (hafresh.Marker.TakeBound): 0 over an absent lock or a held one.
+func (h *Held) viewBound() uint64 {
+ if r := h.view.Lock.Release; r != nil && !h.view.Absent {
+ return r.TakeBound()
+ }
+ return 0
+}
+
+// preSwitchBound is the MinTXID a release of h writes: for a generations
+// lock whose take has not switched head.json (none started, refused,
+// failed, or lost its race), the bound that take enforced or would have
+// (the acquired marker's, raised by the take's own); 0 for any other
+// handle, whose releases are as before.
+func (h *Held) preSwitchBound() uint64 {
+ if h.rn == nil || h.rn.genName == "" {
+ return 0
+ }
+ h.mu.Lock()
+ t := h.take
+ h.mu.Unlock()
+ if t != nil && t.switched() {
+ return 0
+ }
+ b := h.viewBound()
+ if t != nil && t.Bound > b {
+ b = t.Bound
+ }
+ return b
+}
+
// takeWriter is the replica client a handle replicates through
// (newStore): nil for a handle whose lock is not a generations lock (no
// take: the client newStore has always built); ErrGenerationNotSwitched
diff --git a/internal/lease/gentake_test.go b/internal/lease/gentake_test.go
index 01bbcb57a..f6e213e21 100644
--- a/internal/lease/gentake_test.go
+++ b/internal/lease/gentake_test.go
@@ -966,3 +966,99 @@ func TestTakeRequestBudget(t *testing.T) {
t.Fatalf("head names %s, want %s", got.Generation, tk2.Generation)
}
}
+
+// lockView is the stored lock, decoded.
+func (fx *genFixture) lockView(t *testing.T) hafresh.View {
+ t.Helper()
+ body, ok := fx.m.Current(fx.bucket, fx.loc+"/lock.json")
+ if !ok {
+ t.Fatal("no lock.json")
+ }
+ v, err := hafresh.DecodeLock(body, `"e"`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return v
+}
+
+// A release of a generations lock whose take never switched carries the
+// bound that take enforced forward as the marker's min_txid, so a
+// truncated replica (a clean marker at TXID T+50, a plan only to T) is
+// refused by every later take, whether the take refused, never started,
+// or the caller passed no bound at all. A switched take's release
+// carries nothing.
+func TestPreSwitchReleaseCarriesTheTakeBound(t *testing.T) {
+ haBox(t)
+ t.Run("truncated", func(t *testing.T) {
+ fx := newGenFixture(t)
+ _, txid := fx.seed(t, time.Minute, 3)
+ v := fx.lockView(t)
+ m := *v.Lock.Release
+ m.TXID = txid + 50 // the replica's newest L0 is txid: truncated
+ body, err := hafresh.MarkerBody(v.Lock.Generation, m)
+ if err != nil {
+ t.Fatal(err)
+ }
+ fx.m.Put(fx.bucket, fx.loc+"/lock.json", body)
+ want := txid + 50
+ refuses := func(i int) {
+ t.Helper()
+ h := fx.acquire(t, time.Minute)
+ // No bound passed in: the lease applies the acquired marker's.
+ _, err := h.StartGeneration(ctx, fx.st, fx.vs, lease.TakeOptions{Self: selfB, Lifetime: "L1"})
+ var sr *lease.StartRefusal
+ if !errors.As(err, &sr) || sr.Reason != lease.RefuseCleanMarkerAboveL0 {
+ t.Fatalf("take %d: %v, want clean_marker_above_l0", i, err)
+ }
+ if err := h.Release(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if r := fx.lockView(t).Lock.Release; r == nil || r.Clean || !r.Settled || !r.Gen || r.TXID != 0 || r.MinTXID != want || r.TakeBound() != want {
+ t.Fatalf("release after take %d: %+v, want settled with min_txid %d", i, r, want)
+ }
+ }
+ refuses(1)
+ refuses(2)
+ // A failure before any take (the wake gave the lease back first).
+ h := fx.acquire(t, time.Minute)
+ if err := h.Release(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if r := fx.lockView(t).Lock.Release; r == nil || r.MinTXID != want {
+ t.Fatalf("release with no take: %+v, want min_txid %d", r, want)
+ }
+ refuses(3)
+ if got := fx.current(t, fx.loc+"/g-"); len(got) == 0 {
+ t.Fatal("the seed's generation is gone")
+ }
+ })
+ t.Run("switched", func(t *testing.T) {
+ fx := newGenFixture(t)
+ _, txid := fx.seed(t, time.Minute, 3)
+ h := fx.acquire(t, time.Minute)
+ tk, err := h.StartGeneration(ctx, fx.st, fx.vs, lease.TakeOptions{Self: selfB, Lifetime: "L1"})
+ if err != nil || tk.Bound != txid {
+ t.Fatalf("take %+v %v, want bound %d", tk, err, txid)
+ }
+ // Copied, not switched: the release keeps the clean marker's bound.
+ if err := h.Release(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if r := fx.lockView(t).Lock.Release; r == nil || r.MinTXID != txid {
+ t.Fatalf("release before the switch: %+v, want min_txid %d", r, txid)
+ }
+ h = fx.acquire(t, time.Minute)
+ if tk, err = h.StartGeneration(ctx, fx.st, fx.vs, lease.TakeOptions{Self: selfB, Lifetime: "L1"}); err != nil || tk.Bound != txid {
+ t.Fatalf("take over the carried bound %+v %v", tk, err)
+ }
+ if err := tk.Switch(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if err := h.Release(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if r := fx.lockView(t).Lock.Release; r == nil || r.MinTXID != 0 {
+ t.Fatalf("release after the switch: %+v, want no min_txid", r)
+ }
+ })
+}
diff --git a/internal/lease/ha.go b/internal/lease/ha.go
index e1d936436..2588b5eb7 100644
--- a/internal/lease/ha.go
+++ b/internal/lease/ha.go
@@ -175,8 +175,14 @@ func acquireHARestricted(ctx context.Context, bucket, prefix, region string, bas
cur := rn.stop()
relCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
- // Nothing replicated under it: the marker is settled.
- return nil, errors.Join(fmt.Errorf("acquire HA lease: %w", err), releaseWithMarker(relCtx, rn, region, cur, uncleanMarker(base, 0, true)))
+ // Nothing replicated under it: the marker is settled. A generations
+ // lock's take never ran, so the bound it would have enforced is
+ // carried forward (hafresh.Marker.MinTXID).
+ m := uncleanMarker(base, 0, true)
+ if genName != "" && view.Lock.Release != nil {
+ m.MinTXID = view.Lock.Release.TakeBound()
+ }
+ return nil, errors.Join(fmt.Errorf("acquire HA lease: %w", err), releaseWithMarker(relCtx, rn, region, cur, m))
}
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, lockGen: lease.Generation}, nil
diff --git a/internal/lease/lease.go b/internal/lease/lease.go
index ea2239d25..db2467f48 100644
--- a/internal/lease/lease.go
+++ b/internal/lease/lease.go
@@ -349,7 +349,9 @@ func (h *Held) Release(ctx context.Context) error {
return nil
}
if h.ha {
- return releaseWithMarker(ctx, h.rn, h.region, lease, uncleanMarker(h.base, 0, !h.wroteReplica()))
+ m := uncleanMarker(h.base, 0, !h.wroteReplica())
+ m.MinTXID = h.preSwitchBound()
+ return releaseWithMarker(ctx, h.rn, h.region, lease, m)
}
err := h.leaser.ReleaseLease(ctx, lease)
if err != nil && !releaseSettled(err) {
diff --git a/internal/lease/release.go b/internal/lease/release.go
index ee53d5295..8443d6624 100644
--- a/internal/lease/release.go
+++ b/internal/lease/release.go
@@ -127,7 +127,7 @@ func conditionFailed(err error) bool {
// settled says the handle never replicated (hafresh.Marker.Settled).
func uncleanMarker(base hafresh.Marker, txid uint64, settled bool) hafresh.Marker {
m := base
- m.V, m.TXID, m.FilesGen, m.Clean, m.Settled, m.Finalized, m.At = 1, txid, "", false, settled, false, time.Now().UTC()
+ m.V, m.TXID, m.FilesGen, m.Clean, m.Settled, m.Finalized, m.MinTXID, m.At = 1, txid, "", false, settled, false, 0, time.Now().UTC()
return m
}
@@ -183,6 +183,9 @@ func (h *Held) ReleaseMarker(ctx context.Context, m hafresh.Marker) error {
m = withBase(h.base, m)
m.Clean, m.Finalized = false, false
m.Settled = !h.wroteReplica()
+ if b := h.preSwitchBound(); b > m.MinTXID {
+ m.MinTXID = b
+ }
return releaseWithMarker(ctx, h.rn, h.region, lease, m)
}