carlos / platform Public

lease: plan a generation start at the newest L0 and copy it

PlanStart lists the current generation G once (head.json's generation,
or the root layout without a head), keeps current LTX versions only,
takes T as the newest L0 MaxTXID and plans with litestream's
CalcRestorePlan over a pinned client serving files at most T. The copy
set is the plan plus the L0 ending at T. Refusals (*StartRefusal):
no_l0, no_plan_to_l0, clean_marker_above_l0, empty_plan_with_data,
file_over_5gib. A failed listing is an error, never a refusal. An
empty first generation (start_txid 0, no predecessor, no LTX) plans
Empty.

CopyStart copies each planned file by exact version id, create-only,
to the same level and name under g-N/, at most eight in flight; the
first failure cancels the rest and is returned (spec §4 steps 3-4, G3).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 74a48b3d36fe62e11128a184e0c8788c873c4b2f parent 2aa162c
2 files changed, +845 −0
  • internal/lease/genstart.go +300 −0
  • internal/lease/genstart_test.go +545 −0
diff --git a/internal/lease/genstart.go b/internal/lease/genstart.go
new file mode 100644
index 000000000..e012af2cf
--- /dev/null
+++ b/internal/lease/genstart.go
@@ -0,0 +1,300 @@
+package lease
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "os"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/benbjohnson/litestream"
+ "github.com/superfly/ltx"
+
+ "github.com/carlosframework/platform/internal/replicagen"
+)
+
+// The start of a new generation (spec 2026-11-12 region HA storage
+// generations, §4 steps 3-4, invariant G3): list the predecessor G, plan
+// a restore ending exactly at G's newest L0 TXID T, and copy those exact
+// object versions under the new generation's prefix. A write into G after
+// the listing never reaches the copy.
+
+// maxCopyBytes is the single-part CopyObject limit. A planned file above it
+// refuses the take (multipart copy is a follow-up).
+const maxCopyBytes int64 = 5 << 30
+
+// copyParallel bounds the copies in flight.
+const copyParallel = 8
+
+// Refusal reasons: each refuses the wake and raises the suspect-holder page.
+const (
+ RefuseNoL0 = "no_l0" // G holds no L0 file and is not an empty first generation
+ RefuseNoPlanToL0 = "no_plan_to_l0" // no plan over files at most T reaches T
+ 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
+)
+
+// StartRefusal is a take that must not start a generation from G: the
+// state is not one a copy can be proved correct for, and an operator
+// restores by hand. A failed listing or copy is an ordinary error instead.
+type StartRefusal struct{ Reason string }
+
+func (r *StartRefusal) Error() string { return "lease: generation start refused: " + r.Reason }
+
+func refuse(reason, format string, args ...any) error {
+ return fmt.Errorf("%w: "+format, append([]any{&StartRefusal{Reason: reason}}, args...)...)
+}
+
+// PlannedFile is one exact object version of G the start copies.
+type PlannedFile struct {
+ Level int
+ Min, Max uint64
+ Key string // the source key under G's prefix
+ VersionID string
+ Size int64
+}
+
+// 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.
+type StartPlan struct {
+ From string
+ T uint64
+ Files []PlannedFile
+ Empty bool
+}
+
+// PlanStart lists the current generation G (head.Generation, or the root
+// generation when no head was found) and plans its successor's start at
+// G's newest L0 TXID. cleanTXID is the TXID G's clean release marker
+// records, 0 when there is none. It makes exactly one ListVersions call
+// and no other request. A failed listing is an error; a state the start
+// rule cannot copy is a *StartRefusal.
+func PlanStart(ctx context.Context, vs VersionedStore, bucket, loc string, head Head, headFound bool, cleanTXID uint64) (StartPlan, error) {
+ if loc == "" || strings.HasSuffix(loc, "/") {
+ return StartPlan{}, fmt.Errorf("lease: plan start: bad location %q", loc)
+ }
+ from := replicagen.Root
+ if headFound {
+ if head.Generation == replicagen.Root || !replicagen.Valid(head.Generation) {
+ return StartPlan{}, fmt.Errorf("lease: plan start: head.json names generation %q", head.Generation)
+ }
+ from = head.Generation
+ }
+ prefix := replicagen.Prefix(loc, from)
+ listed, err := vs.ListVersions(ctx, bucket, prefix)
+ if err != nil {
+ return StartPlan{}, fmt.Errorf("lease: plan start: list %s: %w", prefix, err)
+ }
+ files := map[ltxPos]ObjectVersion{}
+ for _, v := range listed {
+ if !v.IsLatest || v.DeleteMarker {
+ continue
+ }
+ if pos, ok := parseLTXKey(prefix, v.Key); ok {
+ files[pos] = v
+ }
+ }
+
+ var T uint64
+ for pos := range files {
+ if pos.level == 0 && pos.max > T {
+ T = pos.max
+ }
+ }
+ if T == 0 {
+ 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)
+ }
+ return StartPlan{From: from, Empty: true}, nil
+ }
+ return StartPlan{}, refuse(RefuseNoL0, "%s holds %d LTX files and no L0", from, len(files))
+ }
+ if cleanTXID > T {
+ return StartPlan{}, refuse(RefuseCleanMarkerAboveL0, "%s: clean marker TXID %d, newest L0 %d", from, cleanTXID, T)
+ }
+
+ client := &pinnedLTX{}
+ for pos, v := range files {
+ if pos.max <= T {
+ client.infos = append(client.infos, ltx.FileInfo{Level: pos.level, MinTXID: ltx.TXID(pos.min),
+ MaxTXID: ltx.TXID(pos.max), Size: v.Size, CreatedAt: v.LastModified})
+ }
+ }
+ infos, err := litestream.CalcRestorePlan(ctx, client, ltx.TXID(T), time.Time{}, slog.Default())
+ switch {
+ case errors.Is(err, litestream.ErrTxNotAvailable):
+ return StartPlan{}, refuse(RefuseNoPlanToL0, "%s: no plan reaches its newest L0 %d", from, T)
+ case err != nil:
+ return StartPlan{}, fmt.Errorf("lease: plan start: plan %s to %d: %w", from, T, err)
+ case len(infos) == 0:
+ return StartPlan{}, refuse(RefuseEmptyPlanWithData, "%s: an empty plan over %d LTX files", from, len(files))
+ case uint64(infos[len(infos)-1].MaxTXID) != T:
+ return StartPlan{}, refuse(RefuseNoPlanToL0, "%s: the plan ends at %d, its newest L0 at %d", from, infos[len(infos)-1].MaxTXID, T)
+ }
+
+ plan := StartPlan{From: from, T: T}
+ add := func(pos ltxPos) {
+ v := files[pos]
+ plan.Files = append(plan.Files, PlannedFile{Level: pos.level, Min: pos.min, Max: pos.max, Key: v.Key, VersionID: v.VersionID, Size: v.Size})
+ }
+ for _, info := range infos {
+ add(ltxPos{level: info.Level, min: uint64(info.MinTXID), max: uint64(info.MaxTXID)})
+ }
+ if last := plan.Files[len(plan.Files)-1]; last.Level != 0 {
+ // The L0 file ending at T: Litestream reads its replica position
+ // from L0, so the new generation must hold it. Of several, the
+ // shortest.
+ var l0 *ltxPos
+ for pos := range files {
+ if pos.level == 0 && pos.max == T && (l0 == nil || pos.min > l0.min) {
+ p := pos
+ l0 = &p
+ }
+ }
+ add(*l0)
+ }
+ for _, f := range plan.Files {
+ if f.Size > maxCopyBytes {
+ return StartPlan{}, refuse(RefuseFileOver5GiB, "%s is %d bytes", f.Key, f.Size)
+ }
+ }
+ return plan, nil
+}
+
+// CopyStart copies every planned file, by its exact version id, to the
+// same level and name under generation to's prefix, create-only, with at
+// most eight copies in flight. The first failure cancels the copies not
+// yet done and is returned. An Empty plan copies nothing.
+func CopyStart(ctx context.Context, vs VersionedStore, bucket, loc string, p StartPlan, to string) error {
+ if to == replicagen.Root || !replicagen.Valid(to) || to == p.From {
+ return fmt.Errorf("lease: copy start: bad destination generation %q", to)
+ }
+ if loc == "" || strings.HasSuffix(loc, "/") {
+ return fmt.Errorf("lease: copy start: bad location %q", loc)
+ }
+ if p.Empty {
+ return nil
+ }
+ if len(p.Files) == 0 {
+ return errors.New("lease: copy start: a plan with no files that is not empty")
+ }
+ for _, f := range p.Files {
+ if f.Size > maxCopyBytes {
+ return refuse(RefuseFileOver5GiB, "%s is %d bytes", f.Key, f.Size)
+ }
+ }
+ dst := replicagen.Prefix(loc, to)
+ parent := ctx
+ ctx, cancel := context.WithCancel(ctx)
+ defer cancel()
+ var (
+ wg sync.WaitGroup
+ once sync.Once
+ first error
+ sem = make(chan struct{}, copyParallel)
+ )
+send:
+ for _, f := range p.Files {
+ select {
+ case sem <- struct{}{}:
+ case <-ctx.Done():
+ break send
+ }
+ wg.Add(1)
+ go func(f PlannedFile) {
+ defer wg.Done()
+ defer func() { <-sem }()
+ if ctx.Err() != nil {
+ return
+ }
+ key := dst + ltxRel(f.Level, f.Min, f.Max)
+ if _, _, err := vs.CopyVersion(ctx, bucket, f.Key, f.VersionID, bucket, key, true); err != nil {
+ once.Do(func() {
+ first = fmt.Errorf("lease: copy start: %s@%s -> %s: %w", f.Key, f.VersionID, key, err)
+ cancel()
+ })
+ }
+ }(f)
+ }
+ wg.Wait()
+ if first != nil {
+ return first
+ }
+ return parent.Err()
+}
+
+// ltxPos is an LTX file's place: its level and TXID range.
+type ltxPos struct {
+ level int
+ min, max uint64
+}
+
+// ltxRel is an LTX file's key below a generation prefix, as Litestream's
+// S3 client writes it: a four-digit hex level directory and the file name.
+func ltxRel(level int, min, max uint64) string {
+ return fmt.Sprintf("%04x/%s", level, ltx.FormatFilename(ltx.TXID(min), ltx.TXID(max)))
+}
+
+// parseLTXKey reads key as `<prefix><level>/<min>-<max>.ltx` in exactly
+// Litestream's form, level 0 to SnapshotLevel and 1 <= min <= max.
+// Anything else (lock.json, head.json, files/, another generation's
+// subtree, a stray object) is not an LTX file of this generation.
+func parseLTXKey(prefix, key string) (ltxPos, bool) {
+ rel, ok := strings.CutPrefix(key, prefix)
+ if !ok {
+ return ltxPos{}, false
+ }
+ dir, name, ok := strings.Cut(rel, "/")
+ if !ok || len(dir) != 4 || strings.Contains(name, "/") {
+ return ltxPos{}, false
+ }
+ level, err := strconv.ParseUint(dir, 16, 16)
+ if err != nil || level > litestream.SnapshotLevel || fmt.Sprintf("%04x", level) != dir {
+ return ltxPos{}, false
+ }
+ min, max, err := ltx.ParseFilename(name)
+ if err != nil || min == 0 || min > max || ltx.FormatFilename(min, max) != name {
+ return ltxPos{}, false
+ }
+ return ltxPos{level: int(level), min: uint64(min), max: uint64(max)}, true
+}
+
+// pinnedLTX is a ReplicaClient over a fixed set of listed files, for
+// planning only: it serves listings and never opens, writes or deletes.
+type pinnedLTX struct{ infos []ltx.FileInfo }
+
+func (*pinnedLTX) Type() string { return "generation-start" }
+func (*pinnedLTX) Init(context.Context) error { return nil }
+func (*pinnedLTX) SetLogger(*slog.Logger) {}
+
+func (c *pinnedLTX) LTXFiles(_ context.Context, level int, seek ltx.TXID, _ bool) (ltx.FileIterator, error) {
+ var out []*ltx.FileInfo
+ for i := range c.infos {
+ if c.infos[i].Level == level && c.infos[i].MinTXID >= seek {
+ info := c.infos[i] // a copy: the iterator sorts in place
+ out = append(out, &info)
+ }
+ }
+ sort.Slice(out, func(i, j int) bool { return out[i].MinTXID < out[j].MinTXID })
+ return ltx.NewFileInfoSliceIterator(out), nil
+}
+
+var errPlanOnly = errors.New("lease: the generation start client only plans")
+
+func (*pinnedLTX) OpenLTXFile(context.Context, int, ltx.TXID, ltx.TXID, int64, int64) (io.ReadCloser, error) {
+ return nil, fmt.Errorf("%w: %w", errPlanOnly, os.ErrNotExist)
+}
+func (*pinnedLTX) WriteLTXFile(context.Context, int, ltx.TXID, ltx.TXID, io.Reader) (*ltx.FileInfo, error) {
+ return nil, errPlanOnly
+}
+func (*pinnedLTX) DeleteLTXFiles(context.Context, []*ltx.FileInfo) error { return errPlanOnly }
+func (*pinnedLTX) DeleteAll(context.Context) error { return errPlanOnly }
diff --git a/internal/lease/genstart_test.go b/internal/lease/genstart_test.go
new file mode 100644
index 000000000..f7e003697
--- /dev/null
+++ b/internal/lease/genstart_test.go
@@ -0,0 +1,545 @@
+package lease_test
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
+ "github.com/superfly/ltx"
+
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/lease/leasetest"
+ "github.com/carlosframework/platform/internal/replicagen"
+)
+
+const (
+ gsBucket = "data"
+ gsLoc = "instances/shop.example.com"
+)
+
+var (
+ gsFrom = replicagen.Name(41) // the predecessor generation G
+ gsTo = replicagen.Name(42) // the generation the take starts
+)
+
+// ltxKey is the object key of an LTX file of generation gen under gsLoc,
+// as litestream's S3 client writes it.
+func ltxKey(gen string, level int, min, max uint64) string {
+ return fmt.Sprintf("%s%04x/%s", replicagen.Prefix(gsLoc, gen), level, ltx.FormatFilename(ltx.TXID(min), ltx.TXID(max)))
+}
+
+// genHead is a head.json naming gen as the current generation of a take
+// that copied from an earlier generation.
+func genHead(gen string) lease.Head {
+ return lease.Head{V: 1, Generation: gen, StartTXID: 7, Predecessor: replicagen.Name(30)}
+}
+
+// countingStore counts every request a VersionedStore makes, can rewrite
+// listed sizes, and can intercept copies.
+type countingStore struct {
+ lease.VersionedStore
+ mu sync.Mutex
+ lists int
+ copies int
+ other int
+ inFlight int
+ maxInFlight int
+ sizes map[string]int64 // key -> listed size override
+ onCopy func(ctx context.Context, key string, inFlight int) error // runs before the copy; an error fails it
+}
+
+func newCounting(vs lease.VersionedStore) *countingStore { return &countingStore{VersionedStore: vs} }
+
+func (c *countingStore) ListVersions(ctx context.Context, bucket, prefix string) ([]lease.ObjectVersion, error) {
+ c.mu.Lock()
+ c.lists++
+ c.mu.Unlock()
+ vs, err := c.VersionedStore.ListVersions(ctx, bucket, prefix)
+ for i := range vs {
+ if s, ok := c.sizes[vs[i].Key]; ok {
+ vs[i].Size = s
+ }
+ }
+ return vs, err
+}
+
+func (c *countingStore) CopyVersion(ctx context.Context, srcBucket, srcKey, srcVersionID, dstBucket, dstKey string, createOnly bool) (string, string, error) {
+ c.mu.Lock()
+ c.copies++
+ c.inFlight++
+ if c.inFlight > c.maxInFlight {
+ c.maxInFlight = c.inFlight
+ }
+ n := c.inFlight
+ c.mu.Unlock()
+ defer func() {
+ c.mu.Lock()
+ c.inFlight--
+ c.mu.Unlock()
+ }()
+ if c.onCopy != nil {
+ if err := c.onCopy(ctx, srcKey, n); err != nil {
+ return "", "", err
+ }
+ }
+ return c.VersionedStore.CopyVersion(ctx, srcBucket, srcKey, srcVersionID, dstBucket, dstKey, createOnly)
+}
+
+func (c *countingStore) count(p *int) {
+ c.mu.Lock()
+ *p++
+ c.mu.Unlock()
+}
+
+func (c *countingStore) GetVersion(ctx context.Context, bucket, key, versionID string) ([]byte, error) {
+ c.count(&c.other)
+ return c.VersionedStore.GetVersion(ctx, bucket, key, versionID)
+}
+
+func (c *countingStore) DeleteVersion(ctx context.Context, bucket, key, versionID string) error {
+ c.count(&c.other)
+ return c.VersionedStore.DeleteVersion(ctx, bucket, key, versionID)
+}
+
+func (c *countingStore) PutIfAbsent(ctx context.Context, bucket, key string, body []byte) (string, error) {
+ c.count(&c.other)
+ return c.VersionedStore.PutIfAbsent(ctx, bucket, key, body)
+}
+
+func (c *countingStore) snapshot() (lists, copies, other int) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.lists, c.copies, c.other
+}
+
+func newGenBucket() *leasetest.VersionedBucket {
+ m := leasetest.NewVersionedBucket()
+ m.AddBucket(gsBucket)
+ return m
+}
+
+type ltxSpec struct {
+ level int
+ min, max uint64
+}
+
+// putLTX writes one object per spec into generation gen, body "<key>".
+func putLTX(m *leasetest.VersionedBucket, gen string, files ...ltxSpec) {
+ for _, f := range files {
+ k := ltxKey(gen, f.level, f.min, f.max)
+ m.Put(gsBucket, k, []byte("body of "+k))
+ }
+}
+
+func planPositions(p lease.StartPlan) []string {
+ var out []string
+ for _, f := range p.Files {
+ out = append(out, fmt.Sprintf("L%d[%d..%d]", f.Level, f.Min, f.Max))
+ }
+ return out
+}
+
+func wantPlan(t *testing.T, p lease.StartPlan, from string, T uint64, positions ...string) {
+ t.Helper()
+ if p.From != from || p.T != T || p.Empty {
+ t.Fatalf("plan From=%q T=%d Empty=%v, want From=%q T=%d", p.From, p.T, p.Empty, from, T)
+ }
+ if got := strings.Join(planPositions(p), " "); got != strings.Join(positions, " ") {
+ t.Fatalf("plan files %s, want %s", got, strings.Join(positions, " "))
+ }
+}
+
+func wantRefusal(t *testing.T, err error, reason string) {
+ t.Helper()
+ var r *lease.StartRefusal
+ if !errors.As(err, &r) {
+ t.Fatalf("err = %v, want a *StartRefusal %q", err, reason)
+ }
+ if r.Reason != reason {
+ t.Fatalf("refusal reason %q, want %q (err %v)", r.Reason, reason, err)
+ }
+}
+
+// A snapshot that ran ahead of the uploaded L0 is not copied: the plan
+// ends at the newest L0 from the older snapshot (spec §4 step 4).
+func TestPlanStartSkipsSnapshotAboveL0(t *testing.T) {
+ m := newGenBucket()
+ putLTX(m, gsFrom, ltxSpec{9, 1, 9}, ltxSpec{9, 1, 12}, ltxSpec{0, 10, 10})
+ cs := newCounting(m)
+ p, err := lease.PlanStart(context.Background(), cs, gsBucket, gsLoc, genHead(gsFrom), true, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ wantPlan(t, p, gsFrom, 10, "L9[1..9]", "L0[10..10]")
+ for _, f := range p.Files {
+ if f.Key != ltxKey(gsFrom, f.Level, f.Min, f.Max) || f.VersionID != m.LatestID(gsBucket, f.Key) || f.Size == 0 {
+ t.Fatalf("planned file %+v does not name the listed current version", f)
+ }
+ }
+}
+
+// A drain release leaves one snapshot and one L0 at the same TXID; both
+// are copied, by exact version, under the new generation.
+func TestPlanStartDrainRelease(t *testing.T) {
+ m := newGenBucket()
+ putLTX(m, gsFrom, ltxSpec{9, 1, 20}, ltxSpec{0, 20, 20})
+ cs := newCounting(m)
+ ctx := context.Background()
+ p, err := lease.PlanStart(ctx, cs, gsBucket, gsLoc, genHead(gsFrom), true, 20)
+ if err != nil {
+ t.Fatal(err)
+ }
+ wantPlan(t, p, gsFrom, 20, "L9[1..20]", "L0[20..20]")
+ if err := lease.CopyStart(ctx, cs, gsBucket, gsLoc, p, gsTo); err != nil {
+ t.Fatal(err)
+ }
+ for _, f := range p.Files {
+ got, ok := m.Current(gsBucket, ltxKey(gsTo, f.Level, f.Min, f.Max))
+ if !ok || string(got) != "body of "+f.Key {
+ t.Fatalf("copy of %s = %q, %v", f.Key, got, ok)
+ }
+ }
+ if lists, copies, other := cs.snapshot(); lists != 1 || copies != 2 || other != 0 {
+ t.Fatalf("requests: %d lists, %d copies, %d other; want 1, 2, 0", lists, copies, other)
+ }
+}
+
+// The root generation's LTX files sit directly under the location, next
+// to lock.json, head.json, files/ and the g- subtrees, none of which is a
+// root LTX file. Only current versions count.
+func TestPlanStartRootSkipsEverythingButItsLTX(t *testing.T) {
+ m := newGenBucket()
+ putLTX(m, replicagen.Root, ltxSpec{9, 1, 5}, ltxSpec{0, 6, 6}, ltxSpec{0, 7, 7})
+ m.Put(gsBucket, ltxKey(replicagen.Root, 0, 7, 7), []byte("rewritten")) // the current version wins
+ putLTX(m, replicagen.Root, ltxSpec{0, 8, 8})
+ m.BareDelete(gsBucket, ltxKey(replicagen.Root, 0, 8, 8)) // deleted: not current
+ putLTX(m, gsFrom, ltxSpec{9, 1, 30}, ltxSpec{0, 31, 31}) // another generation's tree
+ for _, k := range []string{"lock.json", "head.json", "files/0/a.bin", "0000/notltx.txt", "zzzz/0000000000000009-0000000000000009.ltx",
+ "000a/0000000000000001-0000000000000009.ltx", "0000/sub/0000000000000009-0000000000000009.ltx"} {
+ m.Put(gsBucket, gsLoc+"/"+k, []byte("x"))
+ }
+ p, err := lease.PlanStart(context.Background(), m, gsBucket, gsLoc, lease.Head{}, false, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ wantPlan(t, p, replicagen.Root, 7, "L9[1..5]", "L0[6..6]", "L0[7..7]")
+ if k := ltxKey(replicagen.Root, 0, 7, 7); p.Files[2].VersionID != m.LatestID(gsBucket, k) {
+ t.Fatalf("planned %s@%s, want the current version %s", k, p.Files[2].VersionID, m.LatestID(gsBucket, k))
+ }
+}
+
+// A compacted file reaching T ends the plan; the L0 ending at T is still
+// copied, so Litestream's replica position starts at T.
+func TestPlanStartAddsTheL0EndingAtT(t *testing.T) {
+ m := newGenBucket()
+ putLTX(m, gsFrom, ltxSpec{9, 1, 4}, ltxSpec{1, 5, 8}, ltxSpec{0, 5, 5}, ltxSpec{0, 6, 6}, ltxSpec{0, 7, 7}, ltxSpec{0, 8, 8})
+ p, err := lease.PlanStart(context.Background(), m, gsBucket, gsLoc, genHead(gsFrom), true, 8)
+ if err != nil {
+ t.Fatal(err)
+ }
+ wantPlan(t, p, gsFrom, 8, "L9[1..4]", "L1[5..8]", "L0[8..8]")
+}
+
+func TestPlanStartRefusesNoL0(t *testing.T) {
+ m := newGenBucket()
+ putLTX(m, gsFrom, ltxSpec{9, 1, 5}, ltxSpec{1, 6, 9})
+ cs := newCounting(m)
+ _, err := lease.PlanStart(context.Background(), cs, gsBucket, gsLoc, genHead(gsFrom), true, 0)
+ wantRefusal(t, err, "no_l0")
+ if _, copies, _ := cs.snapshot(); copies != 0 {
+ t.Fatalf("%d copies on a refusal", copies)
+ }
+}
+
+// A gap at L0 below T that no snapshot or compaction covers: no plan over
+// files at most T reaches T.
+func TestPlanStartRefusesNoPlanToL0(t *testing.T) {
+ m := newGenBucket()
+ putLTX(m, gsFrom, ltxSpec{0, 1, 3}, ltxSpec{0, 5, 6}, ltxSpec{9, 1, 7}) // the L9 is above T
+ cs := newCounting(m)
+ _, err := lease.PlanStart(context.Background(), cs, gsBucket, gsLoc, genHead(gsFrom), true, 0)
+ wantRefusal(t, err, "no_plan_to_l0")
+ if _, copies, _ := cs.snapshot(); copies != 0 {
+ t.Fatalf("%d copies on a refusal", copies)
+ }
+}
+
+func TestPlanStartRefusesCleanMarkerAboveL0(t *testing.T) {
+ m := newGenBucket()
+ putLTX(m, gsFrom, ltxSpec{9, 1, 20}, ltxSpec{0, 20, 20})
+ cs := newCounting(m)
+ _, err := lease.PlanStart(context.Background(), cs, gsBucket, gsLoc, genHead(gsFrom), true, 21)
+ wantRefusal(t, err, "clean_marker_above_l0")
+ if _, copies, _ := cs.snapshot(); copies != 0 {
+ t.Fatalf("%d copies on a refusal", copies)
+ }
+}
+
+// The size comes from the listing: no planned file over 5 GiB is copied,
+// and no copy starts at all.
+func TestPlanStartRefusesFileOver5GiB(t *testing.T) {
+ m := newGenBucket()
+ putLTX(m, gsFrom, ltxSpec{9, 1, 20}, ltxSpec{0, 20, 20})
+ cs := newCounting(m)
+ cs.sizes = map[string]int64{ltxKey(gsFrom, 9, 1, 20): 5<<30 + 1}
+ _, err := lease.PlanStart(context.Background(), cs, gsBucket, gsLoc, genHead(gsFrom), true, 0)
+ wantRefusal(t, err, "file_over_5gib")
+ cs.sizes = map[string]int64{ltxKey(gsFrom, 9, 1, 20): 5 << 30} // exactly the limit copies
+ if _, err := lease.PlanStart(context.Background(), cs, gsBucket, gsLoc, genHead(gsFrom), true, 0); err != nil {
+ t.Fatalf("a file of exactly 5 GiB: %v", err)
+ }
+ if _, copies, _ := cs.snapshot(); copies != 0 {
+ t.Fatalf("%d copies", copies)
+ }
+}
+
+// A listing that fails part-way fails the take with an error, never a
+// refusal and never a plan over what it got.
+func TestPlanStartFailsOnAFailedPage(t *testing.T) {
+ m := newGenBucket()
+ putLTX(m, gsFrom, ltxSpec{9, 1, 20}, ltxSpec{0, 20, 20}, ltxSpec{0, 21, 21})
+ m.PageSize, m.FailListAfterPages = 2, 1
+ cs := newCounting(m)
+ _, err := lease.PlanStart(context.Background(), cs, gsBucket, gsLoc, genHead(gsFrom), true, 0)
+ var r *lease.StartRefusal
+ if err == nil || errors.As(err, &r) {
+ t.Fatalf("err = %v, want a listing error that is not a refusal", err)
+ }
+ if _, copies, _ := cs.snapshot(); copies != 0 {
+ t.Fatalf("%d copies", copies)
+ }
+}
+
+// An empty first generation whose box died before its first upload starts
+// another empty generation instead of refusing (spec §4 step 0).
+func TestPlanStartEmptyFirstGeneration(t *testing.T) {
+ m := newGenBucket()
+ m.Put(gsBucket, gsLoc+"/lock.json", []byte("{}"))
+ m.Put(gsBucket, gsLoc+"/head.json", []byte("{}"))
+ first := lease.Head{V: 1, Generation: gsFrom}
+ cs := newCounting(m)
+ ctx := context.Background()
+ p, err := lease.PlanStart(ctx, cs, gsBucket, gsLoc, first, true, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !p.Empty || p.From != gsFrom || p.T != 0 || len(p.Files) != 0 {
+ t.Fatalf("plan = %+v, want an empty start from %s", p, gsFrom)
+ }
+ if err := lease.CopyStart(ctx, cs, gsBucket, gsLoc, p, gsTo); err != nil {
+ t.Fatal(err)
+ }
+ if _, copies, _ := cs.snapshot(); copies != 0 {
+ t.Fatalf("%d copies for an empty start", copies)
+ }
+
+ // Not a first generation, or holding LTX files: never Empty.
+ for name, h := range map[string]lease.Head{
+ "start_txid": {V: 1, Generation: gsFrom, StartTXID: 3},
+ "predecessor": {V: 1, Generation: gsFrom, Predecessor: replicagen.Root},
+ } {
+ if _, err := lease.PlanStart(ctx, m, gsBucket, gsLoc, h, true, 0); err == nil {
+ t.Fatalf("%s: an empty generation that is not a first one did not refuse", name)
+ } else {
+ wantRefusal(t, err, "no_l0")
+ }
+ }
+ putLTX(m, gsFrom, ltxSpec{9, 1, 5})
+ _, err = lease.PlanStart(ctx, m, gsBucket, gsLoc, first, true, 0)
+ wantRefusal(t, err, "no_l0")
+}
+
+func TestPlanStartRefusesAnInvalidHeadGeneration(t *testing.T) {
+ m := newGenBucket()
+ for _, gen := range []string{"g-42", replicagen.Root, "", "g-00000000000000000041/x"} {
+ h := lease.Head{V: 1, Generation: gen}
+ if _, err := lease.PlanStart(context.Background(), m, gsBucket, gsLoc, h, true, 0); err == nil {
+ t.Fatalf("head generation %q planned", gen)
+ }
+ }
+}
+
+// requestLog records each request's method, path and copy source.
+type requestLog struct {
+ mu sync.Mutex
+ reqs []string
+}
+
+func (l *requestLog) wrap(h http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ l.mu.Lock()
+ l.reqs = append(l.reqs, r.Method+" "+r.URL.RequestURI()+" src="+r.Header.Get("x-amz-copy-source"))
+ l.mu.Unlock()
+ h.ServeHTTP(w, r)
+ })
+}
+
+// G3: a write into G after the listing never changes the new generation.
+// The source is overwritten between the listing and the copy, over the S3
+// wire, and every CopyObject names the listed version.
+func TestCopyStartIsImmuneToALaterOverwrite(t *testing.T) {
+ m := newGenBucket()
+ putLTX(m, gsFrom, ltxSpec{9, 1, 20}, ltxSpec{0, 20, 20})
+ handler, _ := leasetest.NewS3Server(m, gsBucket)
+ var log requestLog
+ srv := httptest.NewServer(log.wrap(handler))
+ t.Cleanup(srv.Close)
+ st := lease.NewVersionedS3WithClients(map[string]*awss3.Client{gsBucket: wireClient(t, srv.URL)})
+ ctx := context.Background()
+
+ p, err := lease.PlanStart(ctx, st, gsBucket, gsLoc, genHead(gsFrom), true, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ wantPlan(t, p, gsFrom, 20, "L9[1..20]", "L0[20..20]")
+ listed := map[string][]byte{}
+ for _, f := range p.Files {
+ body, _ := m.Current(gsBucket, f.Key)
+ listed[f.Key] = body
+ m.Put(gsBucket, f.Key, []byte("a late write into G")) // after the listing, before the copy
+ }
+ if err := lease.CopyStart(ctx, st, gsBucket, gsLoc, p, gsTo); err != nil {
+ t.Fatal(err)
+ }
+ for _, f := range p.Files {
+ got, ok := m.Current(gsBucket, ltxKey(gsTo, f.Level, f.Min, f.Max))
+ if !ok || string(got) != string(listed[f.Key]) {
+ t.Fatalf("g-N copy of %s = %q, want the listed version's %q", f.Key, got, listed[f.Key])
+ }
+ }
+ want := map[string]string{} // bucket/key -> listed version id
+ for _, f := range p.Files {
+ want[gsBucket+"/"+f.Key] = f.VersionID
+ }
+ copies := 0
+ for _, r := range log.reqs {
+ _, src, _ := strings.Cut(r, " src=")
+ if src == "" {
+ continue
+ }
+ copies++
+ path, rawQ, _ := strings.Cut(strings.TrimPrefix(src, "/"), "?")
+ key, _ := url.PathUnescape(path)
+ q, _ := url.ParseQuery(rawQ)
+ if id, ok := want[key]; !ok || q.Get("versionId") != id {
+ t.Fatalf("CopyObject %q does not name a listed version id", r)
+ }
+ delete(want, key)
+ }
+ if copies != len(p.Files) {
+ t.Fatalf("%d CopyObject requests, want %d; log %v", copies, len(p.Files), log.reqs)
+ }
+}
+
+// A plan of k files costs one listing page and k copies, nothing else.
+func TestCopyStartCountsRequests(t *testing.T) {
+ m := newGenBucket()
+ putLTX(m, gsFrom, ltxSpec{9, 1, 10}, ltxSpec{1, 11, 14}, ltxSpec{0, 11, 11}, ltxSpec{0, 12, 12},
+ ltxSpec{0, 13, 13}, ltxSpec{0, 14, 14}, ltxSpec{0, 15, 15}, ltxSpec{0, 16, 16})
+ cs := newCounting(m)
+ ctx := context.Background()
+ p, err := lease.PlanStart(ctx, cs, gsBucket, gsLoc, genHead(gsFrom), true, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ wantPlan(t, p, gsFrom, 16, "L9[1..10]", "L1[11..14]", "L0[15..15]", "L0[16..16]")
+ if err := lease.CopyStart(ctx, cs, gsBucket, gsLoc, p, gsTo); err != nil {
+ t.Fatal(err)
+ }
+ if lists, copies, other := cs.snapshot(); lists != 1 || copies != len(p.Files) || other != 0 {
+ t.Fatalf("requests: %d lists, %d copies, %d other; want 1, %d, 0", lists, copies, other, len(p.Files))
+ }
+}
+
+// manyFiles is a plan of n files: one snapshot and n-1 L0 files.
+func manyFiles(t *testing.T, m *leasetest.VersionedBucket, n int) lease.StartPlan {
+ t.Helper()
+ putLTX(m, gsFrom, ltxSpec{9, 1, 1})
+ for i := 2; i <= n; i++ {
+ putLTX(m, gsFrom, ltxSpec{0, uint64(i), uint64(i)})
+ }
+ p, err := lease.PlanStart(context.Background(), m, gsBucket, gsLoc, genHead(gsFrom), true, 0)
+ if err != nil || len(p.Files) != n {
+ t.Fatalf("plan of %d files: %d, %v", n, len(p.Files), err)
+ }
+ return p
+}
+
+func TestCopyStartRunsAtMostEightCopies(t *testing.T) {
+ m := newGenBucket()
+ p := manyFiles(t, m, 20)
+ cs := newCounting(m)
+ full := make(chan struct{})
+ gate := make(chan struct{})
+ var once sync.Once
+ cs.onCopy = func(ctx context.Context, key string, inFlight int) error {
+ if inFlight >= 8 {
+ once.Do(func() { close(full) })
+ }
+ <-gate
+ return nil
+ }
+ done := make(chan error, 1)
+ go func() { done <- lease.CopyStart(context.Background(), cs, gsBucket, gsLoc, p, gsTo) }()
+ select {
+ case <-full:
+ case <-time.After(5 * time.Second):
+ t.Fatal("eight copies never ran at once")
+ }
+ time.Sleep(50 * time.Millisecond) // room for a ninth to start, if one could
+ close(gate)
+ if err := <-done; err != nil {
+ t.Fatal(err)
+ }
+ if _, copies, _ := cs.snapshot(); copies != 20 || cs.maxInFlight != 8 {
+ t.Fatalf("%d copies, at most %d at once; want 20, 8", copies, cs.maxInFlight)
+ }
+}
+
+func TestCopyStartReturnsTheFirstErrorAndCancelsTheRest(t *testing.T) {
+ m := newGenBucket()
+ p := manyFiles(t, m, 20)
+ cs := newCounting(m)
+ boom := errors.New("injected copy failure")
+ first := p.Files[0].Key
+ cs.onCopy = func(ctx context.Context, key string, _ int) error {
+ if key == first {
+ return boom
+ }
+ <-ctx.Done() // every other copy waits until the failure cancels it
+ return ctx.Err()
+ }
+ err := lease.CopyStart(context.Background(), cs, gsBucket, gsLoc, p, gsTo)
+ if !errors.Is(err, boom) {
+ t.Fatalf("err = %v, want the injected failure", err)
+ }
+ if _, copies, _ := cs.snapshot(); copies > 8 {
+ t.Fatalf("%d copies started after the first failure cancelled the rest", copies)
+ }
+}
+
+func TestCopyStartRefusesABadDestination(t *testing.T) {
+ m := newGenBucket()
+ putLTX(m, gsFrom, ltxSpec{9, 1, 20}, ltxSpec{0, 20, 20})
+ p, err := lease.PlanStart(context.Background(), m, gsBucket, gsLoc, genHead(gsFrom), true, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ cs := newCounting(m)
+ for _, to := range []string{replicagen.Root, "g-42", "", gsFrom} {
+ if err := lease.CopyStart(context.Background(), cs, gsBucket, gsLoc, p, to); err == nil {
+ t.Fatalf("copied into %q", to)
+ }
+ }
+ if _, copies, _ := cs.snapshot(); copies != 0 {
+ t.Fatalf("%d copies", copies)
+ }
+}