carlos / platform Public

drill: restore read-only through the planner's listing (#898 R2)

The nightly drill's pinned restore built a fresh read-write litestream
S3 client and listed every level again. It now restores through the
listing the planner already holds (dbdoor.PlanListed), handed to
lease.VerifyReaderAt: the drill holds only a list/open reader, and
litestream gets a client whose writes have no body but ErrReadOnly.

Each level is listed once per plan attempt, so a host costs 10 LISTs
instead of 20. Pinned TXID, CheckDBContext, damage marking, cleanup and
the os.ErrNotExist replan are unchanged; the replan and corruption tests
now run through the production restore.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 4a9f46b41d21df510749307d97cbbe402ce4e7e0 parent 178dcfe
7 files changed, +293 −19
  • internal/dbdoor/plan_from.go +31 −0
  • internal/dbdoor/plan_from_test.go +43 −0
  • internal/lease/check.go +49 −0
  • internal/lease/check_test.go +79 −0
  • internal/ops/hibernate_verify.go +15 −7
  • internal/ops/hibernate_verify_restore_test.go +72 −8
  • internal/ops/hibernate_verify_test.go +4 −4

Intent

Human

<paseo-system version="1" kind="agent-message" source-agent-id="8a3d302a-eac7-407c-b61c-f5ccc66b5544" message-id="a11a3172-9ce0-4828-8bd8-6d783ae3c7f9"> Agent manager 8a3d302: thank you, clear. Agreed: R1 + R2 on one fix branch (Astra review, merge on green); flagship rolls only a release that carries it, after your dev check. R3 goes on the flagship brief (annie free disk vs the largest nightly restore, before the roll). R4: note it; per-region drill hour can be a follow-up unless barbara&apos;s run shows load. </paseo-system>

Human

<task-notification> <task-id>a498d950348c587ef</task-id> <tool-use-id>toolu_01QELkisk8s1qSKTx9G1AYtH</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ab362fc0-f177-4a7f-a92e-4a29ea210aad/tasks/a498d950348c587ef.output</output-file> <status>completed</status> <summary>Agent "Write slice 2b plan (test line + operator view)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>The plan is written to /home/paulca/amadan.net/carlos/platform/.claude/worktrees/member-backups/docs/superpowers/plans/2026-11-12-member-backups-slice2b.md and is not committed. It has 9 tasks: 0 is the UX pass, 1 the copy review, 2 to 7 the build, 8 the census and close. Tasks 4 and 5 change root-binary code (`internal/backupswords` and the root CLI's test row), so the census overlay is `member-backups-2b`. Nothing on boxes changes. Open decisions, recorded in the plan as B-1 to B-4 for the reviewer to challenge: - **B-1:** `copy_since` is worked out from the record (`LastMove.At`), not stored and stamped by the console. Box-side code closes moves, so a console stamp can't see them. A move changes the region, and a restore or recreate is a new incarnation, so both already hide old verdicts. A test fails when new code writes those record fields. - **B-2:** The JSON door uses `apiSystemRoller` (ops-account owners and `CARLOS_SYSTEM_OPERATORS`). The spec's `apiSystemOperator` is the storage-scanning operators' gate (`CARLOS_STORE_OPERATORS`). - **B-3 and B-4:** Owners only ever see passed or failed. `last_test` gains an `operators_alerted` field so the CLI can print "We've been alerted" like the page. What I found unbuildable against what 2a built: - **Not reached:** 2a's record has no count of hosts the budget didn't reach, so the operator view estimates it from each verdict's time. - **Inert drill:** no box reports whether its drill is inert, so the view lists boxes with sleeping instances whose record is missing or over 36 hours old. - **Roster:** nothing defines one, so the plan uses the boxes' status files. - **Off-account copy and exports:** `control/offsite.json` has no writer or format, so that row always reads "No record". The exports row waits for 3b. - **Reassigned hosts:** the console can keep the old box's last verdict in memory. It can't fix the new box's 7-day alert clock restarting. - **Request budget:** §9 doesn't count the operator view's reads or the 6-hourly list of box status files.</result> <usage><subagent_tokens>265592</subagent_tokens><tool_uses>89</tool_uses><duration_ms>876550</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>ad34c2ecab73f571d</task-id> <tool-use-id>toolu_01HyxCKLpaVUJPcCxAPrFS2V</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ab362fc0-f177-4a7f-a92e-4a29ea210aad/tasks/ad34c2ecab73f571d.output</output-file> <status>completed</status> <summary>Agent "Write slice 1b plan (download)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>I've written the slice 1b plan; it isn't committed. It has 14 tasks (Task 0 to Task 13), and as §2b stands the slice can't serve any instance on today's deployments (first bullet below). **Plan:** `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/member-backups/docs/superpowers/plans/2026-11-12-member-backups-slice1b.md` **Unbuildable against the code:** - **Home region.** The only console runs in the home region, where `CARLOS_REGION` is empty and home records keep `region: ""`. `dbreads` can't address home: requests and queue keys need a region code (`ids.go:38`, `envelope.go:49`), and `dbReadsSettings` won't start on a box without one (`internal/host/dbreads.go:52`). The plan's fix is Task 3, an export-only home queue scope (`_home`) that starts the worker on home boxes for exports only. That is new reach for the root-signed protocol, so it needs Paul's yes and Astra's review. - **Slice 2a has the same gap (side finding).** The armed `hibernate-verify` exits "NOT RUN" on every home box when the region is empty (`internal/ops/ops.go:478`), so home instances likely get no restore tests. **Open decisions:** - **D-E, the promised email.** The approved `backups.preparing.note` says "We'll email you when it's ready", but §2b specifies no email and no pass that runs after the tab closes. Task 11 adds a 30-second pass plus ready and failed emails, which is new copy. The alternative is to re-approve the note without that sentence and drop Task 11. - **Decisions I took that Astra may overturn:** - The agent, not the worker, writes `manifest.json`. - "Rule verified" means the console reads the bucket's lifecycle back at start, which needs a new `s3:GetLifecycleConfiguration` grant on the data bucket. - It's unconfirmed whether MinIO's lifecycle rules support aborting incomplete uploads. The plan accepts the store's own cleanup on S3-compatible stores. - **The MinIO setup contract doesn't exist as a document.** Task 1 writes it into `infra/modules/README.md`, and Task 12 exercises it in `.amadan/ci.d/30-minio-contract`.</result> <usage><subagent_tokens>303586</subagent_tokens><tool_uses>88</tool_uses><duration_ms>1001485</duration_ms></usage> </task-notification>

diff --git a/internal/dbdoor/plan_from.go b/internal/dbdoor/plan_from.go
index 0e3587739..92f1df000 100644
--- a/internal/dbdoor/plan_from.go
+++ b/internal/dbdoor/plan_from.go
@@ -158,6 +158,37 @@ func PlanFrom(ctx context.Context, rd ReplicaReader, at time.Time) (RestorePlan,
return planFrom(ctx, &listing{rd: rd, asOf: !at.IsZero(), maxFiles: -1}, at)
}
+// PlanListed plans the newest copy exactly as PlanFrom(ctx, rd,
+// time.Time{}) does, and returns with it the listing it planned from as a
+// reader (the nightly drill's restore, member backups 2a R2). Its LTXFiles
+// answers each level from what the plan listed (a level the plan did not
+// list is listed once, then kept) and its OpenLTXFile reads rd, so a
+// restore pinned to the plan's TXID through it lists nothing again and
+// reads the same snapshot of the replica the plan did. A file compacted
+// away since still answers its open with rd's error (os.ErrNotExist from
+// the S3 client), which is the caller's cue to plan again. The reader has
+// only those two methods: no write is reachable through it, not even by
+// type assertion.
+func PlanListed(ctx context.Context, rd ReplicaReader) (RestorePlan, ReplicaReader, error) {
+ l := &listing{rd: rd, maxFiles: -1}
+ plan, err := planFrom(ctx, l, time.Time{})
+ if err != nil {
+ return RestorePlan{}, nil, err
+ }
+ return plan, listedReader{l: l}, nil
+}
+
+// listedReader is a listing's read half and nothing else.
+type listedReader struct{ l *listing }
+
+func (r listedReader) LTXFiles(ctx context.Context, level int, seek ltx.TXID, useMetadata bool) (ltx.FileIterator, error) {
+ return r.l.LTXFiles(ctx, level, seek, useMetadata)
+}
+
+func (r listedReader) OpenLTXFile(ctx context.Context, level int, minTXID, maxTXID ltx.TXID, offset, size int64) (io.ReadCloser, error) {
+ return r.l.OpenLTXFile(ctx, level, minTXID, maxTXID, offset, size)
+}
+
// planFrom is PlanFrom over a listing the caller made, so the caller can
// read the same listing afterwards.
func planFrom(ctx context.Context, l *listing, at time.Time) (RestorePlan, error) {
diff --git a/internal/dbdoor/plan_from_test.go b/internal/dbdoor/plan_from_test.go
index 37ccd126d..b696b8c91 100644
--- a/internal/dbdoor/plan_from_test.go
+++ b/internal/dbdoor/plan_from_test.go
@@ -16,6 +16,7 @@ import (
"github.com/superfly/ltx"
"github.com/carlosframework/platform/internal/dbdoor/dbdoortest"
+ "github.com/carlosframework/platform/internal/lease"
)
// metaSpy records every useMetadata the listing passes down: the box must
@@ -410,3 +411,45 @@ func TestPositionAndHistoryFileCap(t *testing.T) {
t.Fatalf("PositionAndHistory over %d files capped at %d = %v, known %v; want ErrTooManyFiles", n, n-1, err, known)
}
}
+
+// PlanListed plans what PlanFrom plans and hands back the listing it
+// planned from as a reader: a restore pinned to the plan's TXID through it
+// lists nothing again (each level once in all, member backups 2a R2), and
+// the reader has no method that writes, not even by type assertion.
+func TestPlanListedRestoresThroughItsListing(t *testing.T) {
+ t.Parallel()
+ dir := t.TempDir()
+ dbdoortest.Replicate(t, dir, 3)
+ want, err := PlanFrom(context.Background(), lsfile.NewReplicaClient(dir), time.Time{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ rd := &countingLists{ReplicaReader: lsfile.NewReplicaClient(dir), lists: map[int]int{}}
+ plan, listed, err := PlanListed(context.Background(), rd)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(plan, want) {
+ t.Fatalf("PlanListed planned %+v, PlanFrom %+v", plan, want)
+ }
+ if _, ok := listed.(litestream.ReplicaClient); ok {
+ t.Fatal("the listed reader is a full replica client: its holder can reach write methods")
+ }
+ if _, err := lease.VerifyReaderAt(context.Background(), listed, "hib/x.example.com", t.TempDir(), plan.TXID); err != nil {
+ t.Fatalf("restore through the listing: %v", err)
+ }
+ for level := 0; level <= litestream.SnapshotLevel; level++ {
+ if n := rd.lists[level]; n != 1 {
+ t.Errorf("level %d listed %d times by the plan and the restore, want once", level, n)
+ }
+ }
+}
+
+// An empty replica is ErrNothingReplicated, with no reader.
+func TestPlanListedAnEmptyReplica(t *testing.T) {
+ t.Parallel()
+ _, listed, err := PlanListed(context.Background(), lsfile.NewReplicaClient(t.TempDir()))
+ if !errors.Is(err, ErrNothingReplicated) || listed != nil {
+ t.Fatalf("PlanListed on an empty replica = %v, %v; want ErrNothingReplicated and no reader", listed, err)
+ }
+}
diff --git a/internal/lease/check.go b/internal/lease/check.go
index 79a9340a4..4d9ca8bb1 100644
--- a/internal/lease/check.go
+++ b/internal/lease/check.go
@@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"io"
+ "log/slog"
"os"
"path/filepath"
"sync"
@@ -259,6 +260,54 @@ func VerifyClientAt(ctx context.Context, client litestream.ReplicaClient, prefix
})
}
+// ReplicaReader is the read half of a replica client: list a level and
+// open a file, nothing that writes. dbdoor.ReplicaReader is the same
+// interface; a planner's listing is one.
+type ReplicaReader interface {
+ LTXFiles(ctx context.Context, level int, seek ltx.TXID, useMetadata bool) (ltx.FileIterator, error)
+ OpenLTXFile(ctx context.Context, level int, minTXID, maxTXID ltx.TXID, offset, size int64) (io.ReadCloser, error)
+}
+
+// VerifyReaderAt is VerifyClientAt over a reader that can only list and
+// open (member backups 2a, R2): the nightly drill restores through the
+// listing it planned from, so it lists each level once and holds nothing
+// that can write. litestream's restore needs a full client, so it is given
+// readOnlyClient, whose three writing methods have no body but ErrReadOnly,
+// whatever rd is underneath.
+func VerifyReaderAt(ctx context.Context, rd ReplicaReader, prefix, dir string, txid uint64) (uint32, error) {
+ return VerifyClientAt(ctx, readOnlyClient{rd: rd}, prefix, dir, txid)
+}
+
+// ErrReadOnly is every write a verify restore's client is asked for.
+var ErrReadOnly = errors.New("lease: this replica client is read-only; a verify restore never writes a replica")
+
+// readOnlyClient is a litestream.ReplicaClient made of a ReplicaReader. It
+// must never implement litestream.ReplicaClientV3, or Restore would take
+// the v0.3 path.
+type readOnlyClient struct{ rd ReplicaReader }
+
+func (c readOnlyClient) Type() string { return "carlos-verify-read-only" }
+func (c readOnlyClient) Init(context.Context) error { return nil }
+func (c readOnlyClient) SetLogger(*slog.Logger) {}
+
+func (c readOnlyClient) LTXFiles(ctx context.Context, level int, seek ltx.TXID, useMetadata bool) (ltx.FileIterator, error) {
+ return c.rd.LTXFiles(ctx, level, seek, useMetadata)
+}
+
+func (c readOnlyClient) OpenLTXFile(ctx context.Context, level int, minTXID, maxTXID ltx.TXID, offset, size int64) (io.ReadCloser, error) {
+ return c.rd.OpenLTXFile(ctx, level, minTXID, maxTXID, offset, size)
+}
+
+func (c readOnlyClient) WriteLTXFile(context.Context, int, ltx.TXID, ltx.TXID, io.Reader) (*ltx.FileInfo, error) {
+ return nil, ErrReadOnly
+}
+
+func (c readOnlyClient) DeleteLTXFiles(context.Context, []*ltx.FileInfo) error { return ErrReadOnly }
+
+func (c readOnlyClient) DeleteAll(context.Context) error { return ErrReadOnly }
+
+var _ litestream.ReplicaClient = readOnlyClient{}
+
// ErrCheckFailed marks a CheckDB error (and so a VerifyReplicaAt error)
// that proves the copy damaged: integrity_check answered something other
// than "ok", SQLite itself reported the file corrupt or not a database, or
diff --git a/internal/lease/check_test.go b/internal/lease/check_test.go
index 6d9ae2791..22715bf2f 100644
--- a/internal/lease/check_test.go
+++ b/internal/lease/check_test.go
@@ -678,3 +678,82 @@ func TestVerifyClientAt(t *testing.T) {
}
assertEmptyDir(t, dir)
}
+
+// writeTrap is a full replica client that fails the test on any write: what
+// a reader handed to VerifyReaderAt may really be underneath.
+type writeTrap struct {
+ *lsfile.ReplicaClient
+ t *testing.T
+}
+
+func (w writeTrap) WriteLTXFile(context.Context, int, ltx.TXID, ltx.TXID, io.Reader) (*ltx.FileInfo, error) {
+ w.t.Error("a verify restore wrote an LTX file")
+ return nil, errors.New("trap")
+}
+
+func (w writeTrap) DeleteLTXFiles(context.Context, []*ltx.FileInfo) error {
+ w.t.Error("a verify restore deleted LTX files")
+ return errors.New("trap")
+}
+
+func (w writeTrap) DeleteAll(context.Context) error {
+ w.t.Error("a verify restore deleted the replica")
+ return errors.New("trap")
+}
+
+// listOpen is only the read half of a replica client.
+type listOpen struct{ rd ReplicaReader }
+
+func (l listOpen) LTXFiles(ctx context.Context, level int, seek ltx.TXID, useMetadata bool) (ltx.FileIterator, error) {
+ return l.rd.LTXFiles(ctx, level, seek, useMetadata)
+}
+
+func (l listOpen) OpenLTXFile(ctx context.Context, level int, minTXID, maxTXID ltx.TXID, offset, size int64) (io.ReadCloser, error) {
+ return l.rd.OpenLTXFile(ctx, level, minTXID, maxTXID, offset, size)
+}
+
+// VerifyReaderAt is VerifyClientAt over a reader that can only list and
+// open (member backups 2a, R2): the same pinned restore, check, counter and
+// sweep, and a client handed to litestream whose writes have no body but
+// ErrReadOnly, whatever the reader is underneath.
+func TestVerifyReaderAt(t *testing.T) {
+ replica, txids := replicatedBatches(t)
+ want, _ := restoredHeader(t, replica, txids[1])
+ trap := writeTrap{ReplicaClient: lsfile.NewReplicaClient(replica), t: t}
+ dir := t.TempDir()
+ got, err := VerifyReaderAt(context.Background(), listOpen{rd: trap}, "hib/x.example.com", dir, uint64(txids[1]))
+ if err != nil || got != want {
+ t.Fatalf("VerifyReaderAt = %d, %v; want %d", got, err, want)
+ }
+ assertEmptyDir(t, dir)
+
+ // The client litestream is given refuses every write, even over a
+ // reader whose dynamic type could write, and is never a v0.3 client.
+ c := readOnlyClient{rd: trap}
+ if _, err := c.WriteLTXFile(context.Background(), 0, 1, 1, strings.NewReader("x")); !errors.Is(err, ErrReadOnly) {
+ t.Fatalf("WriteLTXFile = %v, want ErrReadOnly", err)
+ }
+ if err := c.DeleteLTXFiles(context.Background(), nil); !errors.Is(err, ErrReadOnly) {
+ t.Fatalf("DeleteLTXFiles = %v, want ErrReadOnly", err)
+ }
+ if err := c.DeleteAll(context.Background()); !errors.Is(err, ErrReadOnly) {
+ t.Fatalf("DeleteAll = %v, want ErrReadOnly", err)
+ }
+ if _, ok := any(c).(litestream.ReplicaClientV3); ok {
+ t.Fatal("the read-only client is a v0.3 client; Restore would take the v0.3 path")
+ }
+}
+
+// A planned object gone before the download reads it still reaches the
+// caller as os.ErrNotExist through the read-only client, so the drill
+// replans.
+func TestVerifyReaderAtMissingObject(t *testing.T) {
+ replica, txids := replicatedBatches(t)
+ dir := t.TempDir()
+ rd := &vanishingClient{ReplicaClient: lsfile.NewReplicaClient(replica), dir: replica}
+ _, err := VerifyReaderAt(context.Background(), rd, "hib/x.example.com", dir, uint64(txids[1]))
+ if !errors.Is(err, os.ErrNotExist) || errors.Is(err, ErrCheckFailed) || errors.Is(err, ErrNoReplica) {
+ t.Fatalf("VerifyReaderAt with a vanished object = %v, want os.ErrNotExist", err)
+ }
+ assertEmptyDir(t, dir)
+}
diff --git a/internal/ops/hibernate_verify.go b/internal/ops/hibernate_verify.go
index e3b053137..b786f67ae 100644
--- a/internal/ops/hibernate_verify.go
+++ b/internal/ops/hibernate_verify.go
@@ -137,7 +137,10 @@ var (
openReplica = func(ctx context.Context, bucket, prefix, region string) (dbdoor.ReplicaReader, error) {
return lease.ReadReplicaClient(ctx, bucket, prefix, region)
}
- verifyAt = lease.VerifyReplicaAt
+ // verifyAt restores the planned position through the planner's own
+ // listing (member backups 2a, R2): it holds a reader that can only list
+ // and open, and lists nothing the plan did not.
+ verifyAt = lease.VerifyReaderAt
lockState = lease.LockState
localFreshness = hibernateFreshness
// publishTicker is the run's publication clock: ticks every d, and a
@@ -453,7 +456,8 @@ func bracketReason(code string) string {
return ReasonRecordChanged
}
-// restore plans the newest copy and restores exactly the planned position.
+// restore plans the newest copy and restores exactly the planned position,
+// through the plan's own listing (R2), so the restore lists nothing again.
// Compaction between the two can make that position unrestorable, or
// remove an object the plan named before its header or contents are read
// (os.ErrNotExist, as the S3 client reports a missing key); that is not a
@@ -471,7 +475,7 @@ func bracketReason(code string) string {
func (d Drill) restore(ctx context.Context, prefix, dir string) restoreResult {
var last restoreResult
for attempt := 0; attempt < 2; attempt++ {
- plan, err := d.plan(ctx, prefix)
+ plan, listed, err := d.plan(ctx, prefix)
switch {
case errors.Is(err, dbdoor.ErrNothingReplicated):
return restoreResult{kind: restoreNothing, err: err}
@@ -481,7 +485,7 @@ func (d Drill) restore(ctx context.Context, prefix, dir string) restoreResult {
case err != nil:
return restoreResult{kind: restoreUnavailable, err: fmt.Errorf("plan: %w", err)}
}
- counter, err := verifyAt(ctx, d.Cfg.Bucket, prefix, d.Cfg.Region, dir, plan.TXID)
+ counter, err := verifyAt(ctx, listed, prefix, dir, plan.TXID)
switch {
case err == nil:
return restoreResult{kind: restoreClean, plan: plan, counter: counter}
@@ -536,12 +540,16 @@ func storageError(err error) bool {
errors.As(err, &perr) || errors.As(err, &lerr) || errors.As(err, &serr) || errors.As(err, &errno)
}
-func (d Drill) plan(ctx context.Context, prefix string) (dbdoor.RestorePlan, error) {
+// plan plans the newest copy and returns the listing it planned from, the
+// only reader the restore is given: each level is listed once per attempt,
+// and a file compacted away since answers os.ErrNotExist, which plans
+// again.
+func (d Drill) plan(ctx context.Context, prefix string) (dbdoor.RestorePlan, dbdoor.ReplicaReader, error) {
rd, err := openReplica(ctx, d.Cfg.Bucket, prefix, d.Cfg.Region)
if err != nil {
- return dbdoor.RestorePlan{}, err
+ return dbdoor.RestorePlan{}, nil, err
}
- return dbdoor.PlanFrom(ctx, rd, time.Time{})
+ return dbdoor.PlanListed(ctx, rd)
}
// freshness judges whether a clean replica is still tracking its source,
diff --git a/internal/ops/hibernate_verify_restore_test.go b/internal/ops/hibernate_verify_restore_test.go
index 5f3a9d083..f93049d5b 100644
--- a/internal/ops/hibernate_verify_restore_test.go
+++ b/internal/ops/hibernate_verify_restore_test.go
@@ -121,8 +121,8 @@ func (c *missingClient) OpenLTXFile(ctx context.Context, level int, minTXID, max
// A planned object that disappears before its header or contents are read
// goes through the same bounded replan as an unreachable transaction
-// (Astra P2-3), through the real planner (dbdoor.PlanFrom) and the real
-// downloader and restore (lease.VerifyClientAt): a replan that finds the
+// (Astra P2-3), through the real planner (dbdoor.PlanListed) and the real
+// downloader and restore (lease.VerifyReaderAt): a replan that finds the
// history whole passes, and history still missing on the second plan is
// unverified, plan_moved, never a failure.
func TestVerifyHibernatingReplansAMissingObject(t *testing.T) {
@@ -152,9 +152,7 @@ func TestVerifyHibernatingReplansAMissingObject(t *testing.T) {
plans++
return client, nil
})
- swap(t, &verifyAt, func(ctx context.Context, _, prefix, _, dir string, txid uint64) (uint32, error) {
- return lease.VerifyClientAt(ctx, client, prefix, dir, txid)
- })
+ swap(t, &verifyAt, lease.VerifyReaderAt) // the production restore, over the planner's listing
v := fx.run(context.Background(), fx.drill(), fx.routes(host), nil)[host]
if v.Result != c.result || v.Reason != c.reason {
t.Fatalf("verdict %s/%s, want %s/%s (%+v)", v.Result, v.Reason, c.result, c.reason, v)
@@ -235,12 +233,78 @@ func TestVerifyHibernatingRealCorruptionFails(t *testing.T) {
swap(t, &openReplica, func(context.Context, string, string, string) (dbdoor.ReplicaReader, error) {
return client, nil
})
- swap(t, &verifyAt, func(ctx context.Context, _, prefix, _, dir string, txid uint64) (uint32, error) {
- return lease.VerifyClientAt(ctx, client, prefix, dir, txid)
- })
+ swap(t, &verifyAt, lease.VerifyReaderAt) // the production restore, over the planner's listing
v := fx.run(context.Background(), fx.drill(), fx.routes(host), nil)[host]
if v.Result != dbverify.ResultFailed || v.Reason != ReasonRestoreError || !strings.Contains(v.Detail, "integrity_check") {
t.Fatalf("verdict %+v, want failed/restore_error from integrity_check", v)
}
fx.scratchEmpty()
}
+
+// countingReader counts every listing of each level, per prefix, that a
+// drill makes through the reader openReplica hands it. Its dynamic type is
+// a full file replica client, which could write: the drill must not reach
+// that.
+type countingReader struct {
+ *lsfile.ReplicaClient
+ mu *sync.Mutex
+ lists map[string]map[int]int
+ prefix string
+ t *testing.T
+}
+
+func (c *countingReader) LTXFiles(ctx context.Context, level int, seek ltx.TXID, useMetadata bool) (ltx.FileIterator, error) {
+ c.mu.Lock()
+ if c.lists[c.prefix] == nil {
+ c.lists[c.prefix] = map[int]int{}
+ }
+ c.lists[c.prefix][level]++
+ c.mu.Unlock()
+ return c.ReplicaClient.LTXFiles(ctx, level, seek, useMetadata)
+}
+
+func (c *countingReader) WriteLTXFile(context.Context, int, ltx.TXID, ltx.TXID, io.Reader) (*ltx.FileInfo, error) {
+ c.t.Error("the drill wrote an LTX file")
+ return nil, errors.New("trap")
+}
+
+func (c *countingReader) DeleteLTXFiles(context.Context, []*ltx.FileInfo) error {
+ c.t.Error("the drill deleted LTX files")
+ return errors.New("trap")
+}
+
+func (c *countingReader) DeleteAll(context.Context) error {
+ c.t.Error("the drill deleted a replica")
+ return errors.New("trap")
+}
+
+// The production restore (verifyAt as shipped) reads through the planner's
+// own listing (member backups 2a, R2): each level of each host is listed
+// once per run, by the plan, and never again by the restore (10 LISTs a
+// host, not 20), and nothing the drill holds can write the replica.
+func TestVerifyHibernatingListsEachLevelOncePerHost(t *testing.T) {
+ hosts := []string{"a.example.com", "b.example.com"}
+ fx := newDrillFx(t, hosts...)
+ swap(t, &verifyAt, lease.VerifyReaderAt) // the production restore, not the fixture's stub
+ var mu sync.Mutex
+ lists := map[string]map[int]int{}
+ swap(t, &openReplica, func(_ context.Context, _, prefix, _ string) (dbdoor.ReplicaReader, error) {
+ return &countingReader{ReplicaClient: lsfile.NewReplicaClient(fx.replica), mu: &mu, lists: lists, prefix: prefix, t: t}, nil
+ })
+ got := fx.run(context.Background(), fx.drill(), fx.routes(hosts...), nil)
+ for _, h := range hosts {
+ if v := got[h]; !v.OK() {
+ t.Fatalf("%s: verdict %+v, want passed", h, v)
+ }
+ levels := lists[fx.prefix(h)]
+ for level := 0; level <= litestream.SnapshotLevel; level++ {
+ if n := levels[level]; n != 1 {
+ t.Errorf("%s: level %d listed %d times, want once", h, level, n)
+ }
+ }
+ if len(levels) != litestream.SnapshotLevel+1 {
+ t.Errorf("%s: listed levels %v, want 0 to %d", h, levels, litestream.SnapshotLevel)
+ }
+ }
+ fx.scratchEmpty()
+}
diff --git a/internal/ops/hibernate_verify_test.go b/internal/ops/hibernate_verify_test.go
index a93f85e60..db1dc9d71 100644
--- a/internal/ops/hibernate_verify_test.go
+++ b/internal/ops/hibernate_verify_test.go
@@ -254,7 +254,7 @@ func newDrillFx(t *testing.T, hosts ...string) *drillFx {
}
return &hookReader{ReplicaReader: lsfile.NewReplicaClient(dir), hook: hook}, nil
})
- swap(t, &verifyAt, func(context.Context, string, string, string, string, uint64) (uint32, error) {
+ swap(t, &verifyAt, func(context.Context, lease.ReplicaReader, string, string, uint64) (uint32, error) {
return 1, nil
})
swap(t, &lockState, func(context.Context, string, string, string) (bool, string, time.Time, error) {
@@ -270,9 +270,9 @@ func newDrillFx(t *testing.T, hosts ...string) *drillFx {
// stubVerify replaces the restore; it records the txid it was asked for.
func (fx *drillFx) stubVerify(fn func(ctx context.Context, prefix, dir string, txid uint64) (uint32, error)) {
- swap(fx.t, &verifyAt, func(ctx context.Context, bucket, prefix, region, dir string, txid uint64) (uint32, error) {
- if bucket != fx.cfg.Bucket || region != fx.cfg.Region {
- fx.t.Errorf("restore from %s/%s, want %s/%s", bucket, region, fx.cfg.Bucket, fx.cfg.Region)
+ swap(fx.t, &verifyAt, func(ctx context.Context, rd lease.ReplicaReader, prefix, dir string, txid uint64) (uint32, error) {
+ if rd == nil {
+ fx.t.Error("restore with no reader: it must read the planner's listing")
}
fx.mu.Lock()
fx.verifies = append(fx.verifies, txid)