Repository navigation
fix(consensus,autofile): prevent TempDir cleanup race in TestHandshakeReplayNone - #1367
Conversation
The test was intermittently failing with: testing.go:1464: TempDir RemoveAll cleanup: unlinkat /tmp/TestHandshakeReplayNone.../data: directory not empty Root cause: BaseWAL.Wait() and Group.Wait() only wait on their internal service srvCtx, but processFlushTicks (WAL) and processTicks (Group) are started with the caller-supplied context and exit on ctx.Done() — not on the service srvCtx. In the fast-path (background goroutine already called Stop()), Wait() returned immediately while those goroutines were still mid-execution and could re-open the AutoFile (via openFile()) after the caller assumed the WAL was fully stopped, racing with t.TempDir() cleanup. Fixes applied: - autofile.Group: add goroutineWg (sync.WaitGroup) to track processTicks; expose WaitForGoroutines() that blocks until it has truly exited. - BaseWAL: add goroutineWg to track processFlushTicks; Wait() now calls group.WaitForGoroutines() and wal.goroutineWg.Wait() so all goroutines have exited before the caller can delete temp directories. - replay_test.go / testHandshakeReplay: call wal.Stop() explicitly before wal.Wait() in the cleanup hook so OnStop() (which marks the AutoFile closed) runs synchronously from the cleanup goroutine. - replay_test.go: add missing t.Cleanup for eventBus, buildTMStateFromChain proxyApp/eventBus, and buildAppStateFromChain appClient so services are properly drained before TempDir removal. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
…it deadlock
The previous fix introduced a deadlock: processFlushTicks (BaseWAL) and
processTicks (Group) exited on the caller-supplied ctx, but Stop()/OnStop()
only cancelled the service-internal srvCtx — not the caller ctx. Calling
Wait() (which now blocks on goroutineWg) before the caller ctx was cancelled
would hang forever.
Failing case: TestWALWriteCommit registers `defer cancel()` first (runs
last in LIFO) and `defer { wal.Stop(); wal.Wait() }` second (runs first),
so Wait() blocked with the goroutine stuck in select on an uncancelled ctx.
Production path: state.go receiveRoutine calls wal.Stop() + wal.Wait() in
onExit() without guaranteeing the caller ctx has fired — same deadlock.
Fix: in OnStart, derive a child context (context.WithCancel(ctx)) and store
the cancel func as procCancel on the struct. OnStop calls procCancel() first,
which causes the goroutine to exit on its next select iteration. The child
context inherits cancellation from the parent, so the existing "also exit
when caller ctx cancels" behaviour is preserved.
After this change: Stop() → OnStop() → procCancel() → goroutine exits →
goroutineWg.Wait() / WaitForGoroutines() unblock promptly, regardless of
whether the original caller ctx has been cancelled. The BaseService contract
(Stop precedes Wait) is now unconditionally safe at every call site.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
@thepastaclaw please review — this fixes a production WAL/autofile shutdown-lifecycle bug (Wait() returned before background flush goroutines exited, allowing writes-after-shutdown). Independently verified; a deadlock found in review was fixed in be23ee0. 🤖 Co-authored by Claudius the Magnificent AI Agent |
Replace British spellings in comments added by the prior fix commit: - wal.go:169 behaviour → behavior - wal.go:204 cancelled → canceled - group.go:76 cancelled → canceled - group.go:154 behaviour → behavior Comments-only; no logic changes. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
Pull request overview
This PR addresses a shutdown race in consensus WAL / autofile background tick goroutines that could re-open temp WAL files after tests begin cleaning up t.TempDir(), and follows up with a context-cancellation fix intended to prevent shutdown deadlocks.
Changes:
- Track and cancel background tick goroutines in
autofile.Groupandconsensus.BaseWALusing a derived context +WaitGroup. - Extend
BaseWAL.Wait()to also wait for non-BaseService goroutines (processFlushTicks/processTicks) to fully exit. - Update
TestHandshakeReplayNonecleanup to explicitlyStop()the WAL beforeWait(), and add additional test cleanups.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
| internal/libs/autofile/group.go | Add derived cancel context + WaitGroup for processTicks, and expose WaitForGoroutines() for callers to join. |
| internal/consensus/wal.go | Add derived cancel context + WaitGroup for processFlushTicks, and extend Wait() to join both WAL + Group tick goroutines. |
| internal/consensus/replay_test.go | Adjust WAL cleanup ordering and add cleanups for started services in replay tests. |
|
@thepastaclaw please review |
|
✅ Review complete (commit a742b88) |
thepastaclaw
left a comment
There was a problem hiding this comment.
Code Review
The PR correctly fixes the TempDir cleanup race by adding a tracked WaitGroup and child cancel context to BaseWAL and autofile.Group, and the follow-up commit correctly resolves the deadlock regression that would have surfaced when state.go's receiveRoutine.onExit calls wal.Stop()+wal.Wait(). Two newly added test cleanups in helpers (buildAppStateFromChain, buildTMStateFromChain) register bare Wait without any Stop() or cancel(), which works on the happy path but can deadlock cleanup on failure paths and degrade diagnosis — directly contradicting the spirit of this PR. No consensus-, signing-, or wire-format-affecting changes.
🟡 2 suggestion(s)
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.
In `internal/consensus/replay_test.go`:
- [SUGGESTION] internal/consensus/replay_test.go:864-865: Bare appClient.Wait cleanup can hang on test failure paths
`t.Cleanup(appClient.Wait)` registers only a Wait, with no paired `Stop()` or `cancel()`. `appClient.Wait()` returns only after BaseService.Stop has been invoked, which here happens indirectly when the test ctx is cancelled. On the happy path the outer `t.Cleanup(func() { cancel(); proxyApp.Wait() })` registered later at line 795 runs first (LIFO) and cancels ctx, eventually unblocking this Wait.
If any `require` between buildAppStateFromChain returning (line 776) and the line-795 cleanup being registered fires — e.g. line 792's `proxyApp.Start` failing — cleanups run LIFO without that outer cancel cleanup present. This Wait runs while ctx is still live and nothing is on the way to Stop the service, so it blocks until `go test -timeout` kills the test, masking the real failure.
This is contrary to the explicit `cancel(); Stop(); Wait()` pattern this PR adopts at line 718 (wal cleanup) and is the kind of fragile shutdown hygiene the PR is trying to eliminate. Stop the client explicitly before Wait.
- [SUGGESTION] internal/consensus/replay_test.go:927-928: Bare proxyApp.Wait cleanup can hang on test failure paths
Same defect as the buildAppStateFromChain cleanup: `t.Cleanup(proxyApp.Wait)` registers only a Wait with no paired Stop or cancel. If any later `require` inside buildTMStateFromChain (InitChain at line 932, stateStore.Save at line 937, applyBlock loop, etc.) fails, cleanups run LIFO and this Wait executes while ctx is still alive, with no Stop on the way, blocking until the go test timeout fires.
Match the PR's own Stop-before-Wait invariant by stopping the proxy app explicitly before waiting.
…vent cleanup deadlock Two test helpers in internal/consensus/replay_test.go registered a bare t.Cleanup(*.Wait): - buildAppStateFromChain: t.Cleanup(appClient.Wait) - buildTMStateFromChain: t.Cleanup(proxyApp.Wait) Both appClient and proxyApp are abciclient.Client *interface* values. The service.Service interface only exposes Start/IsRunning/Wait — there is NO Stop() on the interface (it lives on the concrete *BaseService struct). A service is therefore stopped by canceling the context passed to Start(): BaseService.Start spawns a watcher goroutine that calls Stop()->OnStop() when that ctx is canceled, which unblocks Wait(). Consequently a bare Wait() returns only after the caller's ctx is canceled. t.Cleanup runs LIFO, so the helper's Wait() can run BEFORE the caller's cancel() cleanup (or before a deferred cancel if a require fails early), blocking until `go test -timeout` kills the run. Fix: each helper now derives its own child context (context.WithCancel) and cancels it in its cleanup before Wait(), making the helper self-contained regardless of caller cleanup ordering. This matches the cancel()+Wait() pattern already used elsewhere in the file. The team-lead's pasted appClient.Stop()/proxyApp.Stop() snippet would NOT compile — Stop() is not on the interface — so context cancellation is the API-correct mechanism. Note on the CI RED for PR #1367: the failing job (tests (01)) was NOT this deadlock and NOT TestHandshakeReplayNone. It was TestReactorValidatorSetChanges timing out (reactor_test.go:628 context deadline exceeded; node 4 missed the block during a validator-set transition). That test is a long-standing, non-deterministic flake across the tendermint/cometbft/tenderdash lineage (see #1204, #1352, upstream #7985/#3401 and the "fails-non-deterministically" branch) and passes locally x2 with -race on this head. The WAL/autofile goroutine-lifecycle changes only affect Stop/Wait behavior and cannot cause a consensus-layer vote-index mismatch. The CI failure is an UNRELATED FLAKE; a re-run should pass. This commit still lands the latent-deadlock cleanup fix flagged by the bot reviewers (copilot-pull-request-reviewer + thepastaclaw). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
thepastaclaw
left a comment
There was a problem hiding this comment.
Code Review
PR is a sound fix for the WAL/autofile TempDir cleanup race: child contexts + WaitGroups let Stop()/Wait() drain background ticker goroutines independently of the caller ctx. Consensus-critical behavior (on-disk WAL frame format, FlushAndSync-on-stop, signing, BFT) is unchanged. One API-hygiene suggestion: the new goroutine wait is only exposed via a separate WaitForGoroutines() method, so Group.Wait() still returns before processTicks has fully exited — fine for the current sole consumer (BaseWAL chains both), but a footgun for future direct Group callers.
🟡 1 suggestion(s)
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.
In `internal/libs/autofile/group.go`:
- [SUGGESTION] internal/libs/autofile/group.go:165-170: Fold WaitForGoroutines into Group.Wait so the standard service API has the corrected semantics
Group embeds service.BaseService, and BaseService.Wait() returns as soon as cancel() closes the quit channel after OnStop() finishes (libs/service/service.go:153-194). The newly added goroutineWg only drains when callers know to also invoke WaitForGoroutines(). BaseWAL.Wait() correctly chains both (wal.go:239), but any other code that holds a *Group and calls g.Wait() — including future callers, or anyone copying the existing patterns — still observes the pre-PR behavior where processTicks is exiting but not yet joined, which is exactly the race this PR is fixing. Override Wait() on Group so the service's normal wait API is safe by default, and keep WaitForGoroutines() as the explicit form for callers that want only the goroutine half.
|
@thepastaclaw please re-review — both bare- Note: the prior CI red on 🤖 Co-authored by Claudius the Magnificent AI Agent |
… by default Group embeds service.BaseService, whose Wait() returns as soon as OnStop() closes the quit channel — before the procCancel-driven processTicks goroutine (tracked by goroutineWg) is joined. The PR added WaitForGoroutines() for that join, but only BaseWAL.Wait() knew to chain it; any other direct caller of g.Wait() still observed the pre-PR shutdown race (a flush/check tick could touch the file after the caller believed the Group was fully stopped). Override Wait() on *Group to chain BaseService.Wait() + WaitForGoroutines(), so every consumer gets the full shutdown guarantee. WaitForGoroutines() is kept as the explicit form. The override calls g.BaseService.Wait() (the embedded method), not g.Wait(), so there is no recursion; goroutineWg.Wait() is idempotent, so BaseWAL.Wait()'s existing explicit WaitForGoroutines() call (now also reached via group.Wait()) is harmless. Only direct (*Group).Wait() caller is BaseWAL.Wait() (guarded by IsRunning()); no semantic break and no new deadlock (OnStop calls procCancel before the quit channel closes, so the join always unblocks). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
thepastaclaw
left a comment
There was a problem hiding this comment.
Code Review
Targeted goroutine-lifecycle fix for the WAL/autofile.Group cleanup race against t.TempDir(). The two-commit structure correctly addresses the race without reintroducing the BaseService Wait deadlock, and the Group.Wait() override ensures direct Group consumers get the same shutdown guarantee as BaseWAL. No consensus-critical or security-relevant paths are touched. Two minor in-scope nitpicks about clarity/consistency; no blockers.
💬 2 nitpick(s)
| // Wait for context-driven goroutines that are not tracked by BaseService. | ||
| wal.group.WaitForGoroutines() | ||
| wal.goroutineWg.Wait() |
There was a problem hiding this comment.
💬 Nitpick: Add an inline note explaining why WaitForGoroutines() is called after group.Wait()
After commit a742b88, Group.Wait() now invokes WaitForGoroutines() internally, so in the common path the explicit wal.group.WaitForGoroutines() on line 239 looks like a redundant second wait. It is in fact still needed for the case where wal.group.IsRunning() is false (the group.Wait() branch is skipped, but a processTicks goroutine spawned earlier may still be unwinding). The doc block above explains the high-level rationale but does not call out why both calls coexist; a one-line comment at line 239 would prevent a future reader from "simplifying" the call away and re-introducing the TempDir race this PR fixes.
source: ['claude']
| ctx, cancel := context.WithCancel(ctx) | ||
| // start a new app without handshake, play nBlocks blocks | ||
| require.NoError(t, appClient.Start(ctx)) | ||
| t.Cleanup(func() { | ||
| cancel() | ||
| appClient.Wait() | ||
| }) |
There was a problem hiding this comment.
💬 Nitpick: Mixed cleanup styles in nearby helpers (eventBus uses Stop+Wait, proxyApp/appClient use cancel+Wait)
The new helper-owned cleanups for appClient (lines 873-876) and proxyApp (lines 947-950) use cancel(); X.Wait() with a long-form comment explaining that abciclient.Client has no Stop() on the service interface. The neighboring eventBus cleanups (lines 753, 963) instead use eventBus.Stop(); eventBus.Wait(). Both are correct, but the inconsistency in adjacent code invites future readers to copy the wrong pattern for a service that doesn't expose Stop(). Either align the eventBus cleanups with the cancel+Wait pattern (eventBus does expose Stop, so Stop+Wait remains valid) or add a short note that the eventBus path is intentional because Stop is available.
source: ['claude']
Summary
Two commits fixing a TempDir cleanup race in
TestHandshakeReplayNone— and a follow-up fixing a deadlock the first commit introduced.Commit 1 — root cause fix
BaseWAL.Wait()/Group.Wait()returned whileprocessFlushTicks/processTicksgoroutines were still mid-tick and could re-open the AutoFile (openFile()withO_CREATE), racing witht.TempDir()cleanup →ENOTEMPTY.goroutineWg sync.WaitGrouptoBaseWALandautofile.Groupto track those goroutines.BaseWAL.Wait()now callsgroup.WaitForGoroutines()+wal.goroutineWg.Wait()afterBaseService.Wait().wal.Stop()beforewal.Wait()in cleanup hook; missingt.Cleanupadded foreventBus,buildTMStateFromChainproxyApp/eventBus,buildAppStateFromChainappClient.Commit 2 — deadlock fix (⚠️ addresses QA finding)
The first commit introduced a deadlock: both goroutines exited on the caller-supplied ctx, but
Stop()/OnStop()only cancelled the service-internal srvCtx — not the caller ctx.Wait()(blocking ongoroutineWg) would hang forever if called before the caller ctx was cancelled.Failing call sites:
TestWALWriteCommit:defer cancel()registered first (LIFO → runs last),defer { wal.Stop(); wal.Wait() }registered second (runs first) → hang.state.go receiveRoutineonExit(): callswal.Stop(); wal.Wait()with no guarantee caller ctx has fired → production regression.Fix: in
OnStart, deriveprocCtx, procCancel := context.WithCancel(ctx), storeprocCancelon the struct, run goroutines withprocCtx.OnStopcallsprocCancel()first — goroutine exits on next select,goroutineWg.Wait()unblocks promptly. Child ctx still inherits cancellation from parent, so "exit when caller ctx cancels" is preserved.After:
Stop()→OnStop()→procCancel()→ goroutine exits →Wait()returns. Safe at every call site regardless of caller ctx state.Test results (post commit 2, -race)
TestWALWriteCommit -timeout 60s→ PASS (0.046s, no hang)TestHandshakeReplayNone -race -count=2→ PASS (6.7s, no "directory not empty")./internal/libs/autofile/... -race -count=1→ PASSgo vet→ cleanReviewer notes
stdsync "sync"import alias ingroup.go— stdlibsyncis aliased becausego-deadlockalready occupies thesyncname in that file.WaitGroupcomes from stdlibsync;Mutex/RWMutexfromgo-deadlock.procCancelis never nil whengoroutineWg.Wait()is reached:goroutineWg.Add(1)only fires fromOnStart, andOnStartalways setsprocCancelbeforeAdd(1).goroutineWg.Wait()is a no-op ifOnStartwas never called (counter stays 0).autofile.AutoFilehascloseFileRoutine/ SIGHUP goroutines signalled byaf.cancel()but not waited on. They only close FDs (cannot create files), so they are not part of this race — but a similar WaitGroup treatment would be good for goroutine-leak-test hygiene.🤖 Generated with Claude Code