carlos / platform Public

lease: keep grace entries in history; drop the clock check

Task 9 review round 2, ruled a cut:
- The switch now trims head.json's history at the restore window plus
  RetireGrace (an hour), and left is exactly what that trim drops. An
  entry inside the grace stays in history, so it is kept, never an
  abandoned candidate, whatever its objects' age.
- The clock-skew check, its head.json listing and ErrClockSkew are
  removed. S3 refuses a SigV4 request signed more than 15 minutes off
  its own time (RequestTimeTooSkewed), so a box whose deletes succeed is
  within 15 minutes, inside the hour of grace; RetireGenerations' doc
  comment says so. The fake bucket's SetClock goes with it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 2b20865b23d275141d018ed41e4b3eec5214b920 parent 47a5614
6 files changed, +71 −234
  • internal/activator/hagenerations_test.go +0 −54
  • internal/activator/hawake.go +3 −10
  • internal/lease/genretire.go +20 −62
  • internal/lease/genretire_test.go +45 −96
  • internal/lease/gentake.go +3 −4
  • internal/lease/leasetest/bucket.go +0 −8

CI failed — run details

diff --git a/internal/activator/hagenerations_test.go b/internal/activator/hagenerations_test.go
index 353d236cd..6556eca53 100644
--- a/internal/activator/hagenerations_test.go
+++ b/internal/activator/hagenerations_test.go
@@ -1025,57 +1025,3 @@ func TestHAWakeReplicationFailureStartsNoRetirement(t *testing.T) {
}
}
}
-
-// skewedHead reports head.json's versions as written off later than they
-// were: the bucket's clock ahead of the box's.
-type skewedHead struct {
- lease.VersionedStore
- off time.Duration
-}
-
-func (s skewedHead) ListVersions(ctx context.Context, bucket, prefix string) ([]lease.ObjectVersion, error) {
- vs, err := s.VersionedStore.ListVersions(ctx, bucket, prefix)
- for i := range vs {
- if strings.HasSuffix(vs[i].Key, "/head.json") {
- vs[i].LastModified = vs[i].LastModified.Add(s.off)
- }
- }
- return vs, err
-}
-
-// A box whose clock is off the bucket's by more than lease.MaxClockSkew
-// at its switch retires nothing: the pass stops after the head.json
-// listing, logs ha_generation_retire_failed reason=clock_skew, and the
-// wake serves.
-func TestHAWakeClockSkewSkipsRetirement(t *testing.T) {
- prev := newTakeStore
- t.Cleanup(func() { newTakeStore = prev }) // runs after abandon joins the pass
- newTakeStore = func(ctx context.Context, bucket, region string) (lease.VersionedStore, error) {
- vs, err := prev(ctx, bucket, region)
- return skewedHead{VersionedStore: vs, off: 10 * time.Minute}, err
- }
- t.Setenv("CARLOS_HA_GENERATIONS", "on")
- lines := captureLogLines(t)
- s := haService(t, "shop.example.com")
- before := len(s.fx.Requests())
- e, err := s.wakeForTest(context.Background())
- if err != nil {
- t.Fatalf("wake: %v", err)
- }
- s.b.retiring.Wait()
- if n := lines.matching("ha_generation_retire_failed host=shop.example.com reason=clock_skew"); n != 1 {
- t.Fatalf("%d clock_skew lines, want 1", n)
- }
- // (A first wake's acquire lists the location itself, proving it
- // empty, before the take; retirement's ListDirs would follow its
- // head.json listing.)
- reqs := s.fx.Requests()[before:]
- at := slices.Index(reqs, "LISTV "+s.headKey())
- if at < 0 || slices.Contains(reqs[at:], "LIST "+s.loc()+"/") {
- t.Fatalf("requests %v: want the head.json listing and no ListDirs after it", reqs)
- }
- if e == nil || e.state != actAwake {
- t.Fatalf("entry %+v, want awake", e)
- }
- s.stopForTest(e)
-}
diff --git a/internal/activator/hawake.go b/internal/activator/hawake.go
index 2a8446ca5..655e3b67c 100644
--- a/internal/activator/hawake.go
+++ b/internal/activator/hawake.go
@@ -828,9 +828,8 @@ const retireTimeout = 2 * time.Minute
// once @root has left history. A held that is not a storage generations
// lock does nothing. The pass checks the lease through rep (Replicate
// spent held) before each generation, has its own two-minute bound, and
-// a failure is logged as ha_generation_retire_failed (reason=clock_skew
-// when the box's clock is off the bucket's, reason=error otherwise) and
-// never fails the wake: the next take retries what is left.
+// a failure is logged as ha_generation_retire_failed and never fails the
+// wake: the next take retries what is left.
func (b *ExecBackend) startRetirement(host string, held *lease.Held, rep *lease.Replicator) {
if held == nil || rep == nil || held.GenName() == "" {
return
@@ -842,13 +841,7 @@ func (b *ExecBackend) startRetirement(host string, held *lease.Held, rep *lease.
defer cancel()
stats, err := b.retire(ctx, held, rep)
if err != nil {
- reason := "error"
- if errors.Is(err, lease.ErrClockSkew) {
- // The box's clock is off the bucket's: nothing is retired
- // until it is in step (lease.MaxClockSkew).
- reason = "clock_skew"
- }
- log.Printf("ha_generation_retire_failed host=%s reason=%s retired=%v objects=%d: %v", host, reason, stats.Retired, stats.Objects, err)
+ log.Printf("ha_generation_retire_failed host=%s retired=%v objects=%d: %v", host, stats.Retired, stats.Objects, err)
return
}
if len(stats.Retired) > 0 || len(stats.Young) > 0 {
diff --git a/internal/lease/genretire.go b/internal/lease/genretire.go
index c75af1a8d..0fbab85fb 100644
--- a/internal/lease/genretire.go
+++ b/internal/lease/genretire.go
@@ -26,25 +26,15 @@ import (
// (a g-* prefix no head.json names) must be before retirement deletes it.
const AbandonedAge = 24 * time.Hour
-// MaxClockSkew is how far this box's clock may be from the bucket's before
-// retirement refuses to run. The switch trims history by the box's clock
-// and a generation that left it is deleted at once, so a clock running
-// ahead would shrink the restore window by its error.
-const MaxClockSkew = 5 * time.Minute
-
-// RetireGrace is how long past the restore window a history entry waits
-// before the switch that drops it hands it to retirement (left): a
-// point-in-time read that resolved it just before that switch keeps its
-// files. An entry dropped inside the grace is not in left; a later take
-// finds it abandoned, and its objects are over a day old by then.
+// RetireGrace is how long past the restore window a history entry stays
+// in head.json: the switch trims history at SnapshotRetention plus
+// RetireGrace, and only what that trim drops is handed to retirement
+// (left). Until then the entry is in history, so it is kept, never an
+// abandoned candidate. The hour covers a point-in-time read that resolved
+// the entry just before the switch that drops it, and the box's clock
+// error (see RetireGenerations).
const RetireGrace = time.Hour
-// ErrClockSkew refuses a retirement pass whose box clock is more than
-// MaxClockSkew from the bucket's, as measured at its own switch: the
-// head.json the switch wrote records the box's time (created_by.at) and
-// the bucket records its LastModified.
-var ErrClockSkew = errors.New("lease: retire generations: the box clock is off the bucket's")
-
// RetireStats is what one retirement pass did.
type RetireStats struct {
// Retired is each generation whose current objects the pass deleted,
@@ -75,16 +65,7 @@ type retireCandidate struct {
// version (listings with LastModified). healthy is the holder's lease
// check; it runs before each generation, and a failure ends the pass.
//
-// First, one version listing of head.json: its current version's
-// LastModified, the bucket's time at the switch, against head's
-// created_by.at, the box's. More than MaxClockSkew apart (or no head.json,
-// or a head whose created_by.at is unset) refuses the pass, ErrClockSkew
-// for the skew. A newer holder's head.json, written more than
-// MaxClockSkew after this switch, refuses the pass the same way (that
-// holder retires); one written sooner does not, and the pass is safe
-// anyway (the stale-head invariant below).
-//
-// Then one ListDirs of loc/; then, for each generation that may go, one
+// One ListDirs of loc/; then, for each generation that may go, one
// version listing (one per level directory for the root) and one bare
// DELETE per current key:
//
@@ -113,6 +94,15 @@ type retireCandidate struct {
// So nothing any later head names is deleted, whether healthy is checked
// before each generation, each delete, or never; the per-generation check
// only stops a lost holder sooner.
+//
+// Clock error: the switch trims history, and so chooses left, by this
+// box's clock, and a generation in left is deleted at once. There is no
+// separate clock check, because the provider bounds the error: S3 refuses
+// any SigV4-signed request whose signing time is more than 15 minutes from
+// its own (RequestTimeTooSkewed), so a box whose deletes succeed is within
+// 15 minutes of the bucket's time. RetireGrace, an hour past the restore
+// window, is more than that, so no generation still inside the window by
+// the bucket's time is ever in left.
func RetireGenerations(ctx context.Context, st release.Store, vs VersionedStore, bucket, loc string, head Head, mine int64, left []HeadHistory, healthy func() error, now time.Time) (RetireStats, error) {
var stats RetireStats
if st == nil || vs == nil || healthy == nil || bucket == "" {
@@ -130,9 +120,6 @@ func RetireGenerations(ctx context.Context, st release.Store, vs VersionedStore,
if err := healthy(); err != nil {
return stats, fmt.Errorf("lease: retire generations: %w", err)
}
- if err := checkSwitchClock(ctx, vs, bucket, loc, head); err != nil {
- return stats, err
- }
keep := map[string]bool{head.Generation: true}
if head.Predecessor != "" {
keep[head.Predecessor] = true
@@ -270,35 +257,6 @@ func deleteKeys(ctx context.Context, st release.Store, keys []string) (int, erro
return n, errors.Join(errs...)
}
-// checkSwitchClock compares head's created_by.at (the box's clock at its
-// switch) with the LastModified of head.json's current version (the
-// bucket's): one version listing of head.json.
-func checkSwitchClock(ctx context.Context, vs VersionedStore, bucket, loc string, head Head) error {
- if head.CreatedBy.At.IsZero() {
- return fmt.Errorf("%w: head.json for %s records no switch time", ErrClockSkew, head.Generation)
- }
- key := loc + "/" + headName
- versions, err := vs.ListVersions(ctx, bucket, key)
- if err != nil {
- return fmt.Errorf("lease: retire generations: list %s: %w", key, err)
- }
- for _, v := range versions {
- if v.Key != key || !v.IsLatest {
- continue
- }
- if v.DeleteMarker {
- break
- }
- skew := v.LastModified.Sub(head.CreatedBy.At)
- if skew > MaxClockSkew || skew < -MaxClockSkew {
- return fmt.Errorf("%w: %s written at %s by the bucket, %s by this box (%s apart, at most %s)", ErrClockSkew, key,
- v.LastModified.UTC().Format(time.RFC3339), head.CreatedBy.At.UTC().Format(time.RFC3339), skew.Abs().Round(time.Second), MaxClockSkew)
- }
- return nil
- }
- return fmt.Errorf("lease: retire generations: %s has no current version", key)
-}
-
// isLevelDir reports a Litestream level directory name: four lowercase
// hex digits, level 0 to SnapshotLevel (9), as the S3 client writes it.
func isLevelDir(name string) bool {
@@ -329,9 +287,9 @@ func (h *Held) Retire(ctx context.Context, st release.Store, vs VersionedStore,
return RetireGenerations(ctx, st, vs, h.leaser.Bucket, t.loc, head, h.lockGen, left, healthy, now)
}
-// leftHistory is the entries of h whose EndedAt is not after now-window,
-// in their order. The switch passes the restore window plus RetireGrace,
-// so an entry TrimHistory drops within the grace is not among them.
+// leftHistory is the entries of h TrimHistory(h, now, window) drops:
+// those whose EndedAt is not after now-window, in their order. The switch
+// passes the same window to both (SnapshotRetention plus RetireGrace).
func leftHistory(h []HeadHistory, now time.Time, window time.Duration) []HeadHistory {
cutoff := now.Add(-window)
var out []HeadHistory
diff --git a/internal/lease/genretire_test.go b/internal/lease/genretire_test.go
index 85f77f7b4..58ed48268 100644
--- a/internal/lease/genretire_test.go
+++ b/internal/lease/genretire_test.go
@@ -68,25 +68,8 @@ func entries(gens ...string) []lease.HeadHistory {
func healthyAlways() error { return nil }
-// plantHead stores head as head.json, as the holder's switch wrote it,
-// without a request: its LastModified is the bucket's clock, a few
-// seconds after retireEpoch, so created_by.at (retireEpoch) is in step.
-func (fx *genFixture) plantHead(t *testing.T, head lease.Head) {
- t.Helper()
- body, err := json.Marshal(head)
- if err != nil {
- t.Fatal(err)
- }
- fx.m.Put(fx.bucket, fx.loc+"/head.json", body)
-}
-
-// retire stores head as head.json and runs RetireGenerations in phase p.
+// retire runs RetireGenerations in phase p.
func (fx *genFixture) retire(p string, head lease.Head, left []lease.HeadHistory, healthy func() error, now time.Time) (lease.RetireStats, error) {
- body, err := json.Marshal(head)
- if err != nil {
- return lease.RetireStats{}, err
- }
- fx.m.Put(fx.bucket, fx.loc+"/head.json", body)
fx.setPhase(p)
defer fx.setPhase("")
return lease.RetireGenerations(ctx, fx.st, fx.vs, fx.bucket, fx.loc, head, head.CreatedBy.LockGeneration, left, healthy, now)
@@ -284,7 +267,7 @@ func TestRetireNeverTouchesNewerGeneration(t *testing.T) {
t.Fatalf("deleted %v", d)
}
for _, r := range fx.requests("retire") {
- if strings.Contains(r, "versions") && !strings.Contains(r, "head.json") {
+ if strings.Contains(r, "versions") {
t.Errorf("listed a generation it may not touch: %s", r)
}
}
@@ -395,14 +378,11 @@ func TestRetireStopsOnUnhealthyLease(t *testing.T) {
}
}
-// retireRequests classifies phase's requests: the version listing of
-// head.json (the clock check), ListDirs (a delimited ListObjectsV2), the
-// other version listings, delete requests, and anything else.
-func (fx *genFixture) retireRequests(phase string) (heads, dirs, lists, deletes int, other []string) {
+// retireRequests classifies phase's requests: ListDirs (a delimited
+// ListObjectsV2), version listings, delete requests, and anything else.
+func (fx *genFixture) retireRequests(phase string) (dirs, lists, deletes int, other []string) {
for _, r := range fx.requests(phase) {
switch {
- case strings.HasPrefix(r, "GET ") && strings.Contains(r, "versions") && strings.Contains(r, "head.json"):
- heads++
case strings.HasPrefix(r, "GET ") && strings.Contains(r, "list-type=2") && strings.Contains(r, "delimiter="):
dirs++
case strings.HasPrefix(r, "GET ") && strings.Contains(r, "versions"):
@@ -413,13 +393,13 @@ func (fx *genFixture) retireRequests(phase string) (heads, dirs, lists, deletes
other = append(other, r)
}
}
- return heads, dirs, lists, deletes, other
+ return dirs, lists, deletes, other
}
-// The request budget: one version listing of head.json (the clock check),
-// one ListDirs, one version listing per candidate (a generation that may
-// go; a kept one is not listed), and one bare DELETE per current object
-// retired. Nothing else, no GET of head.json.
+// The request budget: one ListDirs, one version listing per candidate (a
+// generation that may go; a kept one is not listed), and one bare DELETE
+// per current object retired. Nothing else: no read of head.json, no
+// clock check.
func TestRetireRequestCount(t *testing.T) {
fx := newGenFixture(t)
g := replicagen.Name
@@ -433,17 +413,17 @@ func TestRetireRequestCount(t *testing.T) {
if !slices.Equal(st.Retired, []string{g(1), g(2), g(3)}) {
t.Fatalf("stats %+v", st)
}
- heads, dirs, lists, deletes, other := fx.retireRequests("retire")
- if heads != 1 || dirs != 1 || lists != 3 || deletes != 6 || len(other) != 0 {
- t.Fatalf("%d head listings, %d ListDirs, %d listings, %d deletes, other %v; want 1, 1, 3, 6, none (%v)", heads, dirs, lists, deletes, other, fx.requests("retire"))
+ dirs, lists, deletes, other := fx.retireRequests("retire")
+ if dirs != 1 || lists != 3 || deletes != 6 || len(other) != 0 {
+ t.Fatalf("%d ListDirs, %d listings, %d deletes, other %v; want 1, 3, 6, none (%v)", dirs, lists, deletes, other, fx.requests("retire"))
}
- // Nothing left to retire: the head listing, one ListDirs, nothing more.
+ // Nothing left to retire: one ListDirs and nothing more.
if _, err := fx.retire("again", head, nil, healthyAlways, retireOld); err != nil {
t.Fatal(err)
}
- if heads, dirs, lists, deletes, other := fx.retireRequests("again"); heads != 1 || dirs != 1 || lists != 0 || deletes != 0 || len(other) != 0 {
- t.Fatalf("again: %d head listings, %d ListDirs, %d listings, %d deletes, other %v", heads, dirs, lists, deletes, other)
+ if dirs, lists, deletes, other := fx.retireRequests("again"); dirs != 1 || lists != 0 || deletes != 0 || len(other) != 0 {
+ t.Fatalf("again: %d ListDirs, %d listings, %d deletes, other %v", dirs, lists, deletes, other)
}
}
@@ -482,7 +462,6 @@ func TestRetirePartialFailureFinishedByNextTake(t *testing.T) {
fail.Delete(stuck)
next := retireHead(6, g(5), g(5), g(4))
- fx.plantHead(t, next)
fx.setPhase("next")
st, err = lease.RetireGenerations(ctx, fx.st, fx.vs, fx.bucket, fx.loc, next, 6, nil, healthyAlways, retireOld)
fx.setPhase("")
@@ -527,30 +506,31 @@ func TestRetireRefusesBadInputs(t *testing.T) {
fx.setPhase("")
}
-// The take hands retirement what its switch dropped: a history entry
-// whose ended_at is past the restore window leaves head.json at the
-// switch, and the holder's Retire deletes that generation (here the root
-// layout the migration left), never the predecessor it just copied.
+// The take hands retirement exactly what its switch's trim dropped. The
+// trim is the restore window plus RetireGrace (an hour): an entry ended 7
+// days 2 hours ago leaves head.json and its generation (here the root
+// layout the migration left) is deleted; one ended 7 days 30 minutes ago
+// stays in history, so it is kept, not an abandoned candidate, even though
+// its objects (written weeks ago on the bucket's clock) are long past a
+// day old. The predecessor the take copied is never touched.
func TestSwitchHandsRetirementTheLeftHistory(t *testing.T) {
haBox(t)
- // The bucket's clock is the box's, so the switch's head.json passes
- // the clock check.
- fx := newGenFixture(t, func(m *leasetest.VersionedBucket) { m.SetClock(time.Now()) })
+ fx := newGenFixture(t)
seedGen, _ := fx.seed(t, time.Minute, 3)
rootLTX := fx.loc + "/0000/0000000000000001-0000000000000001.ltx"
fx.m.Put(fx.bucket, rootLTX, []byte("a root file"))
- // g-0 ended half an hour past the restore window: the switch drops it
- // from head.json, but inside RetireGrace it is not handed over as
- // left, and its objects, written just now, keep it as abandoned.
graceKey := rkey(fx, replicagen.Name(0), 0, 1, 1)
fx.m.Put(fx.bucket, graceKey, []byte("inside the grace"))
+ if vs, err := fx.m.ListVersions(ctx, fx.bucket, graceKey); err != nil || len(vs) != 1 || time.Since(vs[0].LastModified) < 7*24*time.Hour {
+ t.Fatalf("the grace generation's object: %v %v, want one over a week old", vs, err)
+ }
h, etag, found := fx.head(t)
if !found {
t.Fatal("no head after the seed")
}
h.History = []lease.HeadHistory{
{Generation: replicagen.Name(0), EndedAt: time.Now().Add(-lease.SnapshotRetention - 30*time.Minute)},
- {Generation: replicagen.Root, EndedAt: time.Now().Add(-8 * 24 * time.Hour)},
+ {Generation: replicagen.Root, EndedAt: time.Now().Add(-lease.SnapshotRetention - 2*time.Hour)},
}
if _, err := lease.PutHead(ctx, fx.st, fx.loc, h, etag); err != nil {
t.Fatal(err)
@@ -572,8 +552,12 @@ func TestSwitchHandsRetirementTheLeftHistory(t *testing.T) {
t.Fatal(err)
}
head, _, _ := fx.head(t)
- if len(head.History) != 1 || head.History[0].Generation != seedGen {
- t.Fatalf("head history %+v, want only %s", head.History, seedGen)
+ var names []string
+ for _, e := range head.History {
+ names = append(names, e.Generation)
+ }
+ if !slices.Equal(names, []string{seedGen, replicagen.Name(0)}) {
+ t.Fatalf("head history %v, want %s and the grace entry %s", names, seedGen, replicagen.Name(0))
}
fx.setPhase("retire")
st, err := held.Retire(ctx, fx.st, fx.vs, held.Err, time.Now())
@@ -581,13 +565,18 @@ func TestSwitchHandsRetirementTheLeftHistory(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- if !slices.Equal(st.Retired, []string{replicagen.Root}) || st.Objects != 1 || !slices.Equal(st.Young, []string{replicagen.Name(0)}) {
- t.Fatalf("stats %+v, want the root's one LTX file, %s kept young", st, replicagen.Name(0))
+ if !slices.Equal(st.Retired, []string{replicagen.Root}) || st.Objects != 1 || len(st.Young) != 0 {
+ t.Fatalf("stats %+v, want only the root's one LTX file", st)
}
- fx.requireKept(t, graceKey)
if _, ok := fx.m.Current(fx.bucket, rootLTX); ok {
t.Fatal("the root LTX file is still current")
}
+ fx.requireKept(t, graceKey)
+ for _, r := range fx.requests("retire") {
+ if strings.Contains(r, replicagen.Name(0)) {
+ t.Errorf("the grace generation was listed or deleted: %s", r)
+ }
+ }
if got := fx.current(t, replicagen.Prefix(fx.loc, seedGen)); len(got) == 0 {
t.Fatalf("the predecessor %s was retired", seedGen)
}
@@ -596,49 +585,6 @@ func TestSwitchHandsRetirementTheLeftHistory(t *testing.T) {
}
}
-// The clock check: head.json's LastModified (the bucket's time at the
-// switch) against its created_by.at (the box's). More than MaxClockSkew
-// apart either way, or no head.json, and the pass stops after that one
-// listing: no ListDirs, nothing deleted. Inside it, the pass runs.
-func TestRetireRefusesClockSkew(t *testing.T) {
- fx := newGenFixture(t)
- g := replicagen.Name
- plant(fx, g(1))
- for name, off := range map[string]time.Duration{"ahead": 10 * time.Minute, "behind": -10 * time.Minute} {
- head := retireHead(4, "")
- head.CreatedBy.At = retireEpoch.Add(off)
- st, err := fx.retire(name, head, entries(g(1)), healthyAlways, retireOld)
- if !errors.Is(err, lease.ErrClockSkew) {
- t.Fatalf("%s: err %v, want ErrClockSkew", name, err)
- }
- if st.Objects != 0 || len(st.Retired) != 0 {
- t.Fatalf("%s: stats %+v", name, st)
- }
- if heads, dirs, lists, deletes, other := fx.retireRequests(name); heads != 1 || dirs+lists+deletes != 0 || len(other) != 0 {
- t.Fatalf("%s: requests %v, want the head listing only", name, fx.requests(name))
- }
- }
- fx.requireKept(t, rkey(fx, g(1), 0, 1, 1))
-
- // No head.json at all: refused, nothing listed further.
- fx.m.BareDelete(fx.bucket, fx.loc+"/head.json")
- fx.setPhase("absent")
- _, err := lease.RetireGenerations(ctx, fx.st, fx.vs, fx.bucket, fx.loc, retireHead(4, ""), 4, entries(g(1)), healthyAlways, retireOld)
- fx.setPhase("")
- if err == nil {
- t.Fatal("no head.json: no error")
- }
- if heads, dirs, lists, deletes, _ := fx.retireRequests("absent"); heads != 1 || dirs+lists+deletes != 0 {
- t.Fatalf("absent: requests %v", fx.requests("absent"))
- }
-
- head := retireHead(4, "")
- head.CreatedBy.At = retireEpoch.Add(4 * time.Minute)
- if st, err := fx.retire("in step", head, entries(g(1)), healthyAlways, retireOld); err != nil || !slices.Equal(st.Retired, []string{g(1)}) {
- t.Fatalf("within the skew: %+v %v", st, err)
- }
-}
-
// The stale-head invariant: a successor (lock generation 7) switches
// head.json mid-pass, and this holder's lease check has not noticed. The
// pass goes on with its own head, and deletes nothing the successor's
@@ -698,6 +644,9 @@ func TestRetireFirstWakeHeadWithRootFiles(t *testing.T) {
fx.m.Put(fx.bucket, root, []byte("left by an old binary"))
fx.m.Put(fx.bucket, fx.loc+"/lock.json", []byte("{}"))
head := retireHead(1, "")
+ if _, err := lease.PutHead(ctx, fx.st, fx.loc, head, ""); err != nil {
+ t.Fatal(err)
+ }
st, err := fx.retire("young", head, nil, healthyAlways, retireYoung)
if err != nil || len(st.Retired) != 0 || !slices.Equal(st.Young, []string{replicagen.Root}) {
t.Fatalf("young: %+v %v, want the root kept young", st, err)
diff --git a/internal/lease/gentake.go b/internal/lease/gentake.go
index d90fedb87..54425ed2f 100644
--- a/internal/lease/gentake.go
+++ b/internal/lease/gentake.go
@@ -303,7 +303,7 @@ func (t *Take) Reader() litestream.ReplicaClient { return t.reader }
//
// Switch: with the lease healthy, write head.json for g-N
// (predecessor G, history G's entry prepended with ended_at now, trimmed
-// to the restore window), If-Match the ETag step 1 read (create-only when
+// to the restore window plus RetireGrace), If-Match the ETag step 1 read (create-only when
// there was none). A conflict is ErrHeadMoved and deletes nothing. After
// a nil return the handle's Replicate writes only to g-N. A first wake's
// take is switched already; a second Switch after success is nil.
@@ -339,12 +339,11 @@ func (t *Take) Switch(ctx context.Context) error {
history = append(history, HeadHistory{Generation: replicagen.Root, EndedAt: now})
}
head := Head{V: HeadVersion, Generation: t.Generation, CreatedBy: created, StartTXID: t.StartTXID,
- Predecessor: t.Predecessor, History: TrimHistory(history, now, SnapshotRetention)}
+ Predecessor: t.Predecessor, History: TrimHistory(history, now, SnapshotRetention+RetireGrace)}
_, err := PutHead(ctx, t.st, t.loc, head, t.etag)
switch {
case err == nil:
- // What the trim dropped an hour or more ago is retirement's to
- // delete (§8); the rest waits for a later take (RetireGrace).
+ // Exactly what the trim dropped is retirement's to delete (§8).
t.setSwitched(head, leftHistory(history, now, SnapshotRetention+RetireGrace))
return nil
case errors.Is(err, release.ErrCASConflict):
diff --git a/internal/lease/leasetest/bucket.go b/internal/lease/leasetest/bucket.go
index c5fa2005a..cc1f4a824 100644
--- a/internal/lease/leasetest/bucket.go
+++ b/internal/lease/leasetest/bucket.go
@@ -150,14 +150,6 @@ func (f *VersionedBucket) PutMultipart(bucket, key string, body []byte) string {
return f.push(bucket, key, version{body: append([]byte(nil), body...), etag: md5hex(body) + "-2"})
}
-// SetClock sets the bucket's clock: the next write is LastModified t plus
-// a second (every write adds one). The clock starts at 2026-10-05.
-func (f *VersionedBucket) SetClock(t time.Time) {
- f.mu.Lock()
- defer f.mu.Unlock()
- f.clock = t
-}
-
func (f *VersionedBucket) BareDelete(bucket, key string) string {
f.mu.Lock()
defer f.mu.Unlock()