carlos / platform Public

console: replica readers resolve and bind a generation

Generations Task 8 (spec 2026-11-12 §6.1, §6.2; plan corrections from
Astra plan R1 findings 6 and 7, ruling B).

The db door binds one generation per read:
- dbReplica(ctx, prefix, gen, at) returns lease.Resolved: gen set binds
  it (lease.BindReplica, no head.json read); else ResolveReplicaAt.
  The client cache keys on prefix+"\x00"+generation; an unbound
  resolution reads head.json every time and shares the generation's
  one client.
- List and GET accept gen (strict replicagen.Valid, else 400); the list
  accepts at (RFC 3339, else 400) and names its generation.
- An unbound list or GET of a host with head.json is 409 with the
  approved sentence and the generation to bind (dbdoor.GenerationBody);
  no replica file is read. Root-layout hosts keep today's protocol.
- A bound read stays on its generation after head moves. A retired one
  (not in head or history) is 410 generation_gone, checked only on an
  empty snapshot or level-0 listing or a 404 GET. An as-of time before
  every kept generation is 410 with the oldest time.

The CLI client (dbdoor.Client) binds the first generation a listing
names (a 200's, or a 409's marker, followed once) and sends gen on
every later request; an as-of first listing sends at. A bound listing
naming another generation is ErrGenerationChanged. restoreAt restarts
once, unbound, on ErrGenerationGone; twice is os.ErrNotExist, the
existing "changed twice" sentence. A console that names no generation
keeps the client on the unbound protocol.

Backups, the --from seed copy and the leftover rail use the resolver.
The leftover rail counts head.json as data (free: the resolution reads
it) and, on the legacy path, one bounded LIST of <loc>/g- through the
data store for an abandoned generation. replicaDoer ignores the query.
Test fakes and request witnesses are updated for the new seam and the
one new bounded listing.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev f339c6e16933d2fa00a79ec9b0c97bfd378bd22a parent 7f41e09
32 files changed, +1,570 −156
  • internal/console/apibackups_test.go +4 −3
  • internal/console/apidb.go +187 −51
  • internal/console/apidb_generations_test.go +529 −0
  • internal/console/apidb_test.go +29 −17
  • internal/console/apiinstances_haenable_test.go +2 −2
  • internal/console/apiinstanceseed.go +2 −2
  • internal/console/apiinstanceseed_test.go +2 −2
  • internal/console/backups.go +2 −2
  • internal/console/backups_test.go +10 −10
  • internal/console/createleftovers.go +42 −6
  • internal/console/createleftovers_test.go +8 −8
  • internal/console/dbforward_minio_test.go +2 −2
  • internal/console/demo_claim_e2e_test.go +2 −2
  • internal/console/demo_claim_ha_gate_test.go +2 −2
  • internal/console/demo_claim_seed_test.go +2 −2
  • internal/console/demo_claim_transfer_test.go +2 −2
  • internal/console/ha_pool_scope_test.go +6 −6
  • internal/console/hacreate_test.go +7 −4
  • internal/console/hacreatecapacity_test.go +2 −2
  • internal/console/hap2_wiring_test.go +9 −2
  • internal/console/instancepage_test.go +4 −4
  • internal/console/restore_door_test.go +2 −2
  • internal/console/restore_proof_test.go +3 −0
  • internal/console/restore_sim_test.go +2 −2
  • internal/console/seeddoer.go +4 −0
  • internal/console/server.go +4 −3
  • internal/dbdoor/client.go +50 −14
  • internal/dbdoor/client_test.go +3 −0
  • internal/dbdoor/coords.go +37 −3
  • internal/dbdoor/generation.go +142 −0
  • internal/dbdoor/generation_test.go +442 −0
  • internal/dbdoor/restore.go +26 −1
diff --git a/internal/console/apibackups_test.go b/internal/console/apibackups_test.go
index a7af1e5d7..6d239ec81 100644
--- a/internal/console/apibackups_test.go
+++ b/internal/console/apibackups_test.go
@@ -72,12 +72,13 @@ func TestAPIInstanceBackupsKeySets(t *testing.T) {
here := fx.srv.cfg.Region // dbTestHost's record is homed here
const untimed = "untimed.go.tito.io"
onDisk := fx.srv.dbReplica
- fx.srv.dbReplica = func(ctx context.Context, prefix string) (replicaReader, error) {
+ fx.srv.dbReplica = rootReplica(func(ctx context.Context, prefix string) (replicaReader, error) {
if prefix == "instances/"+untimed {
return &untimedReplica{listedReplica{n: 2, at: time.Date(2026, 11, 11, 9, 0, 0, 0, time.UTC)}}, nil
}
- return onDisk(ctx, prefix)
- }
+ res, err := onDisk(ctx, prefix, "", time.Time{})
+ return res.Client, err
+ })
for _, rec := range []provision.Record{
{Host: untimed, Region: here},
{Host: "born-ha.go.tito.io", Region: here, HA: true},
diff --git a/internal/console/apidb.go b/internal/console/apidb.go
index 63672c32c..3ea3814b7 100644
--- a/internal/console/apidb.go
+++ b/internal/console/apidb.go
@@ -26,6 +26,7 @@ import (
"time"
"github.com/aws/smithy-go"
+ "github.com/benbjohnson/litestream"
"github.com/superfly/ltx"
"github.com/carlosframework/platform/internal/activator"
@@ -35,6 +36,7 @@ import (
"github.com/carlosframework/platform/internal/lease"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/replicagen"
)
var (
@@ -101,15 +103,62 @@ type dbRequest struct {
host string
prefix string
rd replicaReader
+ // gen is the replica generation rd reads (spec 2026-11-12 §6.1): the
+ // one the request was bound to, else the one it resolved.
+ gen string
+}
+
+// dbBinding is the bound door's request (spec 2026-11-12 §6.1, §6.2):
+// the generation a read is bound to, or for an unbound as-of listing the
+// time to resolve one for. Both zero is an unbound read of the current
+// generation.
+type dbBinding struct {
+ gen string
+ at time.Time
+}
+
+// dbNeedsNewerCLI is the 409 for an unbound read of a host whose replica
+// has generations: an old CLI, which cannot bind one, would mix them
+// across a switch, so it is refused (ruling B). %s is the host. Approved
+// in copy review (Task 8, 2026-11-17).
+const dbNeedsNewerCLI = "This version of carlos cannot safely read %s's data. Run carlos update, then run carlos db pull or carlos db query again."
+
+// parseDBBinding reads gen (strict: replicagen.Valid) and, when list, at
+// (RFC 3339). Anything else is a 400 before any read, and ok=false means
+// it has been written. A GET ignores at: only an unbound listing resolves.
+func parseDBBinding(w http.ResponseWriter, r *http.Request, list bool) (dbBinding, bool) {
+ q := r.URL.Query()
+ var b dbBinding
+ if q.Has(dbdoor.GenParam) {
+ b.gen = q.Get(dbdoor.GenParam)
+ if !replicagen.Valid(b.gen) {
+ jsonError(w, http.StatusBadRequest, "invalid generation")
+ return dbBinding{}, false
+ }
+ }
+ if list && q.Has(dbdoor.AtParam) {
+ at, err := time.Parse(time.RFC3339Nano, q.Get(dbdoor.AtParam))
+ if err != nil {
+ jsonError(w, http.StatusBadRequest, "invalid time")
+ return dbBinding{}, false
+ }
+ if b.gen == "" {
+ b.at = at
+ }
+ }
+ return b, true
}
// dbGate is the door's whole gate, in the repo's order: principal (cliRoute
// has already refused every service credential at the zero Set) ->
// membership (byte-identical 404) -> budget (429) -> configuration (503) ->
// the record (404 when absent) -> the class rail and residency (409), none
-// of which touches the bucket -> the replica client. ok=false means a
-// response has been written.
-func (s *Server) dbGate(w http.ResponseWriter, r *http.Request) (dbRequest, bool) {
+// of which touches the bucket -> the replica client, bound to sel's
+// generation or resolved (spec 2026-11-12 §6.1). An unbound read of a host
+// with head.json is refused with 409 before any replica read, naming the
+// generation a new CLI binds; a root-layout host keeps today's unbound
+// protocol. ok=false means a response has been written.
+func (s *Server) dbGate(w http.ResponseWriter, r *http.Request, sel dbBinding) (dbRequest, bool) {
// Belt to cliRoute's braces: the zero Set already stops every service
// principal before this runs, so this line is only reached by a request
// that did not come through cliRoute at all.
@@ -168,13 +217,22 @@ func (s *Server) dbGate(w http.ResponseWriter, r *http.Request) (dbRequest, bool
if s.cfg.HostClaim {
return dbRequest{claim: src.claim, acct: acct, actor: actor, app: app, host: host, prefix: src.prefix}, true
}
- rd, err := s.dbReplica(ctx, src.prefix)
- if err != nil {
+ res, err := s.dbReplica(ctx, src.prefix, sel.gen, sel.at)
+ var before *lease.BeforeHistoryError
+ switch {
+ case errors.As(err, &before):
+ oldest := before.Oldest.UTC()
+ writeJSON(w, http.StatusGone, dbdoor.GenerationBody{Oldest: &oldest})
+ return dbRequest{}, false
+ case err != nil:
log.Printf("console: api db %s/%s/%s: replica client: %v", acct.Sqid, app, host, err)
jsonError(w, http.StatusBadGateway, "could not read the replica. Try again.")
return dbRequest{}, false
+ case sel.gen == "" && res.HeadFound:
+ writeJSON(w, http.StatusConflict, dbdoor.GenerationBody{Error: fmt.Sprintf(dbNeedsNewerCLI, host), Generation: res.Generation})
+ return dbRequest{}, false
}
- return dbRequest{acct: acct, actor: actor, app: app, host: host, prefix: src.prefix, rd: rd}, true
+ return dbRequest{acct: acct, actor: actor, app: app, host: host, prefix: src.prefix, rd: res.Client, gen: res.Generation}, true
}
var (
@@ -304,7 +362,11 @@ func (s *Server) handleAPIDBList(w http.ResponseWriter, r *http.Request) {
http.NotFound(w, r)
return
}
- g, ok := s.dbGate(w, r)
+ sel, ok := parseDBBinding(w, r, true)
+ if !ok {
+ return
+ }
+ g, ok := s.dbGate(w, r, sel)
if !ok {
return
}
@@ -323,9 +385,42 @@ func (s *Server) handleAPIDBList(w http.ResponseWriter, r *http.Request) {
s.dbStoreFailure(w, g, fmt.Sprintf("list level %d", level), err)
return
}
+ // A retired generation lists empty. Litestream lists the snapshot
+ // level first and level 0 last in every plan, so asking head.json only
+ // when one of those two is empty catches a retirement before or during
+ // a plan for at most two head reads a restore, not one per empty level.
+ if sel.gen != "" && len(out.Files) == 0 && (level == litestream.SnapshotLevel || level == 0) && s.dbGenerationGone(r.Context(), g) {
+ writeJSON(w, http.StatusGone, dbdoor.GenerationBody{GenerationGone: g.gen})
+ return
+ }
+ out.Generation = g.gen
writeJSON(w, http.StatusOK, out)
}
+// dbGenerationGone reports whether g's bound generation was retired:
+// neither head.json nor its history names it (spec 2026-11-12 §8), or,
+// with no head.json, it is not the root. One head.json read; a failed one
+// is "not gone", and the caller answers as it would have.
+func (s *Server) dbGenerationGone(ctx context.Context, g dbRequest) bool {
+ res, err := s.dbReplica(ctx, g.prefix, "", time.Time{})
+ if err != nil {
+ log.Printf("console: api db %s/%s/%s: is generation %s retired: %v", g.acct.Sqid, g.app, g.host, g.gen, err)
+ return false
+ }
+ if !res.HeadFound {
+ return g.gen != replicagen.Root
+ }
+ if res.Head.Generation == g.gen {
+ return false
+ }
+ for _, e := range res.Head.History {
+ if e.Generation == g.gen {
+ return false
+ }
+ }
+ return true
+}
+
// listReplicaLevel lists one level of rd in the door's wire shape, ordered
// by MinTXID, with an empty level as an empty list. The db door and the
// console's own in-process door (replicaDoer, for --from) both list
@@ -351,7 +446,11 @@ func (s *Server) handleAPIDBGet(w http.ResponseWriter, r *http.Request) {
http.NotFound(w, r)
return
}
- g, ok := s.dbGate(w, r)
+ sel, ok := parseDBBinding(w, r, false)
+ if !ok {
+ return
+ }
+ g, ok := s.dbGate(w, r, sel)
if !ok {
return
}
@@ -393,6 +492,10 @@ func (s *Server) handleAPIDBGet(w http.ResponseWriter, r *http.Request) {
defer watchdog.Stop()
rc, err := g.rd.OpenLTXFile(ctx, level, ltx.TXID(minTXID), ltx.TXID(maxTXID), offset, size)
if errors.Is(err, os.ErrNotExist) {
+ if pinned == nil && sel.gen != "" && s.dbGenerationGone(ctx, g) {
+ writeJSON(w, http.StatusGone, dbdoor.GenerationBody{GenerationGone: g.gen})
+ return
+ }
http.NotFound(w, r)
return
}
@@ -480,90 +583,123 @@ func dbStream(w io.Writer, rw *http.ResponseController, rc io.Reader, watchdog *
// dbReplicaCacheMax bounds the replica-client cache. Each client owns an
// HTTP transport, so one per request would cost a TLS handshake per file and
-// leave an idle connection behind each; one per prefix lets a restore's
+// leave an idle connection behind each; one per generation lets a restore's
// dozens of requests share one. Over the bound the map is dropped
// wholesale, the rateLimiter's rule: forgetting clients costs a handshake,
// 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.
+// dbReplicaResolveLimit bounds one resolution (its head.json read, or a
+// bind's client). It runs detached from the caller that started it, so a
+// caller giving up cannot fail the others waiting on the same flight.
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.
+ mu sync.Mutex
+ // clients holds one read-only client per generation, keyed
+ // prefix+"\x00"+generation (spec 2026-11-12 §6.1). A generation is
+ // never rewritten by a later holder, so its client never goes stale.
+ clients map[string]litestream.ReplicaClient
+ // flights are the resolutions in progress: every miss on one key waits
+ // on its 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.
+// dbReplicaFlight is one resolution in progress; done closes once res and
+// err are set.
type dbReplicaFlight struct {
done chan struct{}
- rd replicaReader
+ res lease.Resolved
err error
}
-// cachedReadReplica is the production dbReplica: lease.ResolveReplica on
-// the configured bucket, one per prefix. The cache still holds the
-// generation a prefix first resolved to; keying it by generation, and
-// 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.
+// cachedReadReplica is the production dbReplica, on the configured
+// bucket:
//
-// 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) {
+// - gen set: lease.BindReplica, which reads no head.json, so a bound
+// read (the CLI's every request after its first listing) costs no
+// request beyond its own.
+// - gen unset: lease.ResolveReplicaAt (at zero: the current generation),
+// one head.json GET per call. The head is read every time, never
+// cached, because it is how a read learns where the replica is now.
+//
+// Either way the client is the generation's one cached client. The
+// cache's lock is held only to look up and insert: a resolution runs
+// outside it, so a slow read on one prefix never holds up another, cached
+// or not. Concurrent misses on one key share a single resolution, and
+// each waiter stops waiting when its own ctx ends.
+func (s *Server) cachedReadReplica(ctx context.Context, prefix, gen string, at time.Time) (lease.Resolved, error) {
c := &s.dbClients
- c.mu.Lock()
- if rd, ok := c.clients[prefix]; ok {
+ if gen != "" {
+ if !replicagen.Valid(gen) {
+ return lease.Resolved{}, fmt.Errorf("db: %q is not a replica generation", gen)
+ }
+ c.mu.Lock()
+ rc, ok := c.clients[prefix+"\x00"+gen]
c.mu.Unlock()
- return rd, nil
+ if ok {
+ return lease.Resolved{Generation: gen, Client: rc}, nil
+ }
+ return s.dbReplicaFlight(ctx, "bind\x00"+prefix+"\x00"+gen, func(ctx context.Context) (lease.Resolved, error) {
+ return lease.BindReplica(ctx, s.cfg.HibernateBucket, prefix, s.cfg.HibernateRegion, gen)
+ }, prefix)
+ }
+ stamp := ""
+ if !at.IsZero() {
+ stamp = at.UTC().Format(time.RFC3339Nano)
}
- f, ok := c.flights[prefix]
+ return s.dbReplicaFlight(ctx, "resolve\x00"+prefix+"\x00"+stamp, func(ctx context.Context) (lease.Resolved, error) {
+ return lease.ResolveReplicaAt(ctx, s.cfg.HibernateBucket, prefix, s.cfg.HibernateRegion, at)
+ }, prefix)
+}
+
+// dbReplicaFlight joins key's flight, starting it with resolve when there
+// is none, and waits for it or for ctx.
+func (s *Server) dbReplicaFlight(ctx context.Context, key string, resolve func(context.Context) (lease.Resolved, error), prefix string) (lease.Resolved, error) {
+ c := &s.dbClients
+ c.mu.Lock()
+ f, ok := c.flights[key]
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.flights[key] = f
+ go s.runReplicaFlight(context.WithoutCancel(ctx), key, prefix, resolve, f)
}
c.mu.Unlock()
select {
case <-f.done:
- return f.rd, f.err
+ return f.res, f.err
case <-ctx.Done():
- return nil, ctx.Err()
+ return lease.Resolved{}, 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) {
+// runReplicaFlight runs f's resolution and publishes it to every waiter.
+// On success the generation's cached client, when there is one, replaces
+// the one just built, so a generation keeps one client (and transport);
+// otherwise the new one is cached.
+func (s *Server) runReplicaFlight(ctx context.Context, key, prefix string, resolve func(context.Context) (lease.Resolved, error), 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 {
- f.rd = r.Client
- }
- f.err = err
+ res, err := resolve(ctx)
c := &s.dbClients
c.mu.Lock()
- delete(c.flights, prefix)
+ delete(c.flights, key)
if err == nil {
- if c.clients == nil || len(c.clients) >= dbReplicaCacheMax {
- c.clients = make(map[string]replicaReader, 8)
+ gkey := prefix + "\x00" + res.Generation
+ if rc, ok := c.clients[gkey]; ok {
+ res.Client = rc
+ } else {
+ if c.clients == nil || len(c.clients) >= dbReplicaCacheMax {
+ c.clients = make(map[string]litestream.ReplicaClient, 8)
+ }
+ c.clients[gkey] = res.Client
}
- c.clients[prefix] = f.rd
}
c.mu.Unlock()
+ f.res, f.err = res, err
close(f.done)
}
diff --git a/internal/console/apidb_generations_test.go b/internal/console/apidb_generations_test.go
new file mode 100644
index 000000000..588198f0f
--- /dev/null
+++ b/internal/console/apidb_generations_test.go
@@ -0,0 +1,529 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/benbjohnson/litestream"
+ lsfile "github.com/benbjohnson/litestream/file"
+ "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/lease/leasetest"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/replicagen"
+)
+
+// rootReplica adapts a test's prefix-only replica opener to dbReplica:
+// every prefix resolves to its root generation, as a host without
+// head.json does, whatever generation or time the caller asks for.
+func rootReplica(open func(context.Context, string) (replicaReader, error)) func(context.Context, string, string, time.Time) (lease.Resolved, error) {
+ return func(ctx context.Context, prefix, _ string, _ time.Time) (lease.Resolved, error) {
+ rd, err := open(ctx, prefix)
+ if err != nil {
+ return lease.Resolved{}, err
+ }
+ if c, ok := rd.(litestream.ReplicaClient); ok {
+ return lease.Resolved{Generation: replicagen.Root, Client: c}, nil
+ }
+ return lease.Resolved{Generation: replicagen.Root, Client: readerClient{rd}}, nil
+ }
+}
+
+// readerClient is a test's two-method replica as the litestream client a
+// resolution carries. The door only reads.
+type readerClient struct{ replicaReader }
+
+func (readerClient) Type() string { return "test" }
+func (readerClient) Init(context.Context) error { return nil }
+func (readerClient) SetLogger(*slog.Logger) {}
+func (readerClient) DeleteAll(context.Context) error { return lease.ErrReadOnlyReplica }
+func (readerClient) DeleteLTXFiles(context.Context, []*ltx.FileInfo) error {
+ return lease.ErrReadOnlyReplica
+}
+func (readerClient) WriteLTXFile(context.Context, int, ltx.TXID, ltx.TXID, io.Reader) (*ltx.FileInfo, error) {
+ return nil, lease.ErrReadOnlyReplica
+}
+
+// isGenerationsProbe is the legacy leftover rail's one bounded listing
+// for an abandoned generation (prefixHoldsGenerations): <loc>/g-. Fakes
+// that sense a different proof through their data store's listings (the
+// HA prefix proof, the restore staging proof) pass it through unseen.
+func isGenerationsProbe(prefix string) bool { return strings.HasSuffix(prefix, "/g-") }
+
+// ---- the bound door (spec 2026-11-12 §6.1, §6.2; generations Task 8) ----
+
+var (
+ genA = replicagen.Name(1)
+ genB = replicagen.Name(2)
+ // genT0 and genT1 are when g-1 and g-2 became current.
+ genT0 = time.Date(2026, 11, 10, 9, 0, 0, 0, time.UTC)
+ genT1 = time.Date(2026, 11, 12, 9, 0, 0, 0, time.UTC)
+)
+
+// wantNeedsNewerCLI is the approved 409 (copy review, ruling B), verbatim.
+const wantNeedsNewerCLI = "This version of carlos cannot safely read %s's data. Run carlos update, then run carlos db pull or carlos db query again."
+
+// genBucket is a data bucket behind leasetest's S3, reached the way
+// production reaches it (CARLOS_S3_ENDPOINT), with every request logged,
+// and the server's dbReplica on the production reader over it.
+type genBucket struct {
+ m *leasetest.VersionedBucket
+ mu sync.Mutex
+ reqs []string // "METHOD key", or "GET ?prefix=<p>" for a listing
+}
+
+func useGenBucket(t *testing.T, s *Server) *genBucket {
+ t.Helper()
+ b := &genBucket{m: leasetest.NewVersionedBucket()}
+ b.m.AddBucket("data-test")
+ handler, _ := leasetest.NewS3Server(b.m)
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ key := strings.TrimPrefix(strings.TrimPrefix(r.URL.Path, "/data-test"), "/")
+ if key == "" {
+ key = "?prefix=" + r.URL.Query().Get("prefix")
+ }
+ b.mu.Lock()
+ b.reqs = append(b.reqs, r.Method+" "+key)
+ b.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")
+ t.Setenv("AWS_SESSION_TOKEN", "")
+ t.Setenv("AWS_REGION", "us-east-1")
+ 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)
+ s.cfg.HibernateBucket = "data-test"
+ s.cfg.HibernateRegion = "us-east-1"
+ s.cfg.HibernatePrefix = "instances"
+ s.dbReplica = s.cachedReadReplica
+ return b
+}
+
+// replica writes a real litestream replica of batches*10 rows into host's
+// generation gen, and returns the file replica it was copied from.
+func (b *genBucket) replica(t *testing.T, host, gen string, batches int) *lsfile.ReplicaClient {
+ t.Helper()
+ dir := t.TempDir()
+ dbdoortest.Replicate(t, dir, batches)
+ if _, err := b.m.PutFileReplica("data-test", replicagen.Prefix("instances/"+host, gen), dir); err != nil {
+ t.Fatal(err)
+ }
+ return lsfile.NewReplicaClient(dir)
+}
+
+func (b *genBucket) head(t *testing.T, host, gen string, at time.Time, history ...lease.HeadHistory) {
+ t.Helper()
+ if history == nil {
+ history = []lease.HeadHistory{}
+ }
+ h := lease.Head{V: lease.HeadVersion, Generation: gen, History: history,
+ CreatedBy: lease.HeadCreator{LockGeneration: 1, Box: "box-a", IID: "i-0abc", Lifetime: "l-1", At: at}}
+ body, err := json.Marshal(h)
+ if err != nil {
+ t.Fatal(err)
+ }
+ b.m.Put("data-test", "instances/"+host+"/head.json", body)
+}
+
+// count is how many logged requests match.
+func (b *genBucket) count(match func(string) bool) int {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ n := 0
+ for _, r := range b.reqs {
+ if match(r) {
+ n++
+ }
+ }
+ return n
+}
+
+func (b *genBucket) all() []string {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ return append([]string(nil), b.reqs...)
+}
+
+func isHeadRead(r string) bool {
+ return strings.HasPrefix(r, "GET ") && strings.HasSuffix(r, "/head.json")
+}
+
+// isLTXRead is a GET of an LTX file: a replica read.
+func isLTXRead(r string) bool { return strings.HasPrefix(r, "GET ") && strings.HasSuffix(r, ".ltx") }
+
+func newestTXID(t *testing.T, rd replicaReader) uint64 {
+ t.Helper()
+ p, err := dbdoor.PlanFrom(context.Background(), rd, time.Time{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ return p.TXID
+}
+
+func genFile(t *testing.T, c *lsfile.ReplicaClient) (*ltx.FileInfo, []byte) {
+ t.Helper()
+ f := listFiles(t, c, 0)[0]
+ body, err := os.ReadFile(c.LTXFilePath(0, f.MinTXID, f.MaxTXID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return f, body
+}
+
+// genDoor is the db door over a genBucket: dbTestHost's record, a member.
+func genDoor(t *testing.T) (*dbFx, *genBucket) {
+ t.Helper()
+ fx := dbFixture(t)
+ return fx, useGenBucket(t, fx.srv)
+}
+
+func (fx *dbFx) list(t *testing.T, host string, level int, query string) (int, string) {
+ t.Helper()
+ return getRaw(t, fx.url(dbdoor.ListPath("bab", "titogo", host, level)+query), fx.member)
+}
+
+// get is a download as the CLI sends it, with its Range header.
+func (fx *dbFx) get(t *testing.T, level int, lo, hi ltx.TXID, query string) (int, string) {
+ t.Helper()
+ u := fx.url(dbdoor.GetPath("bab", "titogo", dbTestHost, level, uint64(lo), uint64(hi)) + query)
+ status, _, out := rawReqHeader(t, http.MethodGet, u, fx.member, "", map[string]string{"Range": dbdoor.RangeHeader(0, 0)})
+ return status, out
+}
+
+func genBody(t *testing.T, out string) dbdoor.GenerationBody {
+ t.Helper()
+ var b dbdoor.GenerationBody
+ if err := json.Unmarshal([]byte(out), &b); err != nil {
+ t.Fatalf("body %q: %v", out, err)
+ }
+ return b
+}
+
+func q(gen string) string { return "?" + dbdoor.GenParam + "=" + url.QueryEscape(gen) }
+
+// The point of binding: a GET carrying g-1 reads g-1 after head has moved
+// to g-2, whose same-named L0 file holds other bytes, and reads no head.
+func TestDoorGetStaysOnTheBoundGeneration(t *testing.T) {
+ fx, b := genDoor(t)
+ one := b.replica(t, dbTestHost, genA, 2)
+ b.head(t, dbTestHost, genA, genT0)
+ status, out := fx.list(t, dbTestHost, 0, "")
+ if status != http.StatusConflict || genBody(t, out).Generation != genA {
+ t.Fatalf("unbound list = %d %s, want 409 naming %s", status, out, genA)
+ }
+ status, out = fx.list(t, dbTestHost, 0, q(genA))
+ var list dbdoor.ListResponse
+ if status != http.StatusOK || json.Unmarshal([]byte(out), &list) != nil || list.Generation != genA || len(list.Files) == 0 {
+ t.Fatalf("bound list = %d %s, want 200 naming %s with g-1's files", status, out, genA)
+ }
+ f, want := genFile(t, one)
+ b.m.Put("data-test", fmt.Sprintf("%s0000/%s", replicagen.Prefix("instances/"+dbTestHost, genB), ltx.FormatFilename(f.MinTXID, f.MaxTXID)), []byte("g-2's other bytes"))
+ b.head(t, dbTestHost, genB, genT1, lease.HeadHistory{Generation: genA, CreatedAt: genT0, EndedAt: genT1})
+ heads := b.count(isHeadRead)
+ if status, got := fx.get(t, 0, f.MinTXID, f.MaxTXID, q(genA)); status != http.StatusPartialContent || got != string(want) {
+ t.Fatalf("GET bound to g-1 after the switch = %d, %d bytes; want 206 and g-1's %d bytes", status, len(got), len(want))
+ }
+ if status, got := fx.get(t, 0, f.MinTXID, f.MaxTXID, q(genB)); status != http.StatusPartialContent || got != "g-2's other bytes" {
+ t.Fatalf("GET bound to g-2 = %d %q, want g-2's bytes", status, got)
+ }
+ if n := b.count(isHeadRead) - heads; n != 0 {
+ t.Fatalf("bound GETs read head.json %d times, want none", n)
+ }
+}
+
+// Ruling B (Astra plan R1 finding 6): an old CLI's exact requests
+// (dbdoor/client.go: GET <ListTail>, then GET <GetTail> with Range, no
+// generation) across a head switch are refused, never mixed: the listing
+// answered from the root, the download after head.json appeared is a 409
+// with the approved sentence, and no replica file is read for it.
+func TestDoorOldCLIAcrossHeadSwitchIsRefusedNeverMixed(t *testing.T) {
+ fx, b := genDoor(t)
+ root := b.replica(t, dbTestHost, replicagen.Root, 2)
+ for _, level := range []int{9, 0} {
+ if status, out := fx.list(t, dbTestHost, level, ""); status != http.StatusOK {
+ t.Fatalf("old CLI list %d before the switch = %d %s, want 200", level, status, out)
+ }
+ }
+ f, _ := genFile(t, root)
+ b.replica(t, dbTestHost, genA, 3)
+ b.head(t, dbTestHost, genA, genT0, lease.HeadHistory{Generation: replicagen.Root, EndedAt: genT0})
+ reads := b.count(isLTXRead)
+ want := fmt.Sprintf(wantNeedsNewerCLI, dbTestHost)
+ if status, out := fx.get(t, 0, f.MinTXID, f.MaxTXID, ""); status != http.StatusConflict || errorText(out) != want {
+ t.Fatalf("old CLI GET after the switch = %d %s, want 409 %q", status, out, want)
+ }
+ if status, out := fx.list(t, dbTestHost, 9, ""); status != http.StatusConflict || errorText(out) != want {
+ t.Fatalf("old CLI list after the switch = %d %s, want 409 %q", status, out, want)
+ }
+ if n := b.count(isLTXRead) - reads; n != 0 {
+ t.Fatalf("the refused requests read %d replica files, want none", n)
+ }
+}
+
+// A root-layout host keeps today's unbound protocol for old and new
+// CLIs; its listing names "@root", and a GET bound to it reads the root.
+func TestDoorRootLayoutKeepsTheUnboundProtocol(t *testing.T) {
+ fx, b := genDoor(t)
+ root := b.replica(t, dbTestHost, replicagen.Root, 2)
+ status, out := fx.list(t, dbTestHost, 0, "")
+ var list dbdoor.ListResponse
+ if status != http.StatusOK || json.Unmarshal([]byte(out), &list) != nil || list.Generation != replicagen.Root || len(list.Files) == 0 {
+ t.Fatalf("unbound list of a root host = %d %s, want 200 naming @root", status, out)
+ }
+ f, want := genFile(t, root)
+ for _, query := range []string{"", q(replicagen.Root)} {
+ if status, got := fx.get(t, 0, f.MinTXID, f.MaxTXID, query); status != http.StatusPartialContent || got != string(want) {
+ t.Fatalf("GET%s = %d, %d bytes; want 206 and the root's %d bytes", query, status, len(got), len(want))
+ }
+ }
+}
+
+// The CLI and the console together: a restore through the door binds g-1
+// on its first listing and stays on it after head moves to g-2.
+func TestDoorCLIRestoreStaysOnTheBoundGeneration(t *testing.T) {
+ fx, b := genDoor(t)
+ one := b.replica(t, dbTestHost, genA, 3)
+ b.replica(t, dbTestHost, genB, 5)
+ b.head(t, dbTestHost, genA, genT0)
+ var mu sync.Mutex
+ var tails []string
+ c := dbdoor.NewClient(func(ctx context.Context, tail string, h http.Header) (*http.Response, error) {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, fx.url(dbdoor.Base("bab", "titogo", dbTestHost)+tail), nil)
+ if err != nil {
+ return nil, err
+ }
+ for k, vs := range h {
+ req.Header[k] = vs
+ }
+ req.Header.Set("Authorization", "Bearer "+fx.member)
+ res, err := http.DefaultClient.Do(req)
+ mu.Lock()
+ tails = append(tails, tail)
+ if len(tails) == 2 { // the first bound listing: head moves on
+ b.head(t, dbTestHost, genB, genT1, lease.HeadHistory{Generation: genA, CreatedAt: genT0, EndedAt: genT1})
+ }
+ mu.Unlock()
+ return res, err
+ })
+ got, err := dbdoor.RestoreTo(context.Background(), c, t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer os.RemoveAll(got.Dir)
+ if want := newestTXID(t, one); got.TXID != want {
+ t.Fatalf("restored to txid %d, want g-1's %d", got.TXID, want)
+ }
+ for _, tail := range tails[1:] {
+ if !strings.Contains(tail, q(genA)[1:]) {
+ t.Errorf("request %s is not bound to %s", tail, genA)
+ }
+ }
+}
+
+// §6.2: an unbound as-of listing binds the generation current at at: a
+// history entry, the current one, or none (410, naming the oldest time).
+// A root host answers its root at any time.
+func TestDoorListAtPicksHistoryGeneration(t *testing.T) {
+ fx, b := genDoor(t)
+ b.replica(t, dbTestHost, genA, 2)
+ b.head(t, dbTestHost, genB, genT1, lease.HeadHistory{Generation: genA, CreatedAt: genT0, EndedAt: genT1})
+ at := func(ts time.Time) string {
+ return "?" + dbdoor.AtParam + "=" + url.QueryEscape(ts.Format(time.RFC3339))
+ }
+ for _, c := range []struct {
+ at time.Time
+ want string
+ }{
+ {genT0.Add(24 * time.Hour), genA},
+ {genT1.Add(time.Hour), genB},
+ } {
+ status, out := fx.list(t, dbTestHost, 0, at(c.at))
+ if status != http.StatusConflict || genBody(t, out).Generation != c.want {
+ t.Fatalf("list at %s = %d %s, want 409 naming %s", c.at, status, out, c.want)
+ }
+ }
+ status, out := fx.list(t, dbTestHost, 0, at(genT0.Add(-time.Hour)))
+ if body := genBody(t, out); status != http.StatusGone || body.Oldest == nil || !body.Oldest.Equal(genT0) {
+ t.Fatalf("list before every generation = %d %s, want 410 naming %s", status, out, genT0)
+ }
+ status, out = fx.list(t, dbTestHost, 0, q(genA))
+ if status != http.StatusOK || !strings.Contains(out, `"generation":"`+genA+`"`) {
+ t.Fatalf("bound history list = %d %s, want 200 on %s", status, out, genA)
+ }
+ const rootHost = "root.go.tito.io"
+ putDBRecord(t, fx.consoleFixture, provision.Record{Host: rootHost})
+ b.replica(t, rootHost, replicagen.Root, 1)
+ if status, out := fx.list(t, rootHost, 0, at(genT0)); status != http.StatusOK || !strings.Contains(out, `"generation":"@root"`) {
+ t.Fatalf("root host at a time = %d %s, want 200 naming @root", status, out)
+ }
+}
+
+// gen is checked strictly (replicagen.Valid) before anything is read, and
+// at must be RFC 3339.
+func TestDoorRejectsInvalidGenName(t *testing.T) {
+ fx, b := genDoor(t)
+ for _, query := range []string{q("../x"), q("g-42"), q(""), q("@root/"), q("g-00000000000000000001/../x"), "?at=yesterday"} {
+ if status, out := fx.list(t, dbTestHost, 0, query); status != http.StatusBadRequest {
+ t.Errorf("list%s = %d %s, want 400", query, status, out)
+ }
+ if !strings.HasPrefix(query, "?at") {
+ if status, out := fx.get(t, 0, 1, 1, query); status != http.StatusBadRequest {
+ t.Errorf("GET%s = %d %s, want 400", query, status, out)
+ }
+ }
+ }
+ if reqs := b.all(); len(reqs) != 0 {
+ t.Fatalf("invalid requests reached the bucket: %q", reqs)
+ }
+}
+
+// The one restart's trigger: a bound read of a generation neither head
+// nor its history names (retired) is 410 generation_gone, on the
+// snapshot listing and on a download. A live generation's empty level
+// and missing file keep their ordinary answers.
+func TestDoorBoundGenerationGoneIs410(t *testing.T) {
+ fx, b := genDoor(t)
+ two := b.replica(t, dbTestHost, genB, 2)
+ b.head(t, dbTestHost, genB, genT1)
+ f, _ := genFile(t, two)
+ for _, level := range []int{dbdoor.MaxLevel, 0} {
+ status, out := fx.list(t, dbTestHost, level, q(genA))
+ if status != http.StatusGone || genBody(t, out).GenerationGone != genA {
+ t.Errorf("list %d bound to retired g-1 = %d %s, want 410 generation_gone", level, status, out)
+ }
+ }
+ if status, out := fx.get(t, 0, f.MinTXID, f.MaxTXID, q(genA)); status != http.StatusGone || genBody(t, out).GenerationGone != genA {
+ t.Errorf("GET bound to retired g-1 = %d %s, want 410 generation_gone", status, out)
+ }
+ if status, out := fx.list(t, dbTestHost, dbdoor.MaxLevel, q(genB)); status != http.StatusOK || !strings.Contains(out, `"files":[]`) {
+ t.Errorf("live g-2's empty snapshot level = %d %s, want 200 and an empty list", status, out)
+ }
+ if status, out := fx.get(t, 0, 900, 901, q(genB)); status != http.StatusNotFound {
+ t.Errorf("live g-2's missing file = %d %s, want 404", status, out)
+ }
+}
+
+// The cache keys on prefix and generation: an unbound resolution reads
+// head.json every time (it is how a read learns the generation) and
+// shares the generation's one client; a bound one reads no head.
+func TestCachedReadReplicaKeysByGeneration(t *testing.T) {
+ s := &Server{}
+ b := useGenBucket(t, s)
+ const host = "a.example.com"
+ prefix := "instances/" + host
+ b.replica(t, host, replicagen.Root, 1)
+ ctx := context.Background()
+ r1, err := s.cachedReadReplica(ctx, prefix, "", time.Time{})
+ if err != nil || r1.Generation != replicagen.Root || r1.HeadFound {
+ t.Fatalf("unbound root = %+v, %v", r1, err)
+ }
+ r2, _ := s.cachedReadReplica(ctx, prefix, "", time.Time{})
+ rb, _ := s.cachedReadReplica(ctx, prefix, replicagen.Root, time.Time{})
+ if r2.Client != r1.Client || rb.Client != r1.Client {
+ t.Fatal("one generation built two clients")
+ }
+ if n := b.count(isHeadRead); n != 2 {
+ t.Fatalf("%d head reads, want one per unbound resolution (2)", n)
+ }
+ b.replica(t, host, genA, 2)
+ b.head(t, host, genA, genT0, lease.HeadHistory{Generation: replicagen.Root, EndedAt: genT0})
+ r3, err := s.cachedReadReplica(ctx, prefix, "", time.Time{})
+ if err != nil || r3.Generation != genA || !r3.HeadFound || r3.Client == r1.Client {
+ t.Fatalf("unbound after the switch = %+v, %v; want g-1 on its own client", r3, err)
+ }
+ r4, _ := s.cachedReadReplica(ctx, prefix, genA, time.Time{})
+ again, _ := s.cachedReadReplica(ctx, prefix, replicagen.Root, time.Time{})
+ if r4.Client != r3.Client || again.Client != r1.Client {
+ t.Fatal("a bound resolution did not reuse its generation's client")
+ }
+ if n := b.count(isHeadRead); n != 3 {
+ t.Fatalf("%d head reads, want 3: bound resolutions read none", n)
+ }
+ if _, err := s.cachedReadReplica(ctx, prefix, "../x", time.Time{}); err == nil {
+ t.Fatal("bound to ../x: want a refusal")
+ }
+}
+
+// Backups read the generation head.json names, not the root.
+func TestBackupsResolveHead(t *testing.T) {
+ s := &Server{}
+ b := useGenBucket(t, s)
+ const host = "shop.example.com"
+ root := b.replica(t, host, replicagen.Root, 2)
+ two := b.replica(t, host, genB, 4)
+ b.head(t, host, genB, genT1, lease.HeadHistory{Generation: replicagen.Root, EndedAt: genT1})
+ v, _ := s.readBackups(context.Background(), provision.Record{Host: host})
+ want := newestTXID(t, two)
+ if want == newestTXID(t, root) {
+ t.Fatal("fixture: the root and g-2 end at the same txid")
+ }
+ if v.CopiedTo == nil || v.CopiedTo.Transaction != want {
+ t.Fatalf("backups = %+v, want g-2's position %d", v, want)
+ }
+}
+
+// A --from copy restores the generation head.json names.
+func TestSeedFromResolvesHead(t *testing.T) {
+ f := newFromFixture(t, 2)
+ b := useGenBucket(t, f.fx.srv)
+ f.fx.srv.cfg.Region = ""
+ root := b.replica(t, fromSource, replicagen.Root, 2)
+ two := b.replica(t, fromSource, genB, 4)
+ b.head(t, fromSource, genB, genT1, lease.HeadHistory{Generation: replicagen.Root, EndedAt: genT1})
+ want := newestTXID(t, two)
+ if want == newestTXID(t, root) {
+ t.Fatal("fixture: the root and g-2 end at the same txid")
+ }
+ rec := f.copy(t, fromBody)
+ requireReady(t, rec)
+ if rec.Seed.TXID != strconv.FormatUint(want, 10) {
+ t.Fatalf("copied at txid %s, want g-2's %d", rec.Seed.TXID, want)
+ }
+}
+
+// The leftover rail sees a generations host: head.json alone, or an
+// abandoned g-*/ prefix no head names, is replica data.
+func TestCreateLeftoversSeesGenerations(t *testing.T) {
+ s := &Server{}
+ b := useGenBucket(t, s)
+ data, err := release.NewS3Store(context.Background(), "data-test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ s.cfg.SeedData = data
+ b.head(t, "head.example.com", genA, genT0)
+ b.m.Put("data-test", replicagen.Prefix("instances/abandoned.example.com", genB)+"0000/"+ltx.FormatFilename(1, 1), []byte("ltx"))
+ b.m.Put("data-test", "instances/files.example.com/files/0/manifest.json", []byte("{}"))
+ for host, want := range map[string]bool{
+ "empty.example.com": false,
+ "head.example.com": true,
+ "abandoned.example.com": true,
+ "files.example.com": false,
+ } {
+ held, err := s.hostHoldsReplicaData(context.Background(), host)
+ if err != nil || held != want {
+ t.Errorf("%s holds replica data = %v, %v; want %v", host, held, err, want)
+ }
+ }
+}
diff --git a/internal/console/apidb_test.go b/internal/console/apidb_test.go
index 349510989..c43823cd6 100644
--- a/internal/console/apidb_test.go
+++ b/internal/console/apidb_test.go
@@ -26,6 +26,7 @@ import (
"github.com/carlosframework/platform/internal/dbdoor/dbdoortest"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/replicagen"
"github.com/carlosframework/platform/internal/svcrole"
)
@@ -153,10 +154,10 @@ func dbFixture(t *testing.T) *dbFx {
fx.srv.cfg.HibernateBucket = "data-test"
fx.srv.cfg.HibernatePrefix = "instances"
opens := new(atomic.Int32)
- fx.srv.dbReplica = func(_ context.Context, prefix string) (replicaReader, error) {
+ fx.srv.dbReplica = rootReplica(func(_ context.Context, prefix string) (replicaReader, error) {
opens.Add(1)
return lsfile.NewReplicaClient(filepath.Join(root, prefix)), nil
- }
+ })
putDBRecord(t, fx, provision.Record{Host: dbTestHost})
return &dbFx{consoleFixture: fx, member: member, root: root, opens: opens}
}
@@ -449,9 +450,9 @@ func TestAPIDBWithoutADataBucketIs503(t *testing.T) {
// bucket name, never reaches the caller.
func TestAPIDBAccessDeniedIsTheResidencyRefusal(t *testing.T) {
fx := dbFixture(t)
- fx.srv.dbReplica = func(context.Context, string) (replicaReader, error) {
+ fx.srv.dbReplica = rootReplica(func(context.Context, string) (replicaReader, error) {
return deniedReplica{}, nil
- }
+ })
for _, p := range []string{
dbdoor.ListPath("bab", "titogo", dbTestHost, 0),
dbdoor.GetPath("bab", "titogo", dbTestHost, 0, 1, 1),
@@ -495,6 +496,16 @@ func TestAPIDBGetIsAudited(t *testing.T) {
t.Fatalf("no db-read audit row naming %s and txid %d: %+v", dbTestHost, f.MaxTXID, evs)
}
+// cachedClient is s's production reader for prefix, unbound: the client
+// the resolution binds.
+func cachedClient(s *Server, ctx context.Context, prefix string) (replicaReader, error) {
+ r, err := s.cachedReadReplica(ctx, prefix, "", time.Time{})
+ if err != nil {
+ return nil, err
+ }
+ return r.Client, nil
+}
+
// One replica client per prefix: a restore's dozens of requests share one
// transport rather than paying a handshake each. And the production reader
// is the resolver's (no head.json: the root) on the configured bucket at
@@ -503,12 +514,12 @@ func TestCachedReadReplicaIsOnePerPrefix(t *testing.T) {
s := &Server{}
b := useFakeDataBucket(t, s, ltxKey("instances/a.example.com", 0))
ctx := context.Background()
- a1, err := s.cachedReadReplica(ctx, "instances/a.example.com")
+ a1, err := cachedClient(s, ctx, "instances/a.example.com")
if err != nil {
t.Fatal(err)
}
- a2, _ := s.cachedReadReplica(ctx, "instances/a.example.com")
- bc, _ := s.cachedReadReplica(ctx, "instances/b.example.com")
+ a2, _ := cachedClient(s, ctx, "instances/a.example.com")
+ bc, _ := cachedClient(s, ctx, "instances/b.example.com")
if a1 != a2 {
t.Error("the same prefix built two clients")
}
@@ -530,7 +541,7 @@ func TestCachedReadReplicaIsOnePerPrefix(t *testing.T) {
// 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.
+// cached for everyone: a read bound to its generation reads no head.
func TestCachedReadReplicaStalledMissBlocksNoOtherPrefix(t *testing.T) {
s := &Server{}
data := &fakeDataBucket{keys: []string{ltxKey("instances/slow.example.com", 0)}}
@@ -562,7 +573,7 @@ func TestCachedReadReplicaStalledMissBlocksNoOtherPrefix(t *testing.T) {
s.cfg.HibernateRegion = "us-east-1"
ctx := context.Background()
- cached, err := s.cachedReadReplica(ctx, "instances/a.example.com")
+ cached, err := cachedClient(s, ctx, "instances/a.example.com")
if err != nil {
t.Fatal(err)
}
@@ -572,7 +583,7 @@ func TestCachedReadReplicaStalledMissBlocksNoOtherPrefix(t *testing.T) {
}
slow := make(chan answer, 1)
go func() {
- rd, err := s.cachedReadReplica(ctx, "instances/slow.example.com")
+ rd, err := cachedClient(s, ctx, "instances/slow.example.com")
slow <- answer{rd, err}
}()
select {
@@ -592,19 +603,19 @@ func TestCachedReadReplicaStalledMissBlocksNoOtherPrefix(t *testing.T) {
}
}
within("a cached prefix", func() {
- if rd, err := s.cachedReadReplica(ctx, "instances/a.example.com"); err != nil || rd != cached {
+ if rd, err := cachedClient(s, 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 {
+ if _, err := cachedClient(s, 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) {
+ if _, err := cachedClient(s, wctx, "instances/slow.example.com"); !errors.Is(err, context.DeadlineExceeded) {
t.Errorf("a waiter past its deadline = %v, want context.DeadlineExceeded", err)
}
})
@@ -622,8 +633,9 @@ func TestCachedReadReplicaStalledMissBlocksNoOtherPrefix(t *testing.T) {
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)
+ // Bound to the generation it resolved, the next read reads no head.
+ if r, err := s.cachedReadReplica(ctx, "instances/slow.example.com", replicagen.Root, time.Time{}); err != nil || r.Client != got.rd {
+ t.Fatalf("after the release: %v, %v; want the one cached client", r.Client, err)
}
mu.Lock()
defer mu.Unlock()
@@ -757,10 +769,10 @@ func (zeros) Read(p []byte) (int, error) { clear(p); return len(p), nil }
func (fx *dbFx) stall(endless bool) *stallReplica {
sr := &stallReplica{endless: endless, opened: make(chan struct{}, 16)}
- fx.srv.dbReplica = func(_ context.Context, prefix string) (replicaReader, error) {
+ fx.srv.dbReplica = rootReplica(func(_ context.Context, prefix string) (replicaReader, error) {
sr.replicaReader = lsfile.NewReplicaClient(filepath.Join(fx.root, prefix))
return sr, nil
- }
+ })
return sr
}
diff --git a/internal/console/apiinstances_haenable_test.go b/internal/console/apiinstances_haenable_test.go
index 194eb681b..d4051ac3c 100644
--- a/internal/console/apiinstances_haenable_test.go
+++ b/internal/console/apiinstances_haenable_test.go
@@ -52,9 +52,9 @@ func haEnableWorld(t *testing.T, region string, tweak func(*Config)) *haPoolWorl
t.Fatal(err)
}
reject, root := w.srv.dbReplica, t.TempDir()
- w.srv.dbReplica = func(_ context.Context, prefix string) (replicaReader, error) {
+ w.srv.dbReplica = rootReplica(func(_ context.Context, prefix string) (replicaReader, error) {
return lsfile.NewReplicaClient(filepath.Join(root, prefix)), nil
- }
+ })
if code, res := w.enable(t, "plainapp", `{}`); code != http.StatusOK || res["pool"] != "" || res["regions"] != nil {
t.Fatalf("world control: plain enable = %d %v, want 200 with no pool or regions", code, res)
}
diff --git a/internal/console/apiinstanceseed.go b/internal/console/apiinstanceseed.go
index 273ad33bc..a5b3a383a 100644
--- a/internal/console/apiinstanceseed.go
+++ b/internal/console/apiinstanceseed.go
@@ -283,13 +283,13 @@ func (s *Server) beginFrom(w http.ResponseWriter, r *http.Request, c seedCreate,
jsonError(w, http.StatusConflict, "a copy stays in its source's region. To run it elsewhere, create it here and then run carlos move.")
return nil
}
- rd, err := s.dbReplica(ctx, src.prefix)
+ res, err := s.dbReplica(ctx, src.prefix, "", time.Time{})
if err != nil {
log.Printf("console: from %s: replica client: %v", source, err)
jsonError(w, http.StatusBadGateway, failed)
return nil
}
- client := dbdoor.NewClient(replicaDoer(rd))
+ client := dbdoor.NewClient(replicaDoer(res.Client))
planCtx, planCancel := context.WithTimeout(ctx, instanceStoreTimeout)
plan, err := planRestore(planCtx, client, from.TXID)
planCancel()
diff --git a/internal/console/apiinstanceseed_test.go b/internal/console/apiinstanceseed_test.go
index 3088400ca..99b27cfda 100644
--- a/internal/console/apiinstanceseed_test.go
+++ b/internal/console/apiinstanceseed_test.go
@@ -78,9 +78,9 @@ func newFromFixture(t *testing.T, txns int) fromFixture {
}
fx.srv.seedScratch = newSeedScratch(scratch, func(string) (int64, error) { return 64 << 30, nil })
root := t.TempDir()
- fx.srv.dbReplica = func(_ context.Context, prefix string) (replicaReader, error) {
+ fx.srv.dbReplica = rootReplica(func(_ context.Context, prefix string) (replicaReader, error) {
return lsfile.NewReplicaClient(filepath.Join(root, prefix)), nil
- }
+ })
f := fromFixture{fx: fx, fake: fake, token: token, data: data, url: instancesURL(fx, "bab", fromApp), root: root, txns: txns}
f.addSource(t, provision.Record{Host: fromSource, Slug: "main"}, txns)
publishSeedsFloorFx(t, fx, "v0.27.0")
diff --git a/internal/console/backups.go b/internal/console/backups.go
index a81e401fe..4981909a9 100644
--- a/internal/console/backups.go
+++ b/internal/console/backups.go
@@ -289,7 +289,7 @@ func (s *Server) readBackups(ctx context.Context, rec provision.Record) (v backu
log.Printf("console: backups %s: resolve: %v", rec.Host, err)
return notShown(backupReasonUnavailable), false
}
- rd, err := s.dbReplica(ctx, prefix)
+ res, err := s.dbReplica(ctx, prefix, "", time.Time{})
switch {
case errors.Is(err, context.DeadlineExceeded):
// The deadline is the read's whole budget, setup included.
@@ -298,7 +298,7 @@ func (s *Server) readBackups(ctx context.Context, rec provision.Record) (v backu
log.Printf("console: backups %s: replica client: %v", rec.Host, err)
return notShown(backupReasonUnavailable), false
}
- plan, from, known, err := dbdoor.PositionAndHistory(ctx, rd, backupsMaxFiles)
+ plan, from, known, err := dbdoor.PositionAndHistory(ctx, res.Client, backupsMaxFiles)
switch {
case errors.Is(err, dbdoor.ErrNothingReplicated):
return notShown(backupReasonNothing), false
diff --git a/internal/console/backups_test.go b/internal/console/backups_test.go
index c3f55423a..3f159ce1d 100644
--- a/internal/console/backups_test.go
+++ b/internal/console/backups_test.go
@@ -238,10 +238,10 @@ func TestBackupsForReadsPositionAndHistory(t *testing.T) {
func TestBackupsForNotShownNeverReadsBucket(t *testing.T) {
fx := dbFixture(t)
- fx.srv.dbReplica = func(context.Context, string) (replicaReader, error) {
+ fx.srv.dbReplica = rootReplica(func(context.Context, string) (replicaReader, error) {
t.Error("dbReplica called for a record the door does not read")
return nil, errors.New("no")
- }
+ })
for _, row := range backupsRows() {
if row.class == backupReplicated {
continue
@@ -295,10 +295,10 @@ func TestBackupsForHostClaimReadsNothing(t *testing.T) {
fx := dbFixture(t)
fx.replicate(t, dbTestHost, 1)
fx.srv.cfg.HostClaim = true
- fx.srv.dbReplica = func(context.Context, string) (replicaReader, error) {
+ fx.srv.dbReplica = rootReplica(func(context.Context, string) (replicaReader, error) {
t.Error("dbReplica called with host claims on")
return nil, errors.New("no")
- }
+ })
v := fx.srv.backupsFor(t.Context(), provision.Record{Host: dbTestHost, Region: fx.srv.cfg.Region, Hibernate: backupsYes()})
if v.Class != backupNotShown || v.Reason != "unavailable" || v.CopiedTo != nil {
t.Fatalf("view = %+v, want not_shown/unavailable", v)
@@ -371,7 +371,7 @@ func TestBackupsForBounds(t *testing.T) {
return provision.Record{Host: slug + ".go.tito.io", Hibernate: backupsYes()}
}
serve := func(fx *dbFx, m map[string]replicaReader, opens *atomic.Int32) {
- fx.srv.dbReplica = func(_ context.Context, prefix string) (replicaReader, error) {
+ fx.srv.dbReplica = rootReplica(func(_ context.Context, prefix string) (replicaReader, error) {
opens.Add(1)
rd, ok := m[prefix]
if !ok {
@@ -379,7 +379,7 @@ func TestBackupsForBounds(t *testing.T) {
return nil, errors.New("unexpected prefix")
}
return rd, nil
- }
+ })
}
t.Run("file cap", func(t *testing.T) {
@@ -418,11 +418,11 @@ func TestBackupsForBounds(t *testing.T) {
fx := dbFixture(t)
fx.srv.backups.deadline = 50 * time.Millisecond
opens := new(atomic.Int32)
- fx.srv.dbReplica = func(ctx context.Context, _ string) (replicaReader, error) {
+ fx.srv.dbReplica = rootReplica(func(ctx context.Context, _ string) (replicaReader, error) {
opens.Add(1)
<-ctx.Done()
return nil, ctx.Err()
- }
+ })
v := fx.srv.backupsFor(t.Context(), rec("setup"))
if v.Class != backupNotShown || v.Reason != "too_large_to_plan" {
t.Fatalf("setup past the deadline = %+v, want not_shown/too_large_to_plan", v)
@@ -484,10 +484,10 @@ func TestBackupsForBounds(t *testing.T) {
t.Run("a failed read is unavailable and not kept", func(t *testing.T) {
fx := dbFixture(t)
opens := new(atomic.Int32)
- fx.srv.dbReplica = func(context.Context, string) (replicaReader, error) {
+ fx.srv.dbReplica = rootReplica(func(context.Context, string) (replicaReader, error) {
opens.Add(1)
return nil, errors.New("s3: something broke")
- }
+ })
for i := 1; i <= 2; i++ {
v := fx.srv.backupsFor(t.Context(), rec("broken"))
if v.Class != backupNotShown || v.Reason != "unavailable" {
diff --git a/internal/console/createleftovers.go b/internal/console/createleftovers.go
index 108fc6294..e871fc4c4 100644
--- a/internal/console/createleftovers.go
+++ b/internal/console/createleftovers.go
@@ -29,10 +29,12 @@ import (
"log"
"net/http"
"strings"
+ "time"
"github.com/carlosframework/platform/internal/activator"
"github.com/carlosframework/platform/internal/dbdoor"
"github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
)
// leftoverCheckApplies reports whether a record homed in region, in pool,
@@ -69,21 +71,31 @@ func (s *Server) leftoverCheckApplies(region, pool string) bool {
// S3 client.) The slash litestream adds is also what keeps app.example.co
// from seeing app.example.com's files.
func (s *Server) hostHoldsReplicaData(ctx context.Context, host string) (bool, error) {
- return s.replicaPrefixesHoldData(ctx,
- activator.HibernatePrefix(s.cfg.HibernatePrefix, host),
- strings.TrimSuffix(activator.MovesPrefix(host), "/"),
- )
+ loc := activator.HibernatePrefix(s.cfg.HibernatePrefix, host)
+ held, err := s.replicaPrefixesHoldData(ctx, loc, strings.TrimSuffix(activator.MovesPrefix(host), "/"))
+ if held || err != nil {
+ return held, err
+ }
+ // Only the instance prefix can hold generations: a move of a
+ // generations host is refused (spec §6.3), so its staging has none.
+ return s.prefixHoldsGenerations(ctx, loc)
}
// replicaPrefixesHoldData keeps one level walker for HA and legacy callers.
+// A prefix whose resolution found head.json (spec 2026-11-12 §3) holds
+// data whatever its root levels say: that read is the resolution's own,
+// so the answer costs no request.
func (s *Server) replicaPrefixesHoldData(ctx context.Context, prefixes ...string) (bool, error) {
for _, prefix := range prefixes {
- rd, err := s.dbReplica(ctx, prefix)
+ res, err := s.dbReplica(ctx, prefix, "", time.Time{})
if err != nil {
return false, fmt.Errorf("replica client for %s: %w", prefix, err)
}
+ if res.HeadFound {
+ return true, nil
+ }
for level := 0; level <= dbdoor.MaxLevel; level++ {
- found, err := anyLTXFile(ctx, rd, level)
+ found, err := anyLTXFile(ctx, res.Client, level)
if err != nil {
return false, fmt.Errorf("list %s level %d: %w", prefix, level, err)
}
@@ -95,6 +107,30 @@ func (s *Server) replicaPrefixesHoldData(ctx context.Context, prefixes ...string
return false, nil
}
+// prefixHoldsGenerations reports whether prefix holds any object under a
+// g-* name: a generation no head.json names (a take whose head write
+// lost, or one head was deleted under) is still a deleted instance's
+// database. One bounded LIST (max-keys 1) of <prefix>/g- through the data
+// bucket's store (SeedData, the bucket the db door reads), firstHALeftover's
+// shape. A console without that store checks the resolution and the root
+// levels only.
+func (s *Server) prefixHoldsGenerations(ctx context.Context, prefix string) (bool, error) {
+ if s.cfg.SeedData == nil {
+ return false, nil
+ }
+ var keys []string
+ var err error
+ if pages, ok := s.cfg.SeedData.(release.PageLister); ok {
+ keys, err = pages.ListPage(ctx, prefix+"/g-", "", 1)
+ } else {
+ keys, err = s.cfg.SeedData.List(ctx, prefix+"/g-") // a store that cannot bound a page
+ }
+ if err != nil {
+ return false, fmt.Errorf("list %s generations: %w", prefix, err)
+ }
+ return len(keys) > 0, nil
+}
+
// anyLTXFile reports whether one level lists at least one file.
func anyLTXFile(ctx context.Context, rd replicaReader, level int) (bool, error) {
itr, err := rd.LTXFiles(ctx, level, 0, false)
diff --git a/internal/console/createleftovers_test.go b/internal/console/createleftovers_test.go
index 13bbe8ec6..ddc713d83 100644
--- a/internal/console/createleftovers_test.go
+++ b/internal/console/createleftovers_test.go
@@ -60,10 +60,10 @@ func leftoverFixture(t *testing.T, code string) *leftoverFx {
fx.srv.cfg.HibernatePrefix = "instances"
fx.srv.cfg.Region = "ie"
opens := new(atomic.Int32)
- fx.srv.dbReplica = func(_ context.Context, prefix string) (replicaReader, error) {
+ fx.srv.dbReplica = rootReplica(func(_ context.Context, prefix string) (replicaReader, error) {
opens.Add(1)
return lsfile.NewReplicaClient(filepath.Join(root, prefix)), nil
- }
+ })
return &leftoverFx{consoleFixture: fx, token: token, root: root, opens: opens}
}
@@ -260,7 +260,7 @@ func TestCreateRefusesWhenTheCheckFails(t *testing.T) {
for seam, open := range seams {
t.Run(d.name+"/"+seam, func(t *testing.T) {
fx := leftoverFixture(t, "code-left-fail-"+d.name+"-"+seam)
- fx.srv.dbReplica = open
+ fx.srv.dbReplica = rootReplica(open)
status, _, out := rawReq(t, http.MethodPost, d.url(fx.consoleFixture), fx.token, d.body)
if status != http.StatusServiceUnavailable || !strings.Contains(out, "could not check whether") {
t.Fatalf("create = %d %s, want the 503 that refuses on uncertainty", status, out)
@@ -291,10 +291,10 @@ func TestCreateValidatesBeforeTheCheck(t *testing.T) {
t.Run(c.door+" "+c.body, func(t *testing.T) {
fx := leftoverFixture(t, "code-left-order")
fx.srv.cfg.Region = c.consoleRegion
- fx.srv.dbReplica = func(context.Context, string) (replicaReader, error) {
+ fx.srv.dbReplica = rootReplica(func(context.Context, string) (replicaReader, error) {
fx.opens.Add(1)
return failingReplica{}, nil
- }
+ })
u := fx.ts.URL + "/api/cli/apps/bab/titogo/" + c.url
status, _, out := rawReq(t, http.MethodPost, u, fx.token, c.body)
if status != http.StatusBadRequest {
@@ -577,9 +577,9 @@ func TestCreateWritesUnderAFreshDeadlineAfterTheCheck(t *testing.T) {
t.Run(d.name, func(t *testing.T) {
fx := leftoverFixture(t, "code-left-deadline-"+d.name)
last := new(atomic.Int64)
- fx.srv.dbReplica = func(_ context.Context, prefix string) (replicaReader, error) {
+ fx.srv.dbReplica = rootReplica(func(_ context.Context, prefix string) (replicaReader, error) {
return slowReplica{lsfile.NewReplicaClient(filepath.Join(fx.root, prefix)), 5 * time.Millisecond, last}, nil
- }
+ })
st := &writeDeadlineStore{Store: fx.srv.cfg.Releases, key: d.recordKey()}
fx.srv.cfg.Releases = st
status, _, out := rawReq(t, http.MethodPost, d.url(fx.consoleFixture), fx.token, d.body)
@@ -613,7 +613,7 @@ func TestCreateRetryOfAnExistingRecordIsTheOrdinaryDuplicate(t *testing.T) {
if seam == "replica" {
fx.leaveReplica(t, d.host)
} else {
- fx.srv.dbReplica = func(context.Context, string) (replicaReader, error) { return failingReplica{}, nil }
+ fx.srv.dbReplica = rootReplica(func(context.Context, string) (replicaReader, error) { return failingReplica{}, nil })
}
before, _, err := fx.rel.Get(context.Background(), d.recordKey())
if err != nil {
diff --git a/internal/console/dbforward_minio_test.go b/internal/console/dbforward_minio_test.go
index dc8d20633..f5b97a441 100644
--- a/internal/console/dbforward_minio_test.go
+++ b/internal/console/dbforward_minio_test.go
@@ -169,9 +169,9 @@ func TestDBForwardMinio(t *testing.T) {
deploy := store(consoleKey, consoleSecret, "dbf-deploy")
fx := newConsoleFixtureOn(t, true, strictStore{Store: deploy, t: t})
fx.srv.cfg.DBForward, fx.srv.cfg.Region, fx.srv.cfg.HibernateBucket = true, "ie", "dbf-data-ie"
- fx.srv.dbReplica = func(_ context.Context, prefix string) (replicaReader, error) {
+ fx.srv.dbReplica = rootReplica(func(_ context.Context, prefix string) (replicaReader, error) {
return replica(consoleKey, consoleSecret, "dbf-data-ie", prefix), nil // the only data bucket this console has
- }
+ })
if _, err := fx.st.CreateAppIn(OpsAccountID, "shop", "paul@keymail.dev", time.Now()); err != nil {
t.Fatal(err)
}
diff --git a/internal/console/demo_claim_e2e_test.go b/internal/console/demo_claim_e2e_test.go
index b684ece54..fb9910ca5 100644
--- a/internal/console/demo_claim_e2e_test.go
+++ b/internal/console/demo_claim_e2e_test.go
@@ -66,9 +66,9 @@ func claimE2ESource(t *testing.T) (*Server, string, DemoRow) {
})}
dataRoot := t.TempDir()
s.cfg.SeedData = release.NewDirStore(dataRoot)
- s.dbReplica = func(_ context.Context, prefix string) (replicaReader, error) {
+ s.dbReplica = rootReplica(func(_ context.Context, prefix string) (replicaReader, error) {
return lsfile.NewReplicaClient(filepath.Join(dataRoot, prefix)), nil
- }
+ })
s.seedScratch = newSeedScratch(t.TempDir(), func(string) (int64, error) { return 4 << 30, nil })
return s, in.Identity.Token, d
}
diff --git a/internal/console/demo_claim_ha_gate_test.go b/internal/console/demo_claim_ha_gate_test.go
index ff56b1bd0..ee9ec2c5c 100644
--- a/internal/console/demo_claim_ha_gate_test.go
+++ b/internal/console/demo_claim_ha_gate_test.go
@@ -67,9 +67,9 @@ func TestDemoClaimReservationBornHA(t *testing.T) {
t.Fatal(err)
}
root := t.TempDir()
- s.dbReplica = func(_ context.Context, prefix string) (replicaReader, error) {
+ s.dbReplica = rootReplica(func(_ context.Context, prefix string) (replicaReader, error) {
return lsfile.NewReplicaClient(filepath.Join(root, prefix)), nil
- }
+ })
rec, err := s.createDemoClaimSeed(t.Context(), op)
if err != nil {
t.Fatal(err)
diff --git a/internal/console/demo_claim_seed_test.go b/internal/console/demo_claim_seed_test.go
index d3c402a08..621a55593 100644
--- a/internal/console/demo_claim_seed_test.go
+++ b/internal/console/demo_claim_seed_test.go
@@ -98,9 +98,9 @@ func claimSeedConsole(t *testing.T) (*Server, claimOp) {
s.cfg.SeedData = release.NewDirStore(root)
s.cfg.HibernateBucket = "data-test"
s.cfg.HibernatePrefix = "instances"
- s.dbReplica = func(_ context.Context, prefix string) (replicaReader, error) {
+ s.dbReplica = rootReplica(func(_ context.Context, prefix string) (replicaReader, error) {
return lsfile.NewReplicaClient(filepath.Join(root, prefix)), nil
- }
+ })
return s, op
}
func TestDemoClaimFreshSeed(t *testing.T) {
diff --git a/internal/console/demo_claim_transfer_test.go b/internal/console/demo_claim_transfer_test.go
index 90db78a27..4269b8eed 100644
--- a/internal/console/demo_claim_transfer_test.go
+++ b/internal/console/demo_claim_transfer_test.go
@@ -76,9 +76,9 @@ func claimTransferFixtureBefore(t *testing.T, before func(*Server, DemoRow, demo
s.demoJobs.peers["box"].ready.MovedCapability = democlaim.MovedCapability
dataRoot := t.TempDir()
s.cfg.SeedData = release.NewDirStore(dataRoot)
- s.dbReplica = func(_ context.Context, prefix string) (replicaReader, error) {
+ s.dbReplica = rootReplica(func(_ context.Context, prefix string) (replicaReader, error) {
return lsfile.NewReplicaClient(filepath.Join(dataRoot, prefix)), nil
- }
+ })
s.cfg.HibernateBucket = "test-data"
s.cfg.HibernatePrefix = "instances"
s.seedScratch = newSeedScratch(t.TempDir(), func(string) (int64, error) { return 4 << 30, nil })
diff --git a/internal/console/ha_pool_scope_test.go b/internal/console/ha_pool_scope_test.go
index dd27a247d..30624128e 100644
--- a/internal/console/ha_pool_scope_test.go
+++ b/internal/console/ha_pool_scope_test.go
@@ -180,10 +180,10 @@ func haPoolWorldNew(t *testing.T, region, pool string, tweak func(*Config)) *haP
}
fx.srv.haCapacity.Store(w.observer)
fx.srv.LoadRegionNames(context.Background())
- fx.srv.dbReplica = func(context.Context, string) (replicaReader, error) {
+ fx.srv.dbReplica = rootReplica(func(context.Context, string) (replicaReader, error) {
t.Error("scoped proof opened the home LTX reader")
return nil, errors.New("unexpected home read")
- }
+ })
w.track()
return w
}
@@ -554,9 +554,9 @@ func TestHAPoolMixedStorage(t *testing.T) {
w.edge(t, "mismatch", func(m map[string]any) { m["data_bucket"] = "other-data" })
w.refresh()
root := t.TempDir()
- w.srv.dbReplica = func(_ context.Context, p string) (replicaReader, error) {
+ w.srv.dbReplica = rootReplica(func(_ context.Context, p string) (replicaReader, error) {
return lsfile.NewReplicaClient(filepath.Join(root, p)), nil
- }
+ })
code, _, out := w.post(t, false, w.body(false))
if code != 201 {
t.Fatalf("unscoped=%d %s", code, out)
@@ -572,9 +572,9 @@ func TestHAPoolTransfersRemainRegional(t *testing.T) {
t.Run(from, func(t *testing.T) {
w := haPoolWorldNew(t, "us", "", nil)
root := t.TempDir()
- w.srv.dbReplica = func(_ context.Context, p string) (replicaReader, error) {
+ w.srv.dbReplica = rootReplica(func(_ context.Context, p string) (replicaReader, error) {
return lsfile.NewReplicaClient(filepath.Join(root, p)), nil
- }
+ })
if err := w.st.SetOperator("alice@keymail.dev", true); err != nil {
t.Fatal(err)
}
diff --git a/internal/console/hacreate_test.go b/internal/console/hacreate_test.go
index 9d24805e4..ff554bf6f 100644
--- a/internal/console/hacreate_test.go
+++ b/internal/console/hacreate_test.go
@@ -52,6 +52,9 @@ func (s *haCreateStore) Get(ctx context.Context, k string) ([]byte, string, erro
return s.Store.Get(ctx, k)
}
func (s *haCreateStore) ListPage(ctx context.Context, p, after string, n int) ([]string, error) {
+ if isGenerationsProbe(p) {
+ return s.Store.(release.PageLister).ListPage(ctx, p, after, n)
+ }
s.mu.Lock()
s.pages = append(s.pages, fmt.Sprintf("%s|%s|%d", p, after, n))
s.mu.Unlock()
@@ -463,7 +466,7 @@ func TestHACreateMoveStagingBudget(t *testing.T) {
for _, seam := range []string{"client", "list", "iterator"} {
t.Run(seam, func(t *testing.T) {
fx := haCreateHome(t)
- fx.srv.dbReplica = func(_ context.Context, p string) (replicaReader, error) {
+ fx.srv.dbReplica = rootReplica(func(_ context.Context, p string) (replicaReader, error) {
if p != "moves/acme.go.tito.io" {
t.Errorf("unexpected replica prefix %q", p)
}
@@ -475,7 +478,7 @@ func TestHACreateMoveStagingBudget(t *testing.T) {
default:
return pagingFailReplica{}, nil
}
- }
+ })
control, data := haCreateTrack(fx)
code, _, out := haCreatePost(t, fx, leftoverDoors[0].body)
if code != 503 || errorText(out) != "could not check this instance's data in ie. nothing was created. try again. persistent failures may require an operator to check data access for this region." {
@@ -552,9 +555,9 @@ func haEmptyHomeData(t *testing.T, s *Server) {
s.cfg.HibernateBucket = "data-test"
s.cfg.SeedData = release.NewDirStore(t.TempDir())
root := t.TempDir()
- s.dbReplica = func(_ context.Context, p string) (replicaReader, error) {
+ s.dbReplica = rootReplica(func(_ context.Context, p string) (replicaReader, error) {
return lsfile.NewReplicaClient(filepath.Join(root, p)), nil
- }
+ })
}
// Exercise the real PageLister, including a truncated result: there is no
diff --git a/internal/console/hacreatecapacity_test.go b/internal/console/hacreatecapacity_test.go
index fb7db0964..db4fd3c45 100644
--- a/internal/console/hacreatecapacity_test.go
+++ b/internal/console/hacreatecapacity_test.go
@@ -106,9 +106,9 @@ func capacityFixture(t *testing.T, mode string) capacityDoorFixture {
f.fx.srv.cfg.SeedData = release.NewDirStore(t.TempDir())
f.fx.srv.cfg.HibernateBucket = "test-data"
root := t.TempDir()
- f.fx.srv.dbReplica = func(_ context.Context, prefix string) (replicaReader, error) {
+ f.fx.srv.dbReplica = rootReplica(func(_ context.Context, prefix string) (replicaReader, error) {
return lsfile.NewReplicaClient(filepath.Join(root, prefix)), nil
- }
+ })
m := titoManifest()
m.Pool = ""
m.Regions = nil
diff --git a/internal/console/hap2_wiring_test.go b/internal/console/hap2_wiring_test.go
index a04585350..44c058e3a 100644
--- a/internal/console/hap2_wiring_test.go
+++ b/internal/console/hap2_wiring_test.go
@@ -431,7 +431,9 @@ func TestHAP2ProductionDoors(t *testing.T) {
// The create door retains main's leftover rail before dispatch
// to import. The regional refusal adds no reads of its own.
// Each prefix's replica is resolved first: one head.json
- // read (absent here: the root layout), then its levels.
+ // read (absent here: the root layout), then its levels;
+ // then one bounded listing of instances/<host>/g- for an
+ // abandoned generation.
var got, want []string
for _, a := range tr.all() {
if a.bucket != "data-test" {
@@ -452,6 +454,7 @@ func TestHAP2ProductionDoors(t *testing.T) {
want = append(want, fmt.Sprintf("%s%s/%04x/", prefix, importHost, level))
}
}
+ want = append(want, "instances/"+importHost+"/g-")
if !reflect.DeepEqual(got, want) {
t.Errorf("import begin retained rail = %v, want %v", got, want)
}
@@ -479,7 +482,7 @@ func TestHAP2ProductionDoors(t *testing.T) {
t.Errorf("rootfs exclusion = %+v", rec)
}
for _, a := range tr.all() {
- if a.bucket == "data-test" && a.query.Get("max-keys") == "1" {
+ if a.bucket == "data-test" && a.query.Get("max-keys") == "1" && a.query.Get("prefix") == "instances/"+rootfsShopHost+"/" {
t.Error("rootfs entered HA prefix proof")
}
}
@@ -653,6 +656,10 @@ func TestHAP2RequestBudget(t *testing.T) {
for level := 0; level < levels; level++ {
want = append(want, fmt.Sprintf("moves/%s/%04x/", host, level))
}
+ if mode == "legacy" {
+ // One bounded listing for an abandoned generation.
+ want = append(want, "instances/"+host+"/g-")
+ }
if !reflect.DeepEqual(got, want) || dataGets != 0 {
t.Errorf("data HTTP attempts=%v + %d non-LIST; want %v", got, dataGets, want)
}
diff --git a/internal/console/instancepage_test.go b/internal/console/instancepage_test.go
index 7256a4c0e..9653e239a 100644
--- a/internal/console/instancepage_test.go
+++ b/internal/console/instancepage_test.go
@@ -303,12 +303,12 @@ func backupsPageFixtureWith(t *testing.T, o consoleFixtureOptions, replicas map[
c := signInPaul(t, fx)
fx.srv.cfg.HibernateBucket = "data-test"
fx.srv.cfg.HibernatePrefix = "instances"
- fx.srv.dbReplica = func(_ context.Context, prefix string) (replicaReader, error) {
+ fx.srv.dbReplica = rootReplica(func(_ context.Context, prefix string) (replicaReader, error) {
if rd, ok := replicas[prefix]; ok {
return rd, nil
}
return nil, errors.New("no such replica")
- }
+ })
return fx, c
}
@@ -536,7 +536,7 @@ func TestBackupsSectionTimes(t *testing.T) {
func TestInstancePageBackupsKnownGaps(t *testing.T) {
no := false
fx, c := backupsPageFixture(t, nil)
- fx.srv.dbReplica = func(_ context.Context, prefix string) (replicaReader, error) {
+ fx.srv.dbReplica = rootReplica(func(_ context.Context, prefix string) (replicaReader, error) {
switch prefix {
case "instances/empty.carlosapp.dev":
return emptyReplica{}, nil
@@ -544,7 +544,7 @@ func TestInstancePageBackupsKnownGaps(t *testing.T) {
return backupsFailReplica{err: context.DeadlineExceeded}, nil
}
return backupsFailReplica{err: errors.New("listing failed")}, nil
- }
+ })
for _, rec := range []provision.Record{
{Host: "awake.carlosapp.dev", Hibernate: &no},
{Host: "addr.carlosapp.dev", Addr: "127.0.0.1:9000"},
diff --git a/internal/console/restore_door_test.go b/internal/console/restore_door_test.go
index 117db3dea..98b9b0576 100644
--- a/internal/console/restore_door_test.go
+++ b/internal/console/restore_door_test.go
@@ -41,9 +41,9 @@ func doorOver(t *testing.T, p *proofFx) *doorFx {
root := t.TempDir()
srv := p.fx.srv
srv.cfg.HibernatePrefix = "instances"
- srv.dbReplica = func(_ context.Context, prefix string) (replicaReader, error) {
+ srv.dbReplica = rootReplica(func(_ context.Context, prefix string) (replicaReader, error) {
return lsfile.NewReplicaClient(filepath.Join(root, prefix)), nil
- }
+ })
return &doorFx{proofFx: p, root: root}
}
diff --git a/internal/console/restore_proof_test.go b/internal/console/restore_proof_test.go
index aaf2ebddb..4f24825e8 100644
--- a/internal/console/restore_proof_test.go
+++ b/internal/console/restore_proof_test.go
@@ -32,6 +32,9 @@ type stagingStore struct {
}
func (s *stagingStore) ListPage(ctx context.Context, prefix, startAfter string, limit int) ([]string, error) {
+ if isGenerationsProbe(prefix) {
+ return s.DirStore.ListPage(ctx, prefix, startAfter, limit)
+ }
s.mu.Lock()
s.listed = append(s.listed, prefix)
fail := s.fail
diff --git a/internal/console/restore_sim_test.go b/internal/console/restore_sim_test.go
index dcffbeff4..fd0125f79 100644
--- a/internal/console/restore_sim_test.go
+++ b/internal/console/restore_sim_test.go
@@ -179,9 +179,9 @@ func newSimWorld(t *testing.T, lifetimesOn, qData bool) *simWorld {
srv.cfg.SeedData, srv.cfg.HibernateBucket, srv.cfg.HomeRegion = w.data, "data-test", "ie"
root := t.TempDir()
srv.cfg.HibernatePrefix = "instances"
- srv.dbReplica = func(_ context.Context, prefix string) (replicaReader, error) {
+ srv.dbReplica = rootReplica(func(_ context.Context, prefix string) (replicaReader, error) {
return lsfile.NewReplicaClient(filepath.Join(root, prefix)), nil
- }
+ })
if mode, err := srv.hostsMode(ctx); err != nil || mode != provision.HostsModeIncomplete {
t.Fatalf("fixture: mode %q %v, want incomplete", mode, err)
}
diff --git a/internal/console/seeddoer.go b/internal/console/seeddoer.go
index d58708123..34faf39b3 100644
--- a/internal/console/seeddoer.go
+++ b/internal/console/seeddoer.go
@@ -27,6 +27,10 @@ import (
// A failed bucket read is returned as the error it is.
func replicaDoer(rd replicaReader) dbdoor.Doer {
return func(ctx context.Context, tail string, h http.Header) (*http.Response, error) {
+ // rd is one resolved generation already, so the bound door's
+ // query (gen, at) has nothing left to choose: it is ignored, as
+ // the door's router would ignore it, and the listing names none.
+ tail, _, _ = strings.Cut(tail, "?")
rest, ok := strings.CutPrefix(tail, "/ltx/")
if !ok {
return doerResponse(http.StatusNotFound, nil), nil
diff --git a/internal/console/server.go b/internal/console/server.go
index 658a9f19d..20690e799 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1229,9 +1229,10 @@ type Server struct {
// load failure, logged) verifies nothing.
boxCerts map[string]*x509.Certificate
// dbReplica opens the read side of one instance's replica for the
- // `carlos db` door (apidb.go). NewServer points it at a small cache of
- // lease.ResolveReplica clients; tests point it at a file replica.
- dbReplica func(ctx context.Context, prefix string) (replicaReader, error)
+ // `carlos db` door (apidb.go): bound to gen when it is set, else the
+ // generation head.json names (at at, when set). NewServer points it at
+ // cachedReadReplica; tests point it at a file replica.
+ dbReplica func(ctx context.Context, prefix, gen string, at time.Time) (lease.Resolved, error)
// replicaHealth reads the hub's live copy table (replicaview.go). nil is
// the agent's private snapshot socket; tests set a fixed table.
replicaHealth func(ctx context.Context) (map[string]replicas.Snapshot, error)
diff --git a/internal/dbdoor/client.go b/internal/dbdoor/client.go
index f1009a8c9..5e5501142 100644
--- a/internal/dbdoor/client.go
+++ b/internal/dbdoor/client.go
@@ -34,6 +34,7 @@ type Doer func(ctx context.Context, tail string, header http.Header) (*http.Resp
// litestream.ReplicaClientV3, or Restore would take the v0.3 path.
type Client struct {
handles dbHandleState
+ gen genBinding
do Doer
logger *slog.Logger
}
@@ -43,6 +44,15 @@ func NewClient(do Doer) *Client {
return &Client{do: do, logger: slog.Default()}
}
+// ErrGenerationGone: the generation a read is bound to was retired under
+// it (spec 2026-11-12 §8). The restore restarts once, unbound.
+var ErrGenerationGone = errors.New("dbdoor: the replica generation this read is bound to is gone")
+
+// ErrGenerationChanged: a listing named a generation other than the one
+// the read is bound to. A bound read never mixes generations, so this is
+// refused rather than followed.
+var ErrGenerationChanged = errors.New("dbdoor: the replica's listing named another generation")
+
// errReadOnly is not a guard that can be switched off: these three methods
// have no other body. The two-replicators hazard internal/caps and
// internal/lease both warn about is unreachable from this client by
@@ -62,6 +72,9 @@ type DoorError struct {
// forward spec §5.5): the instance is readable through the forwarded
// read in Forward.Region. nil for every other refusal.
Forward *Forward
+ // generation is the 409's generation to bind (GenerationBody); the
+ // client follows it once, on an unbound listing.
+ generation string
}
func (e *DoorError) Error() string {
@@ -98,19 +111,38 @@ func (c *Client) LTXFiles(ctx context.Context, level int, seek ltx.TXID, _ bool)
}
func (c *Client) listFiles(ctx context.Context, level int) ([]LTXFile, error) {
- res, err := c.do(ctx, ListTail(level), http.Header{})
- if err != nil {
- return nil, err
- }
- defer res.Body.Close()
- if res.StatusCode != http.StatusOK {
- return nil, doorError(res)
- }
- var list ListResponse
- if err := json.NewDecoder(io.LimitReader(res.Body, 16<<20)).Decode(&list); err != nil {
- return nil, fmt.Errorf("dbdoor: unreadable listing for level %d: %w", level, err)
+ for followed := false; ; followed = true {
+ gen, query := c.gen.listQuery()
+ res, err := c.do(ctx, ListTail(level)+query, http.Header{})
+ if err != nil {
+ return nil, err
+ }
+ if res.StatusCode != http.StatusOK {
+ err := c.refusal(res)
+ res.Body.Close()
+ // An unbound listing of a host with head.json is refused with
+ // the generation to bind (GenerationBody): bind it and list
+ // again, once.
+ var door *DoorError
+ if !followed && gen == "" && errors.As(err, &door) && door.Status == http.StatusConflict && door.generation != "" {
+ if err := c.gen.bind(door.generation); err != nil {
+ return nil, err
+ }
+ continue
+ }
+ return nil, err
+ }
+ var list ListResponse
+ err = json.NewDecoder(io.LimitReader(res.Body, 16<<20)).Decode(&list)
+ res.Body.Close()
+ if err != nil {
+ return nil, fmt.Errorf("dbdoor: unreadable listing for level %d: %w", level, err)
+ }
+ if err := c.gen.named(gen, list.Generation); err != nil {
+ return nil, err
+ }
+ return c.rememberFiles(level, list)
}
- return c.rememberFiles(level, list)
}
func fileIterator(files []LTXFile, level int, seek ltx.TXID) ltx.FileIterator {
@@ -140,7 +172,7 @@ func (c *Client) OpenLTXFile(ctx context.Context, level int, minTXID, maxTXID lt
h.Set(HandleHeader, handle)
}
h.Set("Range", RangeHeader(offset, size))
- res, err := c.do(ctx, GetTail(level, uint64(minTXID), uint64(maxTXID)), h)
+ res, err := c.do(ctx, GetTail(level, uint64(minTXID), uint64(maxTXID))+c.gen.getQuery(), h)
if err != nil {
return nil, err
}
@@ -156,7 +188,7 @@ func (c *Client) OpenLTXFile(ctx context.Context, level int, minTXID, maxTXID lt
return nil, fmt.Errorf("dbdoor: level %d %s: %w", level, Span(uint64(minTXID), uint64(maxTXID)), os.ErrNotExist)
default:
defer res.Body.Close()
- return nil, doorError(res)
+ return nil, c.refusal(res)
}
}
@@ -179,6 +211,7 @@ func doorError(res *http.Response) error {
Region string `json:"region"`
RegionName string `json:"region_name"`
ForwardOps []string `json:"forward_ops"`
+ Generation string `json:"generation"`
}
e := &DoorError{Status: res.StatusCode}
if json.Unmarshal(raw, &body) == nil {
@@ -186,6 +219,9 @@ func doorError(res *http.Response) error {
if res.StatusCode == http.StatusConflict && body.Forward == 1 && forwardRegion.MatchString(body.Region) {
e.Forward = &Forward{Region: body.Region, RegionName: body.RegionName, Ops: body.ForwardOps}
}
+ if res.StatusCode == http.StatusConflict {
+ e.generation = body.Generation
+ }
}
// Seconds only (the door never sends a date), capped so a hostile or
// broken value cannot park a download for hours.
diff --git a/internal/dbdoor/client_test.go b/internal/dbdoor/client_test.go
index 685513ecd..0462d1d74 100644
--- a/internal/dbdoor/client_test.go
+++ b/internal/dbdoor/client_test.go
@@ -83,6 +83,9 @@ func (d *testDoor) do(ctx context.Context, tail string, h http.Header) (*http.Re
}
func (d *testDoor) serve(ctx context.Context, w http.ResponseWriter, tail string, h http.Header) {
+ // A console before generations routes on the path and ignores the
+ // query, as an HTTP server does (an as-of listing sends at).
+ tail, _, _ = strings.Cut(tail, "?")
parts := strings.Split(strings.TrimPrefix(tail, "/ltx/"), "/")
level, err := strconv.Atoi(parts[0])
if err != nil {
diff --git a/internal/dbdoor/coords.go b/internal/dbdoor/coords.go
index a6da38a86..3e2906ea2 100644
--- a/internal/dbdoor/coords.go
+++ b/internal/dbdoor/coords.go
@@ -44,9 +44,43 @@ type LTXFile struct {
// ListResponse contains one ordered level, or a complete restore plan with
// its root first. Clients retain a complete plan across level requests.
type ListResponse struct {
- Protocol int `json:"protocol,omitempty"`
- Plan bool `json:"plan,omitempty"`
- Files []LTXFile `json:"files"`
+ Protocol int `json:"protocol,omitempty"`
+ Plan bool `json:"plan,omitempty"`
+ // Generation is the replica generation the listing read (spec
+ // 2026-11-12 §6.1): "@root" for the root layout, else a head.json
+ // name. A client binds the first one it is given and sends it with
+ // every later request (GenParam). A console from before generations
+ // names none, and the client then stays unbound.
+ Generation string `json:"generation,omitempty"`
+ Files []LTXFile `json:"files"`
+}
+
+// GenParam and AtParam are the bound door's query parameters (spec
+// 2026-11-12 §6.1, §6.2). gen names the generation a read is bound to,
+// on a list or a GET; at (RFC 3339) is the time an unbound as-of listing
+// resolves its generation for. A bound request sends gen alone.
+const (
+ GenParam = "gen"
+ AtParam = "at"
+)
+
+// GenerationBody is the door's answer about a generation, additive to
+// the {"error"} body every CLI reads (ForwardBody's shape):
+//
+// - 409 with Generation: an unbound read of a host with head.json. Error
+// is the sentence an old CLI prints; a new client binds Generation and
+// lists again.
+// - 410 with GenerationGone: the bound generation was retired. The
+// client restarts its read once, unbound (ErrGenerationGone).
+// - 410 with Oldest: an as-of listing earlier than every generation the
+// replica keeps (a *BeforeHistoryError).
+//
+// Only a client that sends gen or at is ever answered 410.
+type GenerationBody struct {
+ Error string `json:"error,omitempty"`
+ Generation string `json:"generation,omitempty"`
+ GenerationGone string `json:"generation_gone,omitempty"`
+ Oldest *time.Time `json:"oldest,omitempty"`
}
// Base is the door's root for one instance: everything below it is a
diff --git a/internal/dbdoor/generation.go b/internal/dbdoor/generation.go
new file mode 100644
index 000000000..178a74067
--- /dev/null
+++ b/internal/dbdoor/generation.go
@@ -0,0 +1,142 @@
+package dbdoor
+
+import (
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/replicagen"
+)
+
+// genBinding is the generation one Client's read is bound to (spec
+// 2026-11-12 §6.1). It starts unbound; the first listing that names a
+// generation binds it (a 200's ListResponse.Generation, or a 409's
+// GenerationBody.Generation), and every later list and GET sends it as
+// gen, so a head.json that moves mid-read cannot move the read. A console
+// from before generations names none, and the client stays unbound, on
+// today's protocol byte for byte.
+type genBinding struct {
+ mu sync.Mutex
+ gen string // "" until a listing names one
+ // at is the as-of time an unbound listing sends (zero: the newest), so
+ // the door resolves the generation that was current then (§6.2).
+ at time.Time
+ // gone is set when the door answered that the bound generation was
+ // retired; restoreAt reads and clears it.
+ gone bool
+}
+
+// setAt sets the time the next unbound listing resolves for.
+func (g *genBinding) setAt(at time.Time) {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ g.at = at
+}
+
+// listQuery is the generation as sent on a listing, and its query: gen
+// when bound, else at for an as-of read, else nothing at all.
+func (g *genBinding) listQuery() (gen, query string) {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ switch {
+ case g.gen != "":
+ return g.gen, "?" + GenParam + "=" + url.QueryEscape(g.gen)
+ case !g.at.IsZero():
+ return "", "?" + AtParam + "=" + url.QueryEscape(g.at.UTC().Format(time.RFC3339Nano))
+ }
+ return "", ""
+}
+
+// getQuery is a download's query: gen when bound, else nothing.
+func (g *genBinding) getQuery() string {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ if g.gen == "" {
+ return ""
+ }
+ return "?" + GenParam + "=" + url.QueryEscape(g.gen)
+}
+
+// bind binds name, which must be a generation name, unless the read is
+// already bound to another: that is ErrGenerationChanged.
+func (g *genBinding) bind(name string) error {
+ if !replicagen.Valid(name) {
+ return fmt.Errorf("dbdoor: the console named %q, which is not a replica generation", name)
+ }
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ switch g.gen {
+ case "":
+ g.gen = name
+ case name:
+ default:
+ return fmt.Errorf("%w: bound to %s, the listing named %s", ErrGenerationChanged, g.gen, name)
+ }
+ return nil
+}
+
+// named checks a 200 listing's generation against the one its request
+// sent: an unbound request binds what the listing names; a bound one must
+// be answered with the same name.
+func (g *genBinding) named(sent, name string) error {
+ switch {
+ case sent == "" && name == "":
+ return nil // a console from before generations
+ case sent == "":
+ return g.bind(name)
+ case name != sent:
+ return fmt.Errorf("%w: bound to %s, the listing named %q", ErrGenerationChanged, sent, name)
+ }
+ return nil
+}
+
+// takeGone reports, and clears, whether the door answered that the bound
+// generation was gone.
+func (g *genBinding) takeGone() bool {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ gone := g.gone
+ g.gone = false
+ return gone
+}
+
+// unbind is a read's one restart after ErrGenerationGone: the next listing
+// is unbound again and binds what head.json names now.
+func (g *genBinding) unbind() {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ g.gen = ""
+}
+
+func (g *genBinding) markGone() {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ g.gone = true
+}
+
+// refusal reads a non-2xx answer. A 410 is the bound door's own
+// (GenerationBody): the bound generation is gone (ErrGenerationGone), or
+// an as-of time is before every kept generation (*BeforeHistoryError).
+// Everything else is doorError's.
+func (c *Client) refusal(res *http.Response) error {
+ if res.StatusCode != http.StatusGone {
+ return doorError(res)
+ }
+ raw, _ := io.ReadAll(io.LimitReader(res.Body, 64<<10))
+ var body GenerationBody
+ if json.Unmarshal(raw, &body) == nil {
+ switch {
+ case body.GenerationGone != "":
+ c.gen.markGone()
+ return fmt.Errorf("%w: %s", ErrGenerationGone, body.GenerationGone)
+ case body.Oldest != nil:
+ return &BeforeHistoryError{Oldest: body.Oldest.UTC()}
+ }
+ }
+ return &DoorError{Status: res.StatusCode, Message: strings.TrimSpace(body.Error)}
+}
diff --git a/internal/dbdoor/generation_test.go b/internal/dbdoor/generation_test.go
new file mode 100644
index 000000000..2003d5ba9
--- /dev/null
+++ b/internal/dbdoor/generation_test.go
@@ -0,0 +1,442 @@
+package dbdoor
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ lsfile "github.com/benbjohnson/litestream/file"
+ "github.com/superfly/ltx"
+
+ "github.com/carlosframework/platform/internal/dbdoor/dbdoortest"
+ "github.com/carlosframework/platform/internal/replicagen"
+)
+
+// The bound door (spec 2026-11-12 §6.1, generations Task 8). genDoor
+// stands in for the console's db door over a replica with generations:
+// an unbound read of a host with head.json is refused with 409 and the
+// generation to bind; a bound read stays on its generation whatever head
+// says now; a bound read of a retired generation is 410 generation_gone.
+// A host with no head.json (head == "") is the root layout: its unbound
+// listing is answered and names "@root".
+
+var (
+ genOne = replicagen.Name(1)
+ genTwo = replicagen.Name(2)
+)
+
+type genDoor struct {
+ t *testing.T
+ mu sync.Mutex
+ head string // "" = no head.json
+ gens map[string]*lsfile.ReplicaClient // the generations that exist
+ // atGen is the generation an unbound at-listing resolves to; "" is head.
+ atGen string
+ // beforeHistory, when set, refuses every at-listing as older than it.
+ beforeHistory time.Time
+ // name, when set, is the generation a bound listing names (a door
+ // that changed generation under the client).
+ name string
+ reqs []string
+ // before and after run around each request, with its index, under mu.
+ before, after func(d *genDoor, i int, tail string)
+}
+
+func newGenDoor(t *testing.T) *genDoor {
+ return &genDoor{t: t, gens: map[string]*lsfile.ReplicaClient{}}
+}
+
+// replica writes a replica of batches*Rows rows into gen.
+func (d *genDoor) replica(gen string, batches int) {
+ dir := d.t.TempDir()
+ dbdoortest.Replicate(d.t, dir, batches)
+ d.gens[gen] = lsfile.NewReplicaClient(dir)
+}
+
+func (d *genDoor) requests() []string {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ return append([]string(nil), d.reqs...)
+}
+
+func (d *genDoor) do(ctx context.Context, tail string, h http.Header) (*http.Response, error) {
+ rec := httptest.NewRecorder()
+ d.mu.Lock()
+ i := len(d.reqs)
+ d.reqs = append(d.reqs, tail)
+ if d.before != nil {
+ d.before(d, i, tail)
+ }
+ d.mu.Unlock()
+ d.serve(ctx, rec, tail, h)
+ if d.after != nil {
+ d.mu.Lock()
+ d.after(d, i, tail)
+ d.mu.Unlock()
+ }
+ return rec.Result(), nil
+}
+
+func writeBody(w http.ResponseWriter, status int, v any) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(status)
+ _ = json.NewEncoder(w).Encode(v)
+}
+
+func (d *genDoor) serve(ctx context.Context, w http.ResponseWriter, tail string, h http.Header) {
+ path, raw, _ := strings.Cut(tail, "?")
+ q, err := url.ParseQuery(raw)
+ if err != nil {
+ d.t.Errorf("unparseable query %q", raw)
+ w.WriteHeader(http.StatusBadRequest)
+ return
+ }
+ parts := strings.Split(strings.TrimPrefix(path, "/ltx/"), "/")
+ level, err := strconv.Atoi(parts[0])
+ if err != nil {
+ http.NotFound(w, nil)
+ return
+ }
+ d.mu.Lock()
+ head, atGen, before, name := d.head, d.atGen, d.beforeHistory, d.name
+ d.mu.Unlock()
+ gen := q.Get(GenParam)
+ if q.Has(GenParam) && !replicagen.Valid(gen) {
+ d.t.Errorf("the client sent an invalid generation %q", gen)
+ w.WriteHeader(http.StatusBadRequest)
+ return
+ }
+ if gen == "" {
+ bind := head
+ if q.Has(AtParam) {
+ if !before.IsZero() {
+ writeBody(w, http.StatusGone, GenerationBody{Oldest: &before})
+ return
+ }
+ if atGen != "" {
+ bind = atGen
+ }
+ }
+ if bind != "" {
+ writeBody(w, http.StatusConflict, GenerationBody{Error: "this carlos is too old", Generation: bind})
+ return
+ }
+ gen = replicagen.Root
+ } else if q.Has(AtParam) {
+ d.t.Errorf("a bound request also sent at: %s", tail)
+ }
+ d.mu.Lock()
+ rc := d.gens[gen]
+ d.mu.Unlock()
+ if rc == nil {
+ writeBody(w, http.StatusGone, GenerationBody{GenerationGone: gen})
+ return
+ }
+ if len(parts) == 1 {
+ itr, _ := rc.LTXFiles(ctx, level, 0, false)
+ named := gen
+ if name != "" {
+ named = name
+ }
+ out := ListResponse{Generation: named, Files: []LTXFile{}}
+ for itr.Next() {
+ 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})
+ }
+ itr.Close()
+ writeBody(w, http.StatusOK, out)
+ return
+ }
+ lo, hi, err := ParseSpan(parts[1])
+ if err != nil {
+ http.NotFound(w, nil)
+ return
+ }
+ off, size, err := ParseRange(h.Get("Range"))
+ if err != nil {
+ w.WriteHeader(http.StatusRequestedRangeNotSatisfiable)
+ return
+ }
+ body, err := rc.OpenLTXFile(ctx, level, ltx.TXID(lo), ltx.TXID(hi), off, size)
+ if errors.Is(err, os.ErrNotExist) {
+ http.NotFound(w, nil)
+ return
+ }
+ if err != nil {
+ w.WriteHeader(http.StatusInternalServerError)
+ return
+ }
+ defer body.Close()
+ w.WriteHeader(http.StatusPartialContent)
+ _, _ = io.Copy(w, body)
+}
+
+func genQuery(tail string) url.Values {
+ _, raw, _ := strings.Cut(tail, "?")
+ q, _ := url.ParseQuery(raw)
+ return q
+}
+
+// unbound counts the requests that named no generation.
+func unbound(reqs []string) int {
+ n := 0
+ for _, r := range reqs {
+ if !genQuery(r).Has(GenParam) {
+ n++
+ }
+ }
+ return n
+}
+
+// Corrections to the plan (Astra plan R1 finding 7): a bound read stays
+// on its generation after head moves. The first listing is unbound and is
+// told the generation to bind; every request after it carries g-1, none
+// names g-2, and the restore is all g-1's.
+func TestDoorBoundListStaysOnG1AfterSwitch(t *testing.T) {
+ d := newGenDoor(t)
+ d.replica(genOne, 3)
+ d.replica(genTwo, 5)
+ d.head = genOne
+ d.after = func(d *genDoor, i int, tail string) {
+ if i == 1 { // the first bound listing: head moves to g-2
+ d.head = genTwo
+ }
+ }
+ got, err := RestoreTo(context.Background(), NewClient(d.do), t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer os.RemoveAll(got.Dir)
+ if rows := countRows(t, got.Path); rows != 3*dbdoortest.Rows {
+ t.Fatalf("restored %d rows, want g-1's %d", rows, 3*dbdoortest.Rows)
+ }
+ reqs := d.requests()
+ if len(reqs) < 3 || genQuery(reqs[0]).Has(GenParam) {
+ t.Fatalf("requests = %q, want an unbound first listing", reqs)
+ }
+ for _, r := range reqs[1:] {
+ if g := genQuery(r).Get(GenParam); g != genOne {
+ t.Errorf("request %s carries generation %q, want %s", r, g, genOne)
+ }
+ }
+}
+
+// The one restart (Astra plan R1 finding 7): the bound generation is
+// gone (retired), so the read restarts once, unbound and then bound to
+// the generation head names now. The copy is all g-2's, never mixed.
+func TestDoorGenerationGoneRestartsOnceUnboundThenBound(t *testing.T) {
+ retire := func(d *genDoor) {
+ delete(d.gens, genOne)
+ d.head = genTwo
+ }
+ for _, c := range []struct {
+ name string
+ set func(d *genDoor)
+ }{
+ {"on a listing", func(d *genDoor) {
+ d.after = func(d *genDoor, i int, _ string) {
+ if i == 1 { // after the first bound listing
+ retire(d)
+ }
+ }
+ }},
+ {"on a download", func(d *genDoor) {
+ d.before = func(d *genDoor, _ int, tail string) {
+ path, _, _ := strings.Cut(tail, "?")
+ if strings.Count(path, "/") == 3 && d.gens[genOne] != nil { // the first download
+ retire(d)
+ }
+ }
+ }},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ d := newGenDoor(t)
+ d.replica(genOne, 3)
+ d.replica(genTwo, 5)
+ d.head = genOne
+ c.set(d)
+ got, err := RestoreTo(context.Background(), NewClient(d.do), t.TempDir())
+ checkG2(t, d, got, err)
+ })
+ }
+}
+
+func checkG2(t *testing.T, d *genDoor, got *Restored, err error) {
+ t.Helper()
+ if err != nil {
+ t.Fatalf("restore across a retired generation = %v, want one restart onto g-2", err)
+ }
+ defer os.RemoveAll(got.Dir)
+ if rows := countRows(t, got.Path); rows != 5*dbdoortest.Rows {
+ t.Fatalf("restored %d rows, want g-2's %d", rows, 5*dbdoortest.Rows)
+ }
+ reqs := d.requests()
+ if n := unbound(reqs); n != 2 {
+ t.Fatalf("%d unbound requests in %q, want two: the first read and its one restart", n, reqs)
+ }
+ restarted := false
+ for _, r := range reqs[1:] {
+ switch g := genQuery(r).Get(GenParam); {
+ case g == "":
+ restarted = true
+ case restarted && g != genTwo:
+ t.Errorf("after the restart %s carries %q, want %s", r, g, genTwo)
+ }
+ }
+}
+
+// Once, not forever: a generation retired under each attempt ends the
+// read as "changed twice" (os.ErrNotExist, the CLI's existing sentence).
+func TestDoorGenerationGoneTwiceStops(t *testing.T) {
+ d := newGenDoor(t)
+ d.replica(genOne, 3)
+ d.replica(genTwo, 5)
+ d.head = genOne
+ d.after = func(d *genDoor, i int, tail string) {
+ if g := genQuery(tail).Get(GenParam); g != "" {
+ delete(d.gens, g)
+ if g == genOne {
+ d.head = genTwo
+ }
+ }
+ }
+ _, err := RestoreTo(context.Background(), NewClient(d.do), t.TempDir())
+ if !errors.Is(err, os.ErrNotExist) || !errors.Is(err, ErrGenerationGone) {
+ t.Fatalf("restore = %v, want os.ErrNotExist wrapping ErrGenerationGone", err)
+ }
+ if n := unbound(d.requests()); n != 2 {
+ t.Fatalf("%d unbound requests, want two", n)
+ }
+}
+
+// A bound listing that names another generation is a door that switched
+// under the client: refused, never mixed, and not a restart.
+func TestDoorListingNamingAnotherGenerationRefuses(t *testing.T) {
+ d := newGenDoor(t)
+ d.replica(genOne, 3)
+ d.head = genOne
+ d.name = genTwo
+ _, err := RestoreTo(context.Background(), NewClient(d.do), t.TempDir())
+ if !errors.Is(err, ErrGenerationChanged) {
+ t.Fatalf("restore = %v, want ErrGenerationChanged", err)
+ }
+ if n := unbound(d.requests()); n != 1 {
+ t.Fatalf("%d unbound requests, want one: no restart", n)
+ }
+}
+
+// A 409 that names something that is not a generation is not followed.
+func TestDoorInvalidGenerationMarkerRefuses(t *testing.T) {
+ d := newGenDoor(t)
+ d.replica(genOne, 3)
+ d.head = "../x"
+ _, err := RestoreTo(context.Background(), NewClient(d.do), t.TempDir())
+ if err == nil || len(d.requests()) != 1 {
+ t.Fatalf("restore = %v after %q, want a refusal after the one listing", err, d.requests())
+ }
+}
+
+// An as-of read sends at on its unbound listing only, and the door picks
+// the generation (a history entry here); every later request is bound.
+func TestDoorAtReadSendsAtThenBindsTheGeneration(t *testing.T) {
+ d := newGenDoor(t)
+ d.replica(genOne, 3)
+ d.replica(genTwo, 5)
+ d.head = genTwo
+ d.atGen = genOne
+ at := time.Now().Add(time.Hour).Truncate(time.Second).UTC()
+ got, err := RestoreAsOf(context.Background(), NewClient(d.do), t.TempDir(), at.Add(500*time.Millisecond))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer os.RemoveAll(got.Dir)
+ if rows := countRows(t, got.Path); rows != 3*dbdoortest.Rows {
+ t.Fatalf("restored %d rows, want g-1's %d", rows, 3*dbdoortest.Rows)
+ }
+ reqs := d.requests()
+ if q := genQuery(reqs[0]); q.Get(AtParam) != at.Format(time.RFC3339Nano) || q.Has(GenParam) {
+ t.Fatalf("first request %s, want at=%s (the second the restore reads to) and no gen", reqs[0], at.Format(time.RFC3339Nano))
+ }
+ for _, r := range reqs[1:] {
+ if q := genQuery(r); q.Get(GenParam) != genOne || q.Has(AtParam) {
+ t.Errorf("request %s, want gen=%s and no at", r, genOne)
+ }
+ }
+}
+
+// A time before every kept generation is the CLI's own BeforeHistoryError,
+// naming the oldest time the door reported.
+func TestDoorAtBeforeEveryGenerationIsBeforeHistory(t *testing.T) {
+ d := newGenDoor(t)
+ d.replica(genOne, 3)
+ d.head = genOne
+ d.beforeHistory = time.Date(2026, 11, 10, 9, 0, 0, 0, time.UTC)
+ _, err := RestoreAsOf(context.Background(), NewClient(d.do), t.TempDir(), time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC))
+ var before *BeforeHistoryError
+ if !errors.As(err, &before) || !before.Oldest.Equal(d.beforeHistory) {
+ t.Fatalf("restore = %v, want a BeforeHistoryError naming %s", err, d.beforeHistory)
+ }
+}
+
+// A root-layout host's listing names "@root": the client binds it, so a
+// head.json that appears mid-read cannot move the read off the root.
+func TestDoorRootListingBindsTheRootGeneration(t *testing.T) {
+ d := newGenDoor(t)
+ d.replica(replicagen.Root, 3)
+ d.replica(genOne, 5)
+ d.after = func(d *genDoor, i int, _ string) {
+ if i == 0 {
+ d.head = genOne
+ }
+ }
+ got, err := RestoreTo(context.Background(), NewClient(d.do), t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer os.RemoveAll(got.Dir)
+ if rows := countRows(t, got.Path); rows != 3*dbdoortest.Rows {
+ t.Fatalf("restored %d rows, want the root's %d", rows, 3*dbdoortest.Rows)
+ }
+ reqs := d.requests()
+ for _, r := range reqs[1:] {
+ if !strings.Contains(r, "gen=%40root") {
+ t.Errorf("request %s, want gen=%%40root", r)
+ }
+ }
+}
+
+// A console from before generations names none: the client stays on
+// today's unbound protocol, byte for byte.
+func TestDoorOldConsoleListingKeepsTheUnboundGenerationlessProtocol(t *testing.T) {
+ dir := t.TempDir()
+ dbdoortest.Replicate(t, dir, 2)
+ door := newTestDoor(t, dir)
+ var mu sync.Mutex
+ var tails []string
+ c := NewClient(func(ctx context.Context, tail string, h http.Header) (*http.Response, error) {
+ mu.Lock()
+ tails = append(tails, tail)
+ mu.Unlock()
+ return door.do(ctx, tail, h)
+ })
+ got, err := RestoreTo(context.Background(), c, t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer os.RemoveAll(got.Dir)
+ for _, tail := range tails {
+ if strings.Contains(tail, "?") {
+ t.Errorf("request %s carries a query; an old console's protocol has none", tail)
+ }
+ }
+}
diff --git a/internal/dbdoor/restore.go b/internal/dbdoor/restore.go
index f646fa40a..3b0f6b7e6 100644
--- a/internal/dbdoor/restore.go
+++ b/internal/dbdoor/restore.go
@@ -148,7 +148,19 @@ func RestoreAsOf(ctx context.Context, c *Client, parent string, at time.Time) (*
// (RestoreToTarget) or an as-of time (RestoreAsOf). Neither is the newest
// copy. Each keeps its own refusal: a target no chain ends at is
// ErrHistoryGone, and a time before the kept history is ErrBeforeHistory.
+//
+// Against a console with generations the read is bound to one (spec
+// 2026-11-12 §6.1): the first listing resolves it (for at, the one
+// current then) and every later request names it, so the copy never mixes
+// generations, whatever head.json does meanwhile. The retry below covers
+// the one case binding cannot: the bound generation retired under the
+// read (ErrGenerationGone). That attempt restarts unbound, then binds
+// what head.json names now.
func restoreAt(ctx context.Context, c *Client, parent string, target uint64, at time.Time) (*Restored, error) {
+ // An unbound as-of listing asks for the generation current at the
+ // whole second restoreOnce reads files to, so the generation chosen
+ // and the files read in it answer the same time.
+ c.gen.setAt(at.Truncate(time.Second))
dir, err := os.MkdirTemp(parent, "carlos-db-")
if err != nil {
return nil, err
@@ -178,8 +190,12 @@ func restoreAt(ctx context.Context, c *Client, parent string, target uint64, at
}
return nil, ErrCheckFailed
}
+ gone := c.gen.takeGone() || errors.Is(err, ErrGenerationGone)
vanished := errors.Is(err, os.ErrNotExist) || rec.sawVanish()
- if attempt == 0 && vanished && ctx.Err() == nil {
+ if attempt == 0 && (vanished || gone) && ctx.Err() == nil {
+ if gone {
+ c.gen.unbind()
+ }
continue
}
os.RemoveAll(dir)
@@ -189,6 +205,12 @@ func restoreAt(ctx context.Context, c *Client, parent string, target uint64, at
return nil, cerr
}
switch {
+ case gone:
+ // Retired under both attempts: the replica changed twice.
+ if !errors.Is(err, ErrGenerationGone) {
+ err = fmt.Errorf("%w: %w", ErrGenerationGone, err)
+ }
+ return nil, fmt.Errorf("%w: %w", os.ErrNotExist, err)
case errors.Is(err, ErrNoTimes):
return nil, ErrNoTimes
case errors.Is(err, litestream.ErrNoSnapshots) || errors.Is(err, litestream.ErrTxNotAvailable):
@@ -514,6 +536,9 @@ const dbDownloadBackoffMax = 8 * time.Second
// or briefly unavailable (429, 502, 503, 504), or no answer at all (a
// transport error). Any other refusal from the door is final.
func transientOpen(err error) bool {
+ if errors.Is(err, ErrGenerationGone) || errors.Is(err, ErrGenerationChanged) {
+ return false
+ }
var door *DoorError
if errors.As(err, &door) {
switch door.Status {