Repository navigation
fix(blocksync): survive transient peer failures and stalls - #1396
Conversation
removePeer re-requested every block it had already received from the peer being removed, but left those responses in pendingToApply. When the re-requested block arrived from a different peer, addBlock rejected it as a duplicate and the synchronizer reported a PeerError against the peer that had served it correctly, evicting it. Under peer churn this cascades: each eviction re-requests more heights, each of those punishes another healthy peer, and block sync can stall long enough to hit the 60s syncTimeout and switch to consensus without being caught up. Delete the pending entry alongside the re-request so the re-fetched block is accepted, dedupe pushedBack so a height is not fetched twice concurrently, and treat a duplicate response as benign rather than as a peer fault. Co-Authored-By: Claude Opus 5 <[email protected]>
Block sync applies blocks on a single goroutine, so sync rate is bounded by the cost of applying one block. That path repeated several expensive operations: - The part set was built twice per block, once inside BlockID(nil) and once explicitly for SaveBlock. Each build serializes the whole block and computes a Merkle tree over its parts. Build it once and pass it to both; BlockID(partSet) is identical to BlockID(nil) for a part set made with BlockPartSizeBytes. - Block.Size() converted the whole block to protobuf twice more, once to feed the peer flow monitor and once for the block size metric. The size is now measured once while decoding the response, on a worker goroutine, and the metric reuses partSet.ByteSize(), which is exactly the length of the serialized block. - ApplyBlock validated every block twice: ProcessProposal(verify=true) and then FinalizeBlock, which calls ValidateBlockWithRoundState with the same arguments and wraps failures in the same ErrInvalidBlock. Each pass costs a threshold signature verification of block.LastCommit. ApplyBlock now passes verify=false; FinalizeBlock validates before any persistence or ABCI call, so no check is lost. - The p2p receive path recomputed proto.Size on every message purely to feed a byte counter, walking the whole decoded message again. len(bz) is the exact wire size and is already in hand. Also records per-stage timings of the apply pipeline and reports them alongside the existing block sync rate log line, so a slow sync can be attributed to serialization, signature verification, disk or the ABCI application without a profiler. Co-Authored-By: Claude Opus 5 <[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 Plus 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)
Comment |
Two ways block sync gives up far too easily. A single failed block request dropped the peer. consumeJobResult called RemovePeer and reported a PeerError for any errBlockFetch, including a plain 15s request timeout, and PeerManager.Errored evicts on the first report. Peers serve block requests one at a time, so a busy peer times out long before it is unhealthy, and dropping it also fails the up to 20 requests already in flight to it - each of which then drops another peer. Count consecutive failures per peer instead and drop only after maxConsecutiveFailures in a row, resetting the count on the first successful response. A failed request also stops being counted as pending, which it previously only did by virtue of the peer being deleted. The p2p client reported the peer itself on every request timeout, which bypassed any caller-side policy. Reject the promise and let the caller decide: blocksync now counts timeouts, statesync's backfill already said it did not want to punish on timeout, and a genuinely dead connection is still caught by the transport's ping/pong. GetBlock is the only production caller of a promise-returning client method, so this is confined to the block sync path. A 60s stall handed over to consensus even when far behind. Nothing switches back to block sync except the state sync path, so a stalled node was demoted permanently to consensus catch-up, which is much slower. A stall is now only a reason to stop when no peer reports a height above ours, or when it has outlasted maxSyncStall, so a wedged synchronizer can still hand over rather than blocking forever. WaitForSync returns whether the node actually caught up, and poolRoutine uses that instead of a second IsCaughtUp call racing the synchronizer it just stopped. Co-Authored-By: Claude Opus 5 <[email protected]>
4071e32 to
09530ab
Compare
CI follow-up
|
Audit Summary — PR #1396
|
| Class | Sev | OWASP / CWE | Location | Finding |
|---|---|---|---|---|
| 🚫 blocking | MEDIUM | A04 Insecure Design, A05 Security Misconfiguration; CWE-841, CWE-799, CWE-400 | internal/blocksync/peer_store.go:130-144, synchronizer.go:239-263, p2p_msg_handler.go:56-64 |
Consecutive-failure counter is reset by any peer-sent StatusResponse, so the new eviction threshold is unreachable for a selectively-failing peer |
| 🚫 blocking | MEDIUM | A04 Insecure Design; CWE-191 Integer Underflow, CWE-770 | internal/blocksync/peer_store.go:136-144 |
AddFailure decrements numPending on a path that previously deleted the peer — failing makes a peer invisible to the slow-peer check and keeps it selectable |
| 🚫 blocking | MEDIUM | logic, doc-accuracy, concurrency | internal/blocksync/synchronizer.go:40-44 |
The "consecutive" failure counter actually counts concurrent in-flight timeouts — the documented intent is not delivered |
| non-blocking | MEDIUM | A04 Insecure Design; CWE-807 Untrusted Input in Security Decision, CWE-400 | internal/blocksync/synchronizer.go:322-404, reactor.go:33-38 |
maxSyncStall extends a peer-controlled block-sync lock-out from 60s to 10 minutes, keyed off an unauthenticated peer-reported height |
| non-blocking | MEDIUM | A04 Insecure Design, A09 Logging & Monitoring Failures; CWE-390, CWE-400 | internal/p2p/client/client.go:397-427,167-227 |
newPromise's timeout no longer reports the peer on any of its 4 shared APIs; only blocksync compensates, and the new caller-owns-punishment contract is undocumented and untested |
| non-blocking | MEDIUM | logging, observability (execution-verified) | internal/blocksync/synchronizer.go:352-362 |
Peer-triggerable Error-level log flood: up to ~540 identical lines per stall episode, proven by execution |
| non-blocking | MEDIUM | test-coverage, concurrency | internal/blocksync/synchronizer.go:322-370, reactor.go:293-300 |
WaitForSync's actual loop and its effect on SwitchToConsensus's skipWAL argument are untested — only the extracted pure function is covered |
| non-blocking | LOW | observability, operator-ux | internal/blocksync/synchronizer.go:339-341 |
Block sync gives up silently on the stopNothingToFetch path — no log line at all |
| non-blocking | LOW | observability, metrics | internal/blocksync/synchronizer.go:244-263 |
New failure/stall states are observable only by grepping logs; no metric, despite existing consensus.Metrics wiring |
| non-blocking | LOW | idiom, encapsulation, DRY | internal/blocksync/peer_store.go:136-144 |
AddFailure breaks the peer store's UpdateFunc idiom, bypasses the wrapper that maintains maxHeight, and hides a pending-count mutation |
| non-blocking | LOW | DRY, readability | internal/blocksync/synchronizer.go:339-362 |
The syncTimeout threshold is evaluated twice — once inside stallVerdictFor, once again in its caller |
| non-blocking | LOW | concurrency, consistency | internal/blocksync/synchronizer.go:330-338 |
The stall decision is assembled from four separately-locked reads that never coexisted |
| non-blocking | LOW | logging, operator-ux | internal/blocksync/synchronizer.go:249-254 |
"keeping peer" is logged for peers that are already gone — AddFailure's bool conflates "kept" with "not found" |
| non-blocking | LOW | dead-branch, naming, test-accuracy | internal/blocksync/synchronizer.go:379-380 |
stopNothingToFetch as documented is unreachable, and one test case exercises a state production cannot produce |
Pre-existing / outside-diff (follow-up, not this PR)
Four findings are real but sit outside this diff's responsibility. They are reported here only, with no inline comments:
- MEDIUM —
internal/p2p/client/— A pre-existing issue was identified in this area during review; this PR marginally widens its exposure window. Given its nature, it is being handled through a private security-disclosure channel rather than described in this public thread. - LOW —
internal/blocksync/reactor.go:32-38— stall constants live inreactor.gobut are used only bysynchronizer.go. - LOW —
docs/tendermint-core/block-sync/reactor.md:240-247— block-sync spec doc still describes the old switch-to-consensus condition. - LOW —
internal/blocksync/peer_store.go:236-237— new godoc sentences omit the trailing period required bySTYLE_GUIDE.md.
Positive observations
- The TOCTOU fix is genuinely correct: threading
caughtUpout ofWaitForSyncintoSwitchToConsensus(ctx, state, caughtUp || stateSynced)removes a real race against a synchronizer that was just stopped, exactly as the PR's own comment claims. - The bounded stall/handover mechanism is well-shaped: replacing an indefinite wedge with an explicit
maxSyncStallceiling is the right structural move, and extractingstallVerdictForas a pure, table-tested decision function is good practice —TestStallVerdictForcovers the decision table thoroughly. - Stack integration is clean: interaction with fix(blocksync): don't punish peers for duplicate block responses #1393's
RemovePeerand perf(blocksync): remove redundant work from the block apply path #1394'sUpdateMonitorwas checked and holds up; no conflicts or double-eviction paths. - Reviewer effort was verification-first: all three blocking findings were reproduced with executable probes rather than asserted from reading the diff.
🤖 Co-authored by Claudius the Magnificent AI Agent
|
⛔ Blockers found — Sonnet deferred (commit d5c1c1e) |
thepastaclaw
left a comment
There was a problem hiding this comment.
Preliminary review — Codex only
The resilience policy is directionally sound, but two interactions prevent it from reliably tolerating transient peer failures. Timeout cleanup still makes valid late responses punish the peer and contains a send-on-closed-channel crash race, while periodic status responses can erase the newly introduced consecutive-failure state.
Validated blockers were found in the Codex precheck. Sonnet is deferred until a fresh Codex revalidation clears the blocker gate.
Review provenance
- Codex reviewers:
gpt-5.6-sol— general (completed),gpt-5.6-sol— tenderdash-consensus-security (completed) - Verifier:
gpt-5.6-sol— verifier - Sonnet: not run (deferred by blocker gate)
🔴 2 blocking
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/p2p/client/client.go`:
- [BLOCKING] internal/p2p/client/client.go:417-424: Timeout cleanup handles valid late responses as peer faults and can panic
The timeout branch now retains the peer, making responses arriving around or just after the deadline an expected condition, but the deferred `removePending` still deletes the request and closes its response channel. A response after deletion makes `resolve` return `pending response ... not found`, and `iter` converts that error into a `PeerError`; at full peer capacity the router evicts the peer, bypassing the new consecutive-failure policy. There is also a crash race: `resolveMessage` can load the channel at line 348, the timeout goroutine can then close it in `removePending`, and the resolver's send at line 356 panics with `send on closed channel`. That panic occurs in the P2P consumer goroutine and bypasses the handler recovery middleware. Keep expired request IDs distinguishable from unsolicited IDs so known late responses can be discarded without reporting the peer, and do not close a channel while a resolver may hold a reference to it.
In `internal/blocksync/synchronizer.go`:
- [BLOCKING] internal/blocksync/synchronizer.go:419-422: Status refreshes erase consecutive block failures
`AddPeer` replaces the complete stored `PeerData`, but the reactor broadcasts a status request every 10 seconds and the response handler calls this method with `newPeerData`, whose `numFailures` is zero. A peer can therefore clear failures merely by answering status requests, even though the new invariant says only a successful block response resets the run. Failures that straddle status refreshes may never reach `maxConsecutiveFailures`, undermining the peer-removal policy introduced by this PR. Updating a known peer's advertised base and height must preserve its failure count and other request-tracking state; add a test with a status refresh between failed block requests.
| // Reject and let the caller decide what a timeout is worth. Reporting | ||
| // the peer here evicts it on a single slow request, which is a poor | ||
| // signal: peers answer requests one at a time, so a busy peer times | ||
| // out long before it is unhealthy, and evicting it also fails every | ||
| // other request already in flight to it. Callers that want to act on | ||
| // repeated timeouts can count them, and a genuinely dead connection | ||
| // is still caught by the transport's ping/pong. | ||
| reject(ErrPeerNotResponded) |
There was a problem hiding this comment.
🔴 Blocking: Timeout cleanup handles valid late responses as peer faults and can panic
The timeout branch now retains the peer, making responses arriving around or just after the deadline an expected condition, but the deferred removePending still deletes the request and closes its response channel. A response after deletion makes resolve return pending response ... not found, and iter converts that error into a PeerError; at full peer capacity the router evicts the peer, bypassing the new consecutive-failure policy. There is also a crash race: resolveMessage can load the channel at line 348, the timeout goroutine can then close it in removePending, and the resolver's send at line 356 panics with send on closed channel. That panic occurs in the P2P consumer goroutine and bypasses the handler recovery middleware. Keep expired request IDs distinguishable from unsolicited IDs so known late responses can be discarded without reporting the peer, and do not close a channel while a resolver may hold a reference to it.
source: ['codex']
Independent re-review: this PR's two stated fixes don't holdA second, independent 3-agent pass (security/project/QA, with QA doing live mutation testing rather than reading the diff) converges on largely the same root causes as the audit above — strong signal, two separate passes landing in the same place. Summarizing in plain terms why this PR doesn't deliver its stated goal, plus one mechanism the earlier audit framed differently and one root cause it didn't isolate: 1. The new eviction threshold is unreachable for the peer it exists to catch. 2. The timeout punishment wasn't removed, it relocated. 3. It can't distinguish "slow" from "lying." 4. The highest-risk new path can't be tested, for an unrelated reason. None of these four are independent nitpicks — they're four different reasons the same underlying claim ("this PR makes block sync tolerant of transient failures without giving up real safety") doesn't currently hold. Full report with locations/recommendations: 🤖 Co-authored by Claudius the Magnificent AI Agent |
- FinalizeBlock's new comment claimed the validation runs before the block reaches the app or the stores. That is false on the block sync path: ProcessProposal has already delivered the block and blockApplier.Apply has already written it. Say what the call actually guards, and why it must not be removed. - NewBlockMeta still converted the whole block to protobuf for its size, on the same serial path this change set is trying to shorten. The part set it already receives holds the serialized block, so its byte size is exactly the block size. - The timing log reported whole milliseconds, which truncates part set building and commit verification - routinely sub-millisecond - to 0 both before and after any improvement, defeating the point of adding the instrumentation. Log durations instead. - Renamed the abci_ms key to exec: the span also covers SaveABCIResponses, the state store write and the mempool update, which are ours rather than the application's. - updateMonitor read maxPeerHeight on every applied block for a line it prints once per interval, and carried a comment about a lock ordering the refactor had already removed. Adds the missing coverage: applyStats averaging, reset-on-read, and sub-millisecond retention, plus a regression test pinning that ApplyBlock still rejects an invalid block. ApplyBlock calls ProcessProposal with verify=false and relies solely on FinalizeBlock's validation, a coupling invisible from either function alone; the test was confirmed to fail when that validation is removed. Co-Authored-By: Claude Opus 5 <[email protected]>
Resolves the conflicts introduced when #1394 was squash-merged as d3baf3f, the same way #1394 resolved the conflicts from #1393's squash as a99ff2a. Each squash drops the shared ancestry with the branch below it in the stack, so the merge base falls back past both parents and their changes resurface as conflicts against the older copies this branch still carries. Conflicts in internal/blocksync/{block_fetch_job.go,synchronizer.go, synchronizer_test.go} and types/block_meta.go, all between work already merged to v1.6-dev and this branch's stale copies. Resolved in favour of v1.6-dev throughout; this branch contributes no change to any of the four: - block_fetch_job.go, synchronizer_test.go: taken from v1.6-dev unchanged. - types/block_meta.go: taken from v1.6-dev unchanged. Keeping this branch's copy would have restored the eager block.Size() call, reintroducing the redundant serialization on the block sync apply path. - synchronizer.go: keeps #1393's dropPeer batching, applyBlock returning the failing response, and the addBlock floor guard, plus #1394's apply-path work, and layers this branch's failure-tracking and stall handling on top. The resolved tree was verified byte-for-byte against a three-way merge of this branch with #1394's pre-squash tip, computed while that ancestry still existed. Net delta against v1.6-dev is this branch's own seven files and nothing else. Co-Authored-By: Claude Opus 5 <[email protected]>
Three defects on the pending-request path, all reachable now that #1396 retains timed-out peers instead of evicting them. 1. Send on closed channel. removePending closed the response channel, so a resolver that had already loaded it panicked on the next send. iter calls resolve directly, outside recoveryP2PMessageHandler, so nothing recovered it and the process died. Deleting the close is correct, not a workaround. removePending has exactly one caller - the promise executor's deferred call - and the channel's only reader is that same executor's select, which has already returned by the time the defer runs. The close therefore signaled nobody. It was unsafe in the other direction too: a closed channel yields a zero result, whose nil Value would panic the type assertion on the receive side. Nothing should reinstate it. 2. A late response evicted the peer. With the entry deleted, a response arriving after the timeout fell through to "pending response not found", which iter turns into a PeerError - evicting at capacity and silently defeating blocksync's maxConsecutiveFailures policy. removePending now leaves a tombstone in place of the channel, so resolveMessage can tell a request we issued and retired (dropped, no error) from an ID we never issued (still reported). Tombstones live 2*reqTimeout on the injected clock and sit in an insertion-ordered list swept from addPending: one push and one pop per request, so no background goroutine and no full-map scan. What we retain is set by the requests we issue, not by anything a peer sends. Every retired request is tombstoned, not only expired ones. That also stops a duplicate BlockResponse for the same request ID from being reported - the client-side counterpart of #1393, which fixed only the height-level case in the synchronizer. 3. Blocking send parked the consumer. resolveMessage sent into a one-slot buffer whose reader may already be gone. Removing the close turned the interleaving that used to panic into a permanent hang instead, stopping every blocksync message until node shutdown. The send is now non-blocking: a full buffer means the answer already arrived, so the extra copy is dropped. Found by code review of the first two fixes, and reproduced before fixing. Tests, under -race -tags deadlock. Each one fails on the code it pins: TestRemovePendingKeepsChannelSendable before: panic: send on closed channel after: PASS TestLateResponseAfterTimeoutIsNotAnError before: pending response <uuid> not found after: PASS TestRetiredRequestIDsAreBounded before: Not equal: expected 100, actual 0 after: PASS TestDuplicateResponseDoesNotBlockResolver before: blocked on a response buffer nobody reads after: PASS TestUnsolicitedResponseIDIsAnError passes both before and after by design: it is the regression guard proving the new silence does not swallow fabricated response IDs. The pre-existing TestGetBlockTimeout still passes. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Three defects on the pending-request path, all reachable now that #1396 retains timed-out peers instead of evicting them. 1. Send on closed channel. removePending closed the response channel, so a resolver that had already loaded it panicked on the next send. iter calls resolve directly, outside recoveryP2PMessageHandler, so nothing recovered it and the process died. Deleting the close is correct, not a workaround. removePending has exactly one caller - the promise executor's deferred call - and the channel's only reader is that same executor's select, which has already returned by the time the defer runs. The close therefore signaled nobody. It was unsafe in the other direction too: a closed channel yields a zero result, whose nil Value would panic the type assertion on the receive side. Nothing should reinstate it. 2. A late response evicted the peer. With the entry deleted, a response arriving after the timeout fell through to "pending response not found", which iter turns into a PeerError - evicting at capacity and silently defeating blocksync's maxConsecutiveFailures policy. removePending now leaves a tombstone in place of the channel, so resolveMessage can tell a request we issued and retired (dropped, no error) from an ID we never issued (still reported). Tombstones live 2*reqTimeout on the injected clock and sit in an insertion-ordered list swept from addPending: one push and one pop per request, so no background goroutine and no full-map scan. What we retain is set by the requests we issue, not by anything a peer sends. Every retired request is tombstoned, not only expired ones. That also stops a duplicate BlockResponse for the same request ID from being reported - the client-side counterpart of #1393, which fixed only the height-level case in the synchronizer. 3. Blocking send parked the consumer. resolveMessage sent into a one-slot buffer whose reader may already be gone. Removing the close turned the interleaving that used to panic into a permanent hang instead, stopping every blocksync message until node shutdown. The send is now non-blocking: a full buffer means the answer already arrived, so the extra copy is dropped. Found by code review of the first two fixes, and reproduced before fixing. Tests, under -race -tags deadlock. Each one fails on the code it pins: TestRemovePendingKeepsChannelSendable before: panic: send on closed channel after: PASS TestLateResponseAfterTimeoutIsNotAnError before: pending response <uuid> not found after: PASS TestRetiredRequestIDsAreBounded before: Not equal: expected 100, actual 0 after: PASS TestDuplicateResponseDoesNotBlockResolver before: blocked on a response buffer nobody reads after: PASS TestUnsolicitedResponseIDIsAnError passes both before and after by design: it is the regression guard proving the new silence does not swallow fabricated response IDs. The pre-existing TestGetBlockTimeout still passes. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Issue being fixed or feature implemented
Two ways block sync gives up far more easily than it should. Neither is a
percentage problem — both make a node stop syncing — so they outweigh any of the
throughput work in the rest of this stack.
1. A single failed block request dropped the peer
consumeJobResultcalledRemovePeerand reported ap2p.PeerErrorfor anyerrBlockFetch, including a plain 15s request timeout.PeerManager.Erroredevicts on the first report:
Peers serve block requests one at a time, so a busy peer times out long before it
is unhealthy. Worse, dropping it also fails the up to 20 requests already in
flight to it (
maxPendingRequestsPerPeer), and each of those failures droppedanother peer in turn.
2. The p2p client reported the peer itself, behind the caller's back
newPromisesent aPeerErroron every request timeout, so no caller-sidepolicy could soften it. Statesync's backfill already documents that it does not
want this:
3. A 60s stall handed over to consensus even when far behind
WaitForSyncreturned ontime.Since(lastAdvance) > syncTimeoutandpoolRoutinethen switched to consensus unconditionally. That is a one-way door— only the state sync path ever calls
SwitchToBlockSync— so a node thatstalled for 60s while thousands of blocks behind was permanently demoted to
consensus catch-up, which is far slower than block sync.
What was done?
maxConsecutiveFailures(5) failures in a row; the count resets on the firstsuccessful response. A failed request also stops being counted as pending,
which previously only happened as a side effect of deleting the peer.
newPromisenow rejectswithout reporting.
GetBlockis the only production caller of anypromise-returning client method —
GetChunk/GetParams/GetLightBlockexiston the interface but statesync uses direct channel sends and its own dispatcher
— so this is confined to the block sync path. A genuinely dead connection is
still caught by the transport's ping/pong (60s interval, 90s timeout).
a height above ours, or when the stall outlasts
maxSyncStall(10 min) so awedged synchronizer can still hand over rather than blocking forever. The
decision is factored into
stallVerdictForso it is testable without waitingon the 1s ticker.
WaitForSyncreturns whether the node actually caught up, andpoolRoutineuses that rather than a second
IsCaughtUp()call racing the synchronizer itjust stopped.
How Has This Been Tested?
New tests:
TestStallVerdictFor— table over the stall decision: progressing, stalledwith nothing left to fetch, stalled while ahead of every peer, stalled with
peers still holding blocks, and either side of the wedge limit.
TestConsumeJobResultKeepsPeerOnTransientFailure— failures below thethreshold keep the peer; the client mock has no
Sendexpectation, soreporting it would fail the test. The next failure crosses the threshold and
does report and remove.
TestAddFailure— threshold behaviour, that a success clears the run, and thatan unknown peer is never reported (so the remaining in-flight failures of an
already-removed peer do not report it again).
TestAddFailureClearsPending— a failed request stops being pending.Two cases in the existing
TestConsumeJobResultencoded the oldone-failure-one-eviction policy. Rather than delete them, the second now seeds
the peer one failure short of the threshold so it still exercises removal and the
re-request of that peer's pending blocks.
go build ./internal/... ./types/... ./node/... ./cmd/...go test -race -tags=deadlock -p 1overblocksync,p2p/...,statesync,consensus,state,store— all passgolangci-lint: 69 issues, identical to the base branchBuilt and tested against
DOCKER/Dockerfile'sdepsstage (Go 1.26.5).Breaking Changes
None to the wire protocol or on-disk format. Behavioural: peers are no longer
evicted on a single failed block request or a single request timeout. That is the
point of the change, but it does mean a bad peer is tolerated for up to 5
requests before removal.
Checklist:
For repository code-owners and collaborators only
🤖 Generated with Claude Code