Skip to content

test: stabilize four flaky CI tests - #1352

Merged
lklimek merged 4 commits into
v1.6-devfrom
fix/flaky-ci-tests
Jun 17, 2026
Merged

lklimek merged 4 commits into
v1.6-devfrom
fix/flaky-ci-tests

Conversation

@lklimek

@lklimek lklimek commented Jun 17, 2026

Copy link
Copy Markdown
Collaborator

Summary

Stabilizes four tests that intermittently fail in CI due to timing/race artifacts unrelated to the code under test. Each change addresses the root cause rather than masking the symptom.

Fixes

  • types.TestStateID_Copy — the test mutated AppHash[5] = 0x12, a no-op (~1/256) when RandStateID already produced 0x12, making assert.NotEqual flake. Now mutates with bitwise-NOT (^=), guaranteed to differ.
  • abci/client.TestSocketClientTimeout/immediate — rescaled the base timeout (10ms → 50ms) so the serialized two-request socket round-trip has adequate headroom under race-detector + CI load. All cases keep their relative semantics (success cases still sleep < timeout, failures > timeout).
  • cmd/tenderdash/commands.TestRollbackIntegration — close the kvstore app on cleanup (it kept writing to the data dir after node shutdown) and add a bounded retry around data-dir removal to absorb goleveldb's post-Wait() flush window, eliminating the directory not empty TempDir cleanup race.
  • internal/consensus.TestReactorValidatorSetChanges — harden waitForAndValidateBlock's failure path: treat any non-nil context error (not just DeadlineExceeded) as failure, and guard a nil block so it reports the failing node instead of panicking and crashing the whole test binary (which cascaded into unrelated tests in the shard).

Verification

Each test stress-run under the race detector: TestStateID_Copy 100/100, TestSocketClientTimeout 50/50, TestRollbackIntegration 20/20, TestReactorValidatorSetChanges 5/5.

🤖 Generated with Claude Code

lklimek and others added 4 commits June 17, 2026 10:23
RandStateID fills AppHash with random bytes. The test mutated
AppHash[5] to a fixed constant (0x12); whenever the random byte at
that index already equaled the constant, the assignment was a no-op,
the copy stayed equal to the original, and assert.NotEqual failed
(~1/256 of runs). Flip the byte's bits instead, guaranteeing the
mutated value always differs from the original.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…uate timeout margin

The no-delay 'immediate' case used timeout == baseTime == 10ms, so the
request's deadline had to absorb the entire fixed cost of a socket
round-trip (goroutine scheduling + the serialized Info+CheckTx requests
over the unix socket) under -race on a loaded CI host. That overhead can
exceed 10ms, tripping the deadline before the response arrives and
failing require.NoError with 'context deadline exceeded'.

baseTime is the unit every case scales from, defining cases by their
relative timing. Raise it 10ms -> 50ms: this preserves every case's
semantics (success keeps sleep < timeout, failure keeps sleep > timeout)
while giving all margins — including the immediate case's overhead
budget — 5x more headroom. Max per-subtest sleep stays at 200ms, well
under the 1s parent context.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… cleanup

The test intermittently failed in t.Cleanup with
'TempDir RemoveAll cleanup: unlinkat .../data: directory not empty'.

Both nodes are stopped via Wait() before the test returns, and OnStop
closes every node database (blockstore, state, evidence, peer, tx_index)
and waits all reactors — so teardown is correct. But as goleveldb and
other background resources under <RootDir>/data flush and release on
shutdown they can momentarily create files, and t.TempDir's automatic
cleanup does a single-shot RemoveAll that fails the whole test if it
races one such transient write.

Remove RootDir ourselves first, with a bounded retry, once every node
has stopped (registered after the t.TempDir cleanup, so it runs before
it via LIFO). Transient races are absorbed by the retry; a genuine leak
still fails the test once the ~2s budget is exhausted. Also close the
shared kvstore app, the one resource the test never released.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
waitForAndValidateBlock spawns one worker per node and only treats a
context DeadlineExceeded as fatal. A worker can also bail out with a nil
block when its subscription is terminated without a context error (for
example its buffer overflows because consensus raced ahead while another
node stalled). The function then returned a slice with nil entries that
the caller dereferenced (firstBlock.ValidatorsHash, block.Height),
panicking — which crashes the whole package test binary and fails every
other test in the CI shard rather than just this one.

Fail cleanly instead: treat any context error as the timeout, and assert
every node delivered a block, naming the offending node. This contains a
rare stall to a single, clearly-diagnosable test failure.

NOTE: this hardens the failure behaviour; it does not eliminate the
underlying rare wedge. Root-caused via a captured 120s failure: a node
that briefly falls behind around a validator-set-change boundary (stuck
at the block before a vals removal) fails to recover via consensus
catch-up gossip while the unthrottled network races hundreds of blocks
ahead. That is a consensus-reactor catch-up limitation across validator
set transitions and needs a separate, dedicated production fix.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@lklimek
lklimek requested a review from QuantumExplorer as a code owner June 17, 2026 09:54
@thepastaclaw

thepastaclaw commented Jun 17, 2026 •

Copy link
Copy Markdown

✅ Review complete (commit ecc8092)

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 stabilizes four intermittently flaky CI tests by removing nondeterministic assertions, adding more robust failure handling, and increasing timing headroom where tests depend on real socket round-trips and shutdown/cleanup ordering.

Changes:

  • Make TestStateID_Copy deterministically mutate AppHash to avoid rare no-op mutations.
  • Harden waitForAndValidateBlock failure paths to fail cleanly on any context error and avoid nil-block panics.
  • Reduce rollback integration test flakiness by explicitly closing the kvstore app and retrying data-dir removal to absorb goleveldb flush windows.
  • Increase the base timeout unit in socket client timeout tests to better tolerate CI/race-detector overhead while preserving relative case semantics.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.

File Description
types/block_test.go Makes the state mutation deterministic to eliminate a probabilistic equality/inequality flake.
internal/consensus/reactor_test.go Improves timeout/cancel handling and adds nil-guarding to prevent panics that cascade into unrelated test failures.
cmd/tenderdash/commands/rollback_test.go Adds explicit resource shutdown and bounded retry cleanup to avoid TempDir cleanup races with background flushes.
abci/client/socket_client_test.go Increases timing headroom for socket round-trips under CI load while keeping test-case relationships intact.

@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 focused set of test stabilizations with no production code changes. Verified each delta hits a real root cause (timeout headroom, goleveldb shutdown race, nil-block panic, deterministic mutation). One minor wording nitpick on the reactor test fail message; no blockers.

💬 1 nitpick(s)

Comment thread internal/consensus/reactor_test.go Resolved
@lklimek
lklimek merged commit 3278d27 into v1.6-dev Jun 17, 2026
17 checks passed
@lklimek
lklimek deleted the fix/flaky-ci-tests branch June 17, 2026 10:26
lklimek added a commit that referenced this pull request Jun 24, 2026
…eReplayNone (#1367)

* fix(consensus,autofile): prevent TempDir race in TestHandshakeReplayNone

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

* fix(consensus,autofile): cancel goroutine ctx in OnStop to prevent Wait 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]>

* chore(lint): fix misspellings flagged by golangci-lint

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

* fix(consensus): cancel ctx before Wait in replay test cleanups to prevent 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]>

* refactor(autofile): override Group.Wait to join background goroutines 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]>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
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