carlos / platform Public

lease: generations locks never replicate to the root; head_missing

Coordinator rulings on the Task 4 concerns.

A Held whose lock is a storage-generations lock (it wrote
carlos_generation, by the switch or by stickiness) builds no replica
store unless its take has switched: Replicate and Checkpoint refuse with
ErrGenerationNotSwitched before anything is built, so its releases stay
settled. The Task 1 marker tests replicate through SwitchedTakeForTest.

PlanStart with no head.json and no root LTX file: without g-* subtrees
under the location it is an Empty start from the root (a replica that
never uploaded boots fresh, as today); with any g-* entry, current or
not, it refuses with the new reason head_missing.

Switch documents that the caller must not release the handle while it
runs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 135e7d6d561f55f5893b25b1b6b5d0e685cba09a parent c536534
6 files changed, +207 −22
  • internal/lease/export_test.go +10 −0
  • internal/lease/generations_lock_test.go +2 −0
  • internal/lease/genstart.go +28 −2
  • internal/lease/genstart_test.go +60 −0
  • internal/lease/gentake.go +32 −18
  • internal/lease/gentake_test.go +75 −2
diff --git a/internal/lease/export_test.go b/internal/lease/export_test.go
index 0a6e699cf..ff8c1f5d2 100644
--- a/internal/lease/export_test.go
+++ b/internal/lease/export_test.go
@@ -139,3 +139,13 @@ func EnforceL0RetentionForTest(r *Replicator) error {
// RetentionEnabledForTest reports whether r's store deletes remotely.
func RetentionEnabledForTest(r *Replicator) bool { return r.db.RetentionEnabled }
+
+// SwitchedTakeForTest gives h a take of its lock's generation that has
+// switched, without any storage request: for tests of the lock and its
+// markers that replicate a generations Held through the local-replica
+// seam (SetReplicaClientForTest).
+func SwitchedTakeForTest(h *Held) {
+ h.mu.Lock()
+ h.take = &Take{Generation: h.rn.genName, h: h, loc: h.leaser.Path, state: takeSwitched}
+ h.mu.Unlock()
+}
diff --git a/internal/lease/generations_lock_test.go b/internal/lease/generations_lock_test.go
index 0e8b5bb80..bf83e116f 100644
--- a/internal/lease/generations_lock_test.go
+++ b/internal/lease/generations_lock_test.go
@@ -233,6 +233,7 @@ func TestGenerationsReleaseUsesGenMarker(t *testing.T) {
"clean release": {func(t *testing.T, fx *leasetest.LockFixture, p string) int64 {
h := genHeld(t, fx, p, lease.LeaseTTL, genOn)
lease.SetReplicaClientForTest(h, lsfile.NewReplicaClient(t.TempDir()))
+ lease.SwitchedTakeForTest(h) // a generations lock replicates only after its switch
r, err := h.Replicate(ctx, tempDB(t), 0)
if err != nil {
t.Fatal(err)
@@ -249,6 +250,7 @@ func TestGenerationsReleaseUsesGenMarker(t *testing.T) {
"close": {func(t *testing.T, fx *leasetest.LockFixture, p string) int64 {
h := genHeld(t, fx, p, lease.LeaseTTL, genOn)
lease.SetReplicaClientForTest(h, lsfile.NewReplicaClient(t.TempDir()))
+ lease.SwitchedTakeForTest(h) // a generations lock replicates only after its switch
r, err := h.Replicate(ctx, tempDB(t), 0)
if err != nil {
t.Fatal(err)
diff --git a/internal/lease/genstart.go b/internal/lease/genstart.go
index e012af2cf..bb9974eda 100644
--- a/internal/lease/genstart.go
+++ b/internal/lease/genstart.go
@@ -39,6 +39,7 @@ const (
RefuseCleanMarkerAboveL0 = "clean_marker_above_l0" // G's clean marker records a TXID above T
RefuseEmptyPlanWithData = "empty_plan_with_data" // no plan files while G holds LTX files
RefuseFileOver5GiB = "file_over_5gib" // a planned file exceeds the single-part copy limit
+ RefuseHeadMissing = "head_missing" // no head.json and no root LTX file, but g-* subtrees under the location
)
// StartRefusal is a take that must not start a generation from G: the
@@ -62,8 +63,9 @@ type PlannedFile struct {
}
// StartPlan is what a new generation starts from: G (From), the TXID the
-// copy ends at (T), and the files to copy in restore order. Empty is an
-// empty first generation: nothing to copy, T is 0.
+// copy ends at (T), and the files to copy in restore order. Empty is a
+// start with nothing to copy, T 0: an empty first generation, or (no
+// head.json) a root that never uploaded and holds no g-* subtree.
type StartPlan struct {
From string
T uint64
@@ -94,7 +96,18 @@ func PlanStart(ctx context.Context, vs VersionedStore, bucket, loc string, head
return StartPlan{}, fmt.Errorf("lease: plan start: list %s: %w", prefix, err)
}
files := map[ltxPos]ObjectVersion{}
+ // subtrees: with no head the listing is the whole location, and any
+ // entry under a g-* directory (current or not) means generations were
+ // written here once.
+ subtrees := false
for _, v := range listed {
+ if !headFound {
+ if rel, ok := strings.CutPrefix(v.Key, prefix); ok {
+ if dir, _, ok := strings.Cut(rel, "/"); ok && strings.HasPrefix(dir, "g-") {
+ subtrees = true
+ }
+ }
+ }
if !v.IsLatest || v.DeleteMarker {
continue
}
@@ -110,6 +123,19 @@ func PlanStart(ctx context.Context, vs VersionedStore, bucket, loc string, head
}
}
if T == 0 {
+ if len(files) == 0 && !headFound {
+ // No head.json and no root LTX file. Without g-* subtrees this
+ // is a replica that never uploaded: a fresh start, as an empty
+ // replica boots fresh today. With them, head.json is missing
+ // from a generations host: never guess which one is current.
+ if subtrees {
+ return StartPlan{}, refuse(RefuseHeadMissing, "%s has no head.json and no root LTX file, but generation subtrees", loc)
+ }
+ if cleanTXID > 0 {
+ return StartPlan{}, refuse(RefuseCleanMarkerAboveL0, "%s is empty but its clean marker records TXID %d", from, cleanTXID)
+ }
+ return StartPlan{From: from, Empty: true}, nil
+ }
if len(files) == 0 && headFound && head.StartTXID == 0 && head.Predecessor == "" {
if cleanTXID > 0 {
return StartPlan{}, refuse(RefuseCleanMarkerAboveL0, "%s is empty but its clean marker records TXID %d", from, cleanTXID)
diff --git a/internal/lease/genstart_test.go b/internal/lease/genstart_test.go
index 3066394da..c3fab4421 100644
--- a/internal/lease/genstart_test.go
+++ b/internal/lease/genstart_test.go
@@ -556,3 +556,63 @@ func TestCopyStartRefusesABadDestination(t *testing.T) {
t.Fatalf("%d copies", copies)
}
}
+
+// No head.json and no root LTX file, with no g-* subtree: a replica that
+// never uploaded. The start is Empty from the root (a fresh boot, as an
+// empty replica boots fresh today), unless a clean marker records a TXID.
+func TestPlanStartHeadAbsentEmptyRootStartsFresh(t *testing.T) {
+ m := newGenBucket()
+ for _, k := range []string{"lock.json", "files/0/manifest.json", "0000/notltx.txt", "generations/x"} {
+ m.Put(gsBucket, gsLoc+"/"+k, []byte("x"))
+ }
+ cs := newCounting(m)
+ ctx := context.Background()
+ p, err := lease.PlanStart(ctx, cs, gsBucket, gsLoc, lease.Head{}, false, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !p.Empty || p.From != replicagen.Root || p.T != 0 || len(p.Files) != 0 {
+ t.Fatalf("plan = %+v, want an empty start from the root", p)
+ }
+ if lists, copies, other := cs.snapshot(); lists != 1 || copies != 0 || other != 0 {
+ t.Fatalf("requests: %d lists, %d copies, %d other; want one list", lists, copies, other)
+ }
+ _, err = lease.PlanStart(ctx, m, gsBucket, gsLoc, lease.Head{}, false, 9)
+ wantRefusal(t, err, "clean_marker_above_l0")
+ // A root with no L0 but other LTX files is not empty: refused as before.
+ putLTX(m, replicagen.Root, ltxSpec{9, 1, 5})
+ _, err = lease.PlanStart(ctx, m, gsBucket, gsLoc, lease.Head{}, false, 0)
+ wantRefusal(t, err, "no_l0")
+}
+
+// No head.json and no root LTX file, but a g-* subtree under the location
+// (current objects, or only old versions or delete markers): head.json is
+// missing from a generations host. Refused, nothing copied.
+func TestPlanStartRefusesHeadMissing(t *testing.T) {
+ for name, seed := range map[string]func(m *leasetest.VersionedBucket){
+ "a current generation": func(m *leasetest.VersionedBucket) {
+ putLTX(m, gsFrom, ltxSpec{9, 1, 30}, ltxSpec{0, 31, 31})
+ },
+ "a deleted generation": func(m *leasetest.VersionedBucket) {
+ putLTX(m, gsFrom, ltxSpec{0, 1, 1})
+ m.BareDelete(gsBucket, ltxKey(gsFrom, 0, 1, 1))
+ },
+ "a stray object in a g- directory": func(m *leasetest.VersionedBucket) {
+ m.Put(gsBucket, gsLoc+"/g-x/anything", []byte("x"))
+ },
+ } {
+ t.Run(name, func(t *testing.T) {
+ m := newGenBucket()
+ m.Put(gsBucket, gsLoc+"/lock.json", []byte("{}"))
+ seed(m)
+ cs := newCounting(m)
+ _, err := lease.PlanStart(context.Background(), cs, gsBucket, gsLoc, lease.Head{}, false, 0)
+ wantRefusal(t, err, "head_missing")
+ if _, copies, _ := cs.snapshot(); copies != 0 {
+ t.Fatalf("%d copies on a refusal", copies)
+ }
+ })
+ }
+ // With root LTX files the root is planned as before, g- subtrees or not
+ // (TestPlanStartRootSkipsEverythingButItsLTX).
+}
diff --git a/internal/lease/gentake.go b/internal/lease/gentake.go
index 9b5d95a2f..2b27b63d4 100644
--- a/internal/lease/gentake.go
+++ b/internal/lease/gentake.go
@@ -45,11 +45,13 @@ var errNotGenerations = errors.New("lease: a generation take needs a held storag
// first, once.
var errTakeStarted = errors.New("lease: a generation take must be the handle's first and only take")
-// errNotSwitched is a replica store asked of a handle whose take has not
-// switched head.json to its generation (or failed): it would write a
-// generation head.json does not name, so it is refused, and the root is
-// never written.
-var errNotSwitched = errors.New("lease: the take has not switched head.json to its generation; replication refused")
+// ErrGenerationNotSwitched refuses a replica store (Replicate,
+// Checkpoint) on a handle whose lock is a storage-generations lock (it
+// wrote carlos_generation) unless its take has switched head.json to its
+// generation: such a handle never writes the root, nor a generation
+// head.json does not name. It refuses before anything is built, so the
+// handle's releases stay settled.
+var ErrGenerationNotSwitched = errors.New("lease: a generations lock replicates only after its take has switched head.json to its generation")
// TakeOptions are a take's inputs.
type TakeOptions struct {
@@ -258,7 +260,12 @@ func (t *Take) switched() bool {
// restore reads it (RestoreTake).
func (t *Take) Reader() litestream.ReplicaClient { return t.reader }
-// Switch is §4 step 5: with the lease healthy, write head.json for g-N
+// Switch is §4 step 5. The caller must not Release (or ReleaseMarker)
+// the handle while its Switch runs: Switch checks the lease before its
+// PUT, not after, and is not serialized with the handle's releases. The
+// wake orders them (the activator).
+//
+// 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
// there was none). A conflict is ErrHeadMoved and deletes nothing. After
@@ -325,28 +332,35 @@ func RestoreTake(ctx context.Context, dbPath string, t *Take) (bool, error) {
return restoreFrom(ctx, t.reader, dbPath, 0)
}
-// takeWriter is the replica client a handle with a take replicates
-// through (newStore): nil without a take, errNotSwitched before a
-// successful Switch, and otherwise the generation writer for g-N.
+// 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
+// for a generations lock without a take, or whose take has not switched;
+// and otherwise the generation writer for g-N.
func (h *Held) takeWriter() (litestream.ReplicaClient, error) {
h.mu.Lock()
t, seam := h.take, h.replicaClient
h.mu.Unlock()
if t == nil {
+ if h.rn != nil && h.rn.genName != "" {
+ return nil, ErrGenerationNotSwitched
+ }
return nil, nil
}
if !t.switched() {
- return nil, errNotSwitched
+ return nil, ErrGenerationNotSwitched
}
- inner := seam
- if inner == nil {
- c, err := newReplicaClient(h.leaser.Bucket, replicagen.ClientPath(t.loc, t.Generation), h.region)
- if err != nil {
- return nil, err
- }
- inner = c
+ if seam != nil {
+ // The local-replica test seam (SetReplicaClientForTest): a
+ // directory, not an S3 path, so there is no Path to check. Only
+ // tests set it; production always builds the S3 client below.
+ return &generationClient{client: seam, check: func(context.Context) error { return h.rn.Err() }, writer: true}, nil
+ }
+ c, err := newReplicaClient(h.leaser.Bucket, replicagen.ClientPath(t.loc, t.Generation), h.region)
+ if err != nil {
+ return nil, err
}
- return newGenerationWriter(inner, h.leaser.Bucket, t.loc, t.Generation, h.rn.Err)
+ return newGenerationWriter(c, h.leaser.Bucket, t.loc, t.Generation, h.rn.Err)
}
// newGenerationWriter is §5.1's writer for generation gen of loc: inner
diff --git a/internal/lease/gentake_test.go b/internal/lease/gentake_test.go
index 3dfbfe482..cc5f36b71 100644
--- a/internal/lease/gentake_test.go
+++ b/internal/lease/gentake_test.go
@@ -551,8 +551,8 @@ func TestReplicateBeforeSwitchRefuses(t *testing.T) {
if ok, err := lease.RestoreTake(ctx, path, tk); err != nil || !ok {
t.Fatalf("restore: %v %v", ok, err)
}
- if _, err := h.Replicate(ctx, path, 0); err == nil {
- t.Fatal("Replicate before the switch succeeded")
+ if _, err := h.Replicate(ctx, path, 0); !errors.Is(err, lease.ErrGenerationNotSwitched) {
+ t.Fatalf("Replicate before the switch: %v, want ErrGenerationNotSwitched", err)
}
if err := tk.Switch(ctx); err != nil {
t.Fatal(err)
@@ -706,3 +706,76 @@ func TestGenerationWriterRefusesOnceTheLeaseIsLost(t *testing.T) {
}
_ = tk
}
+
+// A generations lock never replicates to the root: without a take, or
+// before its take switched, Replicate and Checkpoint refuse with
+// ErrGenerationNotSwitched, nothing is written, and the release is
+// settled (the successor takes at once). That holds for a lock that is in
+// generations mode by stickiness too (the switch off over a generations
+// marker).
+func TestGenerationsLockNeverReplicatesToTheRoot(t *testing.T) {
+ for name, opts := range map[string]lease.AcquireOptions{"switch on": genOn, "sticky, switch off": {}} {
+ t.Run(name, func(t *testing.T) {
+ haBox(t)
+ fx := newGenFixture(t)
+ if name != "switch on" {
+ h := fx.acquire(t, time.Minute) // a generations lock, released settled
+ if err := h.Release(ctx); err != nil {
+ t.Fatal(err)
+ }
+ }
+ fx.setPhase("held")
+ h, err := lease.AcquireHAOptsForTest(ctx, fx.bucket, fx.loc, fx.region, hafresh.Marker{V: 1, Lifetime: "L1"}, eligibleProofs(), time.Minute, opts)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if h.GenName() == "" {
+ t.Fatal("fixture: not a generations lock")
+ }
+ path := filepath.Join(t.TempDir(), "w.example.com.db")
+ witnessExec(t, path, `PRAGMA journal_mode=WAL`, `CREATE TABLE t (id INTEGER PRIMARY KEY, body TEXT)`, `INSERT INTO t (body) VALUES ('x')`)
+ if _, err := h.Replicate(ctx, path, 0); !errors.Is(err, lease.ErrGenerationNotSwitched) {
+ t.Fatalf("Replicate without a take: %v, want ErrGenerationNotSwitched", err)
+ }
+ if _, err := h.Checkpoint(ctx, path); !errors.Is(err, lease.ErrGenerationNotSwitched) {
+ t.Fatalf("Checkpoint without a take: %v, want ErrGenerationNotSwitched", err)
+ }
+ for _, k := range fx.keys("held", false) {
+ if !strings.HasSuffix(k, "/lock.json") {
+ t.Errorf("written: %s", k)
+ }
+ }
+ if err := h.Release(ctx); err != nil {
+ t.Fatal(err)
+ }
+ body, _ := fx.m.Current(fx.bucket, fx.loc+"/lock.json")
+ if v, err := hafresh.DecodeLock(body, ""); err != nil || v.Lock.Release == nil || !v.Lock.Release.Settled {
+ t.Fatalf("release after the refusals: %+v %v, want settled", v.Lock.Release, err)
+ }
+ })
+ }
+}
+
+// A take over a location with no head.json and an empty root (a replica
+// that never uploaded, under a lock that is not a first wake) starts an
+// empty generation and switches create-only, instead of refusing.
+func TestTakeOverAnEmptyRootStartsFresh(t *testing.T) {
+ haBox(t)
+ fx := newGenFixture(t)
+ h := fx.acquire(t, time.Minute)
+ tk, err := h.StartGeneration(ctx, fx.st, fx.vs, lease.TakeOptions{Self: selfA, Lifetime: "L1"})
+ if err != nil {
+ t.Fatalf("take over an empty root: %v", err)
+ }
+ if !tk.Empty || tk.Predecessor != "" || tk.StartTXID != 0 {
+ t.Fatalf("take %+v: want an empty start", tk)
+ }
+ if err := tk.Switch(ctx); err != nil {
+ t.Fatal(err)
+ }
+ head, _, found := fx.head(t)
+ if !found || head.Generation != tk.Generation || head.Predecessor != "" || head.StartTXID != 0 ||
+ len(head.History) != 1 || head.History[0].Generation != replicagen.Root {
+ t.Fatalf("head %+v: want an empty %s after the root", head, tk.Generation)
+ }
+}