carlos / platform Public

ltx: a truncated LTX file fails with ErrUnexpectedEOF, never panics

A file cut within the 8 bytes after its page block panicked
Decoder.Close (negative slice bound) inside litestream's restore
compactor goroutine, killing the process: the agent on a wake, the
console on a seed, the drill. A cut at a page boundary or inside page
data read as the end of the page block.

The decoder's input now goes through one reader (inputReader) that
turns io.EOF into io.ErrUnexpectedEOF: an LTX file ends only after its
trailer, which Close reads from the raw input. So only the decoded zero
page header ends a page block, and every early end of the header, page
headers, page data, page index, index size or trailer is
io.ErrUnexpectedEOF. Transport errors pass unchanged, and
readLZ4Trailer now wraps the read's error instead of dropping it.
Recorded as CARLOS patch (sqlite-integrity-safe) and in go.mod.

Tests: a cut at every byte of two real multi-page LTX files through the
Decoder and ltx.NewCompactor, alone and beside a whole input; a read
failing at every byte keeps its own error; the real pinned verify
restore of a replica whose newest file is cut returns an error (it
panicked before).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 5162ff6df90fa43757734479c6243a93291ecb00 parent 90112d4
3 files changed, +306 −10
  • go.mod +3 −1
  • internal/lease/ltxtruncate_test.go +253 −0
  • third_party/ltx/decoder.go +50 −9
diff --git a/go.mod b/go.mod
index 5b70f4361..8cfc1d148 100644
--- a/go.mod
+++ b/go.mod
@@ -100,7 +100,9 @@ require (
replace amadan.net/carlos/platform.git/launchctx => ./launchctx
// litestream 0.5.14 and ltx 0.5.1 with two upstream fixes backported
-// (#1443); see the CARLOS patch comments in third_party. The 0.5.18
+// (#1443), and one of ours in ltx's decoder (sqlite-integrity-safe): a
+// truncated LTX file fails with io.ErrUnexpectedEOF instead of panicking
+// or passing; see the CARLOS patch comments in third_party. The 0.5.18
// upgrade changes the LTX page format and waits for a readers-first
// rollout (branch litestream-0518-1443).
replace github.com/benbjohnson/litestream => ./third_party/litestream
diff --git a/internal/lease/ltxtruncate_test.go b/internal/lease/ltxtruncate_test.go
new file mode 100644
index 000000000..1fb967802
--- /dev/null
+++ b/internal/lease/ltxtruncate_test.go
@@ -0,0 +1,253 @@
+package lease
+
+import (
+ "bytes"
+ "context"
+ "database/sql"
+ "encoding/binary"
+ "errors"
+ "fmt"
+ "io"
+ "math/rand"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/benbjohnson/litestream"
+ lsfile "github.com/benbjohnson/litestream/file"
+ "github.com/superfly/ltx"
+ _ "modernc.org/sqlite"
+)
+
+// replicatedLTX is one LTX file a real litestream replication wrote.
+type replicatedLTX struct {
+ info *ltx.FileInfo
+ path string
+ data []byte
+ pages int
+}
+
+// multiPageReplica replicates a database through litestream to a file
+// replica in two syncs, each writing rows that do not compress away, and
+// returns the replica directory and its level-0 files in TXID order. Both
+// the snapshot and the file after it span several pages.
+func multiPageReplica(t *testing.T) (string, []replicatedLTX) {
+ t.Helper()
+ path := filepath.Join(t.TempDir(), "source.db")
+ writer, err := sql.Open("sqlite", path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { writer.Close() })
+ if _, err := writer.Exec(`PRAGMA journal_mode=WAL`); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := writer.Exec(`CREATE TABLE t (id INTEGER PRIMARY KEY, body TEXT)`); err != nil {
+ t.Fatal(err)
+ }
+ rng := rand.New(rand.NewSource(1443))
+ insert := func(n int) {
+ for i := 0; i < n; i++ {
+ body := make([]byte, 400)
+ rng.Read(body)
+ if _, err := writer.Exec(`INSERT INTO t (body) VALUES (?)`, fmt.Sprintf("%x", body)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ insert(12)
+
+ replica := t.TempDir()
+ client := lsfile.NewReplicaClient(replica)
+ db := litestream.NewDB(path)
+ db.MonitorInterval = 0
+ db.Replica = litestream.NewReplicaWithClient(db, client)
+ db.Replica.MonitorEnabled = false
+ if err := db.Open(); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = db.Close(context.Background()) })
+ if err := db.SyncAndWait(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ insert(12)
+ if err := db.SyncAndWait(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+
+ itr, err := client.LTXFiles(context.Background(), 0, 0, false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer itr.Close()
+ var files []replicatedLTX
+ for itr.Next() {
+ info := itr.Item()
+ p := client.LTXFilePath(0, info.MinTXID, info.MaxTXID)
+ data, err := os.ReadFile(p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ dec := ltx.NewDecoder(bytes.NewReader(data))
+ if err := dec.Verify(); err != nil {
+ t.Fatalf("fixture: %s does not verify whole: %v", p, err)
+ }
+ files = append(files, replicatedLTX{info: info, path: p, data: data, pages: dec.PageN()})
+ }
+ if err := itr.Close(); err != nil {
+ t.Fatal(err)
+ }
+ if len(files) < 2 {
+ t.Fatalf("fixture: %d level-0 files, want at least 2", len(files))
+ }
+ last, prev := files[len(files)-1], files[len(files)-2]
+ if prev.pages < 3 || last.pages < 3 {
+ t.Fatalf("fixture: the last two files hold %d and %d pages, want at least 3 each", prev.pages, last.pages)
+ }
+ return replica, files
+}
+
+// decodeAll runs one prefix through the Decoder as a restore of a single
+// file would (Verify: header, every page, page index, trailer), turning a
+// panic into a test failure that names the cut.
+func decodeAll(t *testing.T, what string, r io.Reader) (err error) {
+ t.Helper()
+ defer func() {
+ if p := recover(); p != nil {
+ t.Fatalf("%s: decoder panicked: %v", what, p)
+ }
+ }()
+ return ltx.NewDecoder(r).Verify()
+}
+
+// compactAll runs inputs through ltx.NewCompactor and Compact as
+// litestream's restore does (replica.go), turning a panic into a test
+// failure that names the cut.
+func compactAll(t *testing.T, what string, inputs ...io.Reader) (err error) {
+ t.Helper()
+ defer func() {
+ if p := recover(); p != nil {
+ t.Fatalf("%s: compactor panicked: %v", what, p)
+ }
+ }()
+ c, err := ltx.NewCompactor(io.Discard, inputs)
+ if err != nil {
+ return err
+ }
+ c.HeaderFlags = ltx.HeaderFlagNoChecksum
+ return c.Compact(context.Background())
+}
+
+// An LTX file cut anywhere is a file that ended early, and says so:
+// io.ErrUnexpectedEOF in the chain, from the decoder and from the
+// compactor, alone and beside a whole second input. It never panics (a
+// cut in the 8 bytes after the page block's terminator used to panic
+// Decoder.Close, inside the restore's compactor goroutine) and never
+// passes (a cut at a page boundary used to read as the end of the pages).
+func TestTruncatedLTXNeverPanicsOrPasses(t *testing.T) {
+ _, files := multiPageReplica(t)
+ prev, last := files[len(files)-2], files[len(files)-1]
+ if !ltx.IsContiguous(prev.info.MaxTXID, last.info.MinTXID, last.info.MaxTXID) {
+ t.Fatalf("fixture: %s then %s are not contiguous", prev.path, last.path)
+ }
+
+ // The whole files pass every path: the sweep below fails for the cut,
+ // not for the fixture.
+ if err := compactAll(t, "whole", bytes.NewReader(prev.data), bytes.NewReader(last.data)); err != nil {
+ t.Fatalf("compacting the whole files: %v", err)
+ }
+
+ for _, f := range []replicatedLTX{prev, last} {
+ for cut := 0; cut < len(f.data); cut++ {
+ short := f.data[:cut]
+ what := fmt.Sprintf("txids %s-%s cut to %d of %d bytes", f.info.MinTXID, f.info.MaxTXID, cut, len(f.data))
+ if err := decodeAll(t, what, bytes.NewReader(short)); !errors.Is(err, io.ErrUnexpectedEOF) {
+ t.Fatalf("%s: decode = %v, want io.ErrUnexpectedEOF", what, err)
+ }
+ if err := compactAll(t, what, bytes.NewReader(short)); !errors.Is(err, io.ErrUnexpectedEOF) {
+ t.Fatalf("%s: compact alone = %v, want io.ErrUnexpectedEOF", what, err)
+ }
+ inputs := []io.Reader{bytes.NewReader(prev.data), bytes.NewReader(short)}
+ if f.path == prev.path {
+ inputs = []io.Reader{bytes.NewReader(short), bytes.NewReader(last.data)}
+ }
+ if err := compactAll(t, what, inputs...); !errors.Is(err, io.ErrUnexpectedEOF) {
+ t.Fatalf("%s: compact beside a whole file = %v, want io.ErrUnexpectedEOF", what, err)
+ }
+ }
+ }
+}
+
+// failingReader gives n bytes of data and then err, never io.EOF: a
+// transfer that broke.
+type failingReader struct {
+ data []byte
+ err error
+}
+
+func (r *failingReader) Read(p []byte) (int, error) {
+ if len(r.data) == 0 {
+ return 0, r.err
+ }
+ n := copy(p, r.data)
+ r.data = r.data[n:]
+ return n, nil
+}
+
+// A read that fails partway through a file keeps its own error: the
+// decoder names an early end only when the input itself ended, so a broken
+// transfer is never mistaken for a short file, wherever it breaks.
+func TestLTXReadErrorIsKept(t *testing.T) {
+ _, files := multiPageReplica(t)
+ f := files[len(files)-1]
+ reset := errors.New("connection reset by peer")
+ for cut := 0; cut < len(f.data); cut++ {
+ what := fmt.Sprintf("read failing after %d of %d bytes", cut, len(f.data))
+ err := decodeAll(t, what, &failingReader{data: f.data[:cut], err: reset})
+ if !errors.Is(err, reset) || errors.Is(err, io.ErrUnexpectedEOF) {
+ t.Fatalf("%s: decode = %v, want the read's own error and no io.ErrUnexpectedEOF", what, err)
+ }
+ err = compactAll(t, what, &failingReader{data: f.data[:cut], err: reset})
+ if !errors.Is(err, reset) || errors.Is(err, io.ErrUnexpectedEOF) {
+ t.Fatalf("%s: compact = %v, want the read's own error and no io.ErrUnexpectedEOF", what, err)
+ }
+ }
+}
+
+// pageBlockEnd is the offset just past an LTX file's page block: the file
+// ends with the page index, its 8-byte size, and the trailer.
+func pageBlockEnd(t *testing.T, data []byte) int {
+ t.Helper()
+ tail := len(data) - ltx.TrailerSize - 8
+ if tail < ltx.HeaderSize {
+ t.Fatalf("fixture: %d bytes is too short to be an LTX file", len(data))
+ }
+ return tail - int(binary.BigEndian.Uint64(data[tail:tail+8]))
+}
+
+// A replica whose newest file was cut just past its page block (the cut
+// that panicked Decoder.Close inside litestream's compactor goroutine,
+// taking down the agent on a wake, the console on a seed, or the drill)
+// fails the real pinned verify restore with an error naming the early
+// end, and leaves nothing behind.
+func TestTruncatedReplicaFileRestoreFailsWithoutPanic(t *testing.T) {
+ replica, files := multiPageReplica(t)
+ last := files[len(files)-1]
+ cut := pageBlockEnd(t, last.data) + 4
+ if err := os.WriteFile(last.path, last.data[:cut], 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ dir := t.TempDir()
+ _, err := VerifyClientAt(context.Background(), lsfile.NewReplicaClient(replica), "hib/x.example.com", dir, uint64(last.info.MaxTXID))
+ if err == nil {
+ t.Fatal("a restore through a truncated file passed")
+ }
+ if !errors.Is(err, io.ErrUnexpectedEOF) {
+ t.Fatalf("restore = %v, want io.ErrUnexpectedEOF in the chain", err)
+ }
+ if errors.Is(err, ErrCheckFailed) {
+ t.Fatalf("restore = %v: a short file is not a failed check", err)
+ }
+ assertEmptyDir(t, dir)
+}
diff --git a/third_party/ltx/decoder.go b/third_party/ltx/decoder.go
index af4dfe296..1ac46e5cf 100644
--- a/third_party/ltx/decoder.go
+++ b/third_party/ltx/decoder.go
@@ -13,8 +13,8 @@ import (
// Decoder represents a decoder of an LTX file.
type Decoder struct {
- r io.Reader // main reader
- zr *lz4.Reader // lz4 reader
+ r *inputReader // main reader
+ zr *lz4.Reader // lz4 reader
header Header
trailer Trailer
@@ -29,9 +29,10 @@ type Decoder struct {
// NewDecoder returns a new instance of Decoder.
func NewDecoder(r io.Reader) *Decoder {
+ in := &inputReader{r: r}
return &Decoder{
- r: r,
- zr: lz4.NewReader(r),
+ r: in,
+ zr: lz4.NewReader(in),
state: stateHeader,
hash: crc64.New(crc64.MakeTable(crc64.ISO)),
}
@@ -73,11 +74,16 @@ func (dec *Decoder) Close() error {
}
// Slurp the remaining data in to memory so we can use the ByteReader interface.
- remainingBytes, err := io.ReadAll(dec.r)
+ // CARLOS patch (sqlite-integrity-safe): the end of the input is expected
+ // here, so the raw reader is read; fewer bytes than a checksum is a file
+ // cut short, not a panic, and the rest is read through inputReader.
+ remainingBytes, err := io.ReadAll(dec.r.r)
if err != nil {
return fmt.Errorf("read all: %w", err)
+ } else if len(remainingBytes) < ChecksumSize {
+ return fmt.Errorf("read trailer: %w", io.ErrUnexpectedEOF)
}
- remaining := bytes.NewReader(remainingBytes)
+ remaining := &inputReader{r: bytes.NewReader(remainingBytes)}
// Write everything but the file checksum to the hash.
dec.writeToHash(remainingBytes[:len(remainingBytes)-ChecksumSize])
@@ -90,7 +96,7 @@ func (dec *Decoder) Close() error {
// Read trailer.
b := make([]byte, TrailerSize)
if _, err := io.ReadFull(remaining, b); err != nil {
- return err
+ return fmt.Errorf("read trailer: %w", err)
} else if err := dec.trailer.UnmarshalBinary(b); err != nil {
return fmt.Errorf("unmarshal trailer: %w", err)
}
@@ -174,7 +180,12 @@ func (dec *Decoder) DecodePage(hdr *PageHeader, data []byte) error {
// Read page data next.
dec.zr.Reset(dec.r)
- if _, err := io.ReadFull(dec.zr, data); err != nil {
+ if _, err := io.ReadFull(dec.zr, data); err == io.EOF {
+ // CARLOS patch (sqlite-integrity-safe): the input never says io.EOF,
+ // so this is an lz4 frame that held no data. Only the zero page
+ // header may end the page block.
+ return io.ErrUnexpectedEOF
+ } else if err != nil {
return err
}
dec.writeToHash(data)
@@ -274,12 +285,42 @@ func (dec *Decoder) writeToHash(b []byte) {
// readLZ4Trailer reads the LZ4 trailer frame to ensure we hit EOF.
func (dec *Decoder) readLZ4Trailer() error {
- if _, err := io.ReadFull(dec.zr, make([]byte, 1)); err != io.EOF {
+ if _, err := io.ReadFull(dec.zr, make([]byte, 1)); err == nil {
return fmt.Errorf("expected lz4 end frame")
+ } else if err != io.EOF {
+ // CARLOS patch (sqlite-integrity-safe): keep the read's own error.
+ return fmt.Errorf("expected lz4 end frame: %w", err)
}
return nil
}
+// inputReader is the Decoder's input. CARLOS patch (sqlite-integrity-safe):
+// an LTX file ends only after its trailer, which Close reads, so any io.EOF
+// from the input before that is a file cut short and reads as
+// io.ErrUnexpectedEOF. Classifying it here, where every read of the file
+// passes (header, page headers, lz4 page data, page index and its size,
+// trailer), means DecodePage can return io.EOF only for the zero page header
+// that ends the page block, and a cut file never passes for a complete one.
+// Every other error is returned unchanged.
+type inputReader struct{ r io.Reader }
+
+func (in *inputReader) Read(p []byte) (int, error) {
+ n, err := in.r.Read(p)
+ if err == io.EOF { // io.EOF's contract: returned as itself, never wrapped
+ err = io.ErrUnexpectedEOF
+ }
+ return n, err
+}
+
+// ReadByte serves DecodePageIndex, which reads uvarints.
+func (in *inputReader) ReadByte() (byte, error) {
+ var b [1]byte
+ if _, err := io.ReadFull(in, b[:]); err != nil {
+ return 0, err
+ }
+ return b[0], nil
+}
+
// DecodeHeader decodes the header from r. Returns the header & read bytes.
func DecodeHeader(r io.Reader) (hdr Header, data []byte, err error) {
data = make([]byte, HeaderSize)