carlos / platform Public

dbdoor: PositionAndHistory, one listing and one boundary rule (#898)

PositionAndHistory plans the newest copy (as PlanFrom with a zero time)
and finds the earliest --at a restore accepts, from one listing of each
level that the call caches, so both describe the same replica. It stops
with the new ErrTooManyFiles past maxFiles listed files, passes
ErrNothingReplicated through, and reports the history start unknown when
the listing carries no times.

isHistoryStart and historyBoundary are now the one rule PlanFrom,
PositionAndHistory and the CLI restore (restoreAt, recorder) share; the
three copies of it are gone. The restore's behaviour is unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 25cedabcf96e531cb295fc72dbf570d59604bd5d parent b358d51
4 files changed, +342 −18
  • internal/dbdoor/plan_from.go +104 −14
  • internal/dbdoor/plan_from_test.go +192 −0
  • internal/dbdoor/restore.go +17 −4
  • internal/dbdoor/restore_test.go +29 −0

CI failed — run details

Intent

Attributed to this commit: 20.2 g CO₂e (2,612,038 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on member-backups-1, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/dbdoor/plan_from.go b/internal/dbdoor/plan_from.go
index a0764c837..0e3587739 100644
--- a/internal/dbdoor/plan_from.go
+++ b/internal/dbdoor/plan_from.go
@@ -22,25 +22,42 @@ type ReplicaReader interface {
OpenLTXFile(ctx context.Context, level int, minTXID, maxTXID ltx.TXID, offset, size int64) (io.ReadCloser, error)
}
+// ErrTooManyFiles: the replica lists more files than a bounded planner
+// (PositionAndHistory) may read in one call (spec R1-13).
+var ErrTooManyFiles = errors.New("dbdoor: the replica lists more files than the planner may read")
+
// ListLevel lists one level of rd in the door's wire shape, ordered by
// MinTXID, with an empty level as an empty list, and with S3's LastModified
// as CreatedAt (useMetadata false). The console's door and the box's planner
// both list through it, so a forwarded --at stops at the transaction an
// in-region one does (spec §6, T6).
func ListLevel(ctx context.Context, rd ReplicaReader, level int) (ListResponse, error) {
+ return listLevel(ctx, rd, level, -1)
+}
+
+// listLevel is ListLevel that stops with ErrTooManyFiles once the level
+// holds more than limit files, without listing the rest. A negative limit
+// is no limit.
+func listLevel(ctx context.Context, rd ReplicaReader, level, limit int) (ListResponse, error) {
itr, err := rd.LTXFiles(ctx, level, 0, false)
if err != nil {
return ListResponse{}, err
}
out := ListResponse{Files: []LTXFile{}}
for itr.Next() {
+ if limit >= 0 && len(out.Files) >= limit {
+ err = ErrTooManyFiles
+ break
+ }
f := itr.Item()
out.Files = append(out.Files, LTXFile{
Level: level, MinTXID: uint64(f.MinTXID), MaxTXID: uint64(f.MaxTXID),
Size: f.Size, CreatedAt: f.CreatedAt,
})
}
- err = itr.Err()
+ if err == nil {
+ err = itr.Err()
+ }
if cerr := itr.Close(); err == nil {
err = cerr
}
@@ -52,40 +69,70 @@ func ListLevel(ctx context.Context, rd ReplicaReader, level int) (ListResponse,
}
// listing is a read-only litestream.ReplicaClient over rd that lists through
-// ListLevel. For an as-of plan it also does what the CLI's recorder does
-// over the door's listings: refuse a listing with no times (ErrNoTimes) and
-// remember the earliest file a restore could start from.
+// ListLevel. It lists each level once and keeps what it saw for the rest of
+// the one call it serves, so a plan and a history scan in that call read
+// the same snapshot of the replica. For an as-of plan it also does what the
+// CLI's recorder does over the door's listings: refuse a listing with no
+// times (ErrNoTimes) and remember the earliest file a restore could start
+// from.
type listing struct {
- rd ReplicaReader
- asOf bool
- mu sync.Mutex
- oldest time.Time
+ rd ReplicaReader
+ asOf bool
+ maxFiles int // files the call may list across every level; negative: no cap
+ mu sync.Mutex
+ levels map[int][]LTXFile // each level as first listed
+ listed int // files listed so far, every level
+ oldest time.Time
}
func (l *listing) Type() string { return "carlos-db-listing" }
func (l *listing) Init(context.Context) error { return nil }
func (l *listing) SetLogger(*slog.Logger) {}
+// files is level as first listed in this call, listing it now if it has not
+// been. Past maxFiles listed files it is ErrTooManyFiles.
+func (l *listing) files(ctx context.Context, level int) ([]LTXFile, error) {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ if fs, ok := l.levels[level]; ok {
+ return fs, nil
+ }
+ limit := -1
+ if l.maxFiles >= 0 {
+ limit = l.maxFiles - l.listed
+ }
+ out, err := listLevel(ctx, l.rd, level, limit)
+ if err != nil {
+ return nil, err
+ }
+ if l.levels == nil {
+ l.levels = map[int][]LTXFile{}
+ }
+ l.levels[level] = out.Files
+ l.listed += len(out.Files)
+ return out.Files, nil
+}
+
func (l *listing) LTXFiles(ctx context.Context, level int, seek ltx.TXID, _ bool) (ltx.FileIterator, error) {
- out, err := ListLevel(ctx, l.rd, level)
+ fs, err := l.files(ctx, level)
if err != nil {
return nil, err
}
if l.asOf {
l.mu.Lock()
defer l.mu.Unlock()
- for _, f := range out.Files {
+ for _, f := range fs {
if f.CreatedAt.IsZero() {
return nil, ErrNoTimes
}
- if level == litestream.SnapshotLevel || f.MinTXID == 1 {
+ if isHistoryStart(f) {
if l.oldest.IsZero() || f.CreatedAt.Before(l.oldest) {
l.oldest = f.CreatedAt
}
}
}
}
- return fileIterator(out.Files, level, seek), nil
+ return fileIterator(fs, level, seek), nil
}
func (l *listing) OpenLTXFile(ctx context.Context, level int, minTXID, maxTXID ltx.TXID, offset, size int64) (io.ReadCloser, error) {
@@ -108,7 +155,12 @@ var _ litestream.ReplicaClient = (*listing)(nil)
// RestoreAsOf's: ErrNothingReplicated, a *BeforeHistoryError naming the
// oldest point kept, ErrNoTimes.
func PlanFrom(ctx context.Context, rd ReplicaReader, at time.Time) (RestorePlan, error) {
- l := &listing{rd: rd, asOf: !at.IsZero()}
+ return planFrom(ctx, &listing{rd: rd, asOf: !at.IsZero(), maxFiles: -1}, at)
+}
+
+// planFrom is PlanFrom over a listing the caller made, so the caller can
+// read the same listing afterwards.
+func planFrom(ctx context.Context, l *listing, at time.Time) (RestorePlan, error) {
var ts time.Time
if !at.IsZero() {
if at.Truncate(time.Second).Before(EarliestAsOf) {
@@ -126,7 +178,7 @@ func PlanFrom(ctx context.Context, rd ReplicaReader, at time.Time) (RestorePlan,
l.mu.Unlock()
if !ts.IsZero() && !oldest.IsZero() {
if !oldest.Before(ts) {
- return RestorePlan{}, &BeforeHistoryError{Oldest: oldest.Truncate(time.Second).Add(time.Second)}
+ return RestorePlan{}, &BeforeHistoryError{Oldest: historyBoundary(oldest)}
}
return RestorePlan{}, err
}
@@ -139,6 +191,44 @@ func PlanFrom(ctx context.Context, rd ReplicaReader, at time.Time) (RestorePlan,
return finishPlan(ctx, l, infos, 0)
}
+// PositionAndHistory plans the newest copy, exactly as PlanFrom(ctx, rd,
+// time.Time{}) does, and finds where the kept history starts: the earliest
+// --at a restore accepts, by the rule the CLI restore names in its
+// *BeforeHistoryError. Both come from one listing of each level, so they
+// describe the same moment of the replica.
+//
+// It lists at most maxFiles files across every level and stops with
+// ErrTooManyFiles past that (a maxFiles below 1 admits none). An empty
+// replica is ErrNothingReplicated. known is false, and from zero, when the
+// listing carries no times (the claim-mode door), since no --at can then be
+// answered; the plan still stands.
+func PositionAndHistory(ctx context.Context, rd ReplicaReader, maxFiles int) (plan RestorePlan, from time.Time, known bool, err error) {
+ l := &listing{rd: rd, maxFiles: max(maxFiles, 0)}
+ plan, err = planFrom(ctx, l, time.Time{})
+ if err != nil {
+ return RestorePlan{}, time.Time{}, false, err
+ }
+ var oldest time.Time
+ for level := 0; level <= litestream.SnapshotLevel; level++ {
+ fs, err := l.files(ctx, level)
+ if err != nil {
+ return RestorePlan{}, time.Time{}, false, err
+ }
+ for _, f := range fs {
+ if f.CreatedAt.IsZero() {
+ return plan, time.Time{}, false, nil
+ }
+ if isHistoryStart(f) && (oldest.IsZero() || f.CreatedAt.Before(oldest)) {
+ oldest = f.CreatedAt
+ }
+ }
+ }
+ if oldest.IsZero() {
+ return plan, time.Time{}, false, nil
+ }
+ return plan, historyBoundary(oldest), true, nil
+}
+
// RestoreLocal restores the replica c holds, a litestream file replica in a
// private directory (the db-read worker's, or the CLI's for a forwarded
// pull), exactly to target, at out, and proves it with lease.CheckDBContext.
diff --git a/internal/dbdoor/plan_from_test.go b/internal/dbdoor/plan_from_test.go
index 95b907511..37ccd126d 100644
--- a/internal/dbdoor/plan_from_test.go
+++ b/internal/dbdoor/plan_from_test.go
@@ -6,6 +6,7 @@ import (
"io"
"os"
"path/filepath"
+ "reflect"
"sync"
"testing"
"time"
@@ -218,3 +219,194 @@ func TestRestoreLocalStopsReadingOnceCancelled(t *testing.T) {
t.Fatalf("something is at out: %v", err)
}
}
+
+// countingLists counts every listing of each level a ReplicaReader is asked
+// for.
+type countingLists struct {
+ ReplicaReader
+ mu sync.Mutex
+ lists map[int]int
+}
+
+func (c *countingLists) LTXFiles(ctx context.Context, level int, seek ltx.TXID, useMetadata bool) (ltx.FileIterator, error) {
+ c.mu.Lock()
+ c.lists[level]++
+ c.mu.Unlock()
+ return c.ReplicaReader.LTXFiles(ctx, level, seek, useMetadata)
+}
+
+// timeless lists every file with no time, as the claim-mode door does.
+type timeless struct{ ReplicaReader }
+
+func (z timeless) LTXFiles(ctx context.Context, level int, seek ltx.TXID, useMetadata bool) (ltx.FileIterator, error) {
+ itr, err := z.ReplicaReader.LTXFiles(ctx, level, seek, useMetadata)
+ if err != nil {
+ return nil, err
+ }
+ defer itr.Close()
+ var out []*ltx.FileInfo
+ for itr.Next() {
+ f := *itr.Item()
+ f.CreatedAt = time.Time{}
+ out = append(out, &f)
+ }
+ return ltx.NewFileInfoSliceIterator(out), itr.Err()
+}
+
+// beforeHistoryAt asks the CLI's own restore for a copy as of at and
+// returns the oldest point its refusal names.
+func beforeHistoryAt(t *testing.T, dir string, at time.Time) time.Time {
+ t.Helper()
+ _, err := restoreAt(context.Background(), NewClient(newTestDoor(t, dir).do), t.TempDir(), 0, at)
+ var bh *BeforeHistoryError
+ if !errors.As(err, &bh) {
+ t.Fatalf("the CLI restore as of %v = %v, want a *BeforeHistoryError", at, err)
+ }
+ return bh.Oldest
+}
+
+// The history start PositionAndHistory reports is exactly the boundary the
+// CLI restore names: the earliest --at that restores. One second earlier
+// is before the history, and the plan is the newest copy PlanFrom makes
+// (spec §1 history_from, R1-7).
+func TestPositionAndHistoryMatchesRestoreBoundary(t *testing.T) {
+ t.Parallel()
+ before := time.Now().Add(-time.Hour)
+ dir := t.TempDir()
+ src := dbdoortest.Replicate(t, dir, 2)
+ pause()
+ addBatch(t, src, dir, 2)
+ files := collect(t, NewClient(newTestDoor(t, dir).do), 0, 0)
+ if len(files) < 3 {
+ t.Fatalf("want one L0 file per batch, got %d", len(files))
+ }
+ snap := snapshotThrough(t, dir, files[:2])
+ for _, f := range files[:2] {
+ if err := os.Remove(litestream.LTXFilePath(dir, 0, f.MinTXID, f.MaxTXID)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ rd := lsfile.NewReplicaClient(dir)
+
+ plan, from, known, err := PositionAndHistory(context.Background(), rd, 1000)
+ if err != nil || !known {
+ t.Fatalf("PositionAndHistory = %v, known %v", err, known)
+ }
+ if want := snap.CreatedAt.Truncate(time.Second).Add(time.Second); !from.Equal(want) {
+ t.Fatalf("history from %v, want the second after the snapshot, %v", from, want)
+ }
+ if oldest := beforeHistoryAt(t, dir, before); !from.Equal(oldest) {
+ t.Fatalf("history from %v, the CLI restore names %v", from, oldest)
+ }
+ if _, err := PlanFrom(context.Background(), rd, from); err != nil {
+ t.Fatalf("PlanFrom at the history start %v = %v", from, err)
+ }
+ var bh *BeforeHistoryError
+ if _, err := PlanFrom(context.Background(), rd, from.Add(-time.Second)); !errors.As(err, &bh) || !bh.Oldest.Equal(from) {
+ t.Fatalf("PlanFrom a second before the history start = %v, want before history at %v", err, from)
+ }
+ newest, err := PlanFrom(context.Background(), rd, time.Time{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(plan, newest) {
+ t.Fatalf("plan %+v, PlanFrom's newest %+v", plan, newest)
+ }
+}
+
+// A file beginning at transaction 1 that is older than every snapshot is
+// where the history starts, as the CLI restore admits it.
+func TestPositionAndHistoryTxidOneFileBeforeSnapshot(t *testing.T) {
+ t.Parallel()
+ before := time.Now().Add(-time.Hour)
+ dir := t.TempDir()
+ src := dbdoortest.Replicate(t, dir, 1)
+ pause()
+ addBatch(t, src, dir, 1)
+ addBatch(t, src, dir, 2)
+ files := collect(t, NewClient(newTestDoor(t, dir).do), 0, 0)
+ if len(files) < 3 || files[0].MinTXID != 1 {
+ t.Fatalf("want one L0 file per batch from transaction 1, got %d", len(files))
+ }
+ snap := snapshotThrough(t, dir, files[:2])
+ first := files[0].CreatedAt.Truncate(time.Second)
+ if !snap.CreatedAt.Truncate(time.Second).After(first) {
+ t.Fatalf("the snapshot (%v) must list in a later second than the first file (%v)", snap.CreatedAt, files[0].CreatedAt)
+ }
+ rd := lsfile.NewReplicaClient(dir)
+
+ _, from, known, err := PositionAndHistory(context.Background(), rd, 1000)
+ if err != nil || !known {
+ t.Fatalf("PositionAndHistory = %v, known %v", err, known)
+ }
+ if want := first.Add(time.Second); !from.Equal(want) {
+ t.Fatalf("history from %v, want the second after the transaction-1 file, %v", from, want)
+ }
+ if oldest := beforeHistoryAt(t, dir, before); !from.Equal(oldest) {
+ t.Fatalf("history from %v, the CLI restore names %v", from, oldest)
+ }
+ if _, err := PlanFrom(context.Background(), rd, from); err != nil {
+ t.Fatalf("PlanFrom at the history start %v = %v", from, err)
+ }
+}
+
+func TestPositionAndHistoryEmpty(t *testing.T) {
+ t.Parallel()
+ _, _, known, err := PositionAndHistory(context.Background(), lsfile.NewReplicaClient(t.TempDir()), 1000)
+ if !errors.Is(err, ErrNothingReplicated) || known {
+ t.Fatalf("PositionAndHistory on nothing = %v, known %v; want ErrNothingReplicated", err, known)
+ }
+}
+
+// A listing without times still plans the newest copy; the history start
+// is then not known, never guessed.
+func TestPositionAndHistoryWithoutTimes(t *testing.T) {
+ t.Parallel()
+ dir := t.TempDir()
+ dbdoortest.Replicate(t, dir, 2)
+ plan, from, known, err := PositionAndHistory(context.Background(), timeless{lsfile.NewReplicaClient(dir)}, 1000)
+ if err != nil || known || !from.IsZero() || plan.Files == 0 {
+ t.Fatalf("PositionAndHistory without times = %+v, %v, known %v, %v; want the plan and no history start", plan, from, known, err)
+ }
+}
+
+// One call lists each level once: the plan and the history start read the
+// same listing (R1-13).
+func TestPositionAndHistoryListsEachLevelOnce(t *testing.T) {
+ t.Parallel()
+ dir := t.TempDir()
+ dbdoortest.Replicate(t, dir, 3)
+ files := collect(t, NewClient(newTestDoor(t, dir).do), 0, 0)
+ snapshotThrough(t, dir, files[:2])
+ rd := &countingLists{ReplicaReader: lsfile.NewReplicaClient(dir), lists: map[int]int{}}
+ if _, _, known, err := PositionAndHistory(context.Background(), rd, 1000); err != nil || !known {
+ t.Fatalf("PositionAndHistory = %v, known %v", err, known)
+ }
+ for level := 0; level <= litestream.SnapshotLevel; level++ {
+ if n := rd.lists[level]; n != 1 {
+ t.Errorf("level %d listed %d times, want once", level, n)
+ }
+ }
+ if len(rd.lists) != litestream.SnapshotLevel+1 {
+ t.Errorf("listed levels %v, want 0 to %d", rd.lists, litestream.SnapshotLevel)
+ }
+}
+
+// Past maxFiles listed files the planner stops: exactly maxFiles is
+// planned, one more is ErrTooManyFiles.
+func TestPositionAndHistoryFileCap(t *testing.T) {
+ t.Parallel()
+ dir := t.TempDir()
+ dbdoortest.Replicate(t, dir, 3)
+ files := collect(t, NewClient(newTestDoor(t, dir).do), 0, 0)
+ snapshotThrough(t, dir, files[:2])
+ n := len(files) + 1 // the L0 files and the snapshot
+ rd := lsfile.NewReplicaClient(dir)
+ if _, _, _, err := PositionAndHistory(context.Background(), rd, n); err != nil {
+ t.Fatalf("PositionAndHistory over exactly %d files = %v", n, err)
+ }
+ _, _, known, err := PositionAndHistory(context.Background(), rd, n-1)
+ if !errors.Is(err, ErrTooManyFiles) || known {
+ t.Fatalf("PositionAndHistory over %d files capped at %d = %v, known %v; want ErrTooManyFiles", n, n-1, err, known)
+ }
+}
diff --git a/internal/dbdoor/restore.go b/internal/dbdoor/restore.go
index 98024a5ff..f646fa40a 100644
--- a/internal/dbdoor/restore.go
+++ b/internal/dbdoor/restore.go
@@ -57,6 +57,21 @@ func (e *BeforeHistoryError) Error() string {
func (e *BeforeHistoryError) Is(target error) bool { return target == ErrBeforeHistory }
+// isHistoryStart reports whether a restore can start from f: any snapshot,
+// or a file beginning at the first transaction. The earliest such file
+// listed is where the kept history starts. PlanFrom, PositionAndHistory and
+// the CLI restore all decide it here, so they cannot drift (spec R1-7).
+func isHistoryStart(f LTXFile) bool {
+ return f.Level == litestream.SnapshotLevel || f.MinTXID == 1
+}
+
+// historyBoundary is the earliest --at that includes the oldest file a
+// restore can start from, listed at oldest: the first whole second after
+// it, since an --at is rounded down to its second before it is compared.
+func historyBoundary(oldest time.Time) time.Time {
+ return oldest.Truncate(time.Second).Add(time.Second)
+}
+
// Restored is a private copy of a replica on this machine.
type Restored struct {
// Path is the restored database. It lives inside Dir.
@@ -182,9 +197,7 @@ func restoreAt(ctx context.Context, c *Client, parent string, target uint64, at
}
if oldest := rec.oldestStart(); !at.IsZero() && !oldest.IsZero() {
if !oldest.Before(at.Truncate(time.Second)) {
- // The first whole second after the oldest file: the
- // earliest --at that, rounded down, still includes it.
- return nil, &BeforeHistoryError{Oldest: oldest.Truncate(time.Second).Add(time.Second)}
+ return nil, &BeforeHistoryError{Oldest: historyBoundary(oldest)}
}
return nil, err
}
@@ -278,7 +291,7 @@ func (r *recorder) LTXFiles(ctx context.Context, level int, seek ltx.TXID, useMe
if f.CreatedAt.IsZero() {
return nil, ErrNoTimes
}
- if level == litestream.SnapshotLevel || f.MinTXID == 1 {
+ if isHistoryStart(LTXFile{Level: level, MinTXID: uint64(f.MinTXID)}) {
if r.oldest.IsZero() || f.CreatedAt.Before(r.oldest) {
r.oldest = f.CreatedAt
}
diff --git a/internal/dbdoor/restore_test.go b/internal/dbdoor/restore_test.go
index 2be975f52..dc4dedba1 100644
--- a/internal/dbdoor/restore_test.go
+++ b/internal/dbdoor/restore_test.go
@@ -542,3 +542,32 @@ func TestDownloadTempFileFailure(t *testing.T) {
})
}
}
+
+// The one history-boundary rule PlanFrom, PositionAndHistory and the CLI
+// restore share: a restore can start from any snapshot or from a file
+// beginning at transaction 1, and the earliest --at is the first whole
+// second after the oldest such file was listed.
+func TestHistoryBoundaryRule(t *testing.T) {
+ for _, c := range []struct {
+ f LTXFile
+ want bool
+ }{
+ {LTXFile{Level: 9, MinTXID: 40}, true},
+ {LTXFile{Level: 0, MinTXID: 1}, true},
+ {LTXFile{Level: 3, MinTXID: 1}, true},
+ {LTXFile{Level: 0, MinTXID: 2}, false},
+ {LTXFile{Level: 8, MinTXID: 40}, false},
+ } {
+ if got := isHistoryStart(c.f); got != c.want {
+ t.Errorf("isHistoryStart(level %d, min %d) = %v, want %v", c.f.Level, c.f.MinTXID, got, c.want)
+ }
+ }
+ oldest := time.Date(2026, 11, 4, 9, 10, 0, 700_000_000, time.UTC)
+ if got, want := historyBoundary(oldest), time.Date(2026, 11, 4, 9, 10, 1, 0, time.UTC); !got.Equal(want) {
+ t.Errorf("historyBoundary(%v) = %v, want %v", oldest, got, want)
+ }
+ whole := time.Date(2026, 11, 4, 9, 10, 0, 0, time.UTC)
+ if got, want := historyBoundary(whole), whole.Add(time.Second); !got.Equal(want) {
+ t.Errorf("historyBoundary(%v) = %v, want %v", whole, got, want)
+ }
+}