Merge main into flake-demo-claim-stage-hold
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+433
−5
docs/superpowers/notes/census-proposal-flake-lease-teardown.md+11 −0docs/superpowers/reviews/FINDINGS-flake-lease-teardown.md+31 −0docs/superpowers/reviews/REVIEW-BRIEF-flake-lease-teardown.md+157 −0internal/lease/lease.go+2 −1internal/lease/snapshotpipe.go+36 −0internal/lease/teardown_linux_test.go+192 −4internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/provision/testdata/plan14-root-reads-flake-lease-teardown.tsv+3 −0
diff --git a/docs/superpowers/notes/census-proposal-flake-lease-teardown.md b/docs/superpowers/notes/census-proposal-flake-lease-teardown.md| new file mode 100644 |
| index 000000000..26c2a4009 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-flake-lease-teardown.md |
| @@ -0,0 +1,11 @@ |
| +# Census approval: flake-lease-teardown |
| + |
| +Ruling `census-ruling-flake-lease-teardown`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +Envelopes re-pinned: `internal/lease`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
| + |
| +Seal: `5d4a5eea79394145fdd59aa5eb87115cc1ee396e02e0ab4b21decd2b3a10e3b4` → `5d4a5eea79394145fdd59aa5eb87115cc1ee396e02e0ab4b21decd2b3a10e3b4`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-flake-lease-teardown.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
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/docs/superpowers/reviews/REVIEW-BRIEF-flake-lease-teardown.md b/docs/superpowers/reviews/REVIEW-BRIEF-flake-lease-teardown.md| new file mode 100644 |
| index 000000000..3ebe07062 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/REVIEW-BRIEF-flake-lease-teardown.md |
| @@ -0,0 +1,157 @@ |
| +# Review brief: flake-lease-teardown |
| + |
| +You are the independent reviewer (Astra). Review branch `flake-lease-teardown` |
| +on origin (amadan.net) against `origin/main`. The fix is commits `c297d61b` |
| +(code and tests) and `057e43b0` (census re-pin); the merge of main after them |
| +brings in nothing under `internal/lease`. |
| + |
| +## The failure |
| + |
| +`internal/lease` `TestTeardownIsTerminal/abandon_then_close_proven` failed once |
| +on main CI at `0acb2767` (2026-11-19, shard `rest/internal_lease`) and passed on |
| +rerun: |
| + |
| +``` |
| +teardown_linux_test.go:80: the first teardown left 1 descriptors on the database open |
| +``` |
| + |
| +The test tears a non-HA replicator down (Close or Abandon), counts this |
| +process's descriptors on `app.db`, `app.db-wal` and `app.db-shm` through |
| +`/proc/self/fd`, and requires zero. It then calls Close or CloseProven again |
| +and requires ErrSpent, no bucket requests and still zero descriptors. |
| + |
| +## Root cause, with the evidence |
| + |
| +Nothing else opens the counted paths. Each subtest uses its own `t.TempDir()` |
| +database, and the package's tests cannot run in parallel (the lock fixture |
| +uses `t.Setenv`). The descriptor is the WAL, held by litestream v0.5.14's |
| +snapshot encoder: the goroutine `DB.SnapshotReader` starts (db.go:2368). It |
| +opens the WAL read-only, writes the snapshot into an `io.Pipe`, and closes the |
| +WAL in a `defer`. Nothing can join that goroutine. The store's snapshot |
| +monitor runs a pass at `Store.Open`. In the fixture's request log every run |
| +shows a `PUT .../0009/...` (the snapshot), interleaved with the test's own |
| +sync, so that pass is often still running when the test tears down. |
| + |
| +There are two outcomes. I reproduced both. |
| + |
| +1. **A delayed close (test only).** The encoder closes its pipe (success, |
| + or `CloseWithError` once `DB.Close` has nil'd `db.f`: logs show |
| + `write snapshot ltx: read database page 2: invalid argument` 739 times |
| + across the stress runs). The upload returns, `Store.Close`'s `wg.Wait` |
| + returns, and only after that does the encoder's deferred |
| + `walFile.Close()` run. The race window is between the pipe close and |
| + that `defer`. |
| + - Unchanged test under stress: 2 failures, both `app.db-wal`, both |
| + closed by the next scan ("immediately after 0, 200ms later 0"). |
| + - Deterministic: a scratch copy of litestream (via `-modfile` replace) |
| + that sleeps 100 ms before that `defer`'s close made the unchanged test |
| + fail 20/20 with the exact CI message. The fixed test passes 80/80 |
| + against the same copy. |
| + |
| +2. **A permanent leak (a production bug, #811 on non-HA stores).** If |
| + `Store.Close` cancels the monitor after litestream's |
| + `s3.ReplicaClient.WriteLTXFile` has peeked the LTX header |
| + (`ltx.PeekHeader`) but before the AWS uploader reads the body, the |
| + uploader's `partPool.Get(ctx)` (feature/s3/manager v1.20.18, |
| + upload.go:504) refuses the cancelled context. The upload then returns |
| + without reading the rest. litestream never closes the pipe, so the |
| + encoder blocks in `io.(*pipe).write` (inside `ltx.(*Encoder).EncodePage`) |
| + and holds the WAL descriptor and its goroutine for the life of the |
| + process. |
| + - Stress with the test-side fix only: 1 failure at the 30 s guard ("1 |
| + descriptors on .../app.db-wal after 30s"). |
| + - Deterministic: a scratch test cancelled the upload context once the |
| + header had been read, going through the real S3 client and the lock |
| + fixture. The WAL stayed open 3/3, and a goroutine dump showed the |
| + encoder blocked as described. |
| + |
| + The HA path was already guarded: `fenceGate.WriteLTXFile` closes the |
| + pipe, and so do `generationClient` and `snapshotWithin`. A plain non-HA |
| + store had no guard. |
| + |
| +## The fix |
| + |
| +- `internal/lease/snapshotpipe.go` (new): `pipeClosingClient` embeds |
| + `litestream.ReplicaClient`. Its `WriteLTXFile` closes an `*io.PipeReader` |
| + body on every outcome. |
| +- `internal/lease/lease.go:481` (`newStore`): every store's replica client |
| + is wrapped in `pipeClosingClient`. The HA fence gate still wraps the |
| + result in `Replicate`, and a double close of a `PipeReader` is harmless. |
| +- `internal/lease/teardown_linux_test.go`: |
| + - `tornDownFiles`: the database file and `-shm` must be closed as soon as |
| + the teardown returns. Any open SQLite connection, and litestream's own |
| + `db.f`, holds a descriptor on the database file, so these are checked |
| + at once. Only the WAL is waited on, through `WaitDescriptorsForTest` |
| + (the package's #1193 helper, 30 s guard). |
| + - The second-call check in `TestTeardownIsTerminal` is unchanged and |
| + still immediate. By then the encoder has closed its WAL, and a reopen |
| + (DB.init) holds descriptors that do not go away. |
| + - `TestTeardownReleasesACancelledSnapshot` (new): wraps the real S3 |
| + client (`lease.ReadReplicaClient` against the lock fixture) so that the |
| + snapshot upload's context is cancelled once the header has been read. |
| + It asserts the upload really was cancelled (`context.Canceled`), then |
| + Abandons and calls `tornDownFiles`. With `newStore` reverted to the bare |
| + client it fails at the guard ("the teardown left the WAL open: 1 |
| + descriptors ... after 30s"). With the fix it passes. |
| +- Census: envelope `internal/lease` re-pinned; no unit changed |
| + (`docs/superpowers/notes/census-proposal-flake-lease-teardown.md`). |
| + |
| +## Verification run (docs-t1, load average about 55 on 16 cores) |
| + |
| +| Run | Result | |
| +|---|---| |
| +| Before: `go test ./internal/lease -run TestTeardownIsTerminal -count=200` | ok (0/800 subtests) | |
| +| Before: test binary, `-test.count=300`, GOMAXPROCS 1/2/4 at once | 1/3600 subtests failed (WAL, delayed close) | |
| +| Before: 4 processes at GOMAXPROCS=4, `-test.count=300` | 1/4800 failed (WAL, delayed close) | |
| +| Test-side fix only: 7 processes, `-test.count=300` | 1/8400 failed (WAL still open after 30 s: the leak) | |
| +| Both fixes: 8 processes (GOMAXPROCS 1, 2, 4×6), `-test.count=300`, both tests | 0/9600 + 0/2400 | |
| +| Both fixes: `go test ./internal/lease -count=3` (whole package) | ok, 466.9 s | |
| +| Mutation: never close the encoder's WAL (scratch litestream) | fixed test fails at the 30 s guard | |
| +| Mutation: drop the `tornDown` guards in `beginClose` and `guardedSync` | all 4 subtests fail at the second check (requests, 5 descriptors) | |
| +| Mutation: Abandon skips `store.Close` | abandon subtests fail at once ("4 descriptors on the database or its -shm") | |
| +| `go test ./internal/provision -run Census` | failed (envelope), re-pinned, then ok | |
| +| `make code-health` | PASS | |
| + |
| +`-race` on these tests fails on main and on this branch alike: 5 and 2 |
| +reports per 100 runs. The race is `DB.Close` writing `db.f` (db.go:802) |
| +while the encoder reads it (db.go:2099). This is the litestream-internal |
| +race that `.amadan/ci.d/70-race` already gives as the reason |
| +`internal/lease` is left out of the race step (fixed upstream in v0.5.18). |
| +This branch neither causes nor fixes it. |
| + |
| +## What to check |
| + |
| +1. Is the root cause right? Is there any other way the counted paths could |
| + have a descriptor open after a teardown that the fix does not cover? |
| +2. `tornDownFiles`: does checking the database file and `-shm` at once still |
| + catch every real teardown leak, and is waiting on the WAL alone sound? |
| + Could an immediate count of the database file ever see a descriptor that |
| + closes asynchronously too? |
| +3. `pipeClosingClient`: is closing the pipe after a successful |
| + `WriteLTXFile` always safe for every client in use (S3, `lsfile`, |
| + `generationClient`, `fenceGate`, the compactor's own pipes)? It hides the |
| + inner client's optional `ReplicaClientV3`. Confirm nothing restores |
| + through a store's `db.Replica`, and that no other optional interface or |
| + concrete-type assertion on `db.Replica.Client` is lost. |
| +4. Under v0.5.18, which stops the monitors before closing the databases, |
| + the cancellation path in item 2 of the root cause becomes more likely, |
| + not less. Is the wrapper still the right layer for that? |
| +5. Does `TestTeardownReleasesACancelledSnapshot` go through production |
| + wiring (`Held.Replicate`, `newStore`, the real S3 client and uploader), |
| + and is it impossible for it to pass vacuously? It asserts the snapshot |
| + upload was cancelled before tearing down. |
| +6. Census: is the `internal/lease` envelope re-pin acceptable (no root-read |
| + change)? |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, won't compile, a test fails, or it won't work. |
| +- **P2**: wrong or missing; can be fixed without reopening the design. |
| +- **P3**: polish. |
| + |
| +## Output contract |
| + |
| +List findings ranked P1, then P2, then P3, each with `file:line` and a |
| +one-line fix. End with exactly one of: **READY**, **READY AFTER FIXES**, |
| +**NOT READY**. Do not edit files. Do not run full suites; targeted |
| +`go test ./internal/lease -run '<name>'` runs are fine. |
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..7fabd2535 100644 |
| --- a/internal/lease/teardown_linux_test.go |
| +++ b/internal/lease/teardown_linux_test.go |
| @@ -3,10 +3,19 @@ |
| package lease_test |
| import ( |
| + "context" |
| "errors" |
| + "fmt" |
| + "io" |
| "os" |
| "path/filepath" |
| + "runtime" |
| + "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 +25,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 +42,39 @@ 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 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() |
| + 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 }) |
| + } |
| +} |
| + |
| // 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 +117,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 +127,152 @@ 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 |
| +} |
| + |
| +// 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. The first |
| +// snapshot's upload is reported on done. |
| +type cancelledSnapshot struct { |
| + litestream.ReplicaClient |
| + 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 <- 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 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" |
| + 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 cancelledUpload, 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) |
| + } |
| + var up cancelledUpload |
| + select { |
| + 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) |
| +} |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index 33351eace..db17bb86b 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -252,3 +252,4 @@ plan14-root-reads-staticcheck-sa1012.tsv 5fcd060180e923773dad3faee7cc60ee250779a |
| plan14-root-reads-staticcheck-sa1019.tsv f9be26c06eb1c844b91a75f65faa51997048cb2900f3ed078be2ae28c65c0e98 |
| plan14-root-reads-small-fixes-1246-1248.tsv c6d366dcf2211b714977b7a69180289555b362dfe5f36a5780af90b5ece82998 |
| plan14-root-reads-edge-ppv2-idle.tsv 5d4a5eea79394145fdd59aa5eb87115cc1ee396e02e0ab4b21decd2b3a10e3b4 |
| +plan14-root-reads-flake-lease-teardown.tsv 5d4a5eea79394145fdd59aa5eb87115cc1ee396e02e0ab4b21decd2b3a10e3b4 |
diff --git a/internal/provision/testdata/plan14-root-reads-flake-lease-teardown.tsv b/internal/provision/testdata/plan14-root-reads-flake-lease-teardown.tsv| new file mode 100644 |
| index 000000000..fbc2ef5c4 |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-flake-lease-teardown.tsv |
| @@ -0,0 +1,3 @@ |
| +# Census overlay flake-lease-teardown, written by census-propose (#369). census-ruling-flake-lease-teardown, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-flake-lease-teardown.md. |
| +# 0 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +@coverage internal/lease 1af3b69b91061e6f593bc4df2756308fb4befed1fba5b4b41adff42254426a81 |