carlos / platform Public

lease, activator: retirement checks the clock and waits an hour

Task 9 review round 1 fixes:
- Before a pass, one version listing of head.json compares the bucket's
  LastModified with created_by.at; more than 5 minutes apart refuses
  with ErrClockSkew (logged ha_generation_retire_failed
  reason=clock_skew).
- The switch hands retirement only entries ended over the restore
  window plus an hour (RetireGrace); the rest wait for a later take.
- RetireGenerations states the stale-head invariant; tests pin a
  successor switching mid-pass, a first-wake head over root files, and
  claim-shaped names.
- haSvc.abandon joins background retirement; the wake is shown not to
  wait for a held retirement, and a failed replicator start makes no
  retirement request.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 47a5614cda652c016618035a7b4ddb8f008aa54e parent 0b8e00d
7 files changed, +474 −29
  • internal/activator/hagenerations_test.go +169 −0
  • internal/activator/harelease_test.go +6 −1
  • internal/activator/hawake.go +10 −3
  • internal/lease/genretire.go +76 −3
  • internal/lease/genretire_test.go +202 −20
  • internal/lease/gentake.go +3 −2
  • internal/lease/leasetest/bucket.go +8 −0
diff --git a/internal/activator/hagenerations_test.go b/internal/activator/hagenerations_test.go
index b385aec0c..353d236cd 100644
--- a/internal/activator/hagenerations_test.go
+++ b/internal/activator/hagenerations_test.go
@@ -910,3 +910,172 @@ func TestHAWakeRetirementFailureNeverFailsTheWake(t *testing.T) {
}
s.stopForTest(e)
}
+
+// listDirsBlocks holds ListDirs of one prefix until unblock closes,
+// closing entered when the first such call arrives.
+type listDirsBlocks struct {
+ release.Store
+ prefix string
+ entered, unblock chan struct{}
+ once sync.Once
+}
+
+func (l *listDirsBlocks) ListDirs(ctx context.Context, prefix string) ([]string, error) {
+ if prefix == l.prefix {
+ l.once.Do(func() { close(l.entered) })
+ select {
+ case <-l.unblock:
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+ }
+ return l.Store.ListDirs(ctx, prefix)
+}
+
+// The wake never waits for retirement: retirement's listing is held, and
+// the wake still completes and serves while it is held; retirement
+// finishes once the listing is let go.
+func TestHAWakeDoesNotWaitForRetirement(t *testing.T) {
+ t.Setenv("CARLOS_HA_GENERATIONS", "on")
+ s := haService(t, "shop.example.com")
+ blk := &listDirsBlocks{Store: s.b.FilesStore, prefix: s.loc() + "/", entered: make(chan struct{}), unblock: make(chan struct{})}
+ s.b.FilesStore = blk
+ var unblockOnce sync.Once
+ unblock := func() { unblockOnce.Do(func() { close(blk.unblock) }) }
+ t.Cleanup(unblock) // before abandon joins the retirement
+
+ type result struct {
+ e *actEntry
+ err error
+ }
+ woke := make(chan result, 1)
+ go func() {
+ e, err := s.wakeForTest(context.Background())
+ woke <- result{e, err}
+ }()
+ select {
+ case <-blk.entered:
+ case <-time.After(30 * time.Second):
+ t.Fatal("retirement never reached its listing")
+ }
+ var r result
+ select {
+ case r = <-woke:
+ case <-time.After(30 * time.Second):
+ t.Fatal("the wake waited on the held retirement")
+ }
+ if r.err != nil || r.e == nil || r.e.state != actAwake {
+ t.Fatalf("wake: %+v %v, want awake while retirement is held", r.e, r.err)
+ }
+ retired := make(chan struct{})
+ go func() { s.b.retiring.Wait(); close(retired) }()
+ select {
+ case <-retired:
+ t.Fatal("retirement finished while its listing was held")
+ case <-time.After(50 * time.Millisecond):
+ }
+ unblock()
+ select {
+ case <-retired:
+ case <-time.After(30 * time.Second):
+ t.Fatal("retirement did not finish once let go")
+ }
+ s.stopForTest(r.e)
+}
+
+// Retirement starts only after replication has started: a wake whose
+// replicator fails to open (litestream cannot clear a temporary file in
+// its state directory) makes no retirement request at all, neither the
+// head.json listing nor the ListDirs, and starts no background pass.
+func TestHAWakeReplicationFailureStartsNoRetirement(t *testing.T) {
+ if os.Geteuid() == 0 {
+ t.Skip("root removes a file from a read-only directory")
+ }
+ t.Setenv("CARLOS_HA_GENERATIONS", "on")
+ s, e := haServiceEntry(t, "shop.example.com")
+ s.b.retiring.Wait()
+ s.stopForTest(e)
+
+ db := s.b.pathsFor(s.rt).dbPath
+ locked := filepath.Join(filepath.Dir(db), ".activator-"+filepath.Base(db)+"-litestream", "locked")
+ if err := os.MkdirAll(locked, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(locked, "stuck.tmp"), nil, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chmod(locked, 0o500); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.Chmod(locked, 0o700) })
+
+ before := len(s.fx.Requests())
+ e, err := s.wakeForTest(context.Background())
+ if err == nil {
+ s.stopForTest(e)
+ t.Fatal("the wake served with a replicator that cannot open")
+ }
+ if !strings.Contains(err.Error(), "cannot remove tmp files") {
+ t.Fatalf("wake: %v, want the replicator's open to fail", err)
+ }
+ s.b.retiring.Wait()
+ for _, r := range s.fx.Requests()[before:] {
+ if r == "LISTV "+s.headKey() || r == "LIST "+s.loc()+"/" {
+ t.Errorf("a retirement request after a failed replicator start: %s", r)
+ }
+ }
+}
+
+// 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/harelease_test.go b/internal/activator/harelease_test.go
index 3ff0cd22f..36e12fab4 100644
--- a/internal/activator/harelease_test.go
+++ b/internal/activator/harelease_test.go
@@ -323,7 +323,8 @@ func (s *haSvc) peer(t *testing.T) *haSvc {
// F5): every background job the agent owns is stopped and joined (the
// service lifetime's work, each entry's files publisher, and each
// replica's renewer and replication, by lease's Abandon: no final sync, no
-// marker, no delete), and nothing else changes. The fixture's unit, its
+// marker, no delete; and each generation retirement, joined), and nothing
+// else changes. The fixture's unit, its
// serving socket and the lock survive, as they outlive a crash.
// Idempotent.
func (s *haSvc) abandon() {
@@ -358,6 +359,10 @@ func (s *haSvc) abandon() {
cancel()
}
}
+ // A generation retirement still running (startRetirement) is the
+ // agent's own background work too: joined before the test goes on, and
+ // so before its cleanup restores the environment or closes the bucket.
+ s.b.retiring.Wait()
}
func (s *haSvc) lockKey() string { return lockKeyOf(s.b, s.rt) }
diff --git a/internal/activator/hawake.go b/internal/activator/hawake.go
index 655e3b67c..2a8446ca5 100644
--- a/internal/activator/hawake.go
+++ b/internal/activator/hawake.go
@@ -828,8 +828,9 @@ 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 and never fails the
-// wake: the next take retries what is left.
+// 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.
func (b *ExecBackend) startRetirement(host string, held *lease.Held, rep *lease.Replicator) {
if held == nil || rep == nil || held.GenName() == "" {
return
@@ -841,7 +842,13 @@ func (b *ExecBackend) startRetirement(host string, held *lease.Held, rep *lease.
defer cancel()
stats, err := b.retire(ctx, held, rep)
if err != nil {
- log.Printf("ha_generation_retire_failed host=%s retired=%v objects=%d: %v", host, stats.Retired, stats.Objects, err)
+ 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)
return
}
if len(stats.Retired) > 0 || len(stats.Young) > 0 {
diff --git a/internal/lease/genretire.go b/internal/lease/genretire.go
index 973faeb9b..c75af1a8d 100644
--- a/internal/lease/genretire.go
+++ b/internal/lease/genretire.go
@@ -26,6 +26,25 @@ 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.
+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,
@@ -56,7 +75,16 @@ 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.
//
-// One ListDirs of loc/; then, for each generation that may go, one
+// 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
// version listing (one per level directory for the root) and one bare
// DELETE per current key:
//
@@ -73,6 +101,18 @@ type retireCandidate struct {
//
// A failed listing or delete leaves that generation for the next take
// and the pass goes on; the error joins every failure.
+//
+// Safety with a stale head (the invariant the pass rests on): head is
+// what this holder's switch wrote, and the pass may run on after a newer
+// holder (lock generation above mine) has switched, before healthy
+// notices the lost lease. That is safe. Every later head names the
+// generation its take created (above mine, so never a candidate) and a
+// history that is this head's own generation and history, trimmed further
+// by time: all in keep. An abandoned g-<M> below mine that this head does
+// not name was never current after it, so no later head names it either.
+// 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.
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 == "" {
@@ -90,6 +130,9 @@ 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
@@ -227,6 +270,35 @@ 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 {
@@ -257,8 +329,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 TrimHistory drops: those whose EndedAt
-// is not after now-window, in their order.
+// 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.
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 dc81ba7f4..85f77f7b4 100644
--- a/internal/lease/genretire_test.go
+++ b/internal/lease/genretire_test.go
@@ -1,6 +1,7 @@
package lease_test
import (
+ "encoding/json"
"errors"
"fmt"
"net/http"
@@ -50,7 +51,7 @@ func plant(fx *genFixture, gens ...string) {
// retireHead is the head.json of the holder of lock generation mine, with
// history hist (newest first).
func retireHead(mine int64, pred string, hist ...string) lease.Head {
- h := lease.Head{V: 1, Generation: replicagen.Name(mine), Predecessor: pred, CreatedBy: lease.HeadCreator{LockGeneration: mine}}
+ h := lease.Head{V: 1, Generation: replicagen.Name(mine), Predecessor: pred, CreatedBy: lease.HeadCreator{LockGeneration: mine, At: retireEpoch}}
for _, g := range hist {
h.History = append(h.History, lease.HeadHistory{Generation: g, EndedAt: retireEpoch})
}
@@ -67,8 +68,25 @@ func entries(gens ...string) []lease.HeadHistory {
func healthyAlways() error { return nil }
-// retire runs RetireGenerations in phase p.
+// 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.
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)
@@ -266,7 +284,7 @@ func TestRetireNeverTouchesNewerGeneration(t *testing.T) {
t.Fatalf("deleted %v", d)
}
for _, r := range fx.requests("retire") {
- if strings.Contains(r, "versions") {
+ if strings.Contains(r, "versions") && !strings.Contains(r, "head.json") {
t.Errorf("listed a generation it may not touch: %s", r)
}
}
@@ -377,11 +395,14 @@ func TestRetireStopsOnUnhealthyLease(t *testing.T) {
}
}
-// 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) {
+// 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) {
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"):
@@ -392,12 +413,13 @@ func (fx *genFixture) retireRequests(phase string) (dirs, lists, deletes int, ot
other = append(other, r)
}
}
- return dirs, lists, deletes, other
+ return heads, dirs, lists, deletes, other
}
-// 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 GET of head.json.
+// 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.
func TestRetireRequestCount(t *testing.T) {
fx := newGenFixture(t)
g := replicagen.Name
@@ -411,17 +433,17 @@ func TestRetireRequestCount(t *testing.T) {
if !slices.Equal(st.Retired, []string{g(1), g(2), g(3)}) {
t.Fatalf("stats %+v", st)
}
- 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"))
+ 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"))
}
- // Nothing left to retire: one ListDirs and nothing more.
+ // Nothing left to retire: the head listing, one ListDirs, nothing more.
if _, err := fx.retire("again", head, nil, healthyAlways, retireOld); err != nil {
t.Fatal(err)
}
- 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)
+ 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)
}
}
@@ -460,6 +482,7 @@ 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("")
@@ -510,15 +533,25 @@ func TestRetireRefusesBadInputs(t *testing.T) {
// layout the migration left), never the predecessor it just copied.
func TestSwitchHandsRetirementTheLeftHistory(t *testing.T) {
haBox(t)
- fx := newGenFixture(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()) })
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"))
h, etag, found := fx.head(t)
if !found {
t.Fatal("no head after the seed")
}
- h.History = []lease.HeadHistory{{Generation: replicagen.Root, EndedAt: time.Now().Add(-8 * 24 * time.Hour)}}
+ 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)},
+ }
if _, err := lease.PutHead(ctx, fx.st, fx.loc, h, etag); err != nil {
t.Fatal(err)
}
@@ -548,9 +581,10 @@ func TestSwitchHandsRetirementTheLeftHistory(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- if !slices.Equal(st.Retired, []string{replicagen.Root}) || st.Objects != 1 {
- t.Fatalf("stats %+v, want the root's one LTX file", st)
+ 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))
}
+ fx.requireKept(t, graceKey)
if _, ok := fx.m.Current(fx.bucket, rootLTX); ok {
t.Fatal("the root LTX file is still current")
}
@@ -561,3 +595,151 @@ func TestSwitchHandsRetirementTheLeftHistory(t *testing.T) {
t.Fatal(err)
}
}
+
+// 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
+// head names: its own generation (copied before the pass began, so in
+// ListDirs) and its history, which is this head's generation and history.
+func TestRetireSuccessorSwitchMidPass(t *testing.T) {
+ var once sync.Once
+ fx := newGenFixture(t)
+ g := replicagen.Name
+ plant(fx, g(1), g(2), g(3), g(4), g(5), g(7))
+ successor := retireHead(7, g(5), g(5), g(4))
+ body, err := json.Marshal(successor)
+ if err != nil {
+ t.Fatal(err)
+ }
+ fx.setHook(func(r *http.Request, _ []string) func(int) {
+ if r.Method != http.MethodDelete {
+ return nil
+ }
+ return func(int) { once.Do(func() { fx.m.Put(fx.bucket, fx.loc+"/head.json", body) }) }
+ })
+ mine := retireHead(5, g(4), g(4))
+ st, err := fx.retire("retire", mine, entries(g(1)), healthyAlways, retireOld)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Equal(st.Retired, []string{g(1), g(2), g(3)}) {
+ t.Fatalf("stats %+v, want g-1..g-3", st)
+ }
+ stored, _, _ := fx.head(t)
+ if stored.Generation != g(7) {
+ t.Fatalf("head %+v: the successor never switched mid-pass", stored)
+ }
+ named := []string{stored.Generation, stored.Predecessor}
+ for _, e := range stored.History {
+ named = append(named, e.Generation)
+ }
+ for _, n := range named {
+ if got := fx.current(t, replicagen.Prefix(fx.loc, n)); len(got) != 2 {
+ t.Errorf("%s, named by the successor's head, holds %v", n, got)
+ }
+ }
+ for _, k := range fx.deletes("retire") {
+ if !strings.HasPrefix(k, replicagen.Prefix(fx.loc, g(1))) && !strings.HasPrefix(k, replicagen.Prefix(fx.loc, g(2))) && !strings.HasPrefix(k, replicagen.Prefix(fx.loc, g(3))) {
+ t.Errorf("deleted %s", k)
+ }
+ }
+}
+
+// A first wake's head.json (no predecessor, no history) with root LTX
+// files present, which only a fenced old binary could have left after
+// PrefixEmpty: @root is not in history, so the root is abandoned. Its LTX
+// files stay while any is under a day old and go once all are older.
+func TestRetireFirstWakeHeadWithRootFiles(t *testing.T) {
+ fx := newGenFixture(t)
+ root := fx.loc + "/0000/0000000000000001-0000000000000001.ltx"
+ 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, "")
+ 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)
+ }
+ fx.requireKept(t, root)
+ st, err = fx.retire("old", head, nil, healthyAlways, retireOld)
+ if err != nil || !slices.Equal(st.Retired, []string{replicagen.Root}) || st.Objects != 1 {
+ t.Fatalf("old: %+v %v, want the root's LTX file retired", st, err)
+ }
+ fx.requireGone(t, root)
+ fx.requireKept(t, fx.loc+"/lock.json", fx.loc+"/head.json")
+}
+
+// Claim generations and retirement (the invariant): a claim writes
+// g-<gen> under the same location, and ValidClaim refuses every gen whose
+// g-<gen> is a head.json generation name (twenty digits), so no claim can
+// own a prefix retirement may delete. A claim's real name (32 hex
+// characters) fails Valid and is never listed, at any age. A g-<20
+// digits> below mine that no head names is therefore HA's own abandoned
+// generation, and goes once a day old.
+func TestRetireClaimGenerationsAreNeverCandidates(t *testing.T) {
+ fx := newGenFixture(t)
+ claim := replicagen.ClaimName("0123456789abcdef0123456789abcdef")
+ claimKey := fx.loc + "/" + claim + "/0000/0000000000000001-0000000000000001.ltx"
+ fx.m.Put(fx.bucket, claimKey, []byte("a claim's"))
+ twenty := "00000000000000000002"
+ if replicagen.ValidClaim(twenty) {
+ t.Fatalf("ValidClaim(%q): a claim could own g-%s", twenty, twenty)
+ }
+ stray := fx.loc + "/" + replicagen.ClaimName(twenty) + "/0000/0000000000000001-0000000000000001.ltx"
+ fx.m.Put(fx.bucket, stray, []byte("abandoned"))
+ st, err := fx.retire("retire", retireHead(5, ""), nil, healthyAlways, retireOld)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Equal(st.Retired, []string{replicagen.Name(2)}) {
+ t.Fatalf("stats %+v, want the twenty-digit prefix retired", st)
+ }
+ fx.requireKept(t, claimKey)
+ for _, r := range fx.requests("retire") {
+ if strings.Contains(r, claim) {
+ t.Errorf("a request for the claim's prefix: %s", r)
+ }
+ }
+}
diff --git a/internal/lease/gentake.go b/internal/lease/gentake.go
index fefdec8c7..d90fedb87 100644
--- a/internal/lease/gentake.go
+++ b/internal/lease/gentake.go
@@ -343,8 +343,9 @@ func (t *Take) Switch(ctx context.Context) error {
_, err := PutHead(ctx, t.st, t.loc, head, t.etag)
switch {
case err == nil:
- // What the trim dropped is retirement's to delete (§8).
- t.setSwitched(head, leftHistory(history, now, SnapshotRetention))
+ // What the trim dropped an hour or more ago is retirement's to
+ // delete (§8); the rest waits for a later take (RetireGrace).
+ t.setSwitched(head, leftHistory(history, now, SnapshotRetention+RetireGrace))
return nil
case errors.Is(err, release.ErrCASConflict):
t.setState(takeMoved)
diff --git a/internal/lease/leasetest/bucket.go b/internal/lease/leasetest/bucket.go
index cc1f4a824..c5fa2005a 100644
--- a/internal/lease/leasetest/bucket.go
+++ b/internal/lease/leasetest/bucket.go
@@ -150,6 +150,14 @@ 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()