carlos / platform Public

lease: close a failed snapshot's pipe; teardown test waits for the WAL

TestTeardownIsTerminal flaked on CI ("the first teardown left 1
descriptors on the database open"). The descriptor is the WAL, held by
litestream's snapshot encoder (DB.SnapshotReader), a goroutine nothing
can join. The store's snapshot monitor runs a pass at Open, so it is
often in flight when the test tears the replicator down. Two outcomes:

- Benign: the encoder closes its pipe, the upload returns, Store.Close
  returns, and only then does the encoder's deferred walFile.Close run.
  The test now requires the database and -shm closed at once and waits
  for the WAL descriptor itself (WaitDescriptorsForTest, 30 s guard).

- A real leak (#811 on non-HA stores): if Store.Close cancels the
  monitor after litestream has peeked the LTX header, the S3 uploader
  refuses the cancelled context before reading the body, litestream
  never closes the pipe, and the encoder holds the WAL open for the
  life of the process. newStore now wraps every store's replica client
  in pipeClosingClient, which closes a pipe body on every outcome, as
  the fence gate and generationClient already do for their paths.
  TestTeardownReleasesACancelledSnapshot drives that path through the
  real S3 client; it fails at the guard without the wrapper.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev c297d61b55af61174d790ed740358b02c911d8ee parent 12158f4
3 files changed, +154 −5
  • internal/lease/lease.go +2 −1
  • internal/lease/snapshotpipe.go +36 −0
  • internal/lease/teardown_linux_test.go +116 −4
diff --git a/internal/lease/lease.go b/internal/lease/lease.go
index 71a0d0705..f4daab31b 100644
--- a/internal/lease/lease.go
+++ b/internal/lease/lease.go
@@ -477,7 +477,8 @@ func (h *Held) newStore(dbPath string, syncInterval time.Duration) (*litestream.
return nil, nil, err
}
}
- db.Replica = litestream.NewReplicaWithClient(db, client)
+ // A snapshot whose upload fails must not keep the WAL open (#811).
+ db.Replica = litestream.NewReplicaWithClient(db, pipeClosingClient{client})
if syncInterval > 0 {
db.Replica.SyncInterval = syncInterval
}
diff --git a/internal/lease/snapshotpipe.go b/internal/lease/snapshotpipe.go
new file mode 100644
index 000000000..59b02b6b7
--- /dev/null
+++ b/internal/lease/snapshotpipe.go
@@ -0,0 +1,36 @@
+package lease
+
+import (
+ "context"
+ "io"
+
+ "github.com/benbjohnson/litestream"
+ "github.com/superfly/ltx"
+)
+
+// pipeClosingClient is every store's replica client (newStore): its
+// WriteLTXFile closes a pipe body on every outcome, as the fence gate
+// and generationClient do, and as snapshotWithin closes its own reader.
+//
+// litestream's DB.Snapshot never closes its reader when the write fails
+// (#811). The reader is a pipe whose encoder, a goroutine nothing can
+// join, holds the WAL open. The store's snapshot monitor runs a pass at
+// Open, so a teardown soon after a wake can land while that snapshot
+// uploads: the store's Close cancels the monitor, and if the cancel comes
+// after litestream has peeked the LTX header, the S3 uploader refuses the
+// cancelled context before it reads the body. The encoder then waits on
+// the pipe for good, holding the WAL descriptor (and its goroutine) for
+// the life of the process, after a teardown that has otherwise closed
+// the database (TestTeardownReleasesACancelledSnapshot). Closing the pipe
+// fails the encoder's next write, and it closes the WAL as it returns.
+//
+// It hides the inner client's optional ReplicaClientV3, which litestream
+// uses only to restore; nothing restores through a store's replica.
+type pipeClosingClient struct{ litestream.ReplicaClient }
+
+func (c pipeClosingClient) WriteLTXFile(ctx context.Context, level int, minTXID, maxTXID ltx.TXID, r io.Reader) (*ltx.FileInfo, error) {
+ if pipe, ok := r.(*io.PipeReader); ok {
+ defer pipe.Close()
+ }
+ return c.ReplicaClient.WriteLTXFile(ctx, level, minTXID, maxTXID, r)
+}
diff --git a/internal/lease/teardown_linux_test.go b/internal/lease/teardown_linux_test.go
index ea39c2469..3be3481c6 100644
--- a/internal/lease/teardown_linux_test.go
+++ b/internal/lease/teardown_linux_test.go
@@ -3,10 +3,17 @@
package lease_test
import (
+ "context"
"errors"
+ "io"
"os"
"path/filepath"
+ "slices"
"testing"
+ "time"
+
+ "github.com/benbjohnson/litestream"
+ "github.com/superfly/ltx"
"github.com/carlosframework/platform/internal/lease"
leasetest "github.com/carlosframework/platform/internal/lease/locktest"
@@ -16,6 +23,12 @@ import (
// at path and its -wal and -shm files: litestream's DB.init opens the
// database (sql.DB and a long-running descriptor), its Close closes them.
func openDBFiles(t *testing.T, path string) int {
+ t.Helper()
+ return openFiles(t, path, path+"-wal", path+"-shm")
+}
+
+// openFiles counts this process's open file descriptors on any of paths.
+func openFiles(t *testing.T, paths ...string) int {
t.Helper()
fds, err := os.ReadDir("/proc/self/fd")
if err != nil {
@@ -27,13 +40,35 @@ func openDBFiles(t *testing.T, path string) int {
if err != nil {
continue // closed since the listing
}
- if target == path || target == path+"-wal" || target == path+"-shm" {
+ if slices.Contains(paths, target) {
n++
}
}
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.
+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)
+ }
+ 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
// first sync shipped.
func replicating(t *testing.T, fx *leasetest.LockFixture, prefix string) (*lease.Replicator, string) {
@@ -76,9 +111,7 @@ func TestTeardownIsTerminal(t *testing.T) {
if err := tc.first(r); err != nil {
t.Fatalf("first teardown: %v", err)
}
- if n := openDBFiles(t, dbPath); n != 0 {
- t.Fatalf("the first teardown left %d descriptors on the database open", n)
- }
+ tornDownFiles(t, dbPath)
before := len(fx.Requests())
err := tc.again(r)
reqs, open := fx.Requests()[before:], openDBFiles(t, dbPath)
@@ -88,3 +121,82 @@ func TestTeardownIsTerminal(t *testing.T) {
})
}
}
+
+// cancelAfterHeader cancels its upload's context once litestream has
+// read the snapshot's LTX header from it (ltx.PeekHeader): a store's
+// Close cancelling its snapshot monitor at that point.
+type cancelAfterHeader struct {
+ r io.Reader
+ n int
+ cancel context.CancelFunc
+}
+
+func (c *cancelAfterHeader) Read(p []byte) (int, error) {
+ n, err := c.r.Read(p)
+ if c.n += n; c.n >= ltx.HeaderSize {
+ c.cancel()
+ }
+ return n, err
+}
+
+// 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.
+type cancelledSnapshot struct {
+ litestream.ReplicaClient
+ done chan error
+}
+
+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)
+ }
+ ctx, cancel := context.WithCancel(ctx)
+ defer cancel()
+ info, err := c.ReplicaClient.WriteLTXFile(ctx, level, minTXID, maxTXID, &cancelAfterHeader{r: r, cancel: cancel})
+ select {
+ case c.done <- err:
+ default:
+ }
+ return info, err
+}
+
+// #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.
+func TestTeardownReleasesACancelledSnapshot(t *testing.T) {
+ fx := leasetest.NewLockFixture(t)
+ const prefix = "instances/cancelled.example.com"
+ h, err := lease.Acquire(ctx, fx.Bucket, prefix, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ s3, err := lease.ReadReplicaClient(ctx, fx.Bucket, prefix, "us-east-1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ snap := cancelledSnapshot{ReplicaClient: s3, done: make(chan error, 1)}
+ lease.SetReplicaClientForTest(h, snap)
+ dbPath := tempDB(t)
+ r, err := h.Replicate(ctx, dbPath, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { r.Abandon(ctx) })
+ if err := r.SyncAndWait(ctx); err != nil {
+ t.Fatalf("first sync: %v", err)
+ }
+ 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):
+ t.Fatal("the store's snapshot monitor made no snapshot")
+ }
+ r.Abandon(ctx)
+ tornDownFiles(t, dbPath)
+}