carlos / platform Public

litestream monitor snapshot can leak a goroutine and the WAL fd on a failed upload open

Found while fixing #810 (agent manager 8a3d302 asked to file it).

litestream v0.5.14's DB.Snapshot (db.go ~2465) gets an io.Pipe reader from SnapshotReader, starts an encoder goroutine that opens the database's WAL and writes into the pipe, then calls Replica.Client.WriteLTXFile(..., r). If that upload returns an error without reading the body to the end or closing it, DB.Snapshot returns the error and never closes the reader. The encoder goroutine stays blocked in pipe.write, holding the WAL file descriptor, until the process exits. A goroutine dump from the #810 test shows exactly this: SnapshotReader.func1 blocked in ltx.(*Encoder).EncodeHeader -> io.(*pipe).write.

Where it can happen in production: the store's own snapshot monitor (SnapshotInterval, 24 h, plus one pass at Open) calls DB.Snapshot. The drain release's snapshot (32a59ad) already closes its own reader (snapshotWithin), and the generation-bound client (internal/lease/claimgeneration.go, generationClient.WriteLTXFile) closes a pipe body on every outcome. A box whose replica client is NOT the generation-bound wrapper uses litestream's S3 client directly, and an upload that fails before consuming the body (a network or auth error, a refused PUT) leaks one goroutine and one WAL descriptor per failed daily snapshot, until the agent restarts. Low rate, but unbounded over a long-lived process with repeated S3 failures.

Fix idea: wrap every replica client the lease package builds (not only the generation-bound one) in a thin client whose WriteLTXFile closes an *io.PipeReader body on return, as generationClient does. One place, newStore/the Held constructor; a test with a client that refuses before reading asserts the WAL descriptor is released after a monitor snapshot. Not urgent; not in any current branch.