carlos / platform Public

lease: teardown tests answer Astra's two P2s

P2 1: TestTeardownReleasesACancelledSnapshot could pass without
pipeClosingClient, since an encoder descheduled before its body write
could be released by the teardown instead. It now captures litestream's
own snapshot pipe, sees the encoder blocked offering a body write once
the cancelled upload has returned (a zero-length Read, nothing drained),
and requires the pipe's reader closed before any teardown. With the
wrapper removed it fails: "nothing closed the snapshot's pipe in 30s".

P2 2: tornDownFiles no longer assumes the database and -shm close
synchronously (database/sql can roll litestream's read transaction back
after sql.DB.Close returns); it waits on all three paths with the 30 s
guard. The check after the second call stays immediate.

Astra's findings are committed as FINDINGS-flake-lease-teardown.md.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev c8c13836be36a9537818dd3981af8fc53e12e256 parent 1e880e0
2 files changed, +136 −29
  • docs/superpowers/reviews/FINDINGS-flake-lease-teardown.md +31 −0
  • internal/lease/teardown_linux_test.go +105 −29

CI passed — run details

diff --git a/docs/superpowers/reviews/FINDINGS-flake-lease-teardown.md b/docs/superpowers/reviews/FINDINGS-flake-lease-teardown.md
new file mode 100644
index 000000000..c3c8c15db
--- /dev/null
+++ b/docs/superpowers/reviews/FINDINGS-flake-lease-teardown.md
@@ -0,0 +1,31 @@
+Reviewed commit `1e880e094aaed9b8915b1ad85af8a88bbccc2ede` against local `origin/main` (`365a79ca0e60561a38eb31348ea159d1643f7d3c`). No P1 findings. Two P2 findings follow; neither requires redesigning the production wrapper.
+
+1. **P2 — The regression test can pass without the pipe-closing fix.**
+ [internal/lease/teardown_linux_test.go:200](/home/paulca/amadan.net/carlos/platform-flake-lease/internal/lease/teardown_linux_test.go:200)
+
+ Receiving `context.Canceled` proves the uploader stopped, but does not prove the encoder reached its blocked body write. After the header is consumed, the encoder can be descheduled before entering `writeLTXFromDB`. The test then calls `Abandon`, which closes the database and cancels the store context. When the encoder resumes, its context check at Litestream v0.5.14 `db.go:2072`, or database read at `db.go:2099`, can fail and release the WAL without `pipeClosingClient`. The descriptor assertion then passes with the production fix removed.
+
+ **Fault family:** regression-test causality—cleanup must demonstrate the wrapper’s effect.
+ **Fix:** Capture the original snapshot pipe and assert, with bounded synchronization and without draining it, that it is closed before calling `Abandon`; retain the teardown descriptor checks.
+
+2. **P2 — The immediate database/SHM assertion assumes synchronous SQLite cleanup that the fixture does not guarantee.**
+ [internal/lease/teardown_linux_test.go:65](/home/paulca/amadan.net/carlos/platform-flake-lease/internal/lease/teardown_linux_test.go:65)
+
+ If the DB monitor initializes the database before the explicit sync, Litestream’s long-running read transaction inherits `db.ctx` (`db.go:1039`, `1132`, `2706`). `DB.Close` cancels that context, allowing `database/sql.Tx.awaitDone` to start rollback asynchronously. That goroutine marks the transaction done before finishing rollback. Litestream’s explicit rollback can consequently receive the ignored `ErrTxDone` and continue to `sql.DB.Close`.
+
+ Go’s `sql.DB.Close` closes idle connections; it does not join this checked-out transaction’s rollback (`database/sql/sql.go:926`, `2209`, `2326`). Its SQLite connection can therefore retain database and SHM descriptors briefly after teardown returns. This is another possible transient descriptor lifetime, beyond the snapshot WAL. I established this interleaving from source; I could not reproduce it in this read-only session.
+
+ **Fault family:** teardown-test synchronization—an asynchronous close is treated as a permanent leak.
+ **Fix:** Use a bounded descriptor-drain check for all three paths, retaining the immediate second-call assertion, or explicitly synchronize transaction cleanup before the immediate check.
+
+The remaining checks support the production change:
+
+- **Root cause:** Both described WAL failure paths match the pinned v0.5.14 source. `Snapshot` leaves the reader unclosed, and the S3 uploader rejects an already-cancelled context before reading the body.
+- **Wrapper safety:** S3 and `lsfile` finish consuming successful writes before returning. Closing afterward is safe. The generation client, fence gate, and compactor already tolerate repeated pipe closes.
+- **Interfaces and restores:** I found no required optional interface or concrete-client assertion lost on the store path. Restore constructs a separate replica; hiding `ReplicaClientV3` here does not affect it.
+- **v0.5.18 qualification:** Its cached source also adds a deferred reader close in `DB.Snapshot` (`db.go:3065`) and returns a `snapshotReadCloser`. This wrapper’s exact `*io.PipeReader` assertion no longer matches that snapshot reader, but upstream performs the cleanup. The wrapper remains harmless; the brief’s shutdown-order argument alone does not describe the full upgrade behavior.
+- **Census:** **Approve the `internal/lease` envelope re-pin.** The wrapper adds no root read, path selection, or authority bypass. I independently recomputed the envelope as `1af3b69b91061e6f593bc4df2756308fb4befed1fba5b4b41adff42254426a81`, matching the overlay.
+
+`git diff --check` passed. The targeted test command stopped before compilation because Go attempted to update `go.mod` on the read-only filesystem. No full suites ran and no files were edited.
+
+**READY AFTER FIXES**
\ No newline at end of file
diff --git a/internal/lease/teardown_linux_test.go b/internal/lease/teardown_linux_test.go
index 3be3481c6..7fabd2535 100644
--- a/internal/lease/teardown_linux_test.go
+++ b/internal/lease/teardown_linux_test.go
@@ -5,9 +5,11 @@ package lease_test
import (
"context"
"errors"
+ "fmt"
"io"
"os"
"path/filepath"
+ "runtime"
"slices"
"testing"
"time"
@@ -47,26 +49,30 @@ func openFiles(t *testing.T, paths ...string) int {
return n
}
-// tornDownFiles fails t unless the teardown that just returned closed
-// every descriptor on the database at path. The database file and its
-// -shm must be closed already: a SQLite connection holds a descriptor on
-// the database file for as long as it is open, and so does litestream's
-// own. The WAL alone may close a moment later. The store's snapshot
-// monitor runs a pass at Open, concurrently with the test's first sync,
-// and litestream's DB.SnapshotReader encodes in a goroutine nothing can
-// join: it opens the WAL read-only and closes it in a defer that runs
-// after it has closed its pipe. The store's Close waits for the upload
-// reading that pipe, not for the encoder, so it can return in between.
-// The WAL check therefore waits for the descriptor itself (#1193); an
-// encoder that never lets go (#811, pipeClosingClient) fails it at the
-// guard.
+// tornDownFiles fails t unless the teardown that just returned closes
+// every descriptor on the database at path: the database file, its -wal
+// and its -shm. Each check waits for the descriptor itself (#1193), with
+// a guard only a descriptor that never closes meets. Two goroutines that
+// nothing joins can close one a moment after the teardown returns:
+//
+// - litestream's snapshot encoder (DB.SnapshotReader). The store's
+// snapshot monitor runs a pass at Open, concurrently with the test's
+// first sync. The encoder opens the WAL read-only and closes it in a
+// defer that runs after it has closed its pipe, and the store's Close
+// waits for the upload reading that pipe, not for the encoder. An
+// encoder that never lets go (#811, pipeClosingClient) meets the
+// guard.
+// - database/sql's rollback of litestream's long-running read
+// transaction, which runs under the DB's context: DB.Close cancels
+// it, the rollback starts in Tx.awaitDone, and sql.DB.Close does not
+// wait for a connection that transaction still has checked out, so
+// the connection's database and -shm descriptors can outlive it.
func tornDownFiles(t *testing.T, path string) {
t.Helper()
- if n := openFiles(t, path, path+"-shm"); n != 0 {
- t.Fatalf("the teardown left %d descriptors on the database or its -shm open", n)
+ for _, p := range []string{path, path + "-shm", path + "-wal"} {
+ lease.WaitDescriptorsForTest(t, p, "the teardown left "+filepath.Base(p)+" open",
+ func(open int) bool { return open == 0 })
}
- lease.WaitDescriptorsForTest(t, path+"-wal", "the teardown left the WAL open",
- func(open int) bool { return open == 0 })
}
// replicating is a non-HA replicator of a fresh database on prefix, its
@@ -139,34 +145,98 @@ func (c *cancelAfterHeader) Read(p []byte) (int, error) {
return n, err
}
+// snapshotGuard bounds the waits of TestTeardownReleasesACancelledSnapshot,
+// as descriptorGuard bounds the descriptor checks: only a real bug (no
+// snapshot, an encoder that never writes, a pipe nobody closes) meets it.
+const snapshotGuard = 30 * time.Second
+
+// cancelledUpload is what cancelledSnapshot saw of one snapshot upload.
+type cancelledUpload struct {
+ pipe *io.PipeReader // the snapshot's own reader, litestream's pipe
+ err error // the upload's answer
+ // blocked is nil once the encoder was seen offering a body write to
+ // the pipe after the upload returned: blocked on a pipe that nothing
+ // will read again.
+ blocked error
+}
+
// cancelledSnapshot is the real S3 replica client, except that each
-// snapshot upload is cancelled once its header has been read. done
-// receives the upload's answer.
+// snapshot upload is cancelled once its header has been read. The first
+// snapshot's upload is reported on done.
type cancelledSnapshot struct {
litestream.ReplicaClient
- done chan error
+ done chan cancelledUpload
}
func (c cancelledSnapshot) WriteLTXFile(ctx context.Context, level int, minTXID, maxTXID ltx.TXID, r io.Reader) (*ltx.FileInfo, error) {
if level != litestream.SnapshotLevel {
return c.ReplicaClient.WriteLTXFile(ctx, level, minTXID, maxTXID, r)
}
+ up := cancelledUpload{}
+ up.pipe, _ = r.(*io.PipeReader)
ctx, cancel := context.WithCancel(ctx)
defer cancel()
info, err := c.ReplicaClient.WriteLTXFile(ctx, level, minTXID, maxTXID, &cancelAfterHeader{r: r, cancel: cancel})
+ up.err = err
+ up.blocked = errors.New("the snapshot's reader is not litestream's pipe")
+ if up.pipe != nil {
+ up.blocked = offering(up.pipe)
+ }
select {
- case c.done <- err:
+ case c.done <- up:
default:
}
return info, err
}
+// offering waits, up to snapshotGuard, for the writer of pipe to offer a
+// write, and consumes none of it: a zero-length Read returns once a
+// writer is waiting in Write, which then goes on waiting. nil means the
+// writer is blocked in a write; an error that the pipe was closed first.
+func offering(pipe *io.PipeReader) error {
+ got := make(chan error, 1)
+ go func() {
+ _, err := pipe.Read(nil)
+ got <- err
+ }()
+ select {
+ case err := <-got:
+ if err != nil {
+ return fmt.Errorf("the pipe closed before its encoder blocked: %w", err)
+ }
+ return nil
+ case <-time.After(snapshotGuard):
+ return fmt.Errorf("the encoder offered no write in %s", snapshotGuard)
+ }
+}
+
+// readerClosed waits, up to snapshotGuard, until pipe's reader end has
+// been closed (io.ErrClosedPipe), without draining it. Its writer is
+// blocked offering a write (offering), so each zero-length Read returns
+// at once until then.
+func readerClosed(pipe *io.PipeReader) error {
+ for guard := time.Now().Add(snapshotGuard); ; runtime.Gosched() {
+ _, err := pipe.Read(nil)
+ switch {
+ case errors.Is(err, io.ErrClosedPipe):
+ return nil
+ case err != nil:
+ return fmt.Errorf("the pipe's writer ended it first: %w", err)
+ case time.Now().After(guard):
+ return fmt.Errorf("nothing closed the snapshot's pipe in %s", snapshotGuard)
+ }
+ }
+}
+
// #811 on a non-HA replicator: the store's snapshot monitor runs a pass at
// Open, and a teardown that cancels it after litestream has peeked the LTX
// header makes the S3 uploader return before it reads the body. litestream
// never closes that pipe, so its encoder would hold the WAL open for the
-// life of the process; the store's replica client closes it
-// (pipeClosingClient), and the teardown leaves nothing open.
+// life of the process. The test cancels the upload the same way with no
+// teardown, sees the encoder blocked on the pipe once the upload has
+// returned, and requires the store's replica client (pipeClosingClient) to
+// close the pipe before anything is torn down; then the teardown leaves
+// nothing open.
func TestTeardownReleasesACancelledSnapshot(t *testing.T) {
fx := leasetest.NewLockFixture(t)
const prefix = "instances/cancelled.example.com"
@@ -178,7 +248,7 @@ func TestTeardownReleasesACancelledSnapshot(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- snap := cancelledSnapshot{ReplicaClient: s3, done: make(chan error, 1)}
+ snap := cancelledSnapshot{ReplicaClient: s3, done: make(chan cancelledUpload, 1)}
lease.SetReplicaClientForTest(h, snap)
dbPath := tempDB(t)
r, err := h.Replicate(ctx, dbPath, 0)
@@ -189,14 +259,20 @@ func TestTeardownReleasesACancelledSnapshot(t *testing.T) {
if err := r.SyncAndWait(ctx); err != nil {
t.Fatalf("first sync: %v", err)
}
+ var up cancelledUpload
select {
- case err := <-snap.done:
- if !errors.Is(err, context.Canceled) {
- t.Fatalf("the snapshot upload = %v, want it cancelled", err)
- }
- case <-time.After(30 * time.Second):
+ case up = <-snap.done:
+ case <-time.After(snapshotGuard):
t.Fatal("the store's snapshot monitor made no snapshot")
}
+ if !errors.Is(up.err, context.Canceled) || up.blocked != nil {
+ t.Fatalf("the snapshot upload = %v, its encoder: %v; want it cancelled, the encoder blocked on its pipe", up.err, up.blocked)
+ }
+ // Before any teardown: the store's replica client, not a closed
+ // database or a cancelled store, is what releases the encoder.
+ if err := readerClosed(up.pipe); err != nil {
+ t.Fatal(err)
+ }
r.Abandon(ctx)
tornDownFiles(t, dbPath)
}