carlos / platform Public

console: fail closed on the generations probe; check bound reads

Task 8 fix round 1 (Astra R1, three findings).

P1: the leftover rail's g-* probe no longer reads SeedData, and never
passes when it cannot run. It is one LIST of <loc>/g- capped at one key
on the replica's own bucket, through the store the resolver reads
head.json with (lease.NewFilesStore); no bucket, a store failure or a
listing failure is an error and the create is refused. A test's file
replica answers the probe from its directory (generationsProber).

P2 retirement: a bound listing with check=1 (dbdoor.CheckParam) asks
whether the generation is still current or in head.json's history. The
CLI asks it before it reports that a bound read found no plan
(ErrNoSnapshots, ErrTxNotAvailable), and restarts once on
ErrGenerationGone; a check that fails is an error, never "not gone".
The door's retirement checks now answer 502 when head.json cannot be
read, instead of treating it as live.

P2 accounting: production-door witnesses count head.json reads (two
for a bound restore with no snapshot, one per missing bound GET, none
per bound GET, five across a partial-retirement restart) and assert
the probe's max-keys=1. The dbdoor fake answers 410 only where the
console does. The data-store sensor narrowing from the first round is
reverted: the data store is no longer probed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 677877e4400799268c7398097061025dd3d0b646 parent f339c6e
11 files changed, +506 −103
  • internal/console/apidb.go +48 −18
  • internal/console/apidb_generations_test.go +212 −26
  • internal/console/createleftovers.go +58 −33
  • internal/console/createleftovers_test.go +3 −0
  • internal/console/hacreate_test.go +0 −3
  • internal/console/hap2_wiring_test.go +3 −0
  • internal/console/restore_proof_test.go +0 −3
  • internal/dbdoor/coords.go +15 −7
  • internal/dbdoor/generation.go +30 −0
  • internal/dbdoor/generation_test.go +114 −13
  • internal/dbdoor/restore.go +23 −0
diff --git a/internal/console/apidb.go b/internal/console/apidb.go
index 3ea3814b7..07d1ad77d 100644
--- a/internal/console/apidb.go
+++ b/internal/console/apidb.go
@@ -115,6 +115,9 @@ type dbRequest struct {
type dbBinding struct {
gen string
at time.Time
+ // check asks, on a bound listing, whether gen is still current or in
+ // head.json's history before listing it (dbdoor.CheckParam).
+ check bool
}
// dbNeedsNewerCLI is the 409 for an unbound read of a host whose replica
@@ -124,8 +127,9 @@ type dbBinding struct {
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.
+// (RFC 3339) and check (1, with gen). Anything else is a 400 before any
+// read, and ok=false means it has been written. A GET ignores at and
+// check: only a listing resolves or checks.
func parseDBBinding(w http.ResponseWriter, r *http.Request, list bool) (dbBinding, bool) {
q := r.URL.Query()
var b dbBinding
@@ -146,6 +150,13 @@ func parseDBBinding(w http.ResponseWriter, r *http.Request, list bool) (dbBindin
b.at = at
}
}
+ if list && q.Has(dbdoor.CheckParam) {
+ if q.Get(dbdoor.CheckParam) != "1" || b.gen == "" {
+ jsonError(w, http.StatusBadRequest, "invalid generation")
+ return dbBinding{}, false
+ }
+ b.check = true
+ }
return b, true
}
@@ -380,45 +391,65 @@ func (s *Server) handleAPIDBList(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, out)
return
}
+ if sel.check && s.dbAnswerGone(w, r.Context(), g) {
+ return
+ }
out, err := listReplicaLevel(r.Context(), g.rd, level)
if err != nil {
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})
+ // level first and level 0 last in every plan, so asking head.json when
+ // one of those two is empty catches a whole retirement; one that lands
+ // part way through a plan leaves the plan without a chain, and the
+ // client asks (check=1) before it reports that. Levels 1 to 8, often
+ // empty, cost no head read.
+ if !sel.check && sel.gen != "" && len(out.Files) == 0 && (level == litestream.SnapshotLevel || level == 0) && s.dbAnswerGone(w, r.Context(), g) {
return
}
out.Generation = g.gen
writeJSON(w, http.StatusOK, out)
}
+// dbAnswerGone answers 410 generation_gone when g's bound generation was
+// retired, and 502 when head.json cannot be read to say: uncertainty is
+// never "not gone". ok=true means it has answered.
+func (s *Server) dbAnswerGone(w http.ResponseWriter, ctx context.Context, g dbRequest) bool {
+ gone, err := s.dbGenerationGone(ctx, g)
+ switch {
+ case 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)
+ jsonError(w, http.StatusBadGateway, "could not read the replica. Try again.")
+ return true
+ case gone:
+ writeJSON(w, http.StatusGone, dbdoor.GenerationBody{GenerationGone: g.gen})
+ return true
+ }
+ return false
+}
+
// 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 {
+// with no head.json, it is not the root. One head.json read, whose
+// failure is returned.
+func (s *Server) dbGenerationGone(ctx context.Context, g dbRequest) (bool, error) {
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
+ return false, err
}
if !res.HeadFound {
- return g.gen != replicagen.Root
+ return g.gen != replicagen.Root, nil
}
if res.Head.Generation == g.gen {
- return false
+ return false, nil
}
for _, e := range res.Head.History {
if e.Generation == g.gen {
- return false
+ return false, nil
}
}
- return true
+ return true, nil
}
// listReplicaLevel lists one level of rd in the door's wire shape, ordered
@@ -492,8 +523,7 @@ 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})
+ if pinned == nil && sel.gen != "" && s.dbAnswerGone(w, ctx, g) {
return
}
http.NotFound(w, r)
diff --git a/internal/console/apidb_generations_test.go b/internal/console/apidb_generations_test.go
index 588198f0f..67e05d135 100644
--- a/internal/console/apidb_generations_test.go
+++ b/internal/console/apidb_generations_test.go
@@ -3,6 +3,7 @@ package console
import (
"context"
"encoding/json"
+ "errors"
"fmt"
"io"
"log/slog"
@@ -21,24 +22,30 @@ import (
lsfile "github.com/benbjohnson/litestream/file"
"github.com/superfly/ltx"
+ "github.com/carlosframework/platform/internal/activator"
"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.
+// head.json does, whatever generation or time the caller asks for. The
+// client answers the leftover rail's generations probe from its own
+// directory (a file replica: any g-* entry beside its levels), or with
+// none for a two-method fake.
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.(*lsfile.ReplicaClient); ok {
+ return lease.Resolved{Generation: replicagen.Root, Client: fileProbe{c}}, nil
+ }
if c, ok := rd.(litestream.ReplicaClient); ok {
return lease.Resolved{Generation: replicagen.Root, Client: c}, nil
}
@@ -46,6 +53,25 @@ func rootReplica(open func(context.Context, string) (replicaReader, error)) func
}
}
+// fileProbe is a file replica that answers the generations probe from
+// its directory.
+type fileProbe struct{ *lsfile.ReplicaClient }
+
+func (p fileProbe) holdsGenerations(context.Context) (bool, error) {
+ entries, err := os.ReadDir(p.Path())
+ if errors.Is(err, os.ErrNotExist) {
+ return false, nil
+ }
+ for _, e := range entries {
+ if strings.HasPrefix(e.Name(), "g-") {
+ return true, nil
+ }
+ }
+ return false, err
+}
+
+func (readerClient) holdsGenerations(context.Context) (bool, error) { return false, nil }
+
// readerClient is a test's two-method replica as the litestream client a
// resolution carries. The door only reads.
type readerClient struct{ replicaReader }
@@ -61,12 +87,6 @@ func (readerClient) WriteLTXFile(context.Context, int, ltx.TXID, ltx.TXID, io.Re
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 (
@@ -86,7 +106,7 @@ const wantNeedsNewerCLI = "This version of carlos cannot safely read %s's data.
type genBucket struct {
m *leasetest.VersionedBucket
mu sync.Mutex
- reqs []string // "METHOD key", or "GET ?prefix=<p>" for a listing
+ reqs []string // "METHOD key", or "GET ?max-keys=<n>&prefix=<p>" for a listing
}
func useGenBucket(t *testing.T, s *Server) *genBucket {
@@ -97,7 +117,7 @@ func useGenBucket(t *testing.T, s *Server) *genBucket {
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")
+ key = "?max-keys=" + r.URL.Query().Get("max-keys") + "&prefix=" + r.URL.Query().Get("prefix")
}
b.mu.Lock()
b.reqs = append(b.reqs, r.Method+" "+key)
@@ -306,6 +326,30 @@ func TestDoorCLIRestoreStaysOnTheBoundGeneration(t *testing.T) {
one := b.replica(t, dbTestHost, genA, 3)
b.replica(t, dbTestHost, genB, 5)
b.head(t, dbTestHost, genA, genT0)
+ c, tails := doorClient(t, fx, func(i int, _ string) {
+ if i == 1 { // the first bound listing: head moves on
+ b.head(t, dbTestHost, genB, genT1, lease.HeadHistory{Generation: genA, CreatedAt: genT0, EndedAt: genT1})
+ }
+ })
+ 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)
+ }
+ }
+}
+
+// doorClient is the CLI's client over fx's door, as the member, with
+// after called (serially) once each request has been answered.
+func doorClient(t *testing.T, fx *dbFx, after func(i int, tail string)) (*dbdoor.Client, func() []string) {
+ t.Helper()
var mu sync.Mutex
var tails []string
c := dbdoor.NewClient(func(ctx context.Context, tail string, h http.Header) (*http.Response, error) {
@@ -319,24 +363,127 @@ func TestDoorCLIRestoreStaysOnTheBoundGeneration(t *testing.T) {
req.Header.Set("Authorization", "Bearer "+fx.member)
res, err := http.DefaultClient.Do(req)
mu.Lock()
+ defer mu.Unlock()
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})
+ if after != nil {
+ after(len(tails)-1, tail)
}
- mu.Unlock()
return res, err
})
+ return c, func() []string {
+ mu.Lock()
+ defer mu.Unlock()
+ return append([]string(nil), tails...)
+ }
+}
+
+func hasCheck(tail string) bool { return strings.Contains(tail, dbdoor.CheckParam+"=1") }
+
+// Astra Task 8 R1 (request accounting), through the production door and
+// reader: a restore of a generation with no snapshot costs two head.json
+// reads (the first listing's resolution, and the empty bound snapshot
+// level's retirement check); bound levels 1 to 8, empty, cost none; a
+// bound GET of a missing file costs one; a bound GET of a present one none.
+func TestDoorRequestBudgetThroughTheProductionDoor(t *testing.T) {
+ fx, b := genDoor(t)
+ one := b.replica(t, dbTestHost, genA, 3)
+ b.head(t, dbTestHost, genA, genT0)
+ c, tails := doorClient(t, fx, nil)
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)
+ files := len(listFiles(t, one, 0))
+ if n := b.count(isHeadRead); n != 2 {
+ t.Errorf("a bound restore read head.json %d times, want 2", n)
}
- for _, tail := range tails[1:] {
- if !strings.Contains(tail, q(genA)[1:]) {
- t.Errorf("request %s is not bound to %s", tail, genA)
+ if n := b.count(isLTXRead); n != files {
+ t.Errorf("%d LTX reads, want one per file (%d)", n, files)
+ }
+ // One unbound listing (409), ten bound ones, one GET per file; no check.
+ if all := tails(); len(all) != 1+10+files {
+ t.Errorf("door requests %q, want %d", all, 1+10+files)
+ }
+ for _, tail := range tails() {
+ if hasCheck(tail) {
+ t.Errorf("a restore that planned checked its binding: %s", tail)
+ }
+ }
+ heads := b.count(isHeadRead)
+ if status, out := fx.get(t, 0, 900, 901, q(genA)); status != http.StatusNotFound {
+ t.Fatalf("missing bound GET = %d %s, want 404", status, out)
+ }
+ if n := b.count(isHeadRead) - heads; n != 1 {
+ t.Errorf("a missing bound GET read head.json %d times, want 1", n)
+ }
+ f, _ := genFile(t, one)
+ heads = b.count(isHeadRead)
+ if status, _ := fx.get(t, 0, f.MinTXID, f.MaxTXID, q(genA)); status != http.StatusPartialContent {
+ t.Fatalf("bound GET = %d", status)
+ }
+ if n := b.count(isHeadRead) - heads; n != 0 {
+ t.Errorf("a bound GET read head.json %d times, want none", n)
+ }
+}
+
+// Astra Task 8 R1 (P2), through the production door: g-1 is retired part
+// way through a plan (after its empty snapshot level was listed, its first
+// L0 file is deleted and head names g-2 alone), so no listing or GET is
+// answered 410. The client checks its binding (check=1), is told gone,
+// and restarts once onto g-2. Head reads: the resolution and the empty
+// snapshot check on each attempt, plus the one check: five.
+func TestDoorPartialRetirementRestartsThroughTheProductionDoor(t *testing.T) {
+ fx, b := genDoor(t)
+ b.replica(t, dbTestHost, genA, 3)
+ two := b.replica(t, dbTestHost, genB, 5)
+ b.head(t, dbTestHost, genA, genT0)
+ c, tails := doorClient(t, fx, func(i int, _ string) {
+ if i == 1 { // after the first bound listing, the snapshot level
+ b.m.BareDelete("data-test", fmt.Sprintf("%s0000/%s", replicagen.Prefix("instances/"+dbTestHost, genA), ltx.FormatFilename(1, 1)))
+ b.head(t, dbTestHost, genB, genT1)
+ }
+ })
+ got, err := dbdoor.RestoreTo(context.Background(), c, t.TempDir())
+ if err != nil {
+ t.Fatalf("restore across a partial retirement = %v, want one restart onto g-2", err)
+ }
+ defer os.RemoveAll(got.Dir)
+ if want := newestTXID(t, two); got.TXID != want {
+ t.Fatalf("restored to txid %d, want g-2's %d", got.TXID, want)
+ }
+ checks := 0
+ for _, tail := range tails() {
+ if hasCheck(tail) {
+ checks++
+ }
+ }
+ if checks != 1 {
+ t.Errorf("%d binding checks in %q, want one", checks, tails())
+ }
+ if n := b.count(isHeadRead); n != 5 {
+ t.Errorf("head.json read %d times, want 5", n)
+ }
+}
+
+// A retirement check that cannot read head.json is a 502, never "not
+// gone": on check=1, an empty bound snapshot level and a missing bound
+// GET. A live generation's check=1 is its ordinary listing.
+func TestDoorGenerationCheckNeverReadsUncertaintyAsLive(t *testing.T) {
+ fx, b := genDoor(t)
+ b.replica(t, dbTestHost, genA, 2)
+ b.head(t, dbTestHost, genA, genT0)
+ if status, out := fx.list(t, dbTestHost, 0, q(genA)+"&check=1"); status != http.StatusOK || !strings.Contains(out, `"generation":"`+genA+`"`) {
+ t.Fatalf("live check = %d %s, want the listing", status, out)
+ }
+ b.m.Put("data-test", "instances/"+dbTestHost+"/head.json", []byte("{"))
+ for name, do := range map[string]func() (int, string){
+ "check": func() (int, string) { return fx.list(t, dbTestHost, 0, q(genA)+"&check=1") },
+ "empty snapshot": func() (int, string) { return fx.list(t, dbTestHost, dbdoor.MaxLevel, q(genA)) },
+ "missing GET": func() (int, string) { return fx.get(t, 0, 900, 901, q(genA)) },
+ } {
+ if status, out := do(); status != http.StatusBadGateway {
+ t.Errorf("%s with an unreadable head.json = %d %s, want 502", name, status, out)
}
}
}
@@ -383,11 +530,11 @@ func TestDoorListAtPicksHistoryGeneration(t *testing.T) {
// 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"} {
+ for _, query := range []string{q("../x"), q("g-42"), q(""), q("@root/"), q("g-00000000000000000001/../x"), "?at=yesterday", "?check=1", q(genA) + "&check=2"} {
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 strings.HasPrefix(query, "?gen") && !strings.Contains(query, "check") {
if status, out := fx.get(t, 0, 1, 1, query); status != http.StatusBadRequest {
t.Errorf("GET%s = %d %s, want 400", query, status, out)
}
@@ -505,13 +652,8 @@ func TestSeedFromResolvesHead(t *testing.T) {
// 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{}
+ s := &Server{} // no SeedData: the probe uses the replica's own bucket
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("{}"))
@@ -526,4 +668,48 @@ func TestCreateLeftoversSeesGenerations(t *testing.T) {
t.Errorf("%s holds replica data = %v, %v; want %v", host, held, err, want)
}
}
+ // The probe is one LIST of <loc>/g-, capped at one key.
+ if n := b.count(func(r string) bool { return strings.HasSuffix(r, "/g-") }); n != 3 {
+ t.Errorf("%d generations probes, want one for each host the levels did not settle (3)", n)
+ }
+ for _, r := range b.all() {
+ if strings.HasSuffix(r, "/g-") && !strings.Contains(r, "max-keys=1") {
+ t.Errorf("generations probe %q is not capped at one key", r)
+ }
+ }
+ // A probe that cannot run fails closed.
+ b.m.FailOn = func(op, key string) error {
+ if op == "list" && strings.HasSuffix(key, "/g-") {
+ return errors.New("bucket unavailable")
+ }
+ return nil
+ }
+ if held, err := s.hostHoldsReplicaData(context.Background(), "empty.example.com"); err == nil {
+ t.Fatalf("failed probe = %v, nil; want an error (the rail refuses)", held)
+ }
+}
+
+// Astra Task 8 R1 (P1): with the data bucket configured and no SeedData
+// store at all, a create of a host holding only an abandoned generation
+// is refused before anything is written.
+func TestCreateDoorRefusesAnAbandonedGenerationWithoutSeedData(t *testing.T) {
+ for _, d := range leftoverDoors {
+ t.Run(d.name, func(t *testing.T) {
+ fx := leftoverFixture(t, "code-left-gen-"+d.name)
+ b := useGenBucket(t, fx.srv)
+ fx.srv.cfg.SeedData = nil
+ prefix := strings.TrimSuffix(activator.HibernatePrefix("instances", d.host), "/")
+ b.m.Put("data-test", replicagen.Prefix(prefix, genB)+"0000/"+ltx.FormatFilename(1, 1), []byte("ltx"))
+ status, _, out := rawReq(t, http.MethodPost, d.url(fx.consoleFixture), fx.token, d.body)
+ if status != http.StatusConflict || !strings.Contains(out, "still holds data from a deleted") {
+ t.Fatalf("create over an abandoned generation = %d %s, want the 409", status, out)
+ }
+ if d.exists(t, fx.consoleFixture) {
+ t.Fatal("the refused create wrote a record")
+ }
+ if n := b.count(func(r string) bool { return !strings.HasPrefix(r, "GET ") }); n != 0 {
+ t.Fatalf("the refused create wrote to the data bucket: %q", b.all())
+ }
+ })
+ }
}
diff --git a/internal/console/createleftovers.go b/internal/console/createleftovers.go
index e871fc4c4..045511d66 100644
--- a/internal/console/createleftovers.go
+++ b/internal/console/createleftovers.go
@@ -25,6 +25,7 @@ package console
import (
"context"
+ "errors"
"fmt"
"log"
"net/http"
@@ -33,6 +34,7 @@ import (
"github.com/carlosframework/platform/internal/activator"
"github.com/carlosframework/platform/internal/dbdoor"
+ "github.com/carlosframework/platform/internal/lease"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
)
@@ -72,59 +74,82 @@ func (s *Server) leftoverCheckApplies(region, pool string) bool {
// from seeing app.example.com's files.
func (s *Server) hostHoldsReplicaData(ctx context.Context, host string) (bool, error) {
loc := activator.HibernatePrefix(s.cfg.HibernatePrefix, host)
- held, err := s.replicaPrefixesHoldData(ctx, loc, strings.TrimSuffix(activator.MovesPrefix(host), "/"))
+ held, res, err := s.prefixHoldsData(ctx, loc)
if held || err != nil {
return held, err
}
+ if held, err := s.replicaPrefixesHoldData(ctx, strings.TrimSuffix(activator.MovesPrefix(host), "/")); 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)
+ return s.prefixHoldsGenerations(ctx, loc, res.Client)
}
// 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 {
- res, err := s.dbReplica(ctx, prefix, "", time.Time{})
- if err != nil {
- return false, fmt.Errorf("replica client for %s: %w", prefix, err)
+ if held, _, err := s.prefixHoldsData(ctx, prefix); held || err != nil {
+ return held, err
}
- if res.HeadFound {
- return true, nil
+ }
+ return false, nil
+}
+
+// prefixHoldsData resolves prefix and walks its levels. 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) prefixHoldsData(ctx context.Context, prefix string) (bool, lease.Resolved, error) {
+ res, err := s.dbReplica(ctx, prefix, "", time.Time{})
+ if err != nil {
+ return false, res, fmt.Errorf("replica client for %s: %w", prefix, err)
+ }
+ if res.HeadFound {
+ return true, res, nil
+ }
+ for level := 0; level <= dbdoor.MaxLevel; level++ {
+ found, err := anyLTXFile(ctx, res.Client, level)
+ if err != nil {
+ return false, res, fmt.Errorf("list %s level %d: %w", prefix, level, err)
}
- for level := 0; level <= dbdoor.MaxLevel; level++ {
- found, err := anyLTXFile(ctx, res.Client, level)
- if err != nil {
- return false, fmt.Errorf("list %s level %d: %w", prefix, level, err)
- }
- if found {
- return true, nil
- }
+ if found {
+ return true, res, nil
}
}
- return false, nil
+ return false, res, nil
+}
+
+// generationsProber is a replica reader that answers the generations
+// probe itself: a test's file replica. The resolver's S3 clients do not,
+// and are probed through their bucket.
+type generationsProber interface {
+ holdsGenerations(ctx context.Context) (bool, error)
}
// 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
+// lost, or a whole-prefix delete that stopped part way) is still a
+// deleted instance's database. One bounded LIST (max-keys 1) of
+// <prefix>/g- on the replica's own bucket, through the store the resolver
+// reads head.json with (lease.NewFilesStore). It fails closed: a probe
+// that cannot run is an error, and the rail refuses.
+func (s *Server) prefixHoldsGenerations(ctx context.Context, prefix string, rd replicaReader) (bool, error) {
+ if p, ok := rd.(generationsProber); ok {
+ return p.holdsGenerations(ctx)
}
- 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 s.cfg.HibernateBucket == "" {
+ return false, errors.New("no data bucket to list generations in")
+ }
+ st, err := lease.NewFilesStore(ctx, s.cfg.HibernateBucket, s.cfg.HibernateRegion)
+ if err != nil {
+ return false, fmt.Errorf("generations store for %s: %w", prefix, err)
+ }
+ pages, ok := st.(release.PageLister)
+ if !ok {
+ return false, errors.New("the generations store has no bounded listing")
}
+ keys, err := pages.ListPage(ctx, prefix+"/g-", "", 1)
if err != nil {
return false, fmt.Errorf("list %s generations: %w", prefix, err)
}
diff --git a/internal/console/createleftovers_test.go b/internal/console/createleftovers_test.go
index ddc713d83..c941c4104 100644
--- a/internal/console/createleftovers_test.go
+++ b/internal/console/createleftovers_test.go
@@ -465,6 +465,9 @@ func TestLeftoverCheckListsTheExactS3Prefixes(t *testing.T) {
want = append(want, fmt.Sprintf("%s/%04x/", root, level))
}
}
+ // Then the one bounded probe for an abandoned generation, on the
+ // replica's own bucket.
+ want = append(want, "instances/app.example.com/g-")
if got := b.listed(); strings.Join(got, "\n") != strings.Join(want, "\n") {
t.Fatalf("listed prefixes:\n%s\nwant:\n%s", strings.Join(got, "\n"), strings.Join(want, "\n"))
}
diff --git a/internal/console/hacreate_test.go b/internal/console/hacreate_test.go
index ff554bf6f..831f83aad 100644
--- a/internal/console/hacreate_test.go
+++ b/internal/console/hacreate_test.go
@@ -52,9 +52,6 @@ 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()
diff --git a/internal/console/hap2_wiring_test.go b/internal/console/hap2_wiring_test.go
index 44c058e3a..a3c18daa4 100644
--- a/internal/console/hap2_wiring_test.go
+++ b/internal/console/hap2_wiring_test.go
@@ -640,6 +640,9 @@ func TestHAP2RequestBudget(t *testing.T) {
if a.query.Get("prefix") == "instances/"+host+"/" && a.query.Get("max-keys") != "1" {
t.Errorf("unbounded proof: %+v", a)
}
+ if strings.HasSuffix(a.query.Get("prefix"), "/g-") && a.query.Get("max-keys") != "1" {
+ t.Errorf("unbounded generations probe: %+v", a)
+ }
}
var want []string
if proof {
diff --git a/internal/console/restore_proof_test.go b/internal/console/restore_proof_test.go
index 4f24825e8..aaf2ebddb 100644
--- a/internal/console/restore_proof_test.go
+++ b/internal/console/restore_proof_test.go
@@ -32,9 +32,6 @@ 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/dbdoor/coords.go b/internal/dbdoor/coords.go
index 3e2906ea2..f293fd406 100644
--- a/internal/dbdoor/coords.go
+++ b/internal/dbdoor/coords.go
@@ -55,13 +55,18 @@ type ListResponse struct {
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.
+// GenParam, AtParam and CheckParam 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,
+// except a bound listing with check=1, which first asks whether the
+// generation is still current or in head.json's history: 410
+// generation_gone when it is not. The client asks it before it reports
+// that a bound read found nothing to restore.
const (
- GenParam = "gen"
- AtParam = "at"
+ GenParam = "gen"
+ AtParam = "at"
+ CheckParam = "check"
)
// GenerationBody is the door's answer about a generation, additive to
@@ -71,7 +76,10 @@ const (
// 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).
+// door says so where it looks: an empty bound listing of the snapshot
+// level or level 0, a bound GET of a missing file, and a check=1
+// listing. The client restarts its read once, unbound
+// (ErrGenerationGone).
// - 410 with Oldest: an as-of listing earlier than every generation the
// replica keeps (a *BeforeHistoryError).
//
diff --git a/internal/dbdoor/generation.go b/internal/dbdoor/generation.go
index 178a74067..9cdd3fe52 100644
--- a/internal/dbdoor/generation.go
+++ b/internal/dbdoor/generation.go
@@ -1,6 +1,7 @@
package dbdoor
import (
+ "context"
"encoding/json"
"fmt"
"io"
@@ -52,6 +53,13 @@ func (g *genBinding) listQuery() (gen, query string) {
return "", ""
}
+// bound is the generation the read is bound to, "" when unbound.
+func (g *genBinding) bound() string {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ return g.gen
+}
+
// getQuery is a download's query: gen when bound, else nothing.
func (g *genBinding) getQuery() string {
g.mu.Lock()
@@ -119,6 +127,28 @@ func (g *genBinding) markGone() {
g.gone = true
}
+// checkBinding asks the door whether the bound generation is still
+// current or in head.json's history (a check=1 listing): nil when it is,
+// ErrGenerationGone when it was retired, and any other answer (the door
+// could not read head.json, a refusal, the network) as the error it is,
+// never as "not gone". Unbound, there is nothing to check.
+func (c *Client) checkBinding(ctx context.Context) error {
+ gen := c.gen.bound()
+ if gen == "" {
+ return nil
+ }
+ tail := ListTail(MaxLevel) + "?" + GenParam + "=" + url.QueryEscape(gen) + "&" + CheckParam + "=1"
+ res, err := c.do(ctx, tail, http.Header{})
+ if err != nil {
+ return err
+ }
+ defer res.Body.Close()
+ if res.StatusCode == http.StatusOK {
+ return nil
+ }
+ return c.refusal(res)
+}
+
// 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).
diff --git a/internal/dbdoor/generation_test.go b/internal/dbdoor/generation_test.go
index 2003d5ba9..e480c6cbb 100644
--- a/internal/dbdoor/generation_test.go
+++ b/internal/dbdoor/generation_test.go
@@ -26,8 +26,11 @@ import (
// 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
+// says now. A retired generation is 410 generation_gone exactly where the
+// console says so (apidb.go): an empty bound listing of the snapshot
+// level or level 0, a bound GET of a missing file, and a check=1 listing.
+// Every other bound listing of it answers what is left, as S3 would. A
+// host with no head.json (head == "") is the root layout: its unbound
// listing is answered and names "@root".
var (
@@ -39,7 +42,13 @@ type genDoor struct {
t *testing.T
mu sync.Mutex
head string // "" = no head.json
- gens map[string]*lsfile.ReplicaClient // the generations that exist
+ gens map[string]*lsfile.ReplicaClient // the generations with files
+ // retired are the generations neither head nor history names; a
+ // generation with no files is retired too.
+ retired map[string]bool
+ // checkStatus, when set, is the answer to every check=1 listing (a
+ // door that cannot read head.json).
+ checkStatus int
// 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.
@@ -53,7 +62,7 @@ type genDoor struct {
}
func newGenDoor(t *testing.T) *genDoor {
- return &genDoor{t: t, gens: map[string]*lsfile.ReplicaClient{}}
+ return &genDoor{t: t, gens: map[string]*lsfile.ReplicaClient{}, retired: map[string]bool{}}
}
// replica writes a replica of batches*Rows rows into gen.
@@ -137,26 +146,45 @@ func (d *genDoor) serve(ctx context.Context, w http.ResponseWriter, tail string,
}
d.mu.Lock()
rc := d.gens[gen]
+ gone := rc == nil || d.retired[gen]
+ checkStatus := d.checkStatus
d.mu.Unlock()
- if rc == nil {
- writeBody(w, http.StatusGone, GenerationBody{GenerationGone: gen})
- return
- }
+ goneBody := GenerationBody{GenerationGone: gen}
if len(parts) == 1 {
- itr, _ := rc.LTXFiles(ctx, level, 0, false)
+ if q.Get(CheckParam) == "1" {
+ switch {
+ case checkStatus != 0:
+ w.WriteHeader(checkStatus)
+ return
+ case gone:
+ writeBody(w, http.StatusGone, goneBody)
+ return
+ }
+ }
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})
+ if rc != nil {
+ itr, _ := rc.LTXFiles(ctx, level, 0, false)
+ 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()
+ }
+ if len(out.Files) == 0 && (level == MaxLevel || level == 0) && gone {
+ writeBody(w, http.StatusGone, goneBody)
+ return
}
- itr.Close()
writeBody(w, http.StatusOK, out)
return
}
+ if rc == nil {
+ writeBody(w, http.StatusGone, goneBody)
+ return
+ }
lo, hi, err := ParseSpan(parts[1])
if err != nil {
http.NotFound(w, nil)
@@ -169,6 +197,10 @@ func (d *genDoor) serve(ctx context.Context, w http.ResponseWriter, tail string,
}
body, err := rc.OpenLTXFile(ctx, level, ltx.TXID(lo), ltx.TXID(hi), off, size)
if errors.Is(err, os.ErrNotExist) {
+ if gone {
+ writeBody(w, http.StatusGone, goneBody)
+ return
+ }
http.NotFound(w, nil)
return
}
@@ -440,3 +472,72 @@ func TestDoorOldConsoleListingKeepsTheUnboundGenerationlessProtocol(t *testing.T
}
}
}
+
+// Astra Task 8 R1 (P2): a generation retired part way through a plan.
+// The snapshot level lists empty while g-1 is live; then g-1 is retired
+// and its first L0 file deleted, so level 0 still lists files and no
+// listing or download is answered 410. The plan finds no chain, and the
+// client checks its binding before reporting nothing to restore: gone,
+// so it restarts once and restores g-2.
+func TestDoorPartialRetirementChecksTheBindingAndRestarts(t *testing.T) {
+ d := newGenDoor(t)
+ d.replica(genOne, 3)
+ d.replica(genTwo, 5)
+ d.head = genOne
+ d.after = func(d *genDoor, i int, _ string) {
+ if i == 1 { // the first bound listing, the snapshot level
+ d.retired[genOne] = true
+ d.head = genTwo
+ if err := os.Remove(d.gens[genOne].LTXFilePath(0, 1, 1)); err != nil {
+ d.t.Error(err)
+ }
+ }
+ }
+ got, err := RestoreTo(context.Background(), NewClient(d.do), t.TempDir())
+ checkG2(t, d, got, err)
+ checks := 0
+ for _, r := range d.requests() {
+ if genQuery(r).Get(CheckParam) == "1" {
+ checks++
+ if genQuery(r).Get(GenParam) != genOne {
+ t.Errorf("check %s, want it bound to %s", r, genOne)
+ }
+ }
+ }
+ if checks != 1 {
+ t.Fatalf("%d binding checks, want one", checks)
+ }
+}
+
+// A live binding that finds no plan is the plain answer, after one check;
+// a check the door cannot answer is an error, never "not gone".
+func TestDoorBindingCheckOnNoPlan(t *testing.T) {
+ gapped := func(t *testing.T) *genDoor {
+ d := newGenDoor(t)
+ d.replica(genOne, 3)
+ d.head = genOne
+ if err := os.Remove(d.gens[genOne].LTXFilePath(0, 1, 1)); err != nil {
+ t.Fatal(err)
+ }
+ return d
+ }
+ t.Run("live", func(t *testing.T) {
+ d := gapped(t)
+ _, err := RestoreTo(context.Background(), NewClient(d.do), t.TempDir())
+ if !errors.Is(err, ErrNothingReplicated) {
+ t.Fatalf("restore = %v, want ErrNothingReplicated", err)
+ }
+ if n := unbound(d.requests()); n != 1 {
+ t.Fatalf("%d unbound requests, want one: no restart", n)
+ }
+ })
+ t.Run("unreadable head", func(t *testing.T) {
+ d := gapped(t)
+ d.checkStatus = http.StatusBadGateway
+ _, err := RestoreTo(context.Background(), NewClient(d.do), t.TempDir())
+ var door *DoorError
+ if errors.Is(err, ErrNothingReplicated) || !errors.As(err, &door) || door.Status != http.StatusBadGateway {
+ t.Fatalf("restore = %v, want the check's 502, not nothing replicated", err)
+ }
+ })
+}
diff --git a/internal/dbdoor/restore.go b/internal/dbdoor/restore.go
index 3b0f6b7e6..427bbc1a5 100644
--- a/internal/dbdoor/restore.go
+++ b/internal/dbdoor/restore.go
@@ -192,6 +192,23 @@ func restoreAt(ctx context.Context, c *Client, parent string, target uint64, at
}
gone := c.gen.takeGone() || errors.Is(err, ErrGenerationGone)
vanished := errors.Is(err, os.ErrNotExist) || rec.sawVanish()
+ // A bound read that found no plan may be reading a generation
+ // retired part way through its listings (an empty snapshot level,
+ // a compacted file gone, L0 still there): no download failed, so
+ // nothing said so. Ask before reporting "nothing to restore".
+ if !gone && !vanished && ctx.Err() == nil && noPlan(err) {
+ switch cerr := c.checkBinding(ctx); {
+ case errors.Is(cerr, ErrGenerationGone):
+ c.gen.takeGone()
+ gone, err = true, cerr
+ case cerr != nil:
+ os.RemoveAll(dir)
+ if ctxErr := ctx.Err(); ctxErr != nil {
+ return nil, ctxErr
+ }
+ return nil, fmt.Errorf("dbdoor: could not check the replica generation the read is bound to: %w", cerr)
+ }
+ }
if attempt == 0 && (vanished || gone) && ctx.Err() == nil {
if gone {
c.gen.unbind()
@@ -249,6 +266,12 @@ func restoreAt(ctx context.Context, c *Client, parent string, target uint64, at
return &Restored{Path: out, Dir: dir, TXID: txid, At: at}, nil
}
+// noPlan is litestream finding no restore plan: nothing replicated, or no
+// chain reaching the target or time.
+func noPlan(err error) bool {
+ return errors.Is(err, litestream.ErrNoSnapshots) || errors.Is(err, litestream.ErrTxNotAvailable)
+}
+
func restoreOnce(ctx context.Context, client litestream.ReplicaClient, out string, target uint64, at time.Time) error {
opt := litestream.NewRestoreOptions()
opt.OutputPath = out