Skip to content

fix(evidence): make evidence sync resilient to peer-routing race - #1366

Merged
lklimek merged 7 commits into
v1.6-devfrom
fix/flaky-evidence-reactor
Jun 24, 2026
Merged

lklimek merged 7 commits into
v1.6-devfrom
fix/flaky-evidence-reactor

Conversation

@lklimek

@lklimek lklimek commented Jun 22, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

TestReactorBroadcastEvidence_Committed was flaky under load (~1.5–3% failure
rate at 12-way concurrency). Root cause: PeerStatusUp fires before the p2p
router finishes wiring the channel route to the new peer. The one-shot
syncEvidence goroutine sent all pool evidence immediately, the sends returned
nil but envelopes were silently dropped, and the peer permanently missed
evidence that pre-dated its connection. broadcastEvidence only fires on
newly received evidence, so there was no self-heal path.

Fix

Convert the one-shot walk in syncEvidence to a ticker loop that re-sends
every evidenceSyncInterval (1 s) until the peer disconnects. Duplicates are
idempotent on the receiver side (isPending / isCommitted guards in
handleEvidenceMessage) — no protocol changes required.

QA-001 — Deterministic regression guard (TestSyncEvidenceRetries)

Wires a recording p2p.Channel stub and asserts that the same evidence is sent
more than once across ticker ticks (at 20 ms test interval, 150 ms window).
A pre-fix one-shot goroutine would send exactly numEv items and exit, making
count > numEv FAIL — this is a true regression gate.

QA-002 — Peer-flap lifecycle race

With a long-running goroutine (ticker loop), the window where a stale goroutine
and a new one coexist on Down→Up grew. Fixed by:

  1. PeerStatusDown: delete the map entry synchronously (not left for the
    goroutine's deferred cleanup), so a fast Down→Up reconnect always starts
    fresh.
  2. syncEvidence carries a unique identity token (*struct{}); its deferred
    cleanup only removes the map entry if the stored token still matches —
    prevents it from evicting a new goroutine's entry.

QA-003/004 — Documentation & interval

  • doc.go: removed stale broadcastEvidenceIntervalS / 60 s reference;
    documents both propagation paths (per-peer sync loop + broadcast on new
    evidence).
  • reactor.go: evidenceSyncInterval changed from const to var (allows
    test override via SetEvidenceSyncIntervalForTesting), now 1 s with detailed
    comment on resend profile and amplification rationale (10 s was considered but
    causes a 10× test-duration regression).

Before / After

Scenario Before After
Flaky test failure rate (12-way concurrent) ~1.5–3 % 0 % (150/150 in CI)
TestSyncEvidenceRetries (not present) PASS — fails without ticker loop
Full ./internal/evidence/ suite time ~6 s ~6.5 s

Checklist

  • go test -race -count=1 ./internal/evidence/ → PASS (6.5 s)
  • gofmt -w -s on all changed files
  • golangci-lint — no new issues in changed files
  • TestSyncEvidenceRetries fails on pre-fix code (regression gate verified)

🤖 Generated with Claude Code


Review follow-up (thepastaclaw round 3) — addressed in fb86e098

  • uint64 sync-identity token — the per-peer syncEvidence goroutine identity is now a monotonic uint64 counter on the Reactor (incremented under the install mutex) instead of a *int, removing reliance on heap-address distinctness and the latent *struct{}-regression footgun.
  • MaxBytes-bounded resync — each retry tick now sends evpool.PendingEvidence(ConsensusParams.Evidence.MaxBytes) rather than walking the full pending clist, capping per-tick gossip at the same byte budget the proposer uses. Side benefit: the ValidateABCI repair-and-store subpath now actually re-emits via the ticker (the old clist walk skipped it).

Bundled behavior change — rebroadcast suppression on unverifiable evidence: The suppression of rebroadcast on non-ErrInvalidEvidence errors in handleEvidenceMessage is an intentional bundled change. When AddEvidence fails with a plain (non-ErrInvalidEvidence) error — typically because the node is behind and lacks the block needed to verify the evidence — the reactor now returns without re-gossiping, since broadcasting evidence we cannot verify only amplifies it across the mesh without ever converging. Eventual delivery still holds: any evidence that enters the pending set is re-emitted by the per-peer syncEvidence ticker, including the ValidateABCI repair-and-store subpath (verify.go:74-79), which writes the repaired evidence to the pending store and is therefore picked up by the ticker's PendingEvidence read. Locked by TestReactorNoRebroadcastOnNonInvalidEvidenceError.

Summary by CodeRabbit

  • Bug Fixes
    • Improved evidence propagation so connected peers receive updates more reliably over time.
    • Prevented duplicate re-sharing of evidence when a submission can’t be processed for non-validation reasons.
    • Fixed a reconnect edge case where peer sync could be interrupted during quick disconnect/reconnect activity.
    • Updated tests and documentation to match the revised evidence syncing behavior.

syncEvidence was a one-shot walk of the pool that fired immediately on
PeerStatusUp, before the p2p router had finished wiring the channel
route to the new peer. In that window, Send calls succeed at the
transport level but envelopes are silently dropped by the router.
With no retry path, the peer would permanently miss any evidence that
was already in the pool before it connected.

Convert syncEvidence from a one-shot walk to a ticker-based loop that
re-sends all pending evidence to the peer every evidenceSyncInterval
(1 s) until the peer disconnects. The receiver already handles
duplicates via isPending/isCommitted guards, so re-sends are safe.

This is the same class of race as the consensus catch-up wedge fixed
in #1365 (one-shot gossip, route not ready → silent drop → permanent
miss) but in a separate package and mechanism.

Also tidy the test: use evidence.GetChannelDescriptor() for the
p2ptest channel so the test harness matches the production
RecvBufferCapacity, Priority and Name.

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

coderabbitai Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The evidence reactor's broadcast mechanism is rewritten from a one-shot walk to a per-peer ticker-driven loop using evidenceSyncInterval. Each peer gets a peerSyncState with a monotonic id so stale goroutines cannot evict newly-installed state on fast reconnects. Non-ErrInvalidEvidence add failures now suppress re-gossip. Regression tests and test-export helpers cover both behaviors.

Changes

Evidence reactor: per-peer ticker sync and goroutine eviction fix

Layer / File(s) Summary
peerSyncState struct, ticker loop, and error handling
internal/evidence/reactor.go
Adds evidenceSyncInterval variable and peerSyncState struct with cancel and monotonic id. Updates Reactor struct fields and constructor. Rewrites processPeerUpdate to install id-tagged state on PeerStatusUp and synchronously cancel+delete on PeerStatusDown. Rewrites syncEvidence as a ticker-based loop with id-aware deferred cleanup. Changes non-ErrInvalidEvidence failures to log and return nil to suppress re-gossip.
Test export helpers for reactor internals
internal/evidence/export_test.go, internal/evidence/pool_test.go
Exposes SetEvidenceSyncIntervalForTesting, PeerRoutineCount, PeerRoutineActive, PeerRoutineID, and HandleEvidenceMessageForTest. Bumps EvidenceParams.MaxBytes in pool test state to 1 MiB to match production defaults.
TestSyncEvidenceRetries regression test
internal/evidence/reactor_retry_test.go
Adds nopIterator and recordingChannel stubs and TestSyncEvidenceRetries, which asserts the sync goroutine re-sends pooled evidence on every ticker tick.
Peer flap and no-rebroadcast regression tests
internal/evidence/reactor_test.go
Updates test setup to use production channel descriptor. Adds gateChannel for deterministic goroutine interleaving, TestReactorPeerFlapNoGoroutineEviction asserting stale goroutines cannot evict newly-installed state, and TestReactorNoRebroadcastOnNonInvalidEvidenceError asserting the reactor swallows verification failures without re-broadcasting.
Package documentation update
internal/evidence/doc.go
Rewrites the gossiping section to describe the per-peer sync loop on PeerStatusUp and the broadcastEvidence path for newly added evidence.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • dashpay/tenderdash#1339: Modifies internal/evidence/reactor_test.go with timeout- and goroutine-safe polling helpers that directly precede the new deterministic regression tests added here.

Poem

🐇 Hoppity-hop through the evidence lane,
Each peer gets a ticker — no one-shot pain!
Stale goroutines can't stomp on the new,
IDs keep the map honest and true.
Re-gossip is silenced when errors aren't "invalid",
The bunny approves — the reactor's now vivid! 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.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 clearly matches the main fix: making evidence sync resilient to a peer-routing race.
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/flaky-evidence-reactor

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.

…c re-sync

The per-peer `syncEvidence` goroutine previously walked the pool once
then returned.  If PeerStatusUp fired before the p2p channel route was
fully wired, the first burst of sends was silently dropped and the peer
permanently missed evidence that pre-dated its connection.  The fix
converts the one-shot walk into a ticker loop that re-sends every
`evidenceSyncInterval` (1 s default) until the peer disconnects;
duplicates are idempotent on the receiver side via isPending/isCommitted
guards, so no protocol changes are required.

Two additional hardening changes are included:

- Peer-flap lifecycle race (QA-002): on PeerStatusDown the map entry is
  deleted synchronously (not left for the goroutine's deferred cleanup).
  Each goroutine also carries a unique identity token (`*struct{}`) so
  its defer cannot accidentally remove an entry installed by a fast
  Down→Up reconnect.

- Deterministic regression guard (QA-001): `TestSyncEvidenceRetries`
  wires a recording p2p.Channel and asserts that the same evidence is
  sent MORE THAN ONCE across ticker ticks.  A pre-fix one-shot goroutine
  would send exactly `numEv` times, making the `count > numEv` assertion
  fail — a true regression gate.

doc.go is updated to remove the stale `broadcastEvidenceIntervalS`/60 s
reference and document both propagation paths.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@lklimek
lklimek requested a review from Copilot June 22, 2026 13:24
@lklimek
lklimek marked this pull request as ready for review June 22, 2026 13:25
@lklimek
lklimek requested a review from QuantumExplorer as a code owner June 22, 2026 13:25
@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

This PR hardens the internal evidence reactor against a peer-routing race by making per-peer evidence synchronization retry periodically, ensuring peers eventually receive evidence that pre-dated their connection even if the initial delivery is silently dropped.

Changes:

  • Converted syncEvidence from a one-shot pool walk into a ticker-driven retry loop (default evidenceSyncInterval = 1s) and added per-peer identity tokens to avoid Down→Up flap cleanup races.
  • Added a deterministic regression test (TestSyncEvidenceRetries) using a recording p2p.Channel stub plus a test-only interval override helper.
  • Updated evidence reactor documentation and adjusted tests to use the production channel descriptor.

Reviewed changes

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

Show a summary per file
File Description
internal/evidence/reactor.go Implements periodic per-peer sync retries, adds per-peer sync state/identity token, and documents the rationale/interval.
internal/evidence/reactor_test.go Switches tests to use the real evidence channel descriptor for closer-to-production settings.
internal/evidence/reactor_retry_test.go Adds a regression test asserting sync retries by counting repeated Send calls.
internal/evidence/export_test.go Provides a test-only helper to override the sync interval and restore it after tests.
internal/evidence/doc.go Updates package docs to describe both propagation paths (per-peer sync loop + broadcast on new evidence).

Comment thread internal/evidence/reactor.go Resolved
Comment thread internal/evidence/reactor.go Resolved
Comment thread internal/evidence/reactor_retry_test.go Resolved
…st robustness

- Fix amplification-factor comment: clarify that P×M messages/s is the
  worst-case rate and that a larger interval *reduces* send frequency
  (the previous wording implied the opposite).
- Demote per-item "sent evidence to peer" log from Debug → Trace to
  avoid P×M×1/s debug noise when Debug is enabled.
- Replace time.Sleep with require.Eventually in TestSyncEvidenceRetries:
  poll until sendCount > numEv instead of sleeping a fixed 150 ms, making
  the test robust to scheduler jitter on slow/loaded CI runners.

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

lklimek commented Jun 22, 2026

Copy link
Copy Markdown
Collaborator Author

@thepastaclaw please review

🤖 Co-authored by Claudius the Magnificent AI Agent

@thepastaclaw

thepastaclaw commented Jun 23, 2026 •

Copy link
Copy Markdown

✅ Review complete (commit 08abb4e)

@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's core mechanism (1s re-sync ticker) is sound and the Down→Up flap reasoning is mostly correct, but the identity-token implementation defeats itself: *struct{} pointers all alias to runtime.zerobase, so the guard the comments describe never fires. A separate regression also appears at the receiver side — every tick now causes lagging peers that fail verify-block to rebroadcast the same evidence indefinitely, where previously this happened at most once per connection.

🔴 1 blocking | 🟡 1 suggestion(s)

1 additional finding(s) omitted (not in diff).

🤖 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/evidence/reactor.go`:
- [BLOCKING] internal/evidence/reactor.go:67-70: Identity token uses `*struct{}`, so all tokens alias to runtime.zerobase and the Down→Up flap guard never fires
  `peerSyncState.id` is typed `*struct{}` and constructed with `new(struct{})` (reactor.go:281). Per the Go spec: "Pointers to distinct zero-size variables may or may not be equal." In the current Go runtime, every zero-size allocation returns `&runtime.zerobase`, so every `new(struct{})` returns the same address. The `current.id == myID` check in the deferred cleanup (reactor.go:337) therefore always evaluates true regardless of which goroutine owns the entry.

  Concrete failure path — the exact scenario the token was added to prevent:

  1. PeerStatusUp → install entry M1 with token T1 (= &zerobase), start G1.
  2. PeerStatusDown → cancel G1, delete M1 synchronously, release mtx.
  3. G1's defer is preempted before grabbing mtx.
  4. Fast PeerStatusUp arrives → installs M2 with token T2 (= &zerobase), starts G2.
  5. G1's defer finally runs: `&zerobase == &zerobase` → true → G1 deletes M2 from the map.

  Result: G2 keeps running with no map entry, so the next PeerStatusDown for that peer finds nothing to cancel and G2 leaks until the parent ctx ends. If the peer reconnects, PeerStatusUp sees an empty slot and spawns G3 → two ticker loops sending evidence concurrently for the same peer, accumulating over repeated flaps.

  Neither new test exercises this flap path (TestSyncEvidenceRetries does not flap; TestReactorMultiDisconnect does not reconnect), so CI green is not evidence the guard works.

  Fix: use a non-zero-size pointee, e.g. `*int` (or `*uint64`) with `new(int)` at the construction site and update `syncEvidence`'s parameter type accordingly. The comments at 60–70, 244–252 and 327–329 then correctly describe the behavior.
- [SUGGESTION] internal/evidence/reactor.go:174-185: Lagging peers rebroadcast evidence on every tick because handleEvidenceMessage ignores AddEvidence errors
  Receiver-side dedup via `isPending`/`isCommitted` does not engage when the peer is behind the evidence height. In that case `Pool.verify` returns a non-`ErrInvalidEvidence` error (`missing block for height %d` at internal/evidence/verify.go:37–40), `AddEvidence` does not stash the item in pending, and the code falls through and still calls `broadcastEvidence` — and on the next received copy, `isPending`/`isCommitted` are both still false, so the broadcast happens again.

  Pre-PR this was bounded: syncEvidence sent each pre-existing item exactly once per peer connection. Post-PR the new ticker resends the same items every 1 s for the entire pending lifetime, so a lagging peer will keep failing verification and keep rebroadcasting the same evidence to all of its peers every tick until it catches up or disconnects. That's a sustained duplicate-gossip / log-spam regression directly exposed by this PR's new behavior.

  Minimal fix: only broadcast when `AddEvidence` succeeds (the comment immediately above the branch — "If the evidence is already pending or committed, we don't need to broadcast it again" — already implies this was the intent).

Comment thread internal/evidence/reactor.go Resolved
…ddEvidence failure

Two confirmed-real bugs in the evidence reactor, plus a regression test.

1. Non-zero-size per-peer sync identity token (BLOCKING).
   peerSyncState.id was *struct{} (new(struct{})). The Go runtime places every
   zero-size allocation at the single shared runtime.zerobase address, so all
   tokens compared EQUAL. The deferred-cleanup guard
   `current.id == myID` was therefore always true, defeating the Down->Up flap
   protection: a stale goroutine's deferred cleanup could evict a newer
   goroutine's map entry, leaking the new goroutine and (on reconnect) spawning a
   second ticker loop per peer. Changed the token to *int / new(int) and updated
   syncEvidence's parameter type; *int is non-zero-size so each allocation gets a
   unique address. Comments updated to document the MUST-NOT-be-zero-size rule.

2. Stop rebroadcasting when AddEvidence fails (SUGGESTION).
   When a peer is behind, verify() returns a plain "missing block for height"
   error (not *types.ErrInvalidEvidence). handleEvidenceMessage only logged it
   and still fell through to broadcastEvidence. Because the item never entered
   the pending set, isPending stayed false and every received copy was
   re-gossiped, amplifying traffic until the peer caught up. Now we return nil
   (after logging) for any non-ErrInvalidEvidence error; only successfully-added
   evidence is broadcast. ErrInvalidEvidence still returns err (peer removal).

3. Regression test: TestReactorPeerFlapNoGoroutineEviction.
   Deterministically reproduces the Down->Up flap via a gate channel that freezes
   a sync goroutine mid-walk, so the stale goroutine's deferred cleanup runs
   strictly after a replacement goroutine is installed. Asserts the two
   goroutines receive distinct identity tokens and that the stale cleanup does
   not evict the fresh entry (exactly one routine per peer; no leak). Fails
   deterministically on the pre-fix *struct{} token (tokens alias to zerobase),
   passes with *int. Added test-only accessors (PeerRoutineCount/Active/Token)
   in export_test.go.

Resolves thepastaclaw review (commit 6fdb1e6): the BLOCKING *struct{} token
finding and the SUGGESTION on rebroadcast after AddEvidence failure.

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

lklimek commented Jun 24, 2026

Copy link
Copy Markdown
Collaborator Author

@thepastaclaw please re-review — the BLOCKING finding and the rebroadcast suggestion are addressed in 4c9d5f0:

  • peerSyncState.id is now *int (new(int)), syncEvidence param updated to match — non-zero-size so the Down→Up flap guard's identity check actually fires (your suggested *int/new(int) exactly);
  • added TestReactorPeerFlapNoGoroutineEviction, deterministic, fails on the pre-fix *struct{} token / passes with *int;
  • non-ErrInvalidEvidence AddEvidence errors now return nil instead of falling through to broadcastEvidence (no more every-tick rebroadcast for lagging peers).

gofmt/vet/golangci-lint clean; -race ×3 green.

🤖 Co-authored by Claudius the Magnificent AI Agent

@lklimek

lklimek commented Jun 24, 2026

Copy link
Copy Markdown
Collaborator Author

@thepastaclaw review please

@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 #1366 cleanly fixes the peer-routing race in the evidence reactor by converting the one-shot pool walk into a 1s ticker loop and guards Down→Up flaps with a per-goroutine identity token; lifecycle, locking, and idempotency look correct, with two deterministic regression tests added. Worth raising before merge: (a) a quietly bundled behavior change in handleEvidenceMessage that suppresses rebroadcast on non-ErrInvalidEvidence failures, (b) the retry loop is unbounded by the consensus evidence byte budget so a large pending pool can amplify cluster-wide traffic, and (c) the new long-running per-peer goroutine relies entirely on parent-ctx cancellation (OnStop does not cancel it explicitly), which is the existing reactor pattern but is now more load-bearing.

🟡 3 suggestion(s) | 💬 1 nitpick(s)

1 additional finding(s) omitted (not in diff).

🤖 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/evidence/reactor.go`:
- [SUGGESTION] internal/evidence/reactor.go:189-199: Bundled behavior change: handleEvidenceMessage no longer rebroadcasts on non-ErrInvalidEvidence errors — call this out in the PR description
  Pre-fix, when AddEvidence returned a non-ErrInvalidEvidence error (most commonly because the node is behind and lacks the referenced block — verify() in pool/verify.go:39 returns a plain error in that case), the receiver logged and fell through to `broadcastEvidence`, re-gossiping the unverified item. The new `return nil` suppresses that rebroadcast entirely.

  This is defensible on its own merits — gossiping unverified evidence is amplification without convergence — and the inline comment explains the rationale clearly. The issues are scope and propagation:

  1. The PR title and description frame the change as the peer-routing race / ticker loop fix; this hunk is a separate semantic change worth its own mention so reviewers can evaluate the tradeoff explicitly.
  2. During state-sync / fast-sync, lagging nodes used to opportunistically forward evidence they could not yet verify. Post-fix that opportunistic forwarding is gone, and propagation depends entirely on each holder's syncEvidence ticker eventually re-firing to every peer. The ticker loop guarantees eventual delivery so consensus safety is not at risk (DuplicateVoteEvidence is slashing-relevant, not safety-relevant), but the propagation surface is narrower.
  3. Note that verify()'s ValidateABCI repair-and-store branch (verify.go:74-79) inserts the evidence into pending while returning a non-ErrInvalidEvidence error — in that subpath the local syncEvidence loop will re-emit it, so behavior is preserved.

  At minimum, document this in the PR description. A focused unit test (AddEvidence returns non-ErrInvalidEvidence => broadcastEvidence not called) would lock the new contract in.
- [SUGGESTION] internal/evidence/reactor.go:372-399: Bound each retry tick by ConsensusParams.Evidence.MaxBytes instead of walking the full pool clist
  The retry loop walks `EvidenceFront()` to the end and sends every pending item on every tick. The author's inline comment correctly notes the worst-case per-node send rate is P × M messages/s, but it considers a single sender; in a fully-meshed N-node deployment that has all detected the same equivocation, every receiver becomes a sender once it admits the evidence, so steady-state cluster traffic is ≈ N × (N-1) × M envelopes/s while items remain pending. Pools are normally small and drain within a block, so the burst window is short — but the loop has no protocol-level cap.

  The consensus protocol already defines an authoritative byte budget for evidence at any given height: `ConsensusParams.Evidence.MaxBytes`. The pool's own `PendingEvidence(maxBytes)` (pool.go:91) already honors it for proposal selection. Using the same bound on the per-peer retry path keeps the gossip channel symmetric with what the proposer would actually include, and turns this loop's worst case into a fixed-bytes-per-tick ceiling instead of a pool-size-dependent one.

  Not a blocker (the receiver dedupes idempotently and the loop is functionally correct), but a small, low-risk hardening with no behavioral downside.
- [SUGGESTION] internal/evidence/reactor.go:146-148: syncEvidence's long-running loop now relies entirely on parent-ctx cancellation; OnStop should cancel it explicitly
  The loop exits only via `ctx.Done()` or a `Send` error. That ctx is the OnStart ctx, which is NOT canceled by `BaseService.Stop()` — `Stop()` calls `OnStop()` (which only closes the evpool) and cancels an internal `srvCtx` that is never passed to anywhere in the reactor. In normal node shutdown the parent ctx is canceled along with shutdown so the goroutine exits cleanly, and the existing `if !r.IsRunning()` guard on PeerStatusUp prevents new goroutines from being spawned after Stop — so this is not a production leak today.

  However, pre-PR `syncEvidence` was a one-shot pool walk that returned in milliseconds, so calling `Stop()` without also canceling the parent ctx was harmless. Post-PR the goroutine ticks forever in that scenario, which makes a previously-benign pattern observable as a goroutine leak (most likely surfaced first in tests that call `reactor.Stop()` directly).

  Cheapest fix: track a cancel func on the Reactor and call it from `OnStop()`, or store all per-peer cancels and invoke them on stop. This also documents the lifecycle contract explicitly rather than relying on every caller to remember to cancel the OnStart ctx.

Comment thread internal/evidence/reactor.go Resolved
Comment thread internal/evidence/reactor.go Resolved
Comment thread internal/evidence/reactor.go Resolved
lklimek and others added 2 commits June 24, 2026 13:29
…t (review)

Three reviewer-requested hardening changes to the evidence reactor.

(c) Replace the *int per-peer sync identity token with a monotonic uint64
    counter (Reactor.nextSyncID), incremented under the same mutex that installs
    the peerSyncState. The old token's distinctness relied on the allocator
    returning unequal heap addresses; a future switch to *struct{} would silently
    collapse every token onto runtime.zerobase and reintroduce the Down->Up flap
    race. A counter is spoof-proof and self-documenting.

(b) Bound each syncEvidence tick by ConsensusParams.Evidence.MaxBytes via
    evpool.PendingEvidence(maxBytes) instead of walking EvidenceFront()->end and
    sending every pending item. Gossip is now symmetric with what a proposer
    would include (same budget, same store-ordered prefix) and avoids O(N^2*M)
    amplification on a full mesh. As a bonus, the ValidateABCI repair-and-store
    subpath (which writes to the store but not the clist) becomes eligible for
    ticker re-emission.

(a) Lock the bundled handleEvidenceMessage change: a non-ErrInvalidEvidence
    AddEvidence error now returns nil (no rebroadcast) so unverifiable evidence is
    not amplified. New TestReactorNoRebroadcastOnNonInvalidEvidenceError asserts
    broadcastEvidence is not called on that path.

Tests: update TestReactorPeerFlapNoGoroutineEviction to assert distinct uint64
ids (and that a stale defer cannot evict the newer entry); add PeerRoutineID and
HandleEvidenceMessageForTest test hooks; raise the test fixture's
Evidence.MaxBytes to the 1 MiB production default so the bounded resync does not
throttle the broadcast tests.

Co-authored-by: Claudius the Magnificent <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
@lklimek

lklimek commented Jun 24, 2026

Copy link
Copy Markdown
Collaborator Author

@thepastaclaw please re-review — all three round-3 items are addressed in 08abb4e4 (which also includes a fresh v1.6-dev merge, so #1365's catch-up flake fix is now in the branch):

  • uint64 monotonic sync-identity token replacing the *int — no more reliance on heap-address distinctness; the *struct{}-regression footgun is gone (flap test asserts distinct ids).
  • Per-tick resync bounded by ConsensusParams.Evidence.MaxBytes via evpool.PendingEvidence(maxBytes) instead of the full EvidenceFront() walk (also fixes the ValidateABCI repaired-evidence re-emit gap).
  • TestReactorNoRebroadcastOnNonInvalidEvidenceError locks the rebroadcast-suppression contract (negative control verified); the bundled behavior change is now documented in the PR description.

go build ./... + go test -race ./internal/evidence/... green; gofmt/govet/misspell clean. All three review threads resolved.

🤖 Co-authored by Claudius the Magnificent AI Agent

@lklimek

lklimek commented Jun 24, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review all

@coderabbitai

coderabbitai Bot commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

@lklimek Sure, I'll kick off a full review of all the changes in this PR right away!

✅ Action performed

Full review finished.

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

🧹 Nitpick comments (1)
internal/evidence/doc.go (1)

29-31: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Clarify rebroadcast is conditional on successful pool admission.

This currently reads as unconditional rebroadcast, but the reactor only rebroadcasts when AddEvidence succeeds; non-ErrInvalidEvidence add failures are not re-gossiped.

Proposed doc wording
-  - Broadcast on new evidence: when a node adds new evidence received from another peer, it
-    re-broadcasts it to all currently connected peers via broadcastEvidence.
+  - Broadcast on new evidence: when a node successfully adds new evidence received from another
+    peer, it re-broadcasts it to all currently connected peers via broadcastEvidence. Evidence
+    that fails pool admission is not re-gossiped.
🤖 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/doc.go` around lines 29 - 31, Update the
`internal/evidence` package documentation in `doc.go` to make the rebroadcast
behavior conditional: the `broadcastEvidence` path should be described as
happening only after `AddEvidence` succeeds, and not for other add failures
except `ErrInvalidEvidence` handling as currently implemented in the reactor.
Keep the wording aligned with the actual `Reactor`/`AddEvidence` flow so the doc
no longer implies unconditional rebroadcast to all connected peers.
🤖 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.

Nitpick comments:
In `@internal/evidence/doc.go`:
- Around line 29-31: Update the `internal/evidence` package documentation in
`doc.go` to make the rebroadcast behavior conditional: the `broadcastEvidence`
path should be described as happening only after `AddEvidence` succeeds, and not
for other add failures except `ErrInvalidEvidence` handling as currently
implemented in the reactor. Keep the wording aligned with the actual
`Reactor`/`AddEvidence` flow so the doc no longer implies unconditional
rebroadcast to all connected peers.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 8b3d775f-9c4f-4882-bf0e-c2c1abe4e0d5

📥 Commits

Reviewing files that changed from the base of the PR and between cf9e102 and 08abb4e.

📒 Files selected for processing (6)
  • internal/evidence/doc.go
  • internal/evidence/export_test.go
  • internal/evidence/pool_test.go
  • internal/evidence/reactor.go
  • internal/evidence/reactor_retry_test.go
  • internal/evidence/reactor_test.go

@lklimek
lklimek merged commit 82b304f into v1.6-dev Jun 24, 2026
16 checks passed
@lklimek
lklimek deleted the fix/flaky-evidence-reactor branch June 24, 2026 12:44

@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 #1366 correctly hardens the evidence reactor's per-peer sync against the p2p routing race: the monotonic uint64 sync identity prevents flap eviction, PendingEvidence(MaxBytes) keeps resync symmetric with proposer selection, and non-ErrInvalidEvidence AddEvidence failures no longer rebroadcast unverifiable evidence. Both convergent codex findings on OnStop lifecycle are technically real but pre-existing in pattern; the PR amplifies (does not introduce) the dependency on parent ctx cancellation. Keeping one suggestion-level finding for that PR-driven amplification.

🟡 1 suggestion(s)

1 additional finding(s) omitted (not in diff).

🤖 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/evidence/reactor.go`:
- [SUGGESTION] internal/evidence/reactor.go:153-155: OnStop does not cancel per-peer syncEvidence goroutines
  BaseService.Stop() only cancels its own internal srvCtx (libs/service/service.go:128-170), not the ctx passed to OnStart. The per-peer pctx at reactor.go:304 is derived from the OnStart ctx, so Reactor.Stop() leaves the new long-running ticker loops running until the caller separately cancels the parent ctx. Before this PR syncEvidence was a one-shot drain that exited quickly; the ticker loop never exits on its own, so the lifetime amplification turns a previously self-resolving goroutine into an indefinitely live one calling PendingEvidence/Send against a closed pool. In production the node cancels ctx together with Stop so this is not a current runtime hazard, but tests and embedding harnesses that stop the reactor directly will now leak per-peer goroutines. The minimal fix is to walk peerRoutines under mtx in OnStop and call cancel() on each entry before closing the pool.

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