Skip to content

fix(consensus,autofile): prevent TempDir cleanup race in TestHandshakeReplayNone - #1367

Merged
lklimek merged 6 commits into
v1.6-devfrom
fix/flaky-handshake-tempdir-cleanup
Jun 24, 2026
Merged

lklimek merged 6 commits into
v1.6-devfrom
fix/flaky-handshake-tempdir-cleanup

Conversation

@lklimek

@lklimek lklimek commented Jun 22, 2026 •

Copy link
Copy Markdown
Collaborator

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

  • Root cause: BaseWAL.Wait() / Group.Wait() returned while processFlushTicks / processTicks goroutines were still mid-tick and could re-open the AutoFile (openFile() with O_CREATE), racing with t.TempDir() cleanup → ENOTEMPTY.
  • Added goroutineWg sync.WaitGroup to BaseWAL and autofile.Group to track those goroutines.
  • BaseWAL.Wait() now calls group.WaitForGoroutines() + wal.goroutineWg.Wait() after BaseService.Wait().
  • Test: explicit wal.Stop() before wal.Wait() in cleanup hook; missing t.Cleanup added for eventBus, buildTMStateFromChain proxyApp/eventBus, buildAppStateFromChain appClient.

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 on goroutineWg) 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 receiveRoutine onExit(): calls wal.Stop(); wal.Wait() with no guarantee caller ctx has fired → production regression.

Fix: in OnStart, derive procCtx, procCancel := context.WithCancel(ctx), store procCancel on the struct, run goroutines with procCtx. OnStop calls procCancel() 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 → PASS
  • go vet → clean

Reviewer notes

  1. stdsync "sync" import alias in group.go — stdlib sync is aliased because go-deadlock already occupies the sync name in that file. WaitGroup comes from stdlib sync; Mutex/RWMutex from go-deadlock.
  2. procCancel is never nil when goroutineWg.Wait() is reached: goroutineWg.Add(1) only fires from OnStart, and OnStart always sets procCancel before Add(1).
  3. goroutineWg.Wait() is a no-op if OnStart was never called (counter stays 0).
  4. Follow-up opportunity: autofile.AutoFile has closeFileRoutine / SIGHUP goroutines signalled by af.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

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]>
@coderabbitai

coderabbitai Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 2c809a0e-bc83-464d-aa88-732df8f8de2f

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/flaky-handshake-tempdir-cleanup

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

…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]>
@lklimek
lklimek requested a review from Copilot June 22, 2026 14:51
@lklimek

lklimek commented Jun 22, 2026

Copy link
Copy Markdown
Collaborator Author

@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]>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.Group and consensus.BaseWAL using a derived context + WaitGroup.
  • Extend BaseWAL.Wait() to also wait for non-BaseService goroutines (processFlushTicks / processTicks) to fully exit.
  • Update TestHandshakeReplayNone cleanup to explicitly Stop() the WAL before Wait(), 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.

Comment thread internal/consensus/replay_test.go Resolved
Comment thread internal/consensus/replay_test.go Resolved
@lklimek
lklimek marked this pull request as ready for review June 22, 2026 15:21
@lklimek
lklimek requested a review from QuantumExplorer as a code owner June 22, 2026 15:21
@lklimek
lklimek requested a review from Copilot June 22, 2026 15:21
@lklimek

lklimek commented Jun 22, 2026

Copy link
Copy Markdown
Collaborator Author

@thepastaclaw please review

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 3 out of 3 changed files in this pull request and generated no new comments.

@thepastaclaw

thepastaclaw commented Jun 23, 2026 •

Copy link
Copy Markdown

✅ Review complete (commit a742b88)

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread internal/consensus/replay_test.go Resolved
Comment thread internal/consensus/replay_test.go Resolved
…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 thepastaclaw left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread internal/libs/autofile/group.go Resolved
@lklimek

lklimek commented Jun 24, 2026

Copy link
Copy Markdown
Collaborator Author

@thepastaclaw please re-review — both bare-Wait cleanup findings are addressed in e96b469. Implemented via a child context + cancel() rather than the literal .Stop() suggestion: appClient/proxyApp are abciclient.Client interfaces exposing only Start/IsRunning/Wait (Stop() is on the concrete *service.BaseService), so the paste wouldn't compile — canceling the Start() ctx drives the BaseService watcher → Stop()→OnStop()→Wait() returns, independent of t.Cleanup LIFO order.

Note: the prior CI red on tests (01) was an unrelated TestReactorValidatorSetChanges flake (catch-up-gossip wedge), not this PR — that's fixed by PR #1365.

🤖 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 thepastaclaw left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Comment thread internal/consensus/wal.go
Comment on lines +238 to +240
// Wait for context-driven goroutines that are not tracked by BaseService.
wal.group.WaitForGoroutines()
wal.goroutineWg.Wait()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💬 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']

Comment on lines +870 to +876
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()
})

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💬 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']

@lklimek
lklimek merged commit fc932bb into v1.6-dev Jun 24, 2026
16 checks passed
@lklimek
lklimek deleted the fix/flaky-handshake-tempdir-cleanup branch June 24, 2026 11:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants