carlos / platform Public

lease: take a generation, switch head.json, write only there

Spec 2026-11-12 region HA storage generations, §4 steps 0-5 and §5.1.

Held.StartGeneration runs the take on a held generations HA lock: a first
wake creates head.json for an empty g-N create-only; otherwise it reads
head.json (or reuses the caller's), plans at G's newest L0 and copies the
plan into g-N. RestoreTake restores from g-N through the take's read-only
client. Take.Switch checks the lease, then writes head.json for g-N
If-Match the ETag it read (predecessor G, history G prepended and
trimmed); a 412 is ErrHeadMoved and deletes nothing.

After Switch, Held.Replicate builds the generation writer: the existing
generationClient in a writer mode over Litestream's S3 client at exactly
replicagen.ClientPath(loc, g-N), checking the transferred renewer before
every request, with retention on (DeleteLTXFiles allowed inside g-N).
Before Switch a take's handle refuses to replicate. Claim bindings keep
their behaviour.

The leasetest S3 fake answers DeleteObjects (POST ?delete), quiet and
verbose, with per-object bare-key deletes as delete markers.

The late-write witness (8e8a00a0) is adapted to generations and passes:
A's late writes land under A's generation, nothing of B's is replaced,
and the restore through head.json holds B's row and not A's.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev c536534c34008a9034ca45103c6e4cb6ac6e0966 parent f3213a3
9 files changed, +1,609 −9
  • internal/lease/claimgeneration.go +27 −5
  • internal/lease/claimgeneration_test.go +86 −0
  • internal/lease/export_test.go +33 −0
  • internal/lease/gentake.go +371 −0
  • internal/lease/gentake_test.go +708 −0
  • internal/lease/lease.go +16 −1
  • internal/lease/leasetest/s3server.go +83 −3
  • internal/lease/leasetest/s3server_test.go +72 −0
  • internal/lease/stale_holder_witness_test.go +213 −0
diff --git a/internal/lease/claimgeneration.go b/internal/lease/claimgeneration.go
index bd515e71d..9fa2ab2c8 100644
--- a/internal/lease/claimgeneration.go
+++ b/internal/lease/claimgeneration.go
@@ -34,7 +34,7 @@ func (h *Held) BindGeneration(prefix string, check func(context.Context) error)
}
h.mu.Lock()
defer h.mu.Unlock()
- if h.busy || h.spent || h.generationPrefix != "" {
+ if h.busy || h.spent || h.generationPrefix != "" || h.take != nil {
return ErrGenerationBinding
}
client := h.replicaClient
@@ -68,7 +68,7 @@ func (h *Held) BindRoot(check func(context.Context) error) error {
}
h.mu.Lock()
defer h.mu.Unlock()
- if h.busy || h.spent || h.generationPrefix != "" {
+ if h.busy || h.spent || h.generationPrefix != "" || h.take != nil {
return ErrGenerationBinding
}
client := h.replicaClient
@@ -87,9 +87,16 @@ func (h *Held) BindRoot(check func(context.Context) error) error {
return nil
}
+// generationClient confines a replica client to one generation and checks
+// its authority before every request. A claim binding (BindGeneration,
+// BindRoot) refuses retention and bounds each request; a take's writer
+// (writer, newGenerationWriter in gentake.go) lets retention delete inside
+// its generation and leaves request time to Litestream, as the unconfined
+// writer always has.
type generationClient struct {
client litestream.ReplicaClient
check func(context.Context) error
+ writer bool
}
func (c *generationClient) Type() string { return c.client.Type() }
@@ -110,7 +117,12 @@ func (c *generationClient) bounded(ctx context.Context) (context.Context, contex
if ctx == nil {
return nil, nil, ErrGenerationBinding
}
- ctx, cancel := context.WithTimeout(ctx, generationRequestLimit)
+ var cancel context.CancelFunc
+ if c.writer {
+ ctx, cancel = context.WithCancel(ctx)
+ } else {
+ ctx, cancel = context.WithTimeout(ctx, generationRequestLimit)
+ }
if err := c.check(ctx); err != nil {
cancel()
return nil, nil, err
@@ -178,8 +190,18 @@ func (c *generationClient) DeleteLTXFiles(ctx context.Context, files []*ltx.File
return ErrGenerationBinding
}
}
- // FileInfo has no VersionID. Only the park engine may retire exact versions.
- return ErrGenerationRetention
+ if !c.writer {
+ // FileInfo has no VersionID. Only the park engine may retire exact versions.
+ return ErrGenerationRetention
+ }
+ // A take's writer: the inner client's Path is the generation's, so
+ // every key retention deletes is inside it (§5.1).
+ ctx, cancel, err := c.bounded(ctx)
+ if err != nil {
+ return err
+ }
+ defer cancel()
+ return c.client.DeleteLTXFiles(ctx, files)
}
func (c *generationClient) DeleteAll(context.Context) error {
return fmt.Errorf("%w: DeleteAll refused", ErrGenerationBinding)
diff --git a/internal/lease/claimgeneration_test.go b/internal/lease/claimgeneration_test.go
index 65692522a..10bfb51f3 100644
--- a/internal/lease/claimgeneration_test.go
+++ b/internal/lease/claimgeneration_test.go
@@ -13,6 +13,8 @@ import (
"github.com/benbjohnson/litestream"
lss3 "github.com/benbjohnson/litestream/s3"
"github.com/superfly/ltx"
+
+ "github.com/carlosframework/platform/internal/replicagen"
)
type generationFake struct {
@@ -249,3 +251,87 @@ func TestBindRootChecksEveryRequest(t *testing.T) {
t.Fatalf("nil check=%v", err)
}
}
+
+// §5.1: a take's writer is built only over Litestream's S3 client at
+// exactly replicagen.ClientPath(loc, gen) in the lease's bucket. Any other
+// client (the root, another generation, the slash-terminated prefix,
+// another bucket or location, a non-S3 client) is refused.
+func TestGenerationWriterRefusesForeignPath(t *testing.T) {
+ const loc = "instances/w.example.com"
+ gen := replicagen.Name(7)
+ healthy := func() error { return nil }
+ at := func(bucket, path string) *lss3.ReplicaClient {
+ c := lss3.NewReplicaClient()
+ c.Bucket, c.Path = bucket, path
+ return c
+ }
+ w, err := newGenerationWriter(at("data", replicagen.ClientPath(loc, gen)), "data", loc, gen, healthy)
+ if err != nil || !w.writer {
+ t.Fatalf("the generation's own client: %v", err)
+ }
+ for name, c := range map[string]litestream.ReplicaClient{
+ "the root": at("data", loc),
+ "another generation": at("data", replicagen.ClientPath(loc, replicagen.Name(6))),
+ "the slash-terminated prefix": at("data", replicagen.Prefix(loc, gen)),
+ "another bucket": at("other", replicagen.ClientPath(loc, gen)),
+ "another location": at("data", replicagen.ClientPath("instances/x.example.com", gen)),
+ "not the S3 client": &generationFake{},
+ } {
+ if _, err := newGenerationWriter(c, "data", loc, gen, healthy); !errors.Is(err, ErrGenerationBinding) {
+ t.Errorf("%s: %v, want refused", name, err)
+ }
+ }
+ for name, g := range map[string]string{"the root generation": replicagen.Root, "a claim name": "g-x", "empty": ""} {
+ if _, err := newGenerationWriter(at("data", replicagen.ClientPath(loc, g)), "data", loc, g, healthy); !errors.Is(err, ErrGenerationBinding) {
+ t.Errorf("%s: %v, want refused", name, err)
+ }
+ }
+ if _, err := newGenerationWriter(at("data", replicagen.ClientPath(loc, gen)), "data", loc, gen, nil); !errors.Is(err, ErrGenerationBinding) {
+ t.Errorf("no health check: %v, want refused", err)
+ }
+}
+
+// §5.1: the writer forwards retention's deletes (a claim binding refuses
+// them), still refuses DeleteAll, and checks the lease before every
+// request: once it fails, nothing reaches the inner client.
+func TestGenerationWriterChecksEveryRequestAndKeepsRetention(t *testing.T) {
+ f := &generationFake{}
+ var health error
+ c := &generationClient{client: f, check: func(context.Context) error { return health }, writer: true}
+ files := []*ltx.FileInfo{{Level: 0, MinTXID: 1, MaxTXID: 1}, {Level: 1, MinTXID: 1, MaxTXID: 2}}
+ if err := c.DeleteLTXFiles(t.Context(), files); err != nil || f.calls != 1 {
+ t.Fatalf("retention delete: %v (calls %d)", err, f.calls)
+ }
+ if err := c.DeleteLTXFiles(t.Context(), []*ltx.FileInfo{{Level: 0, MinTXID: 2, MaxTXID: 1}}); !errors.Is(err, ErrGenerationBinding) {
+ t.Fatalf("a delete of bad coordinates: %v", err)
+ }
+ if err := c.DeleteAll(t.Context()); !errors.Is(err, ErrGenerationBinding) {
+ t.Fatalf("DeleteAll: %v", err)
+ }
+ if _, err := c.WriteLTXFile(t.Context(), 0, 3, 3, bytes.NewReader(nil)); err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := f.ctx.Deadline(); ok {
+ t.Fatal("the writer bounded a request: Litestream's own uploads have no deadline")
+ }
+ calls := f.calls
+ health = errors.New("lease lost")
+ if _, err := c.WriteLTXFile(t.Context(), 0, 4, 4, bytes.NewReader(nil)); !errors.Is(err, health) {
+ t.Errorf("write: %v", err)
+ }
+ if _, err := c.LTXFiles(t.Context(), 0, 0, false); !errors.Is(err, health) {
+ t.Errorf("list: %v", err)
+ }
+ if _, err := c.OpenLTXFile(t.Context(), 0, 1, 1, 0, 0); !errors.Is(err, health) {
+ t.Errorf("open: %v", err)
+ }
+ if err := c.DeleteLTXFiles(t.Context(), files); !errors.Is(err, health) {
+ t.Errorf("delete: %v", err)
+ }
+ if err := c.Init(t.Context()); !errors.Is(err, health) {
+ t.Errorf("init: %v", err)
+ }
+ if f.calls != calls {
+ t.Fatalf("%d requests reached the client after the lease was lost", f.calls-calls)
+ }
+}
diff --git a/internal/lease/export_test.go b/internal/lease/export_test.go
index 7aa6df16e..0a6e699cf 100644
--- a/internal/lease/export_test.go
+++ b/internal/lease/export_test.go
@@ -2,6 +2,7 @@ package lease
import (
"context"
+ "errors"
"time"
awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
@@ -106,3 +107,35 @@ func SetFenceTripHooksForTest(entry, marked func()) func() {
fenceTripEntryHook, fenceTripMarkedHook = entry, marked
return func() { fenceTripEntryHook, fenceTripMarkedHook = prevEntry, prevMarked }
}
+
+// PoisonForTest poisons h, as a failed checkpoint does.
+func PoisonForTest(h *Held, err error) {
+ h.mu.Lock()
+ h.poison = err
+ h.mu.Unlock()
+}
+
+// LoseHeldLeaseForTest latches h's renewer as lost, as a failed renewal
+// does (LoseLeaseForTest is the Replicator's).
+func LoseHeldLeaseForTest(h *Held) {
+ h.rn.mu.Lock()
+ h.rn.loseLocked(errors.New("lease: lost (test)"))
+ h.rn.mu.Unlock()
+}
+
+// CompactForTest compacts r's database into level, through its replica.
+func CompactForTest(r *Replicator, level int) error {
+ _, err := r.db.Compact(context.Background(), level)
+ return err
+}
+
+// EnforceL0RetentionForTest runs litestream's L0 retention on r's
+// database with a retention of a nanosecond: every L0 file at or below
+// the newest L1 TXID is expired (the newest L0 file is kept).
+func EnforceL0RetentionForTest(r *Replicator) error {
+ r.db.L0Retention = time.Nanosecond
+ return r.db.EnforceL0RetentionByTime(context.Background())
+}
+
+// RetentionEnabledForTest reports whether r's store deletes remotely.
+func RetentionEnabledForTest(r *Replicator) bool { return r.db.RetentionEnabled }
diff --git a/internal/lease/gentake.go b/internal/lease/gentake.go
new file mode 100644
index 000000000..9b5d95a2f
--- /dev/null
+++ b/internal/lease/gentake.go
@@ -0,0 +1,371 @@
+package lease
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/benbjohnson/litestream"
+ lss3 "github.com/benbjohnson/litestream/s3"
+
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/replicagen"
+)
+
+// The take on a held HA lease (spec 2026-11-12 region HA storage
+// generations, §4 steps 0-5) and its confined writer (§5.1). After the
+// acquire wrote lock generation N, the holder reads head.json, copies its
+// predecessor G into g-N (PlanStart, CopyStart), restores locally from
+// g-N (RestoreTake), switches head.json to g-N with If-Match (Switch),
+// and from then on replicates only into g-N (Held.Replicate). A request
+// an earlier holder sent late lands in that holder's own generation,
+// which the successor has copied from and nobody reads as current.
+
+// ErrHeadMoved is a switch whose conditional write found head.json changed
+// since the take read it (§4 step 5, 412): only a holder of an older lock
+// generation can have written it, its own switch in flight when this take
+// won the lock. The take abandons and deletes nothing: its g-N objects are
+// unreferenced and retirement (§8) removes them. The wake releases
+// (settled: it never replicated) and retries once from the acquire.
+var ErrHeadMoved = errors.New("lease: head moved during the take")
+
+// errNotGenerations is a take on a handle whose lock is not a
+// storage-generations lock (no carlos_generation): an HA acquire with
+// GenerationsOn, or over a generations lock, writes one.
+var errNotGenerations = errors.New("lease: a generation take needs a held storage-generations HA lock")
+
+// errTakeStarted is a second take on one handle, or a take on a handle
+// that already built a store or bound a claim generation: the take comes
+// 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")
+
+// TakeOptions are a take's inputs.
+type TakeOptions struct {
+ // First is a first wake (§4 step 0): the acquire took an absent lock
+ // over a proven-empty prefix. The take creates head.json for an empty
+ // g-N, create-only, and copies nothing.
+ First bool
+ // CleanTXID is the TXID the predecessor's clean release marker records
+ // (0: none). PlanStart refuses a G whose newest L0 is below it.
+ CleanTXID uint64
+ // Self is the box head.json's created_by names; zero is CurrentSelf.
+ Self hafresh.Self
+ // Lifetime is the incarnation created_by names.
+ Lifetime string
+ // 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).
+ HeadRead bool
+ Head Head
+ HeadETag string
+ HeadFound bool
+}
+
+// takeState is a take's progress. Only takeSwitched lets the handle build
+// a replica store.
+type takeState int
+
+const (
+ takeStarting takeState = iota // the take's steps 1-4 are running
+ takeCopied // g-N holds the start; Switch may run
+ takeSwitching // Switch's PUT is in flight
+ takeSwitched // head.json names g-N: replication writes only there
+ takeMoved // Switch got 412 (ErrHeadMoved)
+ takeFailed // a step failed; the handle never replicates
+)
+
+// Take is one take of a new generation on a held lease. Generation is
+// g-N; Predecessor the generation head.json will record as copied from
+// ("" for an empty start); StartTXID the TXID the copy ends at; Empty
+// a start with nothing copied (a first wake, or an empty predecessor).
+type Take struct {
+ Generation string
+ Predecessor string
+ StartTXID uint64
+ Empty bool
+
+ h *Held
+ st release.Store
+ loc string
+ reader litestream.ReplicaClient
+ created HeadCreator // At is set at the switch
+ // prev is head.json as step 1 read it, with its ETag; prevFound false
+ // is the root layout (the switch is create-only).
+ prev Head
+ prevFound bool
+ etag string
+
+ mu sync.Mutex
+ state takeState
+}
+
+// StartGeneration runs a take's steps 0-4 on h: on a first wake it creates
+// head.json for an empty g-N (create-only) and the take is already
+// switched; otherwise it reads head.json (unless opt carries it), plans
+// the start at G's newest L0 and copies it into g-N. st is the bucket as
+// a release.Store (head.json, NewFilesStore); vs the same bucket by
+// exact version (NewVersionedS3). h must be an HA handle on a generations
+// lock, healthy, that has not built a store; it takes once. Whatever
+// the outcome, from here on h replicates only after a successful Switch.
+//
+// A *StartRefusal (genstart.go) refuses the wake; ErrHeadMoved on a first
+// wake is a head.json that appeared under a proven-empty prefix.
+func (h *Held) StartGeneration(ctx context.Context, st release.Store, vs VersionedStore, opt TakeOptions) (*Take, error) {
+ if h == nil || h.leaser == nil || st == nil || (vs == nil && !opt.First) {
+ return nil, errors.New("lease: start generation: a held lease, head.json's store and the versioned store are required")
+ }
+ if !h.ha || h.rn.genName == "" {
+ return nil, errNotGenerations
+ }
+ gen := replicagen.Name(h.lockGen)
+ if gen != h.rn.genName {
+ return nil, fmt.Errorf("lease: start generation: lock generation %d names %s, the lock carries %s", h.lockGen, gen, h.rn.genName)
+ }
+ loc := strings.TrimSuffix(h.leaser.Path, "/")
+ bucket := h.leaser.Bucket
+ self := opt.Self
+ if self == (hafresh.Self{}) {
+ self = CurrentSelf()
+ }
+ reader, err := readReplicaClient(bucket, loc, h.region, gen)
+ if err != nil {
+ return nil, err
+ }
+ t := &Take{Generation: gen, 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()
+ switch {
+ case h.spent:
+ err = ErrSpent
+ case h.busy:
+ err = ErrBusy
+ case h.take != nil || h.generationPrefix != "" || h.stored:
+ err = errTakeStarted
+ case h.poison != nil:
+ err = h.poison
+ default:
+ err = h.rn.Err()
+ }
+ if err == nil {
+ h.take = t // from here the handle writes only after Switch
+ }
+ h.mu.Unlock()
+ if err != nil {
+ return nil, err
+ }
+
+ if opt.First {
+ err = t.startFirst(ctx)
+ } else {
+ err = t.start(ctx, vs, bucket, opt)
+ }
+ if err != nil {
+ return nil, err
+ }
+ return t, nil
+}
+
+// startFirst is §4 step 0: head.json for an empty g-N, create-only. The
+// take is switched once it lands; there is nothing to copy or restore.
+func (t *Take) startFirst(ctx context.Context) error {
+ if err := t.h.Err(); err != nil {
+ t.setState(takeFailed)
+ return err
+ }
+ t.Empty = true
+ t.created.At = time.Now().UTC()
+ head := Head{V: HeadVersion, Generation: t.Generation, CreatedBy: t.created, History: []HeadHistory{}}
+ if _, err := PutHead(ctx, t.st, t.loc, head, ""); err != nil {
+ t.setState(takeFailed)
+ if errors.Is(err, release.ErrCASConflict) {
+ return fmt.Errorf("%w: a first wake found %s/head.json: %w", ErrHeadMoved, t.loc, err)
+ }
+ return err
+ }
+ t.setState(takeSwitched)
+ return nil
+}
+
+// start is §4 steps 1-4: read head.json (or take the caller's), plan at
+// G's newest L0 and copy the plan into g-N.
+func (t *Take) start(ctx context.Context, vs VersionedStore, bucket string, opt TakeOptions) (err error) {
+ defer func() {
+ if err != nil {
+ t.setState(takeFailed)
+ }
+ }()
+ head, etag, found := opt.Head, opt.HeadETag, opt.HeadFound
+ if !opt.HeadRead {
+ if head, etag, found, err = ReadHead(ctx, t.st, t.loc); err != nil {
+ return err
+ }
+ } else if found {
+ if err := head.validate(); err != nil {
+ return fmt.Errorf("lease: start generation: the head.json passed in: %w", err)
+ }
+ }
+ if found && etag == "" {
+ return errors.New("lease: start generation: head.json found without its ETag")
+ }
+ plan, err := PlanStart(ctx, vs, bucket, t.loc, head, found, opt.CleanTXID)
+ if err != nil {
+ return err
+ }
+ if err := CopyStart(ctx, vs, bucket, t.loc, plan, t.Generation); err != nil {
+ return err
+ }
+ t.prev, t.prevFound, t.etag = head, found, ""
+ if found {
+ t.etag = etag
+ }
+ t.StartTXID, t.Empty = plan.T, plan.Empty
+ if !plan.Empty {
+ // An empty start copied nothing: it records no predecessor, so the
+ // next take over it starts afresh too (§4 step 0).
+ t.Predecessor = plan.From
+ }
+ t.setState(takeCopied)
+ return nil
+}
+
+func (t *Take) setState(s takeState) {
+ t.mu.Lock()
+ t.state = s
+ t.mu.Unlock()
+}
+
+// switched reports whether head.json names this take's generation.
+func (t *Take) switched() bool {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ return t.state == takeSwitched
+}
+
+// Reader is the take's read-only replica client, bound to g-N: the local
+// 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
+// (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
+// 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.
+func (t *Take) Switch(ctx context.Context) error {
+ t.mu.Lock()
+ state := t.state
+ if state == takeCopied {
+ t.state = takeSwitching
+ }
+ t.mu.Unlock()
+ switch state {
+ case takeSwitched:
+ return nil
+ case takeMoved:
+ return fmt.Errorf("%w: %s", ErrHeadMoved, t.loc)
+ case takeCopied:
+ default:
+ return fmt.Errorf("lease: switch %s: the take did not complete its start", t.Generation)
+ }
+ if err := t.h.Err(); err != nil {
+ t.setState(takeFailed)
+ return fmt.Errorf("lease: switch %s: %w", t.Generation, err)
+ }
+ now := time.Now().UTC()
+ created := t.created
+ created.At = now
+ var history []HeadHistory
+ if t.prevFound {
+ history = append(history, HeadHistory{Generation: t.prev.Generation, StartTXID: t.prev.StartTXID, CreatedAt: t.prev.CreatedBy.At, EndedAt: now})
+ history = append(history, t.prev.History...)
+ } else {
+ // The migration: the root layout was current until now.
+ 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)}
+ _, err := PutHead(ctx, t.st, t.loc, head, t.etag)
+ switch {
+ case err == nil:
+ t.setState(takeSwitched)
+ return nil
+ case errors.Is(err, release.ErrCASConflict):
+ t.setState(takeMoved)
+ return fmt.Errorf("%w: %s: %w", ErrHeadMoved, t.loc, err)
+ default:
+ // The PUT's outcome is unknown: never retried on this handle.
+ t.setState(takeFailed)
+ return err
+ }
+}
+
+// RestoreTake restores t's generation into dbPath through its read-only
+// client, as Restore does for a resolved replica: restored false and a
+// nil error when g-N holds nothing (an empty start boots fresh).
+func RestoreTake(ctx context.Context, dbPath string, t *Take) (bool, error) {
+ if t == nil || t.reader == nil {
+ return false, errors.New("lease: restore take: no take")
+ }
+ if err := os.MkdirAll(filepath.Dir(dbPath), 0o700); err != nil {
+ return false, fmt.Errorf("create %s: %w", filepath.Dir(dbPath), err)
+ }
+ 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.
+func (h *Held) takeWriter() (litestream.ReplicaClient, error) {
+ h.mu.Lock()
+ t, seam := h.take, h.replicaClient
+ h.mu.Unlock()
+ if t == nil {
+ return nil, nil
+ }
+ if !t.switched() {
+ return nil, errNotSwitched
+ }
+ 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
+ }
+ return newGenerationWriter(inner, h.leaser.Bucket, t.loc, t.Generation, h.rn.Err)
+}
+
+// newGenerationWriter is §5.1's writer for generation gen of loc: inner
+// must be Litestream's S3 client for that bucket at exactly
+// replicagen.ClientPath(loc, gen), so every key it builds is under the
+// generation's prefix; anything else is refused. Every request first
+// checks healthy (the renewer the Replicator carries, Replicate having
+// spent the Held), and retention's deletes are allowed: they stay inside
+// the generation.
+func newGenerationWriter(inner litestream.ReplicaClient, bucket, loc, gen string, healthy func() error) (*generationClient, error) {
+ if gen == replicagen.Root || !replicagen.Valid(gen) || healthy == nil || loc == "" || strings.HasSuffix(loc, "/") {
+ return nil, fmt.Errorf("%w: generation writer for %q at %q", ErrGenerationBinding, gen, loc)
+ }
+ c, ok := inner.(*lss3.ReplicaClient)
+ if !ok || c == nil {
+ return nil, fmt.Errorf("%w: generation writer: %T is not the S3 replica client", ErrGenerationBinding, inner)
+ }
+ if want := replicagen.ClientPath(loc, gen); c.Bucket != bucket || c.Path != want {
+ return nil, fmt.Errorf("%w: generation writer: client at s3://%s/%s, want s3://%s/%s", ErrGenerationBinding, c.Bucket, c.Path, bucket, want)
+ }
+ return &generationClient{client: inner, check: func(context.Context) error { return healthy() }, writer: true}, nil
+}
diff --git a/internal/lease/gentake_test.go b/internal/lease/gentake_test.go
new file mode 100644
index 000000000..3dfbfe482
--- /dev/null
+++ b/internal/lease/gentake_test.go
@@ -0,0 +1,708 @@
+package lease_test
+
+import (
+ "bytes"
+ "encoding/xml"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "path/filepath"
+ "slices"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/lease/leasetest"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/replicagen"
+)
+
+// The take (spec 2026-11-12 region HA storage generations, §4 steps 0-5)
+// and the generation writer (§5.1), over the versioned S3 fake through
+// the real clients: the lock, head.json, the copies and Litestream's own.
+
+var (
+ selfA = hafresh.Self{Ref: "a", IID: "i-a", Account: "111122223333", Region: "eu-west-1"}
+ selfB = hafresh.Self{Ref: "b", IID: "i-b", Account: "111122223333", Region: "eu-west-1"}
+)
+
+// sentReq is one write request that reached the server: a PUT (a copy
+// included), a DELETE, or one object of a POST ?delete.
+type sentReq struct{ phase, method, key string }
+
+// genFixture is a versioned bucket behind a recording proxy. hook, when
+// set, sees every request before the server does and may hold it.
+type genFixture struct {
+ m *leasetest.VersionedBucket
+ bucket, loc, region string
+ st release.Store
+ vs lease.VersionedStore
+
+ mu sync.Mutex
+ sent []sentReq
+ phase string
+ hook func(r *http.Request, keys []string)
+}
+
+func newGenFixture(t *testing.T) *genFixture {
+ t.Helper()
+ fx := &genFixture{m: leasetest.NewVersionedBucket(), bucket: "data", loc: "instances/w.example.com", region: "test-region"}
+ fx.m.AddBucket(fx.bucket)
+ inner, _ := leasetest.NewS3Server(fx.m)
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ key, _ := url.PathUnescape(strings.TrimPrefix(r.URL.EscapedPath(), "/"+fx.bucket+"/"))
+ if r.Method == http.MethodPut || r.Method == http.MethodPost {
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ return // the body never arrived: nothing to apply
+ }
+ r.Body = io.NopCloser(bytes.NewReader(body))
+ if r.Method == http.MethodPost && r.URL.Query().Has("delete") {
+ keys := deleteObjectKeys(body)
+ fx.record(r, keys)
+ fx.serve(w, r, inner, keys)
+ return
+ }
+ }
+ fx.record(r, []string{key})
+ fx.serve(w, r, inner, []string{key})
+ }))
+ t.Cleanup(srv.Close)
+ t.Setenv("AWS_ACCESS_KEY_ID", "test-key")
+ t.Setenv("AWS_SECRET_ACCESS_KEY", "test-secret")
+ t.Setenv("AWS_SESSION_TOKEN", "")
+ t.Setenv("AWS_EC2_METADATA_DISABLED", "true")
+ t.Setenv("AWS_CONFIG_FILE", filepath.Join(t.TempDir(), "absent"))
+ t.Setenv("AWS_SHARED_CREDENTIALS_FILE", filepath.Join(t.TempDir(), "absent"))
+ t.Setenv("CARLOS_S3_ENDPOINT", srv.URL)
+ var err error
+ if fx.st, err = lease.NewFilesStore(ctx, fx.bucket, fx.region); err != nil {
+ t.Fatal(err)
+ }
+ if fx.vs, err = lease.NewVersionedS3(ctx, map[string]string{fx.bucket: fx.region}); err != nil {
+ t.Fatal(err)
+ }
+ return fx
+}
+
+func (fx *genFixture) record(r *http.Request, keys []string) {
+ method := r.Method
+ switch method {
+ case http.MethodGet, http.MethodHead:
+ return
+ case http.MethodPost:
+ method = http.MethodDelete
+ }
+ fx.mu.Lock()
+ defer fx.mu.Unlock()
+ for _, k := range keys {
+ fx.sent = append(fx.sent, sentReq{phase: fx.phase, method: method, key: k})
+ }
+}
+
+func (fx *genFixture) serve(w http.ResponseWriter, r *http.Request, inner http.Handler, keys []string) {
+ fx.mu.Lock()
+ hook := fx.hook
+ fx.mu.Unlock()
+ if hook != nil {
+ hook(r, keys)
+ }
+ inner.ServeHTTP(w, r)
+}
+
+func (fx *genFixture) setHook(h func(r *http.Request, keys []string)) {
+ fx.mu.Lock()
+ fx.hook = h
+ fx.mu.Unlock()
+}
+
+func (fx *genFixture) setPhase(p string) {
+ fx.mu.Lock()
+ fx.phase = p
+ fx.mu.Unlock()
+}
+
+// keys is every key written in phase (any phase when ""), in order and
+// once each; putsOnly leaves deletes out.
+func (fx *genFixture) keys(phase string, putsOnly bool) []string {
+ fx.mu.Lock()
+ defer fx.mu.Unlock()
+ var out []string
+ for _, s := range fx.sent {
+ if (phase == "" || s.phase == phase) && (!putsOnly || s.method == http.MethodPut) && !slices.Contains(out, s.key) {
+ out = append(out, s.key)
+ }
+ }
+ return out
+}
+
+// deletes is every key a DELETE or POST ?delete named in phase (any
+// phase when "").
+func (fx *genFixture) deletes(phase string) []string {
+ fx.mu.Lock()
+ defer fx.mu.Unlock()
+ var out []string
+ for _, s := range fx.sent {
+ if s.method == http.MethodDelete && (phase == "" || s.phase == phase) {
+ out = append(out, s.key)
+ }
+ }
+ return out
+}
+
+func deleteObjectKeys(body []byte) []string {
+ var d struct {
+ Objects []struct{ Key string } `xml:"Object"`
+ }
+ if err := xml.Unmarshal(body, &d); err != nil {
+ return []string{"?delete (unreadable)"}
+ }
+ var out []string
+ for _, o := range d.Objects {
+ out = append(out, o.Key)
+ }
+ return out
+}
+
+// isControlKey reports a lock.json or head.json key: not replica data.
+func isControlKey(keys []string) bool {
+ for _, k := range keys {
+ if strings.HasSuffix(k, "/lock.json") || strings.HasSuffix(k, "/head.json") {
+ return true
+ }
+ }
+ return false
+}
+
+func (fx *genFixture) acquire(t *testing.T, ttl time.Duration) *lease.Held {
+ t.Helper()
+ h, err := lease.AcquireHAOptsForTest(ctx, fx.bucket, fx.loc, fx.region, hafresh.Marker{V: 1, Lifetime: "L1"}, eligibleProofs(), ttl, genOn)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return h
+}
+
+func (fx *genFixture) head(t *testing.T) (lease.Head, string, bool) {
+ t.Helper()
+ h, etag, found, err := lease.ReadHead(ctx, fx.st, fx.loc)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return h, etag, found
+}
+
+// current is every key under prefix that holds a current object.
+func (fx *genFixture) current(t *testing.T, prefix string) []string {
+ t.Helper()
+ vs, err := fx.m.ListVersions(ctx, fx.bucket, prefix)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var out []string
+ for _, v := range vs {
+ if v.IsLatest && !v.DeleteMarker {
+ out = append(out, v.Key)
+ }
+ }
+ return out
+}
+
+// seed is a first holder on box a: a first wake into an empty generation,
+// rows replicated into it, released clean (a successor takes at once). It
+// returns the generation and the clean marker's TXID.
+func (fx *genFixture) seed(t *testing.T, ttl time.Duration, rows int) (string, uint64) {
+ t.Helper()
+ h := fx.acquire(t, ttl)
+ tk, err := h.StartGeneration(ctx, fx.st, fx.vs, lease.TakeOptions{First: true, Self: selfA, Lifetime: "L1"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := tk.Switch(ctx); err != nil {
+ t.Fatal(err)
+ }
+ path := filepath.Join(t.TempDir(), "seed.db")
+ witnessExec(t, path, `PRAGMA journal_mode=WAL`, `CREATE TABLE t (id INTEGER PRIMARY KEY, body TEXT)`)
+ for i := range rows {
+ witnessExec(t, path, fmt.Sprintf(`INSERT INTO t (body) VALUES ('row-%d')`, i))
+ }
+ r, err := h.Replicate(ctx, path, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ txid, err := r.Finish(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ m := hafresh.Marker{V: 1, Box: "a", IID: "i-a", Lifetime: "L1", TXID: txid, FilesGen: "1:aa", At: time.Now().UTC().Truncate(time.Second), Clean: true}
+ if err := r.ReleaseMarker(ctx, m); err != nil {
+ t.Fatal(err)
+ }
+ return replicagen.Name(h.LockGeneration()), txid
+}
+
+// requireUnder fails for any key outside gen's prefix or with an empty
+// path segment.
+func requireUnder(t *testing.T, fx *genFixture, keys []string, gen string) {
+ t.Helper()
+ if len(keys) == 0 {
+ t.Fatal("no keys to check")
+ }
+ for _, k := range keys {
+ if !strings.HasPrefix(k, replicagen.Prefix(fx.loc, gen)) || strings.Contains(k, "//") {
+ t.Errorf("%s: outside %s", k, replicagen.Prefix(fx.loc, gen))
+ }
+ }
+}
+
+// §4 step 0: a first wake creates head.json for an empty g-N, create-only,
+// and boots fresh; the holder then writes only under g-N, at the keys
+// Litestream's own client writes (g-N/0000/..., never g-N//).
+func TestFirstWakeCreatesEmptyGeneration(t *testing.T) {
+ haBox(t)
+ fx := newGenFixture(t)
+ h := fx.acquire(t, time.Minute)
+ gen := replicagen.Name(h.LockGeneration())
+ if h.GenName() != gen {
+ t.Fatalf("fixture: lock generation %q, want %q", h.GenName(), gen)
+ }
+ tk, err := h.StartGeneration(ctx, fx.st, fx.vs, lease.TakeOptions{First: true, Self: selfA, Lifetime: "L1"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !tk.Empty || tk.Generation != gen || tk.Predecessor != "" || tk.StartTXID != 0 {
+ t.Fatalf("take %+v: want empty %s from nothing", tk, gen)
+ }
+ head, _, found := fx.head(t)
+ if !found || head.Generation != gen || head.StartTXID != 0 || head.Predecessor != "" || len(head.History) != 0 ||
+ head.CreatedBy.LockGeneration != h.LockGeneration() || head.CreatedBy.Box != "a" || head.CreatedBy.IID != "i-a" || head.CreatedBy.Lifetime != "L1" || head.CreatedBy.At.IsZero() {
+ t.Fatalf("head %+v (found %v)", head, found)
+ }
+ before := len(fx.keys("", false))
+ if err := tk.Switch(ctx); err != nil {
+ t.Fatalf("switch of a first wake: %v", err)
+ }
+ if n := len(fx.keys("", false)); n != before {
+ t.Fatalf("the first wake's switch wrote again: %v", fx.keys("", false)[before:])
+ }
+ path := filepath.Join(t.TempDir(), "w.example.com.db")
+ if ok, err := lease.RestoreTake(ctx, path, tk); err != nil || ok {
+ t.Fatalf("restore of an empty generation: %v %v, want nothing restored", ok, err)
+ }
+ witnessExec(t, path, `PRAGMA journal_mode=WAL`, `CREATE TABLE t (id INTEGER PRIMARY KEY, body TEXT)`, `INSERT INTO t (body) VALUES ('row-0')`)
+ r, err := h.Replicate(ctx, path, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := r.SyncAndWait(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if err := r.Close(ctx); err != nil {
+ t.Fatal(err)
+ }
+ var replica []string
+ for _, k := range fx.keys("", false) {
+ if !isControlKey([]string{k}) {
+ replica = append(replica, k)
+ }
+ }
+ requireUnder(t, fx, replica, gen)
+ if !slices.ContainsFunc(replica, func(k string) bool { return strings.HasPrefix(k, replicagen.Prefix(fx.loc, gen)+"0000/") }) {
+ t.Fatalf("no L0 write at %s0000/: %v", replicagen.Prefix(fx.loc, gen), replica)
+ }
+}
+
+// §4 step 0 and §12: a box that dies before its first upload leaves an
+// empty current generation; the next take starts another empty one
+// instead of refusing, and so does the one after it.
+func TestEmptyGenerationNextTakeStartsAfresh(t *testing.T) {
+ haBox(t)
+ fx := newGenFixture(t)
+ h := fx.acquire(t, time.Minute)
+ first, err := h.StartGeneration(ctx, fx.st, fx.vs, lease.TakeOptions{First: true, Self: selfA, Lifetime: "L1"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := h.Release(ctx); err != nil { // dies before its first upload
+ t.Fatal(err)
+ }
+ prev := first.Generation
+ for i := range 2 {
+ h := fx.acquire(t, time.Minute)
+ tk, err := h.StartGeneration(ctx, fx.st, fx.vs, lease.TakeOptions{Self: selfA, Lifetime: "L2"})
+ if err != nil {
+ t.Fatalf("take %d after an empty generation: %v", i, err)
+ }
+ gen := replicagen.Name(h.LockGeneration())
+ if !tk.Empty || tk.Generation != gen || tk.Predecessor != "" || tk.StartTXID != 0 {
+ t.Fatalf("take %d: %+v, want an empty %s", i, tk, gen)
+ }
+ path := filepath.Join(t.TempDir(), "w.example.com.db")
+ if ok, err := lease.RestoreTake(ctx, path, tk); err != nil || ok {
+ t.Fatalf("take %d restore: %v %v, want nothing restored", i, ok, err)
+ }
+ if err := tk.Switch(ctx); err != nil {
+ t.Fatal(err)
+ }
+ head, _, _ := fx.head(t)
+ if head.Generation != gen || head.Predecessor != "" || head.StartTXID != 0 || len(head.History) == 0 || head.History[0].Generation != prev {
+ t.Fatalf("take %d head %+v: want empty %s after %s", i, head, gen, prev)
+ }
+ if got := fx.current(t, replicagen.Prefix(fx.loc, gen)); len(got) != 0 {
+ t.Fatalf("take %d copied into an empty generation: %v", i, got)
+ }
+ if err := h.Release(ctx); err != nil {
+ t.Fatal(err)
+ }
+ prev = gen
+ }
+}
+
+// heldSwitch makes the next head.json PUT of phase "a" reach the server
+// and wait there until release is called; arrived closes once it has.
+func heldSwitch(fx *genFixture) (arrived <-chan struct{}, release func()) {
+ in, out := make(chan struct{}), make(chan struct{})
+ var once sync.Once
+ fx.setHook(func(r *http.Request, keys []string) {
+ if r.Method != http.MethodPut || len(keys) != 1 || !strings.HasSuffix(keys[0], "/head.json") {
+ return
+ }
+ fx.mu.Lock()
+ phase := fx.phase
+ fx.mu.Unlock()
+ if phase != "a" {
+ return
+ }
+ held := false
+ once.Do(func() { held = true; close(in) })
+ if held {
+ <-out
+ }
+ })
+ return in, sync.OnceFunc(func() { close(out) })
+}
+
+// raceTakes is two takes from the same predecessor: A's (lock generation
+// 2) switch PUT is in flight when it releases, and B (generation 3)
+// takes over. lateFirst lets A's PUT land before B reads head.json.
+func raceTakes(t *testing.T, lateFirst bool) (fx *genFixture, seedGen string, aTake, bTake *lease.Take, aErr error, bHeld *lease.Held) {
+ t.Helper()
+ const ttl = time.Minute
+ haBox(t)
+ fx = newGenFixture(t)
+ seedGen, txid := fx.seed(t, ttl, 10)
+
+ fx.setPhase("a")
+ aHeld := fx.acquire(t, ttl)
+ aTake, err := aHeld.StartGeneration(ctx, fx.st, fx.vs, lease.TakeOptions{CleanTXID: txid, Self: selfA, Lifetime: "L2"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if aTake.Predecessor != seedGen {
+ t.Fatalf("A's take from %q, want %q", aTake.Predecessor, seedGen)
+ }
+ arrived, release := heldSwitch(fx)
+ t.Cleanup(release)
+ done := make(chan error, 1)
+ go func() { done <- aTake.Switch(ctx) }()
+ <-arrived
+ if err := aHeld.Release(ctx); err != nil { // it never replicated: settled
+ t.Fatal(err)
+ }
+ if lateFirst {
+ release()
+ aErr = <-done
+ }
+
+ boxB()
+ fx.setPhase("b")
+ bHeld = fx.acquire(t, ttl)
+ bTake, err = bHeld.StartGeneration(ctx, fx.st, fx.vs, lease.TakeOptions{Self: selfB, Lifetime: "L3"})
+ if err != nil {
+ t.Fatalf("B's take: %v", err)
+ }
+ if !lateFirst {
+ release()
+ aErr = <-done
+ }
+ return fx, seedGen, aTake, bTake, aErr, bHeld
+}
+
+// §4 step 5: two takes switch from the same ETag; the second gets 412,
+// returns ErrHeadMoved, and deletes nothing: head names the first, and
+// the loser's generation stays, unreferenced, for §8 to retire.
+func TestTakeHeadRaceSecondSwitchGets412(t *testing.T) {
+ fx, _, aTake, bTake, aErr, _ := raceTakes(t, false)
+ if aErr != nil {
+ t.Fatalf("A's switch, in flight first: %v", aErr)
+ }
+ copied := fx.current(t, replicagen.Prefix(fx.loc, bTake.Generation))
+ if len(copied) == 0 {
+ t.Fatal("fixture: B copied nothing")
+ }
+ headBefore, _, _ := fx.head(t)
+ err := bTake.Switch(ctx)
+ if !errors.Is(err, lease.ErrHeadMoved) {
+ t.Fatalf("B's switch: %v, want ErrHeadMoved", err)
+ }
+ head, _, _ := fx.head(t)
+ if head.Generation != aTake.Generation || head.CreatedBy != headBefore.CreatedBy {
+ t.Fatalf("head names %s, want the first switch's %s", head.Generation, aTake.Generation)
+ }
+ if got := fx.current(t, replicagen.Prefix(fx.loc, bTake.Generation)); !slices.Equal(got, copied) {
+ t.Fatalf("the loser's generation changed: %v, was %v", got, copied)
+ }
+ if d := append(fx.deletes("a"), fx.deletes("b")...); len(d) != 0 {
+ t.Fatalf("a take deleted: %v", d)
+ }
+ if err := bTake.Switch(ctx); !errors.Is(err, lease.ErrHeadMoved) {
+ t.Fatalf("B's second switch: %v, want ErrHeadMoved again", err)
+ }
+}
+
+// §4: a late switch PUT from a holder that lost its lock lands before the
+// successor reads head.json: the successor copies from that generation
+// (its switch was real) and switches after it, with history intact.
+func TestTakeLateSwitchBeforeSuccessorRead(t *testing.T) {
+ fx, seedGen, aTake, bTake, aErr, _ := raceTakes(t, true)
+ if aErr != nil {
+ t.Fatalf("A's late switch: %v", aErr)
+ }
+ if bTake.Predecessor != aTake.Generation || bTake.StartTXID != aTake.StartTXID {
+ t.Fatalf("B's take from %s at %d, want A's %s at %d", bTake.Predecessor, bTake.StartTXID, aTake.Generation, aTake.StartTXID)
+ }
+ for _, k := range fx.keys("b", true) {
+ if isControlKey([]string{k}) {
+ continue
+ }
+ if !strings.HasPrefix(k, replicagen.Prefix(fx.loc, bTake.Generation)) {
+ t.Errorf("B wrote %s outside its generation", k)
+ }
+ }
+ path := filepath.Join(t.TempDir(), "w.example.com.db")
+ if ok, err := lease.RestoreTake(ctx, path, bTake); err != nil || !ok {
+ t.Fatalf("B restore: %v %v", ok, err)
+ }
+ if n := witnessCount(t, path, `body LIKE 'row-%'`); n != 10 {
+ t.Fatalf("B restored %d rows, want 10", n)
+ }
+ if err := bTake.Switch(ctx); err != nil {
+ t.Fatalf("B's switch: %v", err)
+ }
+ head, _, _ := fx.head(t)
+ if head.Generation != bTake.Generation || head.Predecessor != aTake.Generation || head.StartTXID != bTake.StartTXID {
+ t.Fatalf("head %+v: want %s after %s", head, bTake.Generation, aTake.Generation)
+ }
+ if len(head.History) != 2 || head.History[0].Generation != aTake.Generation || head.History[1].Generation != seedGen ||
+ !head.History[0].EndedAt.Equal(head.CreatedBy.At) || head.History[0].StartTXID != aTake.StartTXID {
+ t.Fatalf("history %+v: want %s ending at %s, then %s", head.History, aTake.Generation, head.CreatedBy.At, seedGen)
+ }
+}
+
+// §4 step 5: the switch is written only with the lease healthy. A
+// poisoned handle and a lost renewal both refuse, and head.json is left
+// as it was.
+func TestSwitchRefusesUnhealthyLease(t *testing.T) {
+ for name, spoil := range map[string]func(h *lease.Held){
+ "poisoned": func(h *lease.Held) { lease.PoisonForTest(h, errors.New("checkpoint failed")) },
+ "lost": lease.LoseHeldLeaseForTest,
+ } {
+ t.Run(name, func(t *testing.T) {
+ haBox(t)
+ fx := newGenFixture(t)
+ fx.seed(t, time.Minute, 3)
+ h := fx.acquire(t, time.Minute)
+ tk, err := h.StartGeneration(ctx, fx.st, fx.vs, lease.TakeOptions{Self: selfA, Lifetime: "L2"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ body, _ := fx.m.Current(fx.bucket, fx.loc+"/head.json")
+ spoil(h)
+ if err := tk.Switch(ctx); err == nil {
+ t.Fatal("switch on an unhealthy lease succeeded")
+ }
+ if after, _ := fx.m.Current(fx.bucket, fx.loc+"/head.json"); !bytes.Equal(after, body) {
+ t.Fatalf("head.json changed: %s", after)
+ }
+ })
+ }
+}
+
+// Before its switch a take's holder never replicates (it would write the
+// root, or a generation head.json does not name); after it, Replicate
+// writes only under g-N.
+func TestReplicateBeforeSwitchRefuses(t *testing.T) {
+ haBox(t)
+ fx := newGenFixture(t)
+ fx.seed(t, time.Minute, 3)
+ fx.setPhase("take")
+ h := fx.acquire(t, time.Minute)
+ tk, err := h.StartGeneration(ctx, fx.st, fx.vs, lease.TakeOptions{Self: selfA, Lifetime: "L2"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ path := filepath.Join(t.TempDir(), "w.example.com.db")
+ 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 := tk.Switch(ctx); err != nil {
+ t.Fatal(err)
+ }
+ r, err := h.Replicate(ctx, path, 0)
+ if err != nil {
+ t.Fatalf("Replicate after the switch: %v", err)
+ }
+ witnessExec(t, path, `INSERT INTO t (body) VALUES ('after')`)
+ if err := r.SyncAndWait(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if err := r.Close(ctx); err != nil {
+ t.Fatal(err)
+ }
+ var replica []string
+ for _, k := range fx.keys("take", false) {
+ if !isControlKey([]string{k}) {
+ replica = append(replica, k)
+ }
+ }
+ requireUnder(t, fx, replica, tk.Generation)
+}
+
+// §5.1: after Replicate returns (the Held is spent; the writer checks the
+// renewer it carries), a write, a compaction, Litestream's L0 retention
+// and the final sync all go to g-N and nowhere else. Retention is on: the
+// expired L0 objects are gone (a delete marker is current).
+func TestGenerationWriterRunsRetention(t *testing.T) {
+ haBox(t)
+ fx := newGenFixture(t)
+ fx.seed(t, time.Minute, 3)
+ fx.setPhase("take")
+ h := fx.acquire(t, time.Minute)
+ tk, err := h.StartGeneration(ctx, fx.st, fx.vs, lease.TakeOptions{Self: selfA, Lifetime: "L2"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ var copies []string
+ for _, k := range fx.keys("take", true) {
+ if !isControlKey([]string{k}) {
+ copies = append(copies, k)
+ }
+ }
+ requireUnder(t, fx, copies, tk.Generation)
+ path := filepath.Join(t.TempDir(), "w.example.com.db")
+ if ok, err := lease.RestoreTake(ctx, path, tk); err != nil || !ok {
+ t.Fatalf("restore: %v %v", ok, err)
+ }
+ if err := tk.Switch(ctx); err != nil {
+ t.Fatal(err)
+ }
+ r, err := h.Replicate(ctx, path, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !lease.RetentionEnabledForTest(r) {
+ t.Fatal("the generation writer's store has retention off")
+ }
+ if err := h.Err(); !errors.Is(err, lease.ErrSpent) {
+ t.Fatalf("fixture: the Held after Replicate: %v, want spent", err)
+ }
+ time.Sleep(1500 * time.Millisecond) // the Open passes
+ for i := range 3 {
+ witnessExec(t, path, fmt.Sprintf(`INSERT INTO t (body) VALUES ('w-%d')`, i))
+ if err := r.SyncAndWait(ctx); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := lease.CompactForTest(r, 1); err != nil {
+ t.Fatalf("compaction: %v", err)
+ }
+ if err := lease.EnforceL0RetentionForTest(r); err != nil {
+ t.Fatalf("L0 retention: %v", err)
+ }
+ deleted := fx.deletes("take")
+ if len(deleted) == 0 {
+ t.Fatal("L0 retention deleted nothing")
+ }
+ requireUnder(t, fx, deleted, tk.Generation)
+ for _, k := range deleted {
+ if _, ok := fx.m.Current(fx.bucket, k); ok {
+ t.Errorf("%s: retention's delete left it current", k)
+ }
+ if !strings.HasPrefix(k, replicagen.Prefix(fx.loc, tk.Generation)+"0000/") {
+ t.Errorf("%s: L0 retention deleted outside L0", k)
+ }
+ }
+ witnessExec(t, path, `INSERT INTO t (body) VALUES ('final')`)
+ if _, err := r.Finish(ctx); err != nil {
+ t.Fatalf("final sync: %v", err)
+ }
+ if err := r.Close(ctx); err != nil {
+ t.Fatal(err)
+ }
+ var replica []string
+ for _, k := range fx.keys("take", false) {
+ if !isControlKey([]string{k}) {
+ replica = append(replica, k)
+ }
+ }
+ requireUnder(t, fx, replica, tk.Generation)
+ if !slices.ContainsFunc(replica, func(k string) bool { return strings.HasPrefix(k, replicagen.Prefix(fx.loc, tk.Generation)+"0001/") }) {
+ t.Fatalf("no compaction write at %s0001/: %v", replicagen.Prefix(fx.loc, tk.Generation), replica)
+ }
+ c := filepath.Join(t.TempDir(), "c.db")
+ if ok, err := lease.Restore(ctx, c, fx.bucket, fx.loc, fx.region); err != nil || !ok {
+ t.Fatalf("restore through head.json: %v %v", ok, err)
+ }
+ if n := witnessCount(t, c, `body = 'final'`); n != 1 {
+ t.Fatalf("restore holds the final row %d times, want 1", n)
+ }
+}
+
+// §5.1: once the lease is lost the writer refuses: nothing more reaches
+// the bucket.
+func TestGenerationWriterRefusesOnceTheLeaseIsLost(t *testing.T) {
+ haBox(t)
+ t.Cleanup(lease.SetShutdownSyncTimeoutForTest(0)) // the abandon's final sync is refused: no retries
+ fx := newGenFixture(t)
+ h := fx.acquire(t, time.Minute)
+ tk, err := h.StartGeneration(ctx, fx.st, fx.vs, lease.TakeOptions{First: true, Self: selfA, Lifetime: "L1"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ 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 ('row-0')`)
+ r, err := h.Replicate(ctx, path, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := r.SyncAndWait(ctx); err != nil {
+ t.Fatal(err)
+ }
+ time.Sleep(1500 * time.Millisecond) // the Open passes
+ lost := errors.New("renewal: AccessDenied")
+ lease.LoseLeaseForTest(r, lost)
+ fx.setPhase("lost")
+ witnessExec(t, path, `INSERT INTO t (body) VALUES ('after')`)
+ if err := r.SyncAndWait(ctx); !errors.Is(err, lost) {
+ t.Fatalf("a sync after the lease was lost: %v, want the writer's refusal (%v)", err, lost)
+ }
+ if err := lease.CompactForTest(r, 1); !errors.Is(err, lost) {
+ t.Fatalf("a compaction after the lease was lost: %v, want the writer's refusal (%v)", err, lost)
+ }
+ r.Abandon(ctx)
+ for _, k := range fx.keys("lost", false) {
+ if !isControlKey([]string{k}) {
+ t.Errorf("written after the lease was lost: %s", k)
+ }
+ }
+ _ = tk
+}
diff --git a/internal/lease/lease.go b/internal/lease/lease.go
index faf95beef..ea2239d25 100644
--- a/internal/lease/lease.go
+++ b/internal/lease/lease.go
@@ -149,6 +149,10 @@ type Held struct {
poison error
replicaClient litestream.ReplicaClient // private local-replica test seam
generationPrefix string
+ // take is the handle's storage-generations take (StartGeneration):
+ // once set, a store writes only through its generation writer, and
+ // only after its Switch. Guarded by mu.
+ take *Take
// owed is the lease record a failed Release could not delete (#292).
// Release spends the handle either way; RetryRelease re-issues the
// same conditional delete until it lands or the lease is no longer
@@ -469,6 +473,13 @@ func (h *Held) Replicate(ctx context.Context, dbPath string, syncInterval time.D
}
func (h *Held) newStore(dbPath string, syncInterval time.Duration) (*litestream.Store, *litestream.DB, error) {
+ // A take's handle writes only into its switched generation (§5.1);
+ // refused before anything is built, so a refusal leaves the handle's
+ // releases settled.
+ takeClient, err := h.takeWriter()
+ if err != nil {
+ return nil, nil, err
+ }
db := litestream.NewDB(dbPath)
// Preserve the activator namespace: sharing the default metadata directory
// with another replicator corrupts shadow state even across sequential runs.
@@ -481,8 +492,10 @@ func (h *Held) newStore(dbPath string, syncInterval time.Duration) (*litestream.
}
h.mu.Unlock()
client := h.replicaClient
+ if takeClient != nil {
+ client = takeClient
+ }
if client == nil {
- var err error
client, err = newReplicaClient(h.leaser.Bucket, h.leaser.Path, h.region)
if err != nil {
return nil, nil, err
@@ -499,6 +512,8 @@ func (h *Held) newStore(dbPath string, syncInterval time.Duration) (*litestream.
}
store.SnapshotInterval = SnapshotInterval
store.SnapshotRetention = SnapshotRetention
+ // A claim binding keeps retention off; a take's generation writer
+ // (generationPrefix unset) keeps it on: its deletes stay inside g-N.
if h.generationPrefix != "" {
// NewStore resets the DB flag. Set all three store/DB/compactor flags
// afterward, before Open starts any monitor or compaction work.
diff --git a/internal/lease/leasetest/s3server.go b/internal/lease/leasetest/s3server.go
index ee7819d3b..59268778a 100644
--- a/internal/lease/leasetest/s3server.go
+++ b/internal/lease/leasetest/s3server.go
@@ -58,7 +58,7 @@ func s3errMsg(w http.ResponseWriter, status int, code, msg string) {
io.WriteString(w, "<Error><Code>"+code+"</Code><Message>"+msg+"</Message></Error>")
}
-// readValidatedBody reads a PUT's body and checks it as real S3 does: its
+// readValidatedBody reads a PUT's (or POST's) body and checks it as real S3 does: its
// length must equal the declared Content-Length (when one is declared), and,
// when x-amz-content-sha256 is a hex digest, its sha256 must equal it. Any
// other value of that header (UNSIGNED-PAYLOAD, a streaming marker) or none
@@ -107,7 +107,7 @@ func writeErr(w http.ResponseWriter, err error) {
}
// NewS3Server speaks the subset of the S3 wire protocol VersionedStore uses,
-// and ListObjectsV2 (serveListV2), path-style, over f, holding f.mu for each request. The second result
+// ListObjectsV2 (serveListV2) and DeleteObjects (serveDeleteObjects), path-style, over f, holding f.mu for each request. The second result
// counts requests served. With serves non-empty, the endpoint answers only
// for those request buckets (a regional endpoint); any other bucket gets
// 301 PermanentRedirect, as S3 answers a wrong-region request. A copy's
@@ -132,7 +132,7 @@ func NewS3Server(f *VersionedBucket, serves ...string) (http.Handler, func() int
return
}
var body []byte
- if r.Method == http.MethodPut { // every PUT, a copy included, is validated before it is applied
+ if r.Method == http.MethodPut || r.Method == http.MethodPost { // every PUT, a copy included, and every DeleteObjects body is validated before it is applied
var ok bool
if body, ok = readValidatedBody(w, r); !ok {
return
@@ -191,6 +191,8 @@ func NewS3Server(f *VersionedBucket, serves ...string) (http.Handler, func() int
w.WriteHeader(http.StatusPartialContent)
}
w.Write(body)
+ case r.Method == http.MethodPost && key == "" && q.Has("delete"):
+ f.serveDeleteObjects(w, bucket, body)
case r.Method == http.MethodPut && r.Header.Get("x-amz-copy-source") != "":
f.serveCopy(w, r, bucket, key)
case r.Method == http.MethodPut:
@@ -460,3 +462,81 @@ func (f *VersionedBucket) serveCopy(w http.ResponseWriter, r *http.Request, buck
w.Header().Set("Content-Type", "application/xml")
io.WriteString(w, `<CopyObjectResult><ETag>"`+etag+`"</ETag><LastModified>2026-10-05T00:00:00Z</LastModified></CopyObjectResult>`)
}
+
+type deleteRequest struct {
+ XMLName xml.Name `xml:"Delete"`
+ Quiet bool
+ Objects []struct {
+ Key string
+ VersionId string
+ } `xml:"Object"`
+}
+
+type xmlDeleted struct {
+ XMLName xml.Name `xml:"Deleted"`
+ Key string
+ VersionId string `xml:",omitempty"`
+ DeleteMarker bool `xml:",omitempty"`
+ DeleteMarkerVersionId string `xml:",omitempty"`
+}
+
+type xmlDeleteError struct {
+ XMLName xml.Name `xml:"Error"`
+ Key string
+ VersionId string `xml:",omitempty"`
+ Code string
+ Message string
+}
+
+type deleteResult struct {
+ XMLName xml.Name `xml:"DeleteResult"`
+ Entries []any
+}
+
+// maxDeleteObjects is S3's limit on the keys of one DeleteObjects request.
+const maxDeleteObjects = 1000
+
+// serveDeleteObjects is DeleteObjects (POST /bucket?delete), as S3 answers
+// it on a versioned bucket. Each object is deleted on its own: a bare key
+// adds a delete marker and removes nothing (Deleted with DeleteMarker and
+// its DeleteMarkerVersionId; a key with no object gets a marker too, as
+// S3 does), a key with a VersionId removes that exact version (Deleted
+// with the VersionId, and DeleteMarker when the version was one). A
+// failed object (FailOn "delete") is an Error entry and the rest still
+// go. Quiet answers with the errors only. A body that is not a Delete,
+// names no object or more than 1000 is 400 MalformedXML, nothing deleted.
+func (f *VersionedBucket) serveDeleteObjects(w http.ResponseWriter, bucket string, body []byte) {
+ var req deleteRequest
+ if err := xml.Unmarshal(body, &req); err != nil || len(req.Objects) == 0 || len(req.Objects) > maxDeleteObjects {
+ s3errMsg(w, http.StatusBadRequest, "MalformedXML", "The XML you provided was not well-formed or did not validate against our published schema.")
+ return
+ }
+ var res deleteResult
+ for _, o := range req.Objects {
+ if o.VersionId == "" {
+ id, err := f.bareDeleteLocked(bucket, o.Key)
+ if err != nil {
+ res.Entries = append(res.Entries, xmlDeleteError{Key: o.Key, Code: "InternalError", Message: err.Error()})
+ continue
+ }
+ if !req.Quiet {
+ res.Entries = append(res.Entries, xmlDeleted{Key: o.Key, DeleteMarker: true, DeleteMarkerVersionId: id})
+ }
+ continue
+ }
+ v, found := f.find(bucket, o.Key, o.VersionId)
+ if err := f.deleteLocked(bucket, o.Key, o.VersionId); err != nil {
+ res.Entries = append(res.Entries, xmlDeleteError{Key: o.Key, VersionId: o.VersionId, Code: "InternalError", Message: err.Error()})
+ continue
+ }
+ if !req.Quiet {
+ d := xmlDeleted{Key: o.Key, VersionId: o.VersionId}
+ if found && v.deleteMarker {
+ d.DeleteMarker, d.DeleteMarkerVersionId = true, o.VersionId
+ }
+ res.Entries = append(res.Entries, d)
+ }
+ }
+ w.Header().Set("Content-Type", "application/xml")
+ xml.NewEncoder(w).Encode(res)
+}
diff --git a/internal/lease/leasetest/s3server_test.go b/internal/lease/leasetest/s3server_test.go
index 93e5efee8..3e7ed82d3 100644
--- a/internal/lease/leasetest/s3server_test.go
+++ b/internal/lease/leasetest/s3server_test.go
@@ -419,3 +419,75 @@ func TestS3ServerListObjectsV2PaginatesTheSDK(t *testing.T) {
}
}
}
+
+// DeleteObjects on a versioned bucket: a bare key gets a delete marker
+// (Deleted, DeleteMarker, its version id) and its versions stay; a key
+// with a VersionId loses that version only. Quiet reports errors only.
+func TestS3ServerDeleteObjects(t *testing.T) {
+ for _, quiet := range []bool{false, true} {
+ t.Run(fmt.Sprintf("quiet=%v", quiet), func(t *testing.T) {
+ m := NewVersionedBucket()
+ m.AddBucket("data")
+ h, _ := NewS3Server(m)
+ v1 := m.Put("data", "g/0000/a.ltx", []byte("a1"))
+ m.Put("data", "g/0000/a.ltx", []byte("a2"))
+ m.Put("data", "g/0000/b.ltx", []byte("b"))
+ m.FailOn = func(op, key string) error {
+ if op == "delete" && key == "g/0000/fail.ltx" {
+ return errors.New("injected")
+ }
+ return nil
+ }
+ body := fmt.Sprintf(`<Delete xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Object><Key>g/0000/b.ltx</Key></Object>`+
+ `<Object><Key>g/0000/a.ltx</Key><VersionId>%s</VersionId></Object><Object><Key>g/0000/fail.ltx</Key></Object><Quiet>%v</Quiet></Delete>`, v1, quiet)
+ rec := do(t, h, http.MethodPost, "/data?delete", body, nil)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("DeleteObjects: %d %s", rec.Code, rec.Body)
+ }
+ var res struct {
+ Deleted []struct {
+ Key, VersionId string
+ DeleteMarker bool
+ DeleteMarkerVersionId string
+ }
+ Error []struct{ Key, Code string }
+ }
+ if err := xml.Unmarshal(rec.Body.Bytes(), &res); err != nil {
+ t.Fatalf("%v: %s", err, rec.Body)
+ }
+ if len(res.Error) != 1 || res.Error[0].Key != "g/0000/fail.ltx" || res.Error[0].Code != "InternalError" {
+ t.Fatalf("errors %+v", res.Error)
+ }
+ if quiet && len(res.Deleted) != 0 {
+ t.Fatalf("quiet answered deletions: %+v", res.Deleted)
+ }
+ if !quiet {
+ if len(res.Deleted) != 2 || res.Deleted[0].Key != "g/0000/b.ltx" || !res.Deleted[0].DeleteMarker || res.Deleted[0].DeleteMarkerVersionId == "" ||
+ res.Deleted[1].Key != "g/0000/a.ltx" || res.Deleted[1].VersionId != v1 || res.Deleted[1].DeleteMarker {
+ t.Fatalf("deleted %+v", res.Deleted)
+ }
+ }
+ if _, ok := m.Current("data", "g/0000/b.ltx"); ok {
+ t.Fatal("b is still current after a bare delete")
+ }
+ if got, _ := m.Current("data", "g/0000/a.ltx"); string(got) != "a2" {
+ t.Fatalf("a's current %q after deleting its old version", got)
+ }
+ if _, err := m.GetVersion(context.Background(), "data", "g/0000/a.ltx", v1); !errors.Is(err, lease.ErrMirrorNotFound) {
+ t.Fatalf("a's deleted version: %v", err)
+ }
+ vs, _ := m.ListVersions(context.Background(), "data", "g/0000/b.ltx")
+ if len(vs) != 2 || !vs[0].DeleteMarker || vs[1].DeleteMarker {
+ t.Fatalf("b's versions %+v: want a marker over the object", vs)
+ }
+ })
+ }
+ m := NewVersionedBucket()
+ m.AddBucket("data")
+ h, _ := NewS3Server(m)
+ for _, body := range []string{"not xml", "<Delete></Delete>"} {
+ if rec := do(t, h, http.MethodPost, "/data?delete", body, nil); rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "MalformedXML") {
+ t.Fatalf("%q: %d %s", body, rec.Code, rec.Body)
+ }
+ }
+}
diff --git a/internal/lease/stale_holder_witness_test.go b/internal/lease/stale_holder_witness_test.go
new file mode 100644
index 000000000..1949f5caf
--- /dev/null
+++ b/internal/lease/stale_holder_witness_test.go
@@ -0,0 +1,213 @@
+package lease_test
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "net/http"
+ "path/filepath"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/replicagen"
+)
+
+// The witness of the wake-race review's P1 (it was
+// TestWitnessLateWriteFromAnEarlierHolderKeepsTheSuccessorsHistory on
+// branch witness-stale-holder-late-write, 8e8a00a0, legacy leases), for
+// region HA with storage generations (spec 2026-11-12 §12, first item).
+//
+// Holder A replicates rows up to TXID P into its own generation, then
+// commits one more transaction ("a-only") whose L0 upload [P+1..P+1]
+// reaches the server but gets no answer: a partition, a timeout, a box
+// that dies. A's release goes through anyway (lock.json is not
+// partitioned), unclean. Successor B takes the lock, starts its own
+// generation as a copy of A's at P (A's upload is not applied yet),
+// restores from it and switches head.json to it. Its first sync writes its
+// own L0 [P+1..P+1], then its row ("b-only") at P+2. Only then does the
+// server apply A's held requests.
+//
+// On the shared root prefix (8e8a00a0) A's object replaced B's, because
+// the S3 write carries no ownership condition. With generations A's late
+// write lands under A's own generation, which nobody reads as current:
+// nothing B wrote is replaced, and the restore through head.json holds
+// B's row and not A's.
+func TestWitnessLateWriteFromAnEarlierHolderKeepsTheSuccessorsHistory(t *testing.T) {
+ const ttl = 3 * time.Second
+ haBox(t)
+ fx := newGenFixture(t)
+ bucket, prefix, region := fx.bucket, fx.loc, fx.region
+
+ // The partition: while it is on, every replica write that reaches the
+ // server (lock.json aside, so A's release goes through) is read in
+ // full, as S3 would have received it, and held unapplied until heal.
+ var (
+ partitioned atomic.Bool
+ healed = make(chan struct{})
+ held sync.WaitGroup
+ mu sync.Mutex
+ heldKeys []string
+ )
+ fx.setHook(func(r *http.Request, keys []string) {
+ if !partitioned.Load() || r.Method == http.MethodGet || isControlKey(keys) {
+ return
+ }
+ held.Add(1)
+ defer held.Done()
+ mu.Lock()
+ heldKeys = append(heldKeys, keys...)
+ mu.Unlock()
+ <-healed
+ })
+ heal := sync.OnceFunc(func() { close(healed) })
+ t.Cleanup(heal)
+ ctx := context.Background()
+
+ // A: a first wake into its own empty generation; rows 0-9 replicated,
+ // P confirmed.
+ fx.setPhase("a")
+ aPath := filepath.Join(t.TempDir(), "w.example.com.db")
+ witnessExec(t, aPath, `PRAGMA journal_mode=WAL`, `CREATE TABLE t (id INTEGER PRIMARY KEY, body TEXT)`)
+ for i := range 10 {
+ witnessExec(t, aPath, fmt.Sprintf(`INSERT INTO t (body) VALUES ('row-%d')`, i))
+ }
+ aHeld := fx.acquire(t, ttl)
+ aTake, err := aHeld.StartGeneration(ctx, fx.st, fx.vs, lease.TakeOptions{First: true, Self: selfA, Lifetime: "L1"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := aTake.Switch(ctx); err != nil {
+ t.Fatal(err)
+ }
+ aGen := replicagen.Name(aHeld.LockGeneration())
+ a, err := aHeld.Replicate(ctx, aPath, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := a.SyncAndWait(ctx); err != nil {
+ t.Fatal(err)
+ }
+
+ // A's next transaction reaches the server unanswered; its release's
+ // final sync times out, and the marker goes through.
+ partitioned.Store(true)
+ witnessExec(t, aPath, `INSERT INTO t (body) VALUES ('a-only')`)
+ closeCtx, cancel := context.WithTimeout(ctx, time.Second)
+ _ = a.Close(closeCtx)
+ cancel()
+ mu.Lock()
+ aHeldKeys := append([]string(nil), heldKeys...)
+ mu.Unlock()
+ if len(aHeldKeys) == 0 {
+ t.Fatal("fixture: no write of A's reached the server")
+ }
+ partitioned.Store(false) // B's writes go through
+
+ // B: takes the lock once A's unclean marker opens (the acquire table
+ // is unchanged until slice 4), starts its generation, restores from
+ // it, switches head.json and writes its own row.
+ body, _ := fx.m.Current(bucket, prefix+"/lock.json")
+ v, err := hafresh.DecodeLock(body, "")
+ if err != nil || v.Lock.Release == nil {
+ t.Fatalf("A's marker: %+v %v", v.Lock.Release, err)
+ }
+ time.Sleep(time.Until(v.Lock.Release.At.Add(ttl)) + 200*time.Millisecond)
+ boxB()
+ fx.setPhase("b")
+ bPath := filepath.Join(t.TempDir(), "w.example.com.db")
+ bHeld := fx.acquire(t, ttl)
+ bTake, err := bHeld.StartGeneration(ctx, fx.st, fx.vs, lease.TakeOptions{Self: selfB, Lifetime: "L2"})
+ if err != nil {
+ t.Fatalf("B's take: %v", err)
+ }
+ if ok, err := lease.RestoreTake(ctx, bPath, bTake); err != nil || !ok {
+ t.Fatalf("B restore: %v %v", ok, err)
+ }
+ if n := witnessCount(t, bPath, `body = 'a-only'`); n != 0 {
+ t.Fatalf("fixture: B restored A's unanswered write (%d)", n)
+ }
+ if err := bTake.Switch(ctx); err != nil {
+ t.Fatalf("B's switch: %v", err)
+ }
+ b, err := bHeld.Replicate(ctx, bPath, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := b.SyncAndWait(ctx); err != nil {
+ t.Fatal(err)
+ }
+ // B's store runs one compaction and snapshot pass at Open (retried a
+ // second later while the database is not ready). Let it finish before
+ // B's row, so the row lives only in B's L0, as a successor's first
+ // writes do until its next compaction.
+ time.Sleep(1500 * time.Millisecond)
+ witnessExec(t, bPath, `INSERT INTO t (body) VALUES ('b-only')`)
+ if err := b.SyncAndWait(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if err := b.Close(ctx); err != nil {
+ t.Fatal(err)
+ }
+
+ // Everything B wrote, as it stands before the heal.
+ bBodies := map[string][]byte{}
+ for _, k := range fx.keys("b", true) {
+ if isControlKey([]string{k}) {
+ continue
+ }
+ body, _ := fx.m.Current(bucket, k)
+ bBodies[k] = body
+ }
+ if len(bBodies) == 0 {
+ t.Fatal("fixture: B wrote no replica object")
+ }
+
+ // The partition heals: the server applies what A sent.
+ heal()
+ held.Wait()
+ t.Logf("A's held writes, applied after B's history: %v", aHeldKeys)
+
+ // The invariant at the object level, whatever a restore happens to
+ // read: no object of B's history is replaced by A's late writes.
+ for k, before := range bBodies {
+ if after, _ := fx.m.Current(bucket, k); !bytes.Equal(after, before) {
+ t.Errorf("the earlier holder's late write replaced the successor's %s", k)
+ }
+ }
+ // Every replica key A sent, the late ones included, is under A's
+ // generation.
+ for _, k := range fx.keys("a", false) {
+ if isControlKey([]string{k}) {
+ continue
+ }
+ if !strings.HasPrefix(k, replicagen.Prefix(prefix, aGen)) {
+ t.Errorf("A sent %s, outside its generation %s", k, aGen)
+ }
+ }
+
+ res, err := lease.ResolveReplica(ctx, bucket, prefix, region)
+ if err != nil {
+ t.Fatalf("resolve after the late writes: %v", err)
+ }
+ if want := replicagen.Name(bHeld.LockGeneration()); res.Generation != want {
+ t.Errorf("head.json names %s after the late writes, want B's %s", res.Generation, want)
+ }
+ cPath := filepath.Join(t.TempDir(), "w.example.com.db")
+ if ok, err := lease.Restore(ctx, cPath, bucket, prefix, region); err != nil || !ok {
+ t.Fatalf("restore after the late writes: %v %v (the successor's history is unreadable)", ok, err)
+ }
+ if got, want := witnessCount(t, cPath, `body = 'b-only'`), 1; got != want {
+ t.Errorf("the restore lost the successor's row: b-only %d, want %d", got, want)
+ }
+ if got := witnessCount(t, cPath, `body = 'a-only'`); got != 0 {
+ t.Errorf("the restore holds the earlier holder's unanswered row: a-only %d, want 0", got)
+ }
+ if got, want := witnessCount(t, cPath, `body LIKE 'row-%'`), 10; got != want {
+ t.Errorf("the restore holds %d of the shared rows, want %d", got, want)
+ }
+}