carlos / platform Public

lease: verify restores keep the storage's error, mark check failures

Final fix wave (#898), lease half of Fable P2-5 and Astra P2-3.

- ErrCheckFailed marks a copy that restored and failed CheckDB, keeping
  the check's message: the only restore outcome that is damage on its
  own.
- A pinned verify restore reads through a readRecorder and a restore
  error carries the last open/read error the replica gave. litestream
  loses it otherwise: ltx v0.5.1's Compactor drops an input's header
  read error and the restore fails as "decode header: EOF", the words a
  truncated file gives. A vanished object now reaches the drill as
  os.ErrNotExist and a dropped connection as its own error.
- VerifyClientAt: VerifyReplicaAt over a caller's replica client, so the
  drill's tests run the real downloader.
- Tests: unavailable target (Task 3's deferred case), vanished object,
  storage error kept, check failure marked, VerifyClientAt.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev c6ce7af3d90da986aac2eb05131aaf134492560d parent f049300
2 files changed, +220 −3
  • internal/lease/check.go +104 −3
  • internal/lease/check_test.go +116 −0
diff --git a/internal/lease/check.go b/internal/lease/check.go
index 0cf5e1218..9b24b0d0f 100644
--- a/internal/lease/check.go
+++ b/internal/lease/check.go
@@ -9,6 +9,7 @@ import (
"io"
"os"
"path/filepath"
+ "sync"
"github.com/benbjohnson/litestream"
"github.com/superfly/ltx"
@@ -23,7 +24,7 @@ var restoreForVerify = func(ctx context.Context, out, bucket, prefix, region str
if err != nil {
return false, err
}
- return restoreFrom(ctx, client, out, txid)
+ return restoreRecorded(ctx, client, out, txid)
}
// verifyReplicaClient is the replica client a verify restore reads, behind
@@ -38,6 +39,73 @@ var verifyReplicaClient = func(ctx context.Context, bucket, prefix, region strin
return newReplicaClient(bucket, prefix, region)
}
+// restoreRecorded is restoreFrom for a verify restore, which must tell the
+// replica's storage failing from the replica's bytes failing: a pinned
+// restore (txid not zero) reads through a readRecorder, and a restore error
+// carries the last error the replica gave an open or a read as well,
+// wrapped, so errors.Is and errors.As reach it. litestream can lose that
+// error on its own: ltx's Compactor drops the error of an input whose
+// header it cannot read (ltx v0.5.1, Compactor.Compact returns nil), and
+// the restore then fails as "decode header: EOF", the same words a
+// truncated file gives. An unpinned restore is not wrapped: it may take
+// litestream's v0.3 path, which needs the client's own type.
+func restoreRecorded(ctx context.Context, client litestream.ReplicaClient, out string, txid ltx.TXID) (bool, error) {
+ if txid == 0 {
+ return restoreFrom(ctx, client, out, txid)
+ }
+ rec := &readRecorder{ReplicaClient: client}
+ ok, err := restoreFrom(ctx, rec, out, txid)
+ if err != nil {
+ if last := rec.last(); last != nil && !errors.Is(err, last) {
+ err = fmt.Errorf("%w (the replica's last read error: %w)", err, last)
+ }
+ }
+ return ok, err
+}
+
+// readRecorder is a replica client that remembers the last error an open
+// or a read of an LTX file returned (io.EOF is a read's normal end, not an
+// error).
+type readRecorder struct {
+ litestream.ReplicaClient
+ mu sync.Mutex
+ err error
+}
+
+func (r *readRecorder) OpenLTXFile(ctx context.Context, level int, minTXID, maxTXID ltx.TXID, offset, size int64) (io.ReadCloser, error) {
+ rc, err := r.ReplicaClient.OpenLTXFile(ctx, level, minTXID, maxTXID, offset, size)
+ if err != nil {
+ r.note(err)
+ return nil, err
+ }
+ return &recordedRead{ReadCloser: rc, r: r}, nil
+}
+
+func (r *readRecorder) note(err error) {
+ r.mu.Lock()
+ r.err = err
+ r.mu.Unlock()
+}
+
+func (r *readRecorder) last() error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return r.err
+}
+
+type recordedRead struct {
+ io.ReadCloser
+ r *readRecorder
+}
+
+func (rr *recordedRead) Read(p []byte) (int, error) {
+ n, err := rr.ReadCloser.Read(p)
+ if err != nil && err != io.EOF {
+ rr.r.note(err)
+ }
+ return n, err
+}
+
// restoreFrom restores client's replica into out through transaction txid,
// with litestream's own restore (RestoreOptions.TXID); zero is the newest
// copy. With txid zero, a replica with nothing to restore is restored=false
@@ -146,7 +214,40 @@ func VerifyReplica(ctx context.Context, bucket, prefix, region, dir string) (uin
// (context.Canceled or context.DeadlineExceeded), not a restore or check
// failure, so a caller out of time can abandon the database instead of
// recording it as damaged.
+//
+// A copy that restored but failed CheckDB is an error wrapping
+// ErrCheckFailed, with the check's own message; any other error is from
+// the restore itself.
func VerifyReplicaAt(ctx context.Context, bucket, prefix, region, dir string, txid uint64) (uint32, error) {
+ return verifyRestored(ctx, prefix, dir, func(out string) (bool, error) {
+ return restoreForVerify(ctx, out, bucket, prefix, region, ltx.TXID(txid))
+ })
+}
+
+// VerifyClientAt is VerifyReplicaAt over a replica client the caller has
+// built (prefix names the copy in dir only): the same pinned restore,
+// check, change counter and sweep.
+func VerifyClientAt(ctx context.Context, client litestream.ReplicaClient, prefix, dir string, txid uint64) (uint32, error) {
+ return verifyRestored(ctx, prefix, dir, func(out string) (bool, error) {
+ return restoreRecorded(ctx, client, out, ltx.TXID(txid))
+ })
+}
+
+// ErrCheckFailed marks a VerifyReplicaAt error from a copy that restored
+// completely and then failed CheckDB: evidence the replica is damaged,
+// where a restore error may be the storage's.
+var ErrCheckFailed = errors.New("lease: the restored copy failed its check")
+
+// checkError is a CheckDB failure carrying ErrCheckFailed and keeping the
+// check's own message.
+type checkError struct{ err error }
+
+func (e checkError) Error() string { return e.err.Error() }
+func (e checkError) Unwrap() []error { return []error{ErrCheckFailed, e.err} }
+
+// verifyRestored is VerifyReplicaAt's body: restore writes the copy at the
+// path it is given.
+func verifyRestored(ctx context.Context, prefix, dir string, restore func(out string) (bool, error)) (uint32, error) {
out := filepath.Join(dir, "verify-"+filepath.Base(prefix)+".db")
// A retry must not trip over a previous attempt's file: litestream refuses
// to restore over an existing output path.
@@ -164,7 +265,7 @@ func VerifyReplicaAt(ctx context.Context, bucket, prefix, region, dir string, tx
_ = os.Remove(out + "-shm")
}()
- restored, err := restoreForVerify(ctx, out, bucket, prefix, region, ltx.TXID(txid))
+ restored, err := restore(out)
if err != nil {
// A download cut off by ctx surfaces from litestream as whatever
// its decoder made of the short stream ("decode header: EOF");
@@ -181,7 +282,7 @@ func VerifyReplicaAt(ctx context.Context, bucket, prefix, region, dir string, tx
if cerr := ctx.Err(); cerr != nil {
return 0, fmt.Errorf("check stopped: %w", cerr)
}
- return 0, err
+ return 0, checkError{err}
}
// The counter is read BEFORE the deferred sweep removes the copy: it is
// what lets the caller ask the second question, whether this replica is
diff --git a/internal/lease/check_test.go b/internal/lease/check_test.go
index 3e4dcee7b..9c5499165 100644
--- a/internal/lease/check_test.go
+++ b/internal/lease/check_test.go
@@ -6,9 +6,12 @@ import (
"errors"
"fmt"
"io"
+ "net"
"os"
"path/filepath"
+ "strings"
"sync"
+ "syscall"
"testing"
"github.com/benbjohnson/litestream"
@@ -483,3 +486,116 @@ func TestVerifyReplicaAtHonoursCancel(t *testing.T) {
assertEmptyDir(t, dir)
})
}
+
+// A pinned target the replica cannot reach is litestream's
+// ErrTxNotAvailable, which the drill replans on, and never ErrNoReplica,
+// which it would read as nothing replicated yet; nothing is left in dir
+// (Task 3's deferred case).
+func TestVerifyReplicaAtUnavailableTarget(t *testing.T) {
+ replica, txids := replicatedBatches(t)
+ useFileReplica(t, lsfile.NewReplicaClient(replica))
+ dir := t.TempDir()
+ _, err := VerifyReplicaAt(context.Background(), "bucket", "hib/x.example.com", "", dir, uint64(txids[2])+100)
+ if !errors.Is(err, litestream.ErrTxNotAvailable) || errors.Is(err, ErrNoReplica) || errors.Is(err, ErrCheckFailed) {
+ t.Fatalf("VerifyReplicaAt past the replica's end = %v, want ErrTxNotAvailable alone", err)
+ }
+ assertEmptyDir(t, dir)
+}
+
+// vanishingClient deletes an LTX file from the file replica the moment the
+// restore opens it, after the listing named it: what compaction does to a
+// planned object between the plan and the download.
+type vanishingClient struct {
+ litestream.ReplicaClient
+ dir string
+}
+
+func (c *vanishingClient) OpenLTXFile(ctx context.Context, level int, minTXID, maxTXID ltx.TXID, offset, size int64) (io.ReadCloser, error) {
+ path := filepath.Join(c.dir, "ltx", fmt.Sprint(level), ltx.FormatFilename(minTXID, maxTXID))
+ if err := os.Remove(path); err != nil {
+ return nil, fmt.Errorf("fixture: %w", err)
+ }
+ return c.ReplicaClient.OpenLTXFile(ctx, level, minTXID, maxTXID, offset, size)
+}
+
+// A planned object that disappears before the download reads it reaches
+// the caller as os.ErrNotExist through litestream's real downloader, so the
+// drill can replan instead of calling it damage; it is not a check failure,
+// and nothing is left in dir (Astra P2-3).
+func TestVerifyReplicaAtMissingObject(t *testing.T) {
+ replica, txids := replicatedBatches(t)
+ useFileReplica(t, &vanishingClient{ReplicaClient: lsfile.NewReplicaClient(replica), dir: replica})
+ dir := t.TempDir()
+ _, err := VerifyReplicaAt(context.Background(), "bucket", "hib/x.example.com", "", dir, uint64(txids[1]))
+ if !errors.Is(err, os.ErrNotExist) || errors.Is(err, ErrCheckFailed) || errors.Is(err, ErrNoReplica) {
+ t.Fatalf("VerifyReplicaAt with a vanished object = %v, want os.ErrNotExist", err)
+ }
+ if strings.Contains(err.Error(), "fixture:") {
+ t.Fatalf("the fixture could not remove the object: %v", err)
+ }
+ assertEmptyDir(t, dir)
+}
+
+// brokenClient fails every open of an LTX file with err, as a storage
+// connection that has gone does.
+type brokenClient struct {
+ litestream.ReplicaClient
+ err error
+}
+
+func (c *brokenClient) OpenLTXFile(context.Context, int, ltx.TXID, ltx.TXID, int64, int64) (io.ReadCloser, error) {
+ return nil, c.err
+}
+
+// litestream turns a storage failure while reading the inputs' headers into
+// "decode header: EOF" (ltx's Compactor drops the input's error); the
+// verify restore puts the storage's own error back in the chain, so the
+// drill can tell it from a damaged replica.
+func TestVerifyReplicaAtKeepsTheStorageError(t *testing.T) {
+ replica, txids := replicatedBatches(t)
+ reset := &net.OpError{Op: "read", Net: "tcp", Err: syscall.ECONNRESET}
+ useFileReplica(t, &brokenClient{ReplicaClient: lsfile.NewReplicaClient(replica), err: reset})
+ dir := t.TempDir()
+ _, err := VerifyReplicaAt(context.Background(), "bucket", "hib/x.example.com", "", dir, uint64(txids[1]))
+ var op *net.OpError
+ if !errors.As(err, &op) || errors.Is(err, ErrCheckFailed) {
+ t.Fatalf("VerifyReplicaAt over a broken connection = %v, want the connection's error in the chain", err)
+ }
+ assertEmptyDir(t, dir)
+}
+
+// A restore that completes into a copy that fails CheckDB is marked
+// ErrCheckFailed, its message unchanged; a restore that fails before the
+// check is not. Only the first is evidence of damage.
+func TestVerifyReplicaAtMarksCheckFailures(t *testing.T) {
+ prev := restoreForVerify
+ t.Cleanup(func() { restoreForVerify = prev })
+
+ restoreForVerify = func(_ context.Context, out, _, _, _ string, _ ltx.TXID) (bool, error) {
+ return true, os.WriteFile(out, []byte("not a database"), 0o600)
+ }
+ _, err := VerifyReplicaAt(context.Background(), "bucket", "hib/x.example.com", "", t.TempDir(), 7)
+ if !errors.Is(err, ErrCheckFailed) || strings.Contains(err.Error(), ErrCheckFailed.Error()) {
+ t.Fatalf("a restored copy that fails its check = %v, want ErrCheckFailed with the check's own message", err)
+ }
+
+ restoreForVerify = func(context.Context, string, string, string, string, ltx.TXID) (bool, error) {
+ return false, errors.New("decode database: invalid LTX file")
+ }
+ if _, err := VerifyReplicaAt(context.Background(), "bucket", "hib/x.example.com", "", t.TempDir(), 7); err == nil || errors.Is(err, ErrCheckFailed) {
+ t.Fatalf("a failed restore = %v, want an error that is not ErrCheckFailed", err)
+ }
+}
+
+// VerifyClientAt is VerifyReplicaAt over a replica client the caller
+// built: the same pinned restore, check, counter and sweep.
+func TestVerifyClientAt(t *testing.T) {
+ replica, txids := replicatedBatches(t)
+ want, _ := restoredHeader(t, replica, txids[1])
+ dir := t.TempDir()
+ got, err := VerifyClientAt(context.Background(), lsfile.NewReplicaClient(replica), "hib/x.example.com", dir, uint64(txids[1]))
+ if err != nil || got != want {
+ t.Fatalf("VerifyClientAt = %d, %v; want %d", got, err, want)
+ }
+ assertEmptyDir(t, dir)
+}