Skip to content

fix(blocksync): survive transient peer failures and stalls - #1396

Merged
shumkov merged 9 commits into
v1.6-devfrom
fix/blocksync-peer-resilience
Aug 8, 2026
Merged

shumkov merged 9 commits into
v1.6-devfrom
fix/blocksync-peer-resilience

Conversation

@QuantumExplorer

Copy link
Copy Markdown
Member

Stacked on #1394, which is stacked on #1393. GitHub will retarget as those
merge. Review only the last commit.

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

consumeJobResult called RemovePeer and reported a p2p.PeerError for any
errBlockFetch, including a plain 15s request timeout. PeerManager.Errored
evicts on the first report:

func (m *PeerManager) Errored(peerID types.NodeID, err error) {
	...
	if m.isConnected(peerID) {
		m.evict[peerID] = true
	}

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 dropped
another peer in turn.

2. The p2p client reported the peer itself, behind the caller's back

newPromise sent a PeerError on every request timeout, so no caller-side
policy could soften it. Statesync's backfill already documents that it does not
want this:

} else if errors.Is(err, context.DeadlineExceeded) {
	// we don't punish the peer as it might just have not responded in time

3. A 60s stall handed over to consensus even when far behind

WaitForSync returned on time.Since(lastAdvance) > syncTimeout and
poolRoutine then switched to consensus unconditionally. That is a one-way door
— only the state sync path ever calls SwitchToBlockSync — so a node that
stalled for 60s while thousands of blocks behind was permanently demoted to
consensus catch-up, which is far slower than block sync.

What was done?

  • Count consecutive failures per peer. Drop a peer only after
    maxConsecutiveFailures (5) failures in a row; the count resets on the first
    successful response. A failed request also stops being counted as pending,
    which previously only happened as a side effect of deleting the peer.
  • Let the caller decide what a timeout is worth. newPromise now rejects
    without reporting. GetBlock is the only production caller of any
    promise-returning client method — GetChunk/GetParams/GetLightBlock exist
    on 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 stall alone no longer ends block sync. It ends only when no peer reports
    a height above ours, or when the stall outlasts maxSyncStall (10 min) so a
    wedged synchronizer can still hand over rather than blocking forever. The
    decision is factored into stallVerdictFor so it is testable without waiting
    on the 1s ticker.
  • WaitForSync returns whether the node actually caught up, and poolRoutine
    uses that rather than a second IsCaughtUp() call racing the synchronizer it
    just stopped.

How Has This Been Tested?

New tests:

  • TestStallVerdictFor — table over the stall decision: progressing, stalled
    with 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 the
    threshold keep the peer; the client mock has no Send expectation, so
    reporting 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 that
    an 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 TestConsumeJobResult encoded the old
one-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 1 over blocksync, p2p/..., statesync,
    consensus, state, store — all pass
  • golangci-lint: 69 issues, identical to the base branch

Built and tested against DOCKER/Dockerfile's deps stage (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:

  • 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

🤖 Generated with Claude Code

QuantumExplorer and others added 2 commits July 25, 2026 17:54
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]>
@QuantumExplorer
QuantumExplorer requested a review from lklimek as a code owner July 27, 2026 07:53
@coderabbitai

coderabbitai Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

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

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 2f3851e2-d079-49d8-814b-dccb9ad2e66d

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

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/blocksync-peer-resilience

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

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]>
@QuantumExplorer
QuantumExplorer force-pushed the fix/blocksync-peer-resilience branch from 4071e32 to 09530ab Compare July 27, 2026 08:17
@QuantumExplorer

Copy link
Copy Markdown
Member Author

CI follow-up

golangci-lint — fixed

unused-parameter: parameter 'pool' on a test closure this PR emptied out. Now
_. Worth recording how it slipped past my local check: CI runs golangci-lint
with only-new-issues: true, which flags findings on changed lines even when
the same finding already exists elsewhere in the file, and pins v2.12. I had
been comparing aggregate issue counts against the base with v2.8. Re-checked by
extracting the exact lines this branch adds or changes and intersecting them with
a full v2.12 run: zero findings on any of them.

tests (01) — flaky, not from this PR. Re-running.

--- FAIL: TestReactorValidatorSetChanges (120.08s) — a timeout, not an
assertion.

This PR cannot reach it:

  • internal/consensus imports neither internal/blocksync nor
    internal/p2p/client, in production or test code, so nothing changed here is
    reachable from that test.
  • The test has prior flakiness fixes on record (test(consensus): fix flaky TestReactorValidatorSetChanges #1204, and earlier upstream
    "reduce size of validator set changes test").

Ran it 5 times in a row locally under -race: all pass, ~12s each against the
120s timeout it hit in CI.

govulncheck — waiting on #1395

The Go stdlib advisory (GO-2026-5856). #1395 bumps to 1.26.5 and is fully
green; this PR clears once that merges and CI is re-run.

🤖 Addressed by Claude Code

@lklimek

lklimek commented Jul 28, 2026 •

Copy link
Copy Markdown
Collaborator

Audit Summary — PR #1396 fix(blocksync): survive transient peer failures and stalls

Reviewed by: Claude Code with a 3-agent team:

  • security-engineer-smythe (opus) — OWASP-classified security review, concurrency and DoS surface
  • project-reviewer-adams (opus) — cross-artifact consistency (code ↔ docs ↔ tests ↔ config), code quality
  • qa-engineer-marvin (sonnet) — adversarial correctness, execution-verified claims

Every one of the 18 findings was then independently re-validated by a 4th adversarial pass (all returned valid). The three blocking findings were not merely read — they were reproduced by throwaway probe tests compiled and run against this worktree at 09530ab:

  • numFailures 4 → 0 after a single StatusResponse (AddPeer → Put wholesale-replaces PeerData)
  • numPending driven to -2 by three failures, after which FindTimedoutPeers() returns empty — the failing peer escapes the slow-peer eviction check entirely
  • eviction verdict returned with 15 requests still pending — five concurrent in-flight timeouts, not five sequential retries

Overall assessment

The PR's stated goal is to survive transient peer failures and stalls without punishing peers unnecessarily. The bounded stall/handover mechanism (maxSyncStall) and the TOCTOU fix threading caughtUp out of WaitForSync are both genuine, correctly-scoped improvements, and integration with the two PRs beneath it in the stack (#1393's RemovePeer, #1394's UpdateMonitor) is clean.

But the core new mechanism — count consecutive failures, evict at a threshold — has three independent logic defects, each of which separately defeats the PR's own stated purpose:

  1. The failure counter is reset by any StatusResponse — which every peer sends every ~10s, unsolicited and unauthenticated, and which the peer store accepts unconditionally. A single failed request costs the full 15s peerTimeout, so a peer failing requests serially can never reach 5 consecutive failures. The eviction threshold is practically unreachable for exactly the deliberate-misbehavior case it exists to catch.
  2. The counter's semantics don't match its name or doc comment — block requests are pipelined (up to 20 concurrent per peer), so one transient outage window times out 5+ requests at once and evicts the peer on the first window. That is precisely the transient-failure case the PR title promises to survive.
  3. AddFailure's unfloored numPending-- drives the count negative — which both exempts the failing peer from the slow-peer eviction check (FindTimedoutPeers requires numPending > 0) and keeps it eligible for selection when honest peers' concurrency caps bind. Failure is rewarded with more traffic, on the exact height that just failed.

Everything else found — a ~540-line Error-level log flood per stall episode, an unauthenticated peer height gating a 10× longer lockout window, an undocumented behavior change on three shared client APIs, structural/idiom nits, and missing coverage on the new instrumentation and the TOCTOU fix itself — is real and worth fixing, but none of it independently breaks the PR's stated contract the way the three blocking items do.

Verdict: request changes. Fix the failure-counting mechanism on three fronts before merge — make the counter resistant to a StatusResponse reset, make it reflect actual failed request rounds rather than concurrent in-flight timeouts, and floor numPending at zero. The stall-handling and TOCTOU-fix portions are sound and can stay as-is; the log-flood, stall-window-trust, and undocumented-API-contract findings are good fast-follow candidates but need not gate this PR.

Findings

18 findings (0 CRITICAL / 0 HIGH / 8 MEDIUM / 10 LOW) — 22 raw, deduplicated to 18 across 3 reviewers (36% redundancy; two findings were independently raised by all three agents).

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 in reactor.go but are used only by synchronizer.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 by STYLE_GUIDE.md.

Positive observations

  • The TOCTOU fix is genuinely correct: threading caughtUp out of WaitForSync into SwitchToConsensus(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 maxSyncStall ceiling is the right structural move, and extracting stallVerdictFor as a pure, table-tested decision function is good practice — TestStallVerdictFor covers the decision table thoroughly.
  • Stack integration is clean: interaction with fix(blocksync): don't punish peers for duplicate block responses #1393's RemovePeer and perf(blocksync): remove redundant work from the block apply path #1394's UpdateMonitor was 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

@thepastaclaw

thepastaclaw commented Jul 30, 2026 •

Copy link
Copy Markdown

⛔ Blockers found — Sonnet deferred (commit d5c1c1e)
Canonical validated blockers: 2

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

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.

Comment on lines +417 to 424
// 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

@Claudius-Maginificent

Copy link
Copy Markdown
Collaborator

Independent re-review: this PR's two stated fixes don't hold

A 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.
AddPeer/Put replaces a peer's entire PeerData struct on every inbound StatusResponse — which this node's own status-request loop solicits every ~10s, faster than the 15s fetch timeout. That silently zeroes numFailures before it can reach the new 5-strike threshold. Confirmed by simulation: 400 consecutive block-fetch timeouts from one peer (structured as repeated [4 failures, 1 status-reset]), zero evictions. A peer that never delivers a usable block but answers status pings on schedule is never removed — worse than the pre-PR behavior (immediate eviction on any failure), not an improvement on it.

2. The timeout punishment wasn't removed, it relocated. newPromise stopped sending PeerError on timeout, but its defer removePending still fires immediately, deleting the pending-request record. When the busy peer's response does arrive late, Client.iter can't find that record and reports p2p.PeerError itself from a completely different code path (client.go:317) — which still evicts on HasMaxPeerCapacity(), i.e. exactly under the load this PR targets. The PR's own motivating scenario (a peer busy serving one request at a time gets punished for answering late) still happens; it's just triggered a few lines later, from a different function.

3. It can't distinguish "slow" from "lying." errBlockFetch wraps five distinct failure kinds (timeout, no-response, malformed block, failed validation, wrong-height response) into one bucket, so a peer sending deliberately wrong-height responses gets the identical 5-strike grace period as one that's merely busy — confirmed by mutation test (4 consecutive deliberate protocol violations, zero eviction attempts). The PR's own comment justifies the tolerance as "usually a timeout, not a bad peer" — that justification doesn't hold once the failure is provably not a timing artifact.

4. The highest-risk new path can't be tested, for an unrelated reason. WaitForSync already uses an injected clockwork.Clock (s.clock) elsewhere in the same function for testability, but its own stall-detection loop reads real wall-clock time via a hardcoded time.NewTicker instead. That makes the new 10-minute stall branch (see the maxSyncStall finding above) structurally impossible to exercise without waiting real minutes — which is presumably why it has zero test coverage today, rather than an oversight independent of the rest.

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: pr-1396-review-report.md (available on request).

🤖 Co-authored by Claudius the Magnificent AI Agent

QuantumExplorer and others added 2 commits August 4, 2026 11:10
- 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]>
Base automatically changed from perf/blocksync-apply-path to v1.6-dev August 8, 2026 14:52
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]>
@shumkov
shumkov merged commit 3b8cca1 into v1.6-dev Aug 8, 2026
16 checks passed
@shumkov
shumkov deleted the fix/blocksync-peer-resilience branch August 8, 2026 15:33
shumkov added a commit that referenced this pull request Aug 17, 2026
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]>
shumkov added a commit that referenced this pull request Aug 17, 2026
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]>
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.

5 participants