Skip to content

test: stabilize flaky tests (rate-limit, evidence, privval-tcp) - #1339

Merged
lklimek merged 6 commits into
v1.6-devfrom
fix/test-stabilization
Jun 15, 2026
Merged

lklimek merged 6 commits into
v1.6-devfrom
fix/test-stabilization

Conversation

@lklimek

@lklimek lklimek commented Jun 13, 2026 •

Copy link
Copy Markdown
Collaborator

Issue being fixed or feature implemented

Three chronic flaky tests in the "Test" CI suite cause spurious red runs independent of code changes:

  • TestSendRateLimit flakes ~25%.
  • internal/evidence can hit the 5-min package timeout on any propagation stall.
  • TestNodeSetPrivValTCP races a tight 100ms timeout and (worse) calls require from a non-test goroutine (illegal FailNow/Goexit).

What was done?

  • T1 internal/p2p/client rate-limit test: replaced exact wall-clock/count assertions with tolerance bands. Production limiter unchanged; no new dependency.
  • T2 internal/evidence: replaced the unbounded waitForEvidence busy-wait with require.Eventually(30s) so a stall fails fast and localized instead of timing out the whole package.
  • T3 node TestNodeSetPrivValTCP: report the server-goroutine error over a channel checked on the test goroutine (fixes the illegal off-goroutine require), wait for listener-ready, and raise the 100ms timeout to 2s.

Test-only — no production behavior change. No new dependencies.

How Has This Been Tested?

-race loops: T1 30/30, T2 10/10, T3 40/40. go build ./..., go vet, gofmt, golangci-lint all clean (no new issues).

Breaking Changes

None — test-only.

Checklist:

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have added or updated relevant unit/integration/functional/e2e tests
  • I have made corresponding changes to the documentation

For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

🤖 Co-authored by Claudius the Magnificent AI Agent

Summary by CodeRabbit

  • Tests
    • Enhanced test robustness with improved goroutine safety and error propagation in multiple test suites.
    • Refined timing assertions for more stable and reliable test execution.

lklimek and others added 3 commits June 13, 2026 21:12
…rate-limit test

parallelSendWithLimit asserted elapsed == 3.0 s exactly via math.Floor, which
flaked (~25%) under load because the wall-clock can drift by several hundred
milliseconds.  assertRateLimits asserted exact token counts, which flaked
when the token bucket refill landed 1 token off due to scheduler jitter.

Replace both with tolerance bands:
- elapsed: GreaterOrEqual(3s) / LessOrEqual(3+2 s) instead of exact equality
- per-peer counts: ±1 slack around the expected value

No production code changed. No new dependencies added.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…imeout)

The inner loop in waitForEvidence had no timeout: any propagation stall
would spin until the 5-minute go test package deadline killed the process,
producing an opaque timeout rather than a useful failure message.

Replace the bare for-loop with require.Eventually (30 s / 100 ms), which
gives a clear diagnostic message and respects test deadlines.  The success
condition is unchanged.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…odeSetPrivValTCP

Two bugs in TestNodeSetPrivValTCP:
1. A spawned goroutine called require.NoError(t, signerServer.Start(ctx)), which
   calls runtime.Goexit on the wrong goroutine — undefined behaviour per the
   testify docs.  Fixed by sending the error on a buffered channel and asserting
   on the test goroutine after the server is confirmed running.
2. The TCP dial/read-write timeout was 100 ms, too tight for cold -race CI.
   Raised to 2 s.  Added require.Eventually to wait for IsRunning before
   the client dials, so there is no race between goroutine scheduling and
   the connection attempt.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 13, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Three test files are updated to fix flaky behavior. waitForEvidence in the evidence reactor test is refactored to return errors instead of asserting inside goroutines, using a buffered channel to collect results on the main test goroutine. TestNodeSetPrivValTCP in the node test applies the same goroutine-safe pattern for signer server startup and increases the TCP dial timeout to 2s. The rate limit test removes exact timing and count assertions in favor of upper-bound and ±1 tolerance checks.

Changes

Test Flakiness Fixes

Layer / File(s) Summary
Goroutine-safe waitForEvidence helper
internal/evidence/reactor_test.go
Inner polling function refactored to return error with a 30s deadline and reflect.DeepEqual mismatch detection. Single-ID path calls synchronously; multi-ID path fans out goroutines that send results to a buffered errCh, with all require.NoError calls on the main test goroutine.
TestNodeSetPrivValTCP goroutine-safe startup
node/node_test.go
TCP dialer timeout increased from 100ms to 2s. signerServer.Start(ctx) is launched in a goroutine that sends its return value over a buffered channel; main goroutine polls IsRunning() with a 5s timeout and reads any early error from the channel.
Rate limit test: relaxed assertions
internal/p2p/client/ratelimit_test.go
Unused math import removed. Elapsed-time check changed to an upper-bound-only assertion. Per-peer message count check loosened to ±1 tolerance.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐇 No more failing from a side-thread's squeak,
Errors now travel the channel they seek.
Timeouts extended, tolerances wide,
The flaky tests finally step aside.
With errCh and polling, the tests hold tight—
This rabbit hops forward, the CI glows bright! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately captures the main objective: stabilizing three flaky tests across rate-limit, evidence, and privval-tcp components.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/test-stabilization

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 and usage tips.

@lklimek
lklimek requested a review from Copilot June 13, 2026 19:35
@lklimek
lklimek marked this pull request as ready for review June 13, 2026 19:36
@lklimek
lklimek requested a review from QuantumExplorer as a code owner June 13, 2026 19:36

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 aims to stabilize three chronically flaky tests by reducing sensitivity to timing jitter and avoiding long-running package-level timeouts, without changing production behavior.

Changes:

  • internal/p2p/client: loosened rate-limit test assertions to tolerate scheduling jitter and slow CI.
  • internal/evidence: replaced an unbounded busy-wait loop with a bounded require.Eventually wait.
  • node: fixed TestNodeSetPrivValTCP to avoid calling require from a non-test goroutine and increased tight TCP timeouts.

Reviewed changes

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

File Description
node/node_test.go Increases dial/read-write timeouts and routes server start errors back to the test goroutine.
internal/p2p/client/ratelimit_test.go Replaces exact wall-clock/count assertions with tolerance bands to reduce flakiness.
internal/evidence/reactor_test.go Converts evidence propagation waiting to a bounded Eventually-based wait to fail fast instead of timing out the package.

Comment thread internal/evidence/reactor_test.go Outdated
Comment on lines 149 to 153
require.Eventually(t, func() bool {
var size int64
localEvList, size = pool.PendingEvidence(int64(len(evList) * 1000))
time.Sleep(time.Millisecond * 100)
t.Log("current wait status:", "|",
"local", len(localEvList), "|",
Comment thread node/node_test.go Resolved
lklimek and others added 3 commits June 13, 2026 22:01
Replace require.Eventually and require.Equalf inside fn (which was dispatched
to spawned goroutines) with a plain time-bounded poll loop that returns an error.
Goroutines send errors to a buffered channel; assertions happen on the test
goroutine after wg.Wait(), satisfying Go's testing package contract that
t.FailNow must not be called from non-test goroutines.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Replace the non-blocking channel drain (which ran after require.Eventually and
could never be reached on Start failure) with a poll loop on the test goroutine
that checks startErrCh on every tick. A Start() failure now surfaces with its
actual error rather than a generic "did not start in time" timeout message.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
The lower-bound check (elapsed >= testTimeSeconds) was guaranteed to pass by
the preceding time.Sleep, making it a no-op. Remove it and add a comment
explaining why; keep only the meaningful upper-bound check (+2 s CI slack).

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@lklimek

lklimek commented Jun 14, 2026

Copy link
Copy Markdown
Collaborator Author

Review-round update (Marvin + Copilot)

Pushed fixes for this round's findings:

  • HIGH (fixed) — require.Eventually/require.Equalf ran inside a spawned (non-test) goroutine in waitForEvidence → illegal t.FailNow() from a non-test goroutine. Reworked to a time-bounded poll that reports via an error channel; all assertions now run on the test goroutine. Also fixed a latent interface-equality bug (!= compared pointers, not values → reflect.DeepEqual).
  • MEDIUM (fixed) — Start() error was masked behind the require.Eventually timeout in TestNodeSetPrivValTCP; now surfaced immediately with the real error.
  • LOW (fixed) — removed a trivially-true lower-bound elapsed-time assertion in the rate-limit test.

Note: a review flagged version/version.go + CHANGELOG.md as "non-test changes in a test-only PR" — that is a false positive. Those are the inherited base commit (#1337 release bump 58912eb) this branch is stacked on; they drop out once #1337 lands on v1.6-dev.

🤖 Co-authored by Claudius the Magnificent AI Agent

@coderabbitai coderabbitai Bot 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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/evidence/reactor_test.go (1)

152-180: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

waitForEvidence no longer fails when extra evidence appears (false-positive risk).

From Line 152 onward, polling stops when len(localEvList) >= len(evList), but the later map check only verifies expected hashes exist. That means extra evidence won’t fail the test, despite the comment saying it will. Add an explicit exact-length assertion before hash/content validation.

Suggested fix
 		for len(localEvList) < len(evList) {
 			...
 		}
+
+		if len(localEvList) != len(evList) {
+			return fmt.Errorf("unexpected evidence count: have %d, want %d",
+				len(localEvList), len(evList))
+		}
 
 		// put the reaped evidence in a map so we can quickly check we got everything
 		evMap := make(map[string]types.Evidence)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/evidence/reactor_test.go` around lines 152 - 180, The
`waitForEvidence` function polls until `len(localEvList) >= len(evList)`, but
the subsequent map-based validation only checks that expected evidence hashes
exist—it does not fail if extra evidence is present, contradicting the comment
that says it will catch extra evidence. Add an explicit length equality
assertion after the map is populated (around where `evMap` is created from
`localEvList`) to verify that `len(localEvList) == len(evList)` before or
immediately after iterating through the expected evidence in the final loop,
ensuring the test fails when unexpected extra evidence appears.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@internal/evidence/reactor_test.go`:
- Around line 152-180: The `waitForEvidence` function polls until
`len(localEvList) >= len(evList)`, but the subsequent map-based validation only
checks that expected evidence hashes exist—it does not fail if extra evidence is
present, contradicting the comment that says it will catch extra evidence. Add
an explicit length equality assertion after the map is populated (around where
`evMap` is created from `localEvList`) to verify that `len(localEvList) ==
len(evList)` before or immediately after iterating through the expected evidence
in the final loop, ensuring the test fails when unexpected extra evidence
appears.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 03258764-782f-4d1e-9e96-9316fabf5a6f

📥 Commits

Reviewing files that changed from the base of the PR and between 58912eb and 1aed10b.

📒 Files selected for processing (3)
  • internal/evidence/reactor_test.go
  • internal/p2p/client/ratelimit_test.go
  • node/node_test.go

@lklimek
lklimek merged commit 6b426dc into v1.6-dev Jun 15, 2026
16 checks passed
@lklimek
lklimek deleted the fix/test-stabilization branch June 15, 2026 08:06
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.

2 participants