carlos / platform Public

lease: bind one generation per read; PITR witness

Task 6 fix round 1 (Astra R1).

1. Ruling kept: inside a generation a point-in-time read uses today's
   CreatedAt rule (S3 LastModified). A real restore witness through the
   fake S3 proves the binding (g-1 restores "one", g-2 "one","two") and
   pins the ruling: g-1's late file is not in a read inside its tenure.
2. G4 across retries: the box db read resolves once per read and the
   restore drill once per restore; a re-plan after head moves still
   reads the first generation.
3. The console replica cache resolves outside its lock, one shared
   resolution per prefix; a stalled head.json read blocks no other
   prefix and each waiter stops with its own ctx.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev d19b7afed494ab868e177dc6f456fa25c7556546 parent c1aa4ef
9 files changed, +558 −75
  • internal/console/apidb.go +59 −7
  • internal/console/apidb_test.go +106 −0
  • internal/dbreads/read.go +31 −15
  • internal/dbreads/resolve_test.go +38 −0
  • internal/lease/resolve.go +3 −1
  • internal/lease/resolve_test.go +183 −4
  • internal/ops/hibernate_verify.go +11 −8
  • internal/ops/hibernate_verify_resolve_test.go +108 −35
  • internal/ops/hibernate_verify_restore_test.go +19 −5
diff --git a/internal/console/apidb.go b/internal/console/apidb.go
index ed9d5aa9b..63672c32c 100644
--- a/internal/console/apidb.go
+++ b/internal/console/apidb.go
@@ -486,9 +486,26 @@ func dbStream(w io.Writer, rw *http.ResponseController, rc io.Reader, watchdog *
// a walk would cost a lock held across every door.
const dbReplicaCacheMax = 64
+// dbReplicaResolveLimit bounds one resolution (its head.json read). It runs
+// detached from the caller that started it, so a caller giving up cannot
+// fail the others waiting on the same prefix.
+const dbReplicaResolveLimit = 30 * time.Second
+
type dbReplicaCache struct {
mu sync.Mutex
clients map[string]replicaReader
+ // flights are the resolutions in progress, one per prefix: every miss
+ // on a prefix waits on the one flight rather than reading head.json
+ // again.
+ flights map[string]*dbReplicaFlight
+}
+
+// dbReplicaFlight is one prefix's resolution in progress; done closes once
+// rd and err are set.
+type dbReplicaFlight struct {
+ done chan struct{}
+ rd replicaReader
+ err error
}
// cachedReadReplica is the production dbReplica: lease.ResolveReplica on
@@ -497,22 +514,57 @@ type dbReplicaCache struct {
// binding a door's flow to the generation it resolved, is the console
// readers' own change (generations Task 8). No host has head.json until
// then, so every prefix resolves to its root, as before.
+//
+// The cache's lock is held only to look up and insert: the resolution's
+// head.json read runs outside it, so a slow read on one prefix never holds
+// up another prefix, cached or not. Misses on one prefix share a single
+// resolution, and each waiter stops waiting when its own ctx ends.
func (s *Server) cachedReadReplica(ctx context.Context, prefix string) (replicaReader, error) {
c := &s.dbClients
c.mu.Lock()
- defer c.mu.Unlock()
if rd, ok := c.clients[prefix]; ok {
+ c.mu.Unlock()
return rd, nil
}
+ f, ok := c.flights[prefix]
+ if !ok {
+ f = &dbReplicaFlight{done: make(chan struct{})}
+ if c.flights == nil {
+ c.flights = map[string]*dbReplicaFlight{}
+ }
+ c.flights[prefix] = f
+ go s.resolveReplicaFlight(context.WithoutCancel(ctx), prefix, f)
+ }
+ c.mu.Unlock()
+ select {
+ case <-f.done:
+ return f.rd, f.err
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+}
+
+// resolveReplicaFlight runs f's resolution and publishes it: into the
+// cache on success, and to every waiter either way.
+func (s *Server) resolveReplicaFlight(ctx context.Context, prefix string, f *dbReplicaFlight) {
+ ctx, cancel := context.WithTimeout(ctx, dbReplicaResolveLimit)
+ defer cancel()
r, err := lease.ResolveReplica(ctx, s.cfg.HibernateBucket, prefix, s.cfg.HibernateRegion)
- if err != nil {
- return nil, err
+ if err == nil {
+ f.rd = r.Client
}
- if c.clients == nil || len(c.clients) >= dbReplicaCacheMax {
- c.clients = make(map[string]replicaReader, 8)
+ f.err = err
+ c := &s.dbClients
+ c.mu.Lock()
+ delete(c.flights, prefix)
+ if err == nil {
+ if c.clients == nil || len(c.clients) >= dbReplicaCacheMax {
+ c.clients = make(map[string]replicaReader, 8)
+ }
+ c.clients[prefix] = f.rd
}
- c.clients[prefix] = r.Client
- return r.Client, nil
+ c.mu.Unlock()
+ close(f.done)
}
// The db door's stream bounds. The per-minute token budget bounds how many
diff --git a/internal/console/apidb_test.go b/internal/console/apidb_test.go
index a6a2ecb31..349510989 100644
--- a/internal/console/apidb_test.go
+++ b/internal/console/apidb_test.go
@@ -526,6 +526,112 @@ func TestCachedReadReplicaIsOnePerPrefix(t *testing.T) {
}
}
+// Task 6 R1 finding 3: a miss resolves outside the cache's lock. While one
+// prefix's head.json read is stalled, a cached prefix answers at once, an
+// uncached one resolves, a second miss on the stalled prefix shares its one
+// read and gives up with its own ctx, and the stalled read, released, is
+// cached for everyone.
+func TestCachedReadReplicaStalledMissBlocksNoOtherPrefix(t *testing.T) {
+ s := &Server{}
+ data := &fakeDataBucket{keys: []string{ltxKey("instances/slow.example.com", 0)}}
+ entered, release := make(chan struct{}), make(chan struct{})
+ var once sync.Once
+ var mu sync.Mutex
+ slowHeads := 0
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/instances/slow.example.com/head.json") {
+ mu.Lock()
+ slowHeads++
+ mu.Unlock()
+ once.Do(func() { close(entered) })
+ select {
+ case <-release:
+ case <-r.Context().Done():
+ return
+ }
+ }
+ data.ServeHTTP(w, r)
+ }))
+ t.Cleanup(srv.Close)
+ t.Setenv("CARLOS_S3_ENDPOINT", srv.URL)
+ 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")
+ s.cfg.HibernateBucket = "data-test"
+ s.cfg.HibernateRegion = "us-east-1"
+ ctx := context.Background()
+
+ cached, err := s.cachedReadReplica(ctx, "instances/a.example.com")
+ if err != nil {
+ t.Fatal(err)
+ }
+ type answer struct {
+ rd replicaReader
+ err error
+ }
+ slow := make(chan answer, 1)
+ go func() {
+ rd, err := s.cachedReadReplica(ctx, "instances/slow.example.com")
+ slow <- answer{rd, err}
+ }()
+ select {
+ case <-entered:
+ case <-time.After(10 * time.Second):
+ t.Fatal("the slow prefix never read head.json")
+ }
+
+ within := func(name string, f func()) {
+ t.Helper()
+ done := make(chan struct{})
+ go func() { f(); close(done) }()
+ select {
+ case <-done:
+ case <-time.After(2 * time.Second):
+ t.Fatalf("%s waited on the stalled resolution", name)
+ }
+ }
+ within("a cached prefix", func() {
+ if rd, err := s.cachedReadReplica(ctx, "instances/a.example.com"); err != nil || rd != cached {
+ t.Errorf("cached prefix = %v, %v; want the cached client", rd, err)
+ }
+ })
+ within("an uncached prefix", func() {
+ if _, err := s.cachedReadReplica(ctx, "instances/b.example.com"); err != nil {
+ t.Errorf("uncached prefix: %v", err)
+ }
+ })
+ within("a second miss with its own deadline", func() {
+ wctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
+ defer cancel()
+ if _, err := s.cachedReadReplica(wctx, "instances/slow.example.com"); !errors.Is(err, context.DeadlineExceeded) {
+ t.Errorf("a waiter past its deadline = %v, want context.DeadlineExceeded", err)
+ }
+ })
+
+ close(release)
+ var got answer
+ select {
+ case got = <-slow:
+ case <-time.After(10 * time.Second):
+ t.Fatal("the released resolution never answered")
+ }
+ if got.err != nil {
+ t.Fatal(got.err)
+ }
+ if found, err := anyLTXFile(ctx, got.rd, 0); err != nil || !found {
+ t.Fatalf("the slow prefix's client lists %v, %v", found, err)
+ }
+ if rd, err := s.cachedReadReplica(ctx, "instances/slow.example.com"); err != nil || rd != got.rd {
+ t.Fatalf("after the release: %v, %v; want the one cached client", rd, err)
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ if slowHeads != 1 {
+ t.Fatalf("%d head.json reads of the slow prefix, want one shared by every miss", slowHeads)
+ }
+}
+
// The door has its own token-keyed budget, separate from the instance
// verbs': spending it does not touch the instance budget, and it applies
// only after membership, so a stranger cannot learn anything from a 429.
diff --git a/internal/dbreads/read.go b/internal/dbreads/read.go
index a397358bb..ed77575a9 100644
--- a/internal/dbreads/read.go
+++ b/internal/dbreads/read.go
@@ -98,6 +98,9 @@ func (a *Agent) read(ctx context.Context, req Request) Result {
return Result{State: StateFailed, Code: CodeInterrupted}
}
at, _ := req.AtTime()
+ // The read's one binding (spec 2026-11-12 G4): the first attempt
+ // resolves the replica, and the retry reads that same generation.
+ var bound readBinding
for attempt := 0; attempt < 2; attempt++ {
if attempt > 0 {
// The first attempt's worker may still be stopping: keep its
@@ -107,7 +110,7 @@ func (a *Agent) read(ctx context.Context, req Request) Result {
return a.ended(pub, req.ID, StateFailed, CodeInterrupted, Summary{}, 0)
}
}
- if res, retry := a.attempt(ctx, req, pub, at); !retry {
+ if res, retry := a.attempt(ctx, req, pub, at, &bound); !retry {
return res
}
}
@@ -136,6 +139,14 @@ func (a *Agent) afterCheckB(ctx context.Context, req Request, pub *ecdh.PublicKe
return a.ended(pub, req.ID, StateFailed, code, s, 0), false
}
+// readBinding is the generation one read resolved, kept across its
+// attempts.
+type readBinding struct {
+ prefix string
+ res lease.Resolved
+ ok bool
+}
+
// settlePoll is how often a retry rereads the unit listing while it waits.
var settlePoll = 200 * time.Millisecond
@@ -143,7 +154,7 @@ var settlePoll = 200 * time.Millisecond
// planned file into a worker that restores and checks it, check B after the
// last byte has left the bucket, and only then run. No output exists before
// check B passes. retry is true when a planned file vanished or changed.
-func (a *Agent) attempt(ctx context.Context, req Request, pub *ecdh.PublicKey, at time.Time) (Result, bool) {
+func (a *Agent) attempt(ctx context.Context, req Request, pub *ecdh.PublicKey, at time.Time, bound *readBinding) (Result, bool) {
fail := func(code string, s Summary) (Result, bool) {
return a.ended(pub, req.ID, StateFailed, code, s, 0), false
}
@@ -164,20 +175,25 @@ func (a *Agent) attempt(ctx context.Context, req Request, pub *ecdh.PublicKey, a
if code != "" {
return refuse(code)
}
- // One resolution per attempt: its plan and every download read the
- // generation it bound. A retry is a fresh attempt, and resolves again.
- res, err := a.cfg.OpenReplica(pctx, activator.HibernatePrefix(a.cfg.HibernatePrefix, rec.Host), at)
- var gone *lease.BeforeHistoryError
- switch {
- case errors.As(err, &gone):
- return failB(CodeHistoryGone, Summary{Oldest: gone.Oldest})
- case errors.Is(err, lease.ErrBeforeHistory):
- return failB(CodeHistoryGone, Summary{})
- case err != nil:
- a.logf("dbreads: %s: open the replica: %v", req.ID, err)
- return fail(CodeInterrupted, Summary{})
+ // One resolution per read: the first attempt binds the generation, and
+ // its plan, every download and the retry's re-plan read it alone. Check
+ // A above still runs on every attempt.
+ prefix := activator.HibernatePrefix(a.cfg.HibernatePrefix, rec.Host)
+ if !bound.ok || bound.prefix != prefix {
+ res, err := a.cfg.OpenReplica(pctx, prefix, at)
+ var gone *lease.BeforeHistoryError
+ switch {
+ case errors.As(err, &gone):
+ return failB(CodeHistoryGone, Summary{Oldest: gone.Oldest})
+ case errors.Is(err, lease.ErrBeforeHistory):
+ return failB(CodeHistoryGone, Summary{})
+ case err != nil:
+ a.logf("dbreads: %s: open the replica: %v", req.ID, err)
+ return fail(CodeInterrupted, Summary{})
+ }
+ *bound = readBinding{prefix: prefix, res: res, ok: true}
}
- var rd dbdoor.ReplicaReader = res.Client
+ var rd dbdoor.ReplicaReader = bound.res.Client
plan, err := dbdoor.PlanFrom(pctx, rd, at)
var before *dbdoor.BeforeHistoryError
switch {
diff --git a/internal/dbreads/resolve_test.go b/internal/dbreads/resolve_test.go
index 025c8eba2..0f29a7870 100644
--- a/internal/dbreads/resolve_test.go
+++ b/internal/dbreads/resolve_test.go
@@ -13,6 +13,7 @@ import (
"github.com/superfly/ltx"
"github.com/carlosframework/platform/internal/dbdoor"
+ "github.com/carlosframework/platform/internal/dbdoor/dbdoortest"
"github.com/carlosframework/platform/internal/lease"
"github.com/carlosframework/platform/internal/replicagen"
)
@@ -79,3 +80,40 @@ func TestDBReadsAtResolvesHistory(t *testing.T) {
t.Fatalf("before history: result %+v summary %+v, want history-gone naming %s", r, s, oldest)
}
}
+
+// G4 across a retry: a planned file vanishes in the first attempt, and head
+// switches to g-2 before the retry. The retry re-plans in g-1, the
+// generation the read resolved, and the opener is never asked again.
+func TestDBReadsRetryKeepsTheGeneration(t *testing.T) {
+ t.Parallel()
+ fx := newFixture(t, 2) // g-1: 20 rows
+ g2 := t.TempDir()
+ dbdoortest.Replicate(t, g2, 3) // g-2: 30 rows
+ g1 := &vanishing{ReplicaReader: lsfile.NewReplicaClient(fx.replica), times: 1}
+ var mu sync.Mutex
+ var opened []string
+ a, _ := fx.agent("uk-1", func(cfg *AgentConfig, _ *inProcWorkers) {
+ cfg.OpenReplica = func(context.Context, string, time.Time) (lease.Resolved, error) {
+ mu.Lock()
+ defer mu.Unlock()
+ opened = append(opened, "open")
+ if len(opened) == 1 {
+ return lease.Resolved{Generation: replicagen.Name(1), Client: readerClient{g1}, HeadFound: true}, nil
+ }
+ // head.json now names g-2.
+ return lease.Resolved{Generation: replicagen.Name(2), Client: lsfile.NewReplicaClient(g2), HeadFound: true}, nil
+ }
+ })
+ rows, _, r := serveOne(t, a, fx, fx.request("SELECT count(*) AS n FROM t", ""))
+ if r.State != StateDone || string(rows) != "n\n20\n" {
+ t.Fatalf("result %+v rows %q, want g-1's 20 rows after the retry", r, rows)
+ }
+ g1.mu.Lock()
+ vanished := g1.times == 0
+ g1.mu.Unlock()
+ mu.Lock()
+ defer mu.Unlock()
+ if !vanished || len(opened) != 1 {
+ t.Fatalf("vanished=%v, resolutions %d; want one vanish and one resolution for the whole read", vanished, len(opened))
+ }
+}
diff --git a/internal/lease/resolve.go b/internal/lease/resolve.go
index 81453c072..8b4d408f8 100644
--- a/internal/lease/resolve.go
+++ b/internal/lease/resolve.go
@@ -65,7 +65,9 @@ func ResolveReplica(ctx context.Context, bucket, loc, region string) (Resolved,
// ended_at. A time older than every kept generation is a
// *BeforeHistoryError; a time no entry covers that is not older than
// all of them (a gap in history) is refused as an error too. With no
-// head.json the root, whatever the time.
+// head.json the root, whatever the time. Inside the bound generation a
+// reader keeps today's CreatedAt rule, S3 LastModified (ruling on Task 6
+// R1 finding 1, spec §6.2): a late file uploaded after at is not read.
func ResolveReplicaAt(ctx context.Context, bucket, loc, region string, at time.Time) (Resolved, error) {
region, err := resolveRegion(ctx, region)
if err != nil {
diff --git a/internal/lease/resolve_test.go b/internal/lease/resolve_test.go
index c9a6b55ff..4ce1d20f0 100644
--- a/internal/lease/resolve_test.go
+++ b/internal/lease/resolve_test.go
@@ -9,7 +9,9 @@ import (
"fmt"
"net/http"
"net/http/httptest"
+ "os"
"path/filepath"
+ "strconv"
"strings"
"sync"
"testing"
@@ -257,10 +259,12 @@ func TestResolveReplicaIsReadOnly(t *testing.T) {
}
}
-// Spec §6.2: a time inside an earlier generation's tenure reads that
-// generation alone, a late file its holder wrote after the successor's
-// copy included; a time at or after the current generation's creation
-// reads the current one; a time before every kept generation is refused.
+// Spec §6.2: a time inside an earlier generation's tenure binds that
+// generation alone (its client lists a late file its holder wrote after
+// the successor's copy; whether a point-in-time restore uses it is the
+// CreatedAt rule, TestPointInTimeRestoreAcrossABoundary); a time at or
+// after the current generation's creation binds the current one; a time
+// before every kept generation is refused.
func TestResolveReplicaAtAcrossABoundary(t *testing.T) {
fx := newRVFixture(t)
g1, g2 := replicagen.Name(1), replicagen.Name(2)
@@ -404,3 +408,178 @@ func TestRestoreFollowsHead(t *testing.T) {
}
}
}
+
+// rows is t's bodies in insertion order.
+func rows(t *testing.T, path string) []string {
+ t.Helper()
+ db, err := sql.Open("sqlite", "file:"+path+"?mode=ro")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ q, err := db.Query("SELECT body FROM t ORDER BY id")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer q.Close()
+ var out []string
+ for q.Next() {
+ var b string
+ if err := q.Scan(&b); err != nil {
+ t.Fatal(err)
+ }
+ out = append(out, b)
+ }
+ return out
+}
+
+// replicaFiles is dir's file replica as level/name pairs ("<level>/<name>").
+func replicaFiles(t *testing.T, dir string) map[string]bool {
+ t.Helper()
+ out := map[string]bool{}
+ levels, err := os.ReadDir(filepath.Join(dir, "ltx"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, lv := range levels {
+ files, err := os.ReadDir(filepath.Join(dir, "ltx", lv.Name()))
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, f := range files {
+ out[lv.Name()+"/"+f.Name()] = true
+ }
+ }
+ return out
+}
+
+// putReplicaFile uploads one file of dir's file replica into gen, in the
+// S3 layout, and returns the LastModified the bucket gave it.
+func (fx *rvFixture) putReplicaFile(t *testing.T, dir, gen, levelName string) time.Time {
+ t.Helper()
+ lv, name, _ := strings.Cut(levelName, "/")
+ level, err := strconv.Atoi(lv)
+ if err != nil {
+ t.Fatal(err)
+ }
+ body, err := os.ReadFile(filepath.Join(dir, "ltx", lv, name))
+ if err != nil {
+ t.Fatal(err)
+ }
+ key := fmt.Sprintf("%s%04x/%s", replicagen.Prefix(rvLoc, gen), level, name)
+ fx.m.Put(rvBucket, key, body)
+ vs, err := fx.m.ListVersions(context.Background(), rvBucket, key)
+ if err != nil || len(vs) == 0 {
+ t.Fatalf("list %s: %v", key, err)
+ }
+ return vs[0].LastModified
+}
+
+// restoreAt is a point-in-time read as the box's db read runs it: plan
+// through the resolver-bound client at at (dbdoor.PlanFrom, the listing's
+// CreatedAt being S3's LastModified), then restore exactly the planned
+// TXID through the same client.
+func restoreAt(t *testing.T, r lease.Resolved, at time.Time) []string {
+ t.Helper()
+ ctx := context.Background()
+ plan, err := dbdoor.PlanFrom(ctx, r.Client, at)
+ if err != nil {
+ t.Fatalf("plan %s at %s: %v", r.Generation, at, err)
+ }
+ out := filepath.Join(t.TempDir(), "pitr.db")
+ if err := dbdoor.RestoreLocal(ctx, r.Client, out, plan.TXID); err != nil {
+ t.Fatalf("restore %s to %d: %v", r.Generation, plan.TXID, err)
+ }
+ return rows(t, out)
+}
+
+// A real witness of §6.2 through the resolver: g-1 holds "one", g-2 holds
+// "one" and "two". A read at a time inside g-1's tenure restores exactly
+// g-1's rows, and one after g-2's creation restores g-2's. The ruling
+// (8a3d302 via the controller, Task 6 R1 finding 1) keeps today's
+// CreatedAt rule, S3's LastModified: g-1's holder's late file, uploaded
+// after g-1's ended_at, is NOT in a read at a time inside g-1's tenure,
+// though g-1's bound client lists it and a newest read of g-1 has it.
+func TestPointInTimeRestoreAcrossABoundary(t *testing.T) {
+ fx := newRVFixture(t)
+ g1, g2 := replicagen.Name(1), replicagen.Name(2)
+ src := filepath.Join(t.TempDir(), "src.db")
+ db, err := sql.Open("sqlite", src)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ if _, err := db.Exec(`PRAGMA journal_mode=WAL; CREATE TABLE t (id INTEGER PRIMARY KEY, body TEXT); INSERT INTO t (body) VALUES ('one')`); err != nil {
+ t.Fatal(err)
+ }
+ dir := t.TempDir()
+ dbdoortest.Sync(t, src, dir)
+ first := replicaFiles(t, dir)
+
+ // g-1: the holder's files for "one".
+ var g1Created, g1Last time.Time
+ for f := range first {
+ lm := fx.putReplicaFile(t, dir, g1, f)
+ if g1Created.IsZero() || lm.Before(g1Created) {
+ g1Created = lm
+ }
+ if lm.After(g1Last) {
+ g1Last = lm
+ }
+ }
+ if _, err := db.Exec(`INSERT INTO t (body) VALUES ('two')`); err != nil {
+ t.Fatal(err)
+ }
+ dbdoortest.Sync(t, src, dir)
+ all := replicaFiles(t, dir)
+ if len(all) <= len(first) {
+ t.Fatalf("fixture: the second sync wrote no file (%d, %d)", len(first), len(all))
+ }
+ // g-2: self-contained, "one" and "two".
+ var g2Last time.Time
+ for f := range all {
+ if lm := fx.putReplicaFile(t, dir, g2, f); lm.After(g2Last) {
+ g2Last = lm
+ }
+ }
+ switchAt := g2Last.Add(500 * time.Millisecond) // g-2 current; g-1 ended
+ // Late: g-1's holder uploads "two" into g-1 after g-1 ended.
+ for f := range all {
+ if !first[f] {
+ if lm := fx.putReplicaFile(t, dir, g1, f); !lm.After(switchAt) {
+ t.Fatalf("fixture: the late file's LastModified %s is not after g-1's end %s", lm, switchAt)
+ }
+ }
+ }
+ fx.head(t, rvLoc, lease.Head{V: 1, Generation: g2, Predecessor: g1,
+ CreatedBy: lease.HeadCreator{LockGeneration: 2, At: switchAt},
+ History: []lease.HeadHistory{{Generation: g1, CreatedAt: g1Created.Add(-time.Second), EndedAt: switchAt}}})
+ ctx := context.Background()
+
+ // After "one" landed (an --at rounds down to its second, and a file
+ // counts only from the next one) and before g-1 ended.
+ inG1 := g1Last.Add(1500 * time.Millisecond)
+ if !inG1.Before(switchAt) {
+ t.Fatalf("fixture: %s is not inside g-1's tenure (ends %s)", inG1, switchAt)
+ }
+ r1, err := lease.ResolveReplicaAt(ctx, rvBucket, rvLoc, rvRegion, inG1)
+ if err != nil || r1.Generation != g1 {
+ t.Fatalf("at %s resolved %q, %v; want g-1", inG1, r1.Generation, err)
+ }
+ if got := restoreAt(t, r1, inG1); strings.Join(got, ",") != "one" {
+ t.Fatalf("a read inside g-1's tenure restored %v, want g-1's [one] without the late file", got)
+ }
+ // The late file is in g-1 and readable: a newest read of g-1 has it.
+ if got := restoreAt(t, r1, time.Time{}); strings.Join(got, ",") != "one,two" {
+ t.Fatalf("a newest read of g-1 restored %v, want [one two] (the late file)", got)
+ }
+
+ after := switchAt.Add(time.Minute)
+ r2, err := lease.ResolveReplicaAt(ctx, rvBucket, rvLoc, rvRegion, after)
+ if err != nil || r2.Generation != g2 {
+ t.Fatalf("at %s resolved %q, %v; want g-2", after, r2.Generation, err)
+ }
+ if got := restoreAt(t, r2, after); strings.Join(got, ",") != "one,two" {
+ t.Fatalf("a read after g-2's creation restored %v, want g-2's [one two]", got)
+ }
+}
diff --git a/internal/ops/hibernate_verify.go b/internal/ops/hibernate_verify.go
index 97aa99332..a99bd1c4f 100644
--- a/internal/ops/hibernate_verify.go
+++ b/internal/ops/hibernate_verify.go
@@ -674,9 +674,16 @@ func bracketReason(code string) string {
// error the drill does not recognise. An error once ctx has ended is the
// run's, and the caller abandons the host.
func (d Drill) restore(ctx context.Context, prefix, dir string) restoreResult {
+ // One resolution for the whole restore (spec 2026-11-12 G4): the re-plan
+ // after a compaction reads the generation the first plan did, even if
+ // head.json has moved on since.
+ rd, err := openReplica(ctx, d.Cfg.Bucket, prefix, d.Cfg.Region)
+ if err != nil {
+ return restoreResult{kind: restoreUnavailable, err: fmt.Errorf("plan: %w", err)}
+ }
var last restoreResult
for attempt := 0; attempt < 2; attempt++ {
- plan, listed, err := d.plan(ctx, prefix)
+ plan, listed, err := d.plan(ctx, rd)
switch {
case errors.Is(err, dbdoor.ErrNothingReplicated):
return restoreResult{kind: restoreNothing, err: err}
@@ -744,13 +751,9 @@ func storageError(err error) bool {
// plan plans the newest copy and returns the listing it planned from, the
// only reader the restore is given: each level is listed once per attempt,
// and a file compacted away since answers os.ErrNotExist, which plans
-// again. Each attempt resolves the replica once (openReplica), so its plan
-// and restore read one generation.
-func (d Drill) plan(ctx context.Context, prefix string) (dbdoor.RestorePlan, dbdoor.ReplicaReader, error) {
- rd, err := openReplica(ctx, d.Cfg.Bucket, prefix, d.Cfg.Region)
- if err != nil {
- return dbdoor.RestorePlan{}, nil, err
- }
+// again. rd is the restore's one resolution (openReplica), so every plan
+// and restore of a host reads one generation.
+func (d Drill) plan(ctx context.Context, rd dbdoor.ReplicaReader) (dbdoor.RestorePlan, dbdoor.ReplicaReader, error) {
return dbdoor.PlanListed(ctx, rd)
}
diff --git a/internal/ops/hibernate_verify_resolve_test.go b/internal/ops/hibernate_verify_resolve_test.go
index d255e3c09..e59783e4b 100644
--- a/internal/ops/hibernate_verify_resolve_test.go
+++ b/internal/ops/hibernate_verify_resolve_test.go
@@ -3,8 +3,12 @@ package ops
import (
"context"
"encoding/json"
+ "net/http"
"net/http/httptest"
+ "os"
"path/filepath"
+ "strings"
+ "sync"
"testing"
"time"
@@ -18,15 +22,32 @@ import (
"github.com/carlosframework/platform/internal/replicagen"
)
-// The restore drill reads through the resolver (spec §6.1): on a host with
-// head.json it plans the current generation, never the root its
-// predecessor left. The production opener runs against leasetest's S3.
-func TestDrillResolvesHead(t *testing.T) {
- const bucket, loc = "data", "hib/shop.example.com"
- m := leasetest.NewVersionedBucket()
- m.AddBucket(bucket)
- handler, _ := leasetest.NewS3Server(m)
- srv := httptest.NewServer(handler)
+const (
+ rsBucket = "data"
+ rsLoc = "hib/shop.example.com"
+)
+
+// rsFixture is the data bucket behind leasetest's S3, reached as
+// production reaches it, counting head.json reads.
+type rsFixture struct {
+ m *leasetest.VersionedBucket
+ mu sync.Mutex
+ heads int
+}
+
+func newRSFixture(t *testing.T) *rsFixture {
+ t.Helper()
+ fx := &rsFixture{m: leasetest.NewVersionedBucket()}
+ fx.m.AddBucket(rsBucket)
+ handler, _ := leasetest.NewS3Server(fx.m)
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/head.json") {
+ fx.mu.Lock()
+ fx.heads++
+ fx.mu.Unlock()
+ }
+ handler.ServeHTTP(w, r)
+ }))
t.Cleanup(srv.Close)
t.Setenv("AWS_ACCESS_KEY_ID", "test-key")
t.Setenv("AWS_SECRET_ACCESS_KEY", "test-secret")
@@ -35,41 +56,93 @@ func TestDrillResolvesHead(t *testing.T) {
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)
+ return fx
+}
- gen := replicagen.Name(42)
- put := func(name string, batches int) string {
- dir := t.TempDir()
- dbdoortest.Replicate(t, dir, batches)
- if _, err := m.PutFileReplica(bucket, replicagen.Prefix(loc, name), dir); err != nil {
- t.Fatal(err)
- }
- return dir
+// replica writes a real replica of batches*10 rows into gen and returns
+// the newest position a plan of it reaches.
+func (fx *rsFixture) replica(t *testing.T, gen string, batches int) uint64 {
+ t.Helper()
+ dir := t.TempDir()
+ dbdoortest.Replicate(t, dir, batches)
+ if _, err := fx.m.PutFileReplica(rsBucket, replicagen.Prefix(rsLoc, gen), dir); err != nil {
+ t.Fatal(err)
+ }
+ p, err := dbdoor.PlanFrom(context.Background(), lsfile.NewReplicaClient(dir), time.Time{})
+ if err != nil {
+ t.Fatal(err)
}
- rootDir := put(replicagen.Root, 1)
- genDir := put(gen, 3)
- body, _ := json.Marshal(lease.Head{V: 1, Generation: gen, StartTXID: 1, Predecessor: replicagen.Root,
+ return p.TXID
+}
+
+func (fx *rsFixture) head(t *testing.T, gen string) {
+ t.Helper()
+ body, err := json.Marshal(lease.Head{V: 1, Generation: gen, StartTXID: 1, Predecessor: replicagen.Root,
CreatedBy: lease.HeadCreator{LockGeneration: 42, At: time.Date(2026, 11, 12, 10, 0, 0, 0, time.UTC)},
History: []lease.HeadHistory{}})
- m.Put(bucket, loc+"/head.json", body)
-
- ctx := context.Background()
- want, err := dbdoor.PlanFrom(ctx, lsfile.NewReplicaClient(genDir), time.Time{})
if err != nil {
t.Fatal(err)
}
- rootPlan, err := dbdoor.PlanFrom(ctx, lsfile.NewReplicaClient(rootDir), time.Time{})
- if err != nil || rootPlan.TXID >= want.TXID {
- t.Fatalf("fixture: root plan %d, generation plan %d, %v", rootPlan.TXID, want.TXID, err)
+ fx.m.Put(rsBucket, rsLoc+"/head.json", body)
+}
+
+func (fx *rsFixture) headReads() int {
+ fx.mu.Lock()
+ defer fx.mu.Unlock()
+ return fx.heads
+}
+
+// The restore drill reads through the resolver (spec §6.1): on a host with
+// head.json it plans and restores the current generation, never the root
+// its predecessor left. The production opener and restore run against
+// leasetest's S3.
+func TestDrillResolvesHead(t *testing.T) {
+ fx := newRSFixture(t)
+ gen := replicagen.Name(42)
+ root := fx.replica(t, replicagen.Root, 1)
+ want := fx.replica(t, gen, 3)
+ if root >= want {
+ t.Fatalf("fixture: root ends at %d, the generation at %d", root, want)
}
- d := Drill{Cfg: &activator.Config{Bucket: bucket, Region: "us-east-1"}}
- plan, listed, err := d.plan(ctx, loc)
- if err != nil {
- t.Fatal(err)
+ fx.head(t, gen)
+ swap(t, &verifyAt, lease.VerifyReaderAt)
+ d := Drill{Cfg: &activator.Config{Bucket: rsBucket, Region: "us-east-1"}}
+ res := d.restore(context.Background(), rsLoc, t.TempDir())
+ if res.kind != restoreClean || res.plan.TXID != want {
+ t.Fatalf("drill restore %v at %d (%v), want clean at the generation's %d", res.kind, res.plan.TXID, res.err, want)
}
- if plan.TXID != want.TXID || plan.Files != want.Files {
- t.Fatalf("drill planned %d (%d files), want the generation's %d (%d files)", plan.TXID, plan.Files, want.TXID, want.Files)
+ if n := fx.headReads(); n != 1 {
+ t.Fatalf("%d head.json reads for one restore, want 1", n)
+ }
+}
+
+// G4 across a re-plan: the first restore attempt finds its planned
+// position compacted away, and head.json switches to g-2 before the
+// re-plan. The re-plan still reads g-1, the generation the drill resolved,
+// and head.json is read once.
+func TestDrillRetryKeepsTheGeneration(t *testing.T) {
+ fx := newRSFixture(t)
+ g1, g2 := replicagen.Name(1), replicagen.Name(2)
+ want := fx.replica(t, g1, 2)
+ if other := fx.replica(t, g2, 3); other == want {
+ t.Fatalf("fixture: both generations end at %d", want)
+ }
+ fx.head(t, g1)
+ calls := 0
+ swap(t, &verifyAt, func(ctx context.Context, rd lease.ReplicaReader, prefix, dir string, txid uint64) (uint32, error) {
+ calls++
+ if calls == 1 {
+ fx.head(t, g2) // the take moved head on
+ return 0, os.ErrNotExist
+ }
+ return lease.VerifyReaderAt(ctx, rd, prefix, dir, txid)
+ })
+ d := Drill{Cfg: &activator.Config{Bucket: rsBucket, Region: "us-east-1"}}
+ res := d.restore(context.Background(), rsLoc, t.TempDir())
+ if res.kind != restoreClean || res.plan.TXID != want || calls != 2 {
+ t.Fatalf("drill restore %v at %d after %d attempts (%v), want clean at g-1's %d after 2", res.kind, res.plan.TXID, calls, res.err, want)
}
- if _, err := lease.VerifyReaderAt(ctx, listed, loc, t.TempDir(), plan.TXID); err != nil {
- t.Fatalf("the drill's restore of the generation: %v", err)
+ if n := fx.headReads(); n != 1 {
+ t.Fatalf("%d head.json reads, want 1 for the whole restore", n)
}
}
diff --git a/internal/ops/hibernate_verify_restore_test.go b/internal/ops/hibernate_verify_restore_test.go
index f93049d5b..a29e481c4 100644
--- a/internal/ops/hibernate_verify_restore_test.go
+++ b/internal/ops/hibernate_verify_restore_test.go
@@ -147,24 +147,38 @@ func TestVerifyHibernatingReplansAMissingObject(t *testing.T) {
t.Run(name, func(t *testing.T) {
fx := newDrillFx(t, host)
client := &missingClient{ReplicaClient: lsfile.NewReplicaClient(fx.replica), gone: c.gone}
- plans := 0
+ opens, plans := 0, 0
swap(t, &openReplica, func(context.Context, string, string, string) (dbdoor.ReplicaReader, error) {
- plans++
- return client, nil
+ opens++
+ return planCounter{ReplicaReader: client, plans: &plans}, nil
})
swap(t, &verifyAt, lease.VerifyReaderAt) // the production restore, over the planner's listing
v := fx.run(context.Background(), fx.drill(), fx.routes(host), nil)[host]
if v.Result != c.result || v.Reason != c.reason {
t.Fatalf("verdict %s/%s, want %s/%s (%+v)", v.Result, v.Reason, c.result, c.reason, v)
}
- if plans != 2 {
- t.Fatalf("planned %d times, want once and one replan", plans)
+ if plans != 2 || opens != 1 {
+ t.Fatalf("planned %d times over %d resolutions, want once and one replan over one (G4)", plans, opens)
}
fx.scratchEmpty()
})
}
}
+// planCounter counts plans: each plan lists the snapshot level of the
+// replica once (dbdoor.PlanListed's listing keeps what it listed).
+type planCounter struct {
+ dbdoor.ReplicaReader
+ plans *int
+}
+
+func (c planCounter) LTXFiles(ctx context.Context, level int, seek ltx.TXID, useMetadata bool) (ltx.FileIterator, error) {
+ if level == litestream.SnapshotLevel {
+ *c.plans++
+ }
+ return c.ReplicaReader.LTXFiles(ctx, level, seek, useMetadata)
+}
+
// corruptReplica writes a one-file replica in dir: an LTX snapshot (TXID
// 1) of a small database whose page 3 is scribbled over. The LTX itself is
// whole and checksummed, so the restore succeeds, and only the check of