carlos / platform Public

ltx: a decode call that stops after a field returns its held read error

Astra R2 P1-1 on sqlite-integrity-safe. inputReader held an error that
came with a field's last bytes, but DecodeHeader then reported success,
so a header-only caller (genselect.checkRoot reads the root's header and
closes the stream) accepted a read that had failed.

Enforced in one place: inputReader.readFull, which DecodeHeader and
DecodePage use for every field, returns a held non-EOF error once the
field is complete. io.EOF with a complete header stays valid (a ranged
read of just the header ends there). inputReader now keeps the input's
own error and maps io.EOF to io.ErrUnexpectedEOF only as a read reports
it.

Guard tests: DecodeHeader alone with the fault reader (reset with the
header: the reset; io.EOF with the header, and a header-only input:
success); DecodePage with the reset in the zero page header's read
returns the reset, not the page block's end. Caller witness:
TestRootHeaderReadError runs genselect.Select through the real
checkRoot over the in-memory versioned bucket (no S3), with the reset
arriving with the root's header bytes: ErrPinnedMismatch wrapping the
reset; with io.EOF instead, the selection succeeds. The round's
findings are committed unedited.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev a50575c6e0d1da35de73af79ad7f9b566065a324 parent 6ca500a
4 files changed, +169 −10
  • docs/superpowers/reviews/CODEX-FINDINGS-sqlite-integrity-safe-R2.md +33 −0
  • internal/genselect/select_test.go +60 −0
  • internal/lease/ltxtruncate_test.go +42 −0
  • third_party/ltx/decoder.go +34 −10
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-sqlite-integrity-safe-R2.md b/docs/superpowers/reviews/CODEX-FINDINGS-sqlite-integrity-safe-R2.md
new file mode 100644
index 000000000..4b8c44aa0
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-sqlite-integrity-safe-R2.md
@@ -0,0 +1,33 @@
+- **R1 P1-1 — Partly resolved.** Full-file verification and compaction preserve a transport error delivered with the last bytes of a field. A caller that stops after `DecodeHeader` can still lose it.
+- **R1 P1-2 — Resolved.** Only journal-mode bytes `(1,1)` can earn `current`. The tests cover mixed versions with equal, higher, and lower counters. [Mode decision](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/sqlite-integrity-safe/internal/ops/freshness.go:112) · [Test cases](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/sqlite-integrity-safe/internal/ops/freshness_test.go:96)
+- **R1 P3 — Not resolved.** The summary wording remains with Paul in copy review.
+
+### P1
+
+1. **A header-only caller can accept a read that reported a transport error.** If the reader returns a complete, valid LTX header and a connection reset together, `inputReader.Read` saves the reset and returns the bytes with `nil`. `DecodeHeader` validates the header and returns success. In production, `genselect.checkRoot` then closes the underlying stream. If that close succeeds and the TXIDs match, it accepts the root without observing the reset. The new regression test reads the whole file, so it always gives the decoder another opportunity to report the error. **Fix and invariant:** Surface an underlying non-EOF error before the public decode operation that consumed those bytes reports success. Keep ordinary EOF alongside a complete, intentionally range-read header valid. Test both outcomes by calling `DecodeHeader` alone with the existing fault reader. [Input reader](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/sqlite-integrity-safe/third_party/ltx/decoder.go:316) · [Header decode](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/sqlite-integrity-safe/third_party/ltx/decoder.go:130) · [Production caller](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/sqlite-integrity-safe/internal/genselect/select.go:554) · [Existing assertion](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/sqlite-integrity-safe/internal/lease/ltxtruncate_test.go:215)
+
+2. **The box drill counts a source with an invalid SQLite signature as current.** `sourceHeader` checks the first 15 bytes of SQLite’s 16-byte signature. I changed only byte 15 of an in-memory SQLite database. Its `(1,1)` mode and counter still matched the clean copy, and SQLite rejected the altered database with `file is not a database`. For those same bytes, `sourceHeader` succeeds and the box drill increments `current`. The pinned SQLite reader checks all 16 bytes. **Fix and invariant:** Require the complete `SQLite format 3\x00` signature before using the source counter as evidence. All 16 bytes are already in the buffer. Add a case with only the terminating NUL damaged and require unknown freshness. [Source signature check](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/sqlite-integrity-safe/internal/ops/freshness.go:150) · [Current verdict](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/sqlite-integrity-safe/internal/ops/freshness.go:112) · [Box tally](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/sqlite-integrity-safe/internal/ops/litestream.go:546) · [Pinned SQLite check](/home/paulca/go/pkg/mod/modernc.org/sqlite@v1.55.0/lib/sqlite_g_0000000000003a80.go:8802)
+
+**P2 and new P3 findings:** None.
+
+Both P1s concern invariants raised in R1. The repository’s two-round stopping rule applies. I recommend Paul’s option of enforcing each invariant in one place, with a guard test at the caller boundary. The other choices are an up-front refusal for the affected case or removing the positive decision that depends on it.
+
+### Verification
+
+At `08856d2b5ce40917a6fc0d9d2d1d051a5b515b82`, I found no healthy-file regression or remaining strict-prefix acceptance in `Verify`, `DecodeDatabaseTo`, or `Compactor.Compact`. Each consumes the page terminator and calls `Decoder.Close`, which checks the index, trailer, and checksum. The tests sweep every strict prefix of two real replicated files and exercise the former panic through `VerifyClientAt`. One existing caller limitation matters when interpreting that result: `lease.fullImage` checks page coverage and returns before validating the trailer, so it can return true for a file cut immediately after the page terminator. [Decoder close](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/sqlite-integrity-safe/third_party/ltx/decoder.go:81) · [Compactor close](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/sqlite-integrity-safe/third_party/ltx/compactor.go:135) · [Prefix sweep](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/sqlite-integrity-safe/internal/lease/ltxtruncate_test.go:160) · [Restore witness](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/sqlite-integrity-safe/internal/lease/ltxtruncate_test.go:265) · [Page-coverage caller](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/sqlite-integrity-safe/internal/lease/continuity.go:598)
+
+I found **zero added S3 requests** across restore, compaction, console seed, drills, moves, and `dbdoor`. The decoder consumes the stream already opened. The box drill retains its one retry and existing failure exits. The hibernate drill checks lease ownership before opening the source and maps WAL, recent lag, mixed mode, and an empty path to unknown without failing a clean restore. [Restore and retry](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/sqlite-integrity-safe/internal/ops/litestream.go:516) · [Exit conditions](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/sqlite-integrity-safe/internal/ops/litestream.go:556) · [Hibernate mapping](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/sqlite-integrity-safe/internal/ops/hibernate_verify.go:767) · [Empty-path guard](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/sqlite-integrity-safe/internal/ops/hibernate_verify.go:905)
+
+The read-only sandbox prevented `TestLTXReadErrorIsKept` from starting because Go could not create its work directory. Amadan was unreachable, so I used the pinned brief’s account of #1673 and could not post the verdicts to #280 or the stopping-rule notice to the branch discussion.
+
+### Census
+
+| Unit or envelope changed since `3aa2a48` | Verdict | Lines read and basis |
+|---|---|---|
+| `Decoder.Close` | APPROVE | `third_party/ltx/decoder.go:69–125`. Checks the saved error before reading the existing stream. The short-tail guard precedes slicing, and both checksum checks remain. |
+| `inputReader.Read` | APPROVE | `third_party/ltx/decoder.go:30–38,311–340`. Reads only the supplied stream. Saving an error adds no input source or path. |
+| `sourceHeader` | APPROVE | `internal/ops/freshness.go:92–116,138–158` and `internal/lease/check.go:399–413`. Opens the same source path and reads the same 28 bytes as its predecessor. The incomplete signature check is inherited. |
+| `internal/ops` | APPROVE | `freshness.go:92–167`, `litestream.go:511–575`, `hibernate_verify.go:767–799,905–909`. Mode and counter interpretation change within the existing config, path, and lease boundaries. |
+| `third_party/ltx` | APPROVE | `decoder.go:30–38,69–150,153–210,290–340,369–404`. LZ4, index, and trailer reads use the original stream or bytes already read from it. Existing validation and checksum checks remain in place. |
+
+**NOT READY**
\ No newline at end of file
diff --git a/internal/genselect/select_test.go b/internal/genselect/select_test.go
index 64e7a82ca..3c2629db5 100644
--- a/internal/genselect/select_test.go
+++ b/internal/genselect/select_test.go
@@ -305,6 +305,66 @@ func TestR13_1UnfinishedRegionalWalk(t *testing.T) {
}
}
+// heldReader gives data and err in the same read, as a reader may, then
+// io.EOF.
+type heldReader struct {
+ data []byte
+ err error
+ done bool
+}
+
+func (r *heldReader) Read(p []byte) (int, error) {
+ if r.done {
+ return 0, io.EOF
+ }
+ n := copy(p, r.data)
+ r.data = r.data[n:]
+ if len(r.data) > 0 {
+ return n, nil
+ }
+ r.done = true
+ return n, r.err
+}
+
+func (r *heldReader) Close() error { return nil }
+
+// checkRoot reads only the root's header and closes the stream, so a
+// transport error that came with the header's last bytes must fail the
+// selection (the decoder returns it), while a header whose read ends with
+// io.EOF is a good root.
+func TestRootHeaderReadError(t *testing.T) {
+ reset := errors.New("connection reset by peer")
+ for _, c := range []struct {
+ name string
+ err error
+ want error
+ }{
+ {"reset with the header", reset, ErrPinnedMismatch},
+ {"EOF with the header", io.EOF, nil},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ f := newFixture(t)
+ f.store = altered{Reader: f.b, open: func(ctx context.Context, bucket, key, id string) (io.ReadCloser, error) {
+ b, err := f.b.GetVersion(ctx, bucket, key, id)
+ if err != nil {
+ return nil, err
+ }
+ return &heldReader{data: b, err: c.err}, nil
+ }}
+ got, err := Select(t.Context(), f.store, f.req)
+ if c.want == nil {
+ if err != nil || got == nil {
+ t.Fatalf("got %+v / %v, want a selection", got, err)
+ }
+ return
+ }
+ if got != nil || !errors.Is(err, c.want) || !errors.Is(err, reset) {
+ t.Fatalf("got %+v / %v, want %v wrapping the reset", got, err, c.want)
+ }
+ })
+ }
+}
+
func TestRefusals(t *testing.T) {
tests := []struct {
name string
diff --git a/internal/lease/ltxtruncate_test.go b/internal/lease/ltxtruncate_test.go
index 7962a3714..c2a00673d 100644
--- a/internal/lease/ltxtruncate_test.go
+++ b/internal/lease/ltxtruncate_test.go
@@ -246,6 +246,48 @@ func TestLTXReadErrorIsKept(t *testing.T) {
}
}
+// A decode call that stops early never reports success over a read error:
+// DecodeHeader alone (a caller such as genselect.checkRoot reads only the
+// header and closes the stream) returns an error that came in the same read
+// as the header's last bytes, and DecodePage returns one that came with the
+// zero page header's last bytes rather than the page block's end. An input
+// that simply ends with the header (a ranged read of just the header) is
+// still a good header, whichever read says io.EOF.
+func TestLTXDecodeStopsOnAHeldReadError(t *testing.T) {
+ _, files := multiPageReplica(t)
+ f := files[len(files)-1]
+ head := f.data[:ltx.HeaderSize]
+ reset := errors.New("connection reset by peer")
+
+ if err := ltx.NewDecoder(&failingReader{data: head, err: reset, withLast: true}).DecodeHeader(); !errors.Is(err, reset) {
+ t.Fatalf("header with a reset in its last read: DecodeHeader = %v, want the reset", err)
+ }
+ if err := ltx.NewDecoder(&failingReader{data: head, err: io.EOF, withLast: true}).DecodeHeader(); err != nil {
+ t.Fatalf("header with io.EOF in its last read: DecodeHeader = %v, want nil", err)
+ }
+ if err := ltx.NewDecoder(bytes.NewReader(head)).DecodeHeader(); err != nil {
+ t.Fatalf("header alone: DecodeHeader = %v, want nil", err)
+ }
+
+ end := pageBlockEnd(t, f.data)
+ dec := ltx.NewDecoder(&failingReader{data: f.data[:end], err: reset, withLast: true})
+ if err := dec.DecodeHeader(); err != nil {
+ t.Fatal(err)
+ }
+ var hdr ltx.PageHeader
+ data := make([]byte, dec.Header().PageSize)
+ for i := 0; ; i++ {
+ err := dec.DecodePage(&hdr, data)
+ if err == nil {
+ continue
+ }
+ if err == io.EOF || !errors.Is(err, reset) {
+ t.Fatalf("page %d, reset with the zero page header: DecodePage = %v, want the reset", i, err)
+ }
+ break
+ }
+}
+
// 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 {
diff --git a/third_party/ltx/decoder.go b/third_party/ltx/decoder.go
index e37063101..fe6a40606 100644
--- a/third_party/ltx/decoder.go
+++ b/third_party/ltx/decoder.go
@@ -78,8 +78,8 @@ func (dec *Decoder) Close() error {
// 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. An
// error the input returned with earlier bytes comes first.
- if err := dec.r.err; err != nil {
- return fmt.Errorf("read all: %w", err)
+ if dec.r.err != nil {
+ return fmt.Errorf("read all: %w", dec.r.early())
}
remainingBytes, err := io.ReadAll(dec.r.r)
if err != nil {
@@ -129,7 +129,7 @@ func (dec *Decoder) Close() error {
// Call Header() to retrieve the header after this is successfully called.
func (dec *Decoder) DecodeHeader() error {
b := make([]byte, HeaderSize)
- if _, err := io.ReadFull(dec.r, b); err != nil {
+ if err := dec.r.readFull(b); err != nil {
return err
} else if err := dec.header.UnmarshalBinary(b); err != nil {
return fmt.Errorf("unmarshal header: %w", err)
@@ -164,7 +164,7 @@ func (dec *Decoder) DecodePage(hdr *PageHeader, data []byte) error {
// Read and unmarshal page header.
b := make([]byte, PageHeaderSize)
- if _, err := io.ReadFull(dec.r, b); err != nil {
+ if err := dec.r.readFull(b); err != nil {
return err
} else if err := hdr.UnmarshalBinary(b); err != nil {
return fmt.Errorf("unmarshal: %w", err)
@@ -308,26 +308,50 @@ func (dec *Decoder) readLZ4Trailer() error {
// Every other error is returned unchanged. An error that comes with bytes is
// held and returned from then on: io.ReadFull drops an error that arrives
// with the bytes that fill its buffer, and the next read could only say EOF.
+// readFull is where a decode call reads a field, and it reports a held
+// error once the field is complete, so no call that stops after a field
+// (DecodeHeader alone, DecodePage at the zero page header) succeeds over a
+// read that failed.
type inputReader struct {
r io.Reader
- err error // held since the read that returned it
+ err error // the input's own error, held since the read that returned it
}
func (in *inputReader) Read(p []byte) (int, error) {
if in.err != nil {
- return 0, in.err
+ return 0, in.early()
}
n, err := in.r.Read(p)
- if err == io.EOF { // io.EOF's contract: returned as itself, never wrapped
- err = io.ErrUnexpectedEOF
- }
if err != nil {
in.err = err
if n > 0 {
return n, nil
}
+ return 0, in.early()
+ }
+ return n, nil
+}
+
+// early is the held error as a read reports it: the input's end before the
+// trailer is a file cut short.
+func (in *inputReader) early() error {
+ if in.err == io.EOF { // io.EOF's contract: returned as itself, never wrapped
+ return io.ErrUnexpectedEOF
}
- return n, err
+ return in.err
+}
+
+// readFull fills b, then returns an error the input gave with b's last bytes.
+// The input's end (io.EOF) is no error for a complete field: a ranged read of
+// just the header ends there.
+func (in *inputReader) readFull(b []byte) error {
+ if _, err := io.ReadFull(in, b); err != nil {
+ return err
+ }
+ if in.err != nil && in.err != io.EOF {
+ return in.err
+ }
+ return nil
}
// ReadByte serves DecodePageIndex, which reads uvarints.