Repository navigation
fix(consensus): resend catch-up block parts to prevent lagging-peer wedge - #1365
Conversation
TestReactorValidatorSetChanges intermittently hung for 120s (e.g. PR #1362 CI: a node stuck at height 17 during a validator-set change). The root cause is a consensus catch-up gossip wedge, not test timing. When a node falls behind, peers catch it up via GossipBlockPartsForCatchup. If the lagging node is still at RoundStepNewHeight/Propose with a nil ProposalBlockParts, it drops the incoming block part ("received a block part when we are not expecting any", state_add_prop_block.go). The sender, however, had already optimistically recorded the part as delivered (updatePeerProposalBlockPart), so prs.ProposalBlockParts.Not().PickRandom() reports nothing missing and the part is never resent. The catch-up commit then arrives, the node stores it and builds an empty part set from the commit header ("Commit came in before proposal", state_data.go), and waits forever for a part that is never resent -> permanent wedge. In production this recovers via propose/round timeouts (which reset peer round state and re-trigger gossip) and via blocksync. The test disables both (onlyOnce mock ticker, consensus-only reactor), turning the latent fragility into a hang. Fix: catch-up block-part gossip no longer optimistically marks the part as delivered; it keeps resending the missing part each gossip tick until the peer applies the block and advances its height. This mirrors the "resend until acked" behavior already used for catch-up commits and removes catch-up's dependency on timeouts to recover a dropped part. Regular same-height block-part gossip is unchanged. Adds TestGossipBlockPartsForCatchupResends as a regression guard. Before: wedge reproduces under high-contention parallel -race stress (captured at heights 17 and 19). After: 0 wedges across ~600 -race runs; the gossiper unit suite and single-instance -race runs pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[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 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)
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. Comment |
|
@thepastaclaw please review |
There was a problem hiding this comment.
Pull request overview
This PR fixes a consensus catch-up gossip wedge where a lagging peer can drop an early block-part, but the sender incorrectly records it as delivered and never resends it—potentially leaving the peer stuck forever at that height.
Changes:
- Adjusted catch-up block-part gossip to not optimistically mark parts as delivered, ensuring missing parts are resent on subsequent gossip ticks until the peer advances.
- Extended
syncProposalBlockPartwith amarkPeerHasPartflag so same-height gossip keeps the existing “optimistic mark” behavior while catch-up gossip disables it. - Added a regression test asserting that catch-up block-part gossip resends and does not update peer state optimistically.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.
| File | Description |
|---|---|
internal/consensus/gossiper.go |
Stops optimistic “peer has part” marking on catch-up block-part sends while preserving same-height behavior. |
internal/consensus/gossiper_test.go |
Adds deterministic regression test verifying catch-up block parts are resent and not marked delivered. |
|
@thepastaclaw please review 🤖 Co-authored by Claudius the Magnificent AI Agent |
|
✅ Review complete (commit 042e7b5) |
thepastaclaw
left a comment
There was a problem hiding this comment.
Code Review
Targeted, intentional fix for a consensus catch-up wedge: removes the optimistic mark on catch-up block parts so a lagging peer keeps receiving them until it actually advances. The change is well-scoped (sender-only, no signing/encoding/validation surface) and ships with a clear regression test. Findings are limited to two misleading new/stale comments, a thin single-part test, and one explicitly acknowledged tradeoff (unbounded resend against a non-progressing peer) that both agents flagged.
🟡 2 suggestion(s) | 💬 2 nitpick(s)
2 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/consensus/gossiper.go`:
- [SUGGESTION] internal/consensus/gossiper.go:169-213: Catch-up resend has no per-peer rate floor or eviction path
With `markPeerHasPart=false`, the local view of the peer's `ProposalBlockParts` bitarray never converges as long as the peer reports a stale height, so every `PeerGossipSleepDuration` tick (100ms default, 5ms validator profile) we call `loadMeta` + `loadPart` (disk reads) and push another block-part envelope. A peer slot occupied by a non-progressing node — accidentally stuck or adversarial — keeps the path hot indefinitely; pre-PR a single pass over the part set put a natural ceiling on this. The PR description already calls this out as an acknowledged tradeoff and the fix is strictly safer than the prior wedge (which was a chain-liveness loss, not just bandwidth), so this is not blocking — but a follow-up to add a coarse per-peer/per-part cooldown, or to bound retries before reconsidering the peer, would close the amplification gap without re-introducing the wedge.
In `internal/consensus/gossiper_test.go`:
- [SUGGESTION] internal/consensus/gossiper_test.go:413-449: Regression test only exercises a single-part block
`TestGossipBlockPartsForCatchupResends` asserts `partSet.Total() == 1` (line 418), so `PickRandom()` over `BitArray().Not()` always returns index 0. The test cannot distinguish "catch-up correctly iterates missing indices" from "the only missing index gets re-picked" — it locks in the single-part wedge case (which is exactly the failure mode the PR fixes) but doesn't document behavior on realistic multi-part blocks where the PR description explicitly notes redundant sends without per-part dedup. A multi-part variant (e.g. `Total() >= 3`) asserting that after N ticks every index has been Sent at least once would lock in the broader resend invariant.
…send test Fix 1 (gossiper.go ~line 207): remove the false claim that catch-up block-part gossip "mirrors the 'resend until acked' behavior used for catch-up commits." GossipCommit is single-shot: updatePeerCommit calls SetHasCommit on first send and GossipCommit early-returns on HasCommit, so commits are never resent. Keeping a false invariant in a comment near consensus-critical gossip logic is a maintenance hazard; the sentence is replaced with a clean full-stop that preserves the correct WHY. Fix 2 (gossiper_test.go): add TestGossipBlockPartsForCatchupResendsMultiPart. The existing single-part test cannot distinguish "iterates all missing indices" from "always re-picks the only index." The new test builds a 3-part block, leaves all parts missing on the lagging peer, runs 90 gossip ticks (coupon-collector ≈5.5 ticks; P(miss any index) <10^-16), and asserts every part index was sent at least once AND the peer's ProposalBlockParts bit-array was never optimistically marked. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
'serialises' → 'serializes' in TestGossipBlockPartsForCatchupResendsMultiPart comment (gossiper_test.go:462), fixing the misspell linter finding that was blocking PR #1365 CI. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
thepastaclaw
left a comment
There was a problem hiding this comment.
Code Review
Narrow, consensus-safe liveness fix for catch-up block-part gossip. Catch-up sends no longer optimistically mark parts as delivered, so a lagging peer at RoundStepNewHeight/Propose that drops the part keeps receiving it until it advances. The same-height gossip fast path is preserved via the new markPeerHasPart flag, the corrected comment removes a misleading 'resend until acked' claim, and the added multi-part regression test exercises iteration across all missing indices.
thepastaclaw
left a comment
There was a problem hiding this comment.
Code Review
PR #1365 is a narrowly scoped, correct fix for a catch-up gossip wedge in internal/consensus/gossiper.go. Same-height gossip behavior is preserved while catch-up sends no longer optimistically mark parts as delivered, ensuring resends continue until the peer applies the block. The sync() helper safely handles a nil syncFunc, and the change ships with both a deterministic regression test and a multi-part resend test. All four agent reviews converged on no in-scope findings.
|
@thepastaclaw please re-review — your two prior suggestions are addressed:
CI should now be fully green (all 6 shards were already passing; misspell was the only blocker). 🤖 Co-authored by Claudius the Magnificent AI Agent |
* fix(evidence): make evidence sync resilient to peer-routing race 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]> * fix(evidence): recover from PeerStatusUp/route-ready race via periodic 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]> * fix(evidence): address copilot review: comment clarity, log level, test 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]> * fix(evidence): use non-zero-size sync token and stop rebroadcast on AddEvidence 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]> * fix(evidence): bound resync by MaxBytes, uint64 sync token, guard test (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]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
…imeouts in reactor test (#1418) * test(consensus): restore real timeout ticker in TestReactorValidatorSetChanges The test drove its 7-node network with newMockTickerFunc(true), which forwards only RoundStepNewHeight timeouts and only the first one; every other scheduled timeout is discarded. That leaves the network without timeoutPropose, without timeoutPrevoteWait/timeoutPrecommitWait and, after the first height, without timeoutNewHeight — so consensus has no way to change round and no way to start a height it committed without receiving a peer commit. Any perturbation is therefore permanent, and the test hangs until its 2-minute context deadline. Both observed CI failure shapes follow from this. A proposal delayed past MessageDelay+Precision makes every validator prevote nil, and the round change that would recover never fires. Separately, a node that applies a commit itself sits at RoundStepNewHeight forever; when it is the next proposer, nobody proposes and nobody times out waiting. Restore the real ticker, which "chore(consensus): stabilize consensus algorithm (#284)" had already established before #1204 reverted it, and give rounds enough wall clock to complete on a loaded runner. Round timeouts only fire when the network stalls, so larger values cost nothing on the healthy path, while 2s/1s makes a starved CI runner abandon rounds it would have completed, leaving it to churn instead of converge. Verified with go test -race -count=10: the old code fails 1/10 on an idle 16-core host, reproducing the CI signature exactly (all seven nodes report a waitForAndValidateBlock deadline, one with "subscription terminated by publisher"); the new code passes 20/20 over two such runs. Under three concurrent copies of the test the pass rate rises from 10/18 to 14/15. Refs #1405 <sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub> Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01RoXmbFrVf1BqVW1BHZv6Va * fix(consensus): bound catch-up block-part resends to one pass per interval GossipBlockPartsForCatchup never marks catch-up parts as delivered, so prs.ProposalBlockParts.Not().PickRandom() keeps finding the same index missing and the part is re-sent on every gossip tick. The loop ends only when our own view of the peer's height advances, and the traffic it generates delays exactly the NewRoundStep messages that would advance it. Measured in a 7-node race-enabled reactor test: 1091 height-11 block parts pushed at a node that had already reached height 12, every one discarded, against 9 completed proposal blocks in the same window. The live round cannot assemble its proposal, every validator prevotes nil, and the height churns rounds until the test deadline. The same loop drives the part-set-header mismatch branch, which logs at error level on every tick without sending anything. Bound it to one part-set pass per catchupResendInterval. A pass spends one send per part; once complete, further ticks are skipped until the interval elapses, then a new pass begins. A peer that silently dropped its parts is therefore still served repeatedly for as long as it stays behind, so the wedge fixed in #1365 stays fixed, while a peer we only believe to be lagging costs one pass rather than one send per tick. Parts are still never marked delivered, keeping that guarantee independent of PeerState bookkeeping — which is unreliable here, since SetHasProposalBlockPart ignores updates whose round differs from the peer's current round and catch-up passes the committed block's round. At 4 concurrent race-enabled copies of TestReactorValidatorSetChanges, where the unbounded loop passes 2/16, this passes 16/16 — matching a full revert of the resend behaviour while keeping its protection. Also 18/18 at 3 concurrent copies and 10/10 unloaded. Wasted catch-up parts drop from 164592 to 2845 per batch (a revert scores 2736), and the wedge precondition "Commit came in before proposal" occurs 632 times across those runs with zero wedges. The two tests from #1365 now assert the bounded contract: parts are still never marked delivered, no resend occurs inside the interval, and a resend follows once the clock advances past it. <sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub> Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01RoXmbFrVf1BqVW1BHZv6Va * fix(consensus): budget catch-up passes by missing parts, not bit-array size beginCatchupAttempt sized a catch-up pass with prs.ProposalBlockParts.Size(), the length of the peer's bit-array, while GossipBlockPartsForCatchup draws indices from prs.ProposalBlockParts.Not().PickRandom() — the unset bits alone. A peer reporting all but one part present therefore had every draw in the pass return that same index, so the one missing part was re-sent once per entry in the array before the interval pause. That bit-array arrives from the network. NewValidBlockMessage. ValidateBasic checks only that its length equals BlockPartSetHeader.Total, never the bit pattern, and PeerState.ApplyNewValidBlockMessage installs it wholesale. A peer can thus pick the amplification factor, up to MaxBlockPartsCount (1601) sends of a single part per interval, which largely defeats the bound. Budget on the number of parts the peer reports missing instead, and return early when none are. CountTrueBits has no nil receiver guard, unlike Size, so the nil bit-array is rejected first; the sole production caller already checks it, but the previous Size call was nil-safe and that property is worth keeping. The bound can now only tighten: missing is at most the array length, and is equal to it in the common case where a lagging peer holds none of the parts, so catch-up throughput for genuinely lagging peers is unchanged. Adds a regression case for a bit-array with a single unset bit, which draws 3 sends per pass before this change and 1 after, plus a case for a peer that reports the complete part set, which must open no pass at all. <sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub> Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01RoXmbFrVf1BqVW1BHZv6Va * fix(consensus): fix the catch-up pass budget against peer bitmap swaps beginCatchupAttempt derived the pass threshold from prs.ProposalBlockParts on every call while catchupAttempts and catchupRetryAt persisted across calls, so the peer that owns that bit-array could move the threshold out from under the counter. Two ways, both reachable through NewValidBlockMessage, whose ValidateBasic checks only the array's length: Lowering the reported missing count to the number of sends already made takes the "pass spent" branch while catchupRetryAt is still zero, because that field was only assigned once the counter reached the earlier, larger threshold. The wait is then measured against the zero time, the counter resets and sending continues. Repeating one decrement at a time telescopes into roughly N^2/2 sends before any wait applies. Raising it afterwards is simpler still: the counter no longer meets the threshold, so the branch holding the deadline check is skipped entirely and a deadline already set is stepped over. Draw from a remaining-budget counter instead. Opening a pass fixes both the budget and the deadline together, and the budget only counts down, so neither can be re-derived from anything the peer sends mid-pass. There is no longer a state where a pass is spent but no deadline exists. The height reset stays: ApplyNewRoundStepMessage drops any message that does not advance the peer's height/round/step, so a peer cannot replay it to reopen passes, and it can only keep doing so by advancing out of the catch-up window. Removing it would instead make every legitimately advancing peer wait an interval per height. Sends per interval remain bounded by the block's real part count: ensurePeerPartSetHeader rejects a fabricated part-set header, so a peer inflating the count buys early exits rather than sends. The regression test drops the reported count to the sends already made and then raises it again, drawing 5 sends from a 3-send pass before this change and 3 after. TestGossiper, TestPeerGossipWorker and TestReactorValidatorSetChanges pass; 16/16 at 4 concurrent race-enabled copies with wasted catch-up parts at 3002 against 2845 before, so the storm bound is unchanged. <sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub> Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01RoXmbFrVf1BqVW1BHZv6Va * fix(consensus): end a catch-up pass that cannot send beginCatchupAttempt charged a budget slot before loadMeta, the part-set header check and loadPart, none of which ended the pass when they failed. The peer supplies both the missing bit-array a pass is budgeted from and the part-set header those checks run against, and ValidateBasic accepts any well-formed pair, so it could open a maximum-size pass under a header matching no stored block. That bought two things. A pass that can never send charged a block-store read and an error log to every gossip tick for its whole budget - roughly 160s at the production 100ms cadence - and since the retry deadline was armed when the pass opened, it had long expired by the time the budget ran out, so the next pass began immediately and the interval never throttled anything. The same inflated budget also survived the peer replacing its state, at the same height, with the stored block's real header and a single missing part: the budget is deliberately not re-derived once a pass is open, so the remainder landed as duplicate sends of that one part. Move the send into sendCatchupBlockPart and abandon the pass, arming a fresh retry deadline, whenever it reports that no part reached the peer. A pass now costs at most one failed attempt per interval, and only a pass that got as far as sending keeps its budget. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01RoXmbFrVf1BqVW1BHZv6Va * fix(consensus): close catch-up pass gaps thepastaclaw flagged as still exploitable Two gaps let a peer defeat the catch-up throttle this PR is adding: - beginCatchupAttempt armed catchupRetryAt when a pass opened. A pass with enough missing parts to span more gossip ticks than catchupResendInterval takes longer than the interval to exhaust its budget, so the deadline had already elapsed by the time the pass finished - the next tick reopened a fresh pass with no quiet gap at all. Arm the deadline when the pass's last attempt is spent instead. - The pass budget was fixed at open and never revisited downward. A peer fully controls ProposalBlockParts over the wire (NewValidBlockMessage. ValidateBasic checks only length, ApplyNewValidBlockMessage installs it wholesale) and can open a pass reporting many parts missing, then swap in a bit-array with only one unset bit — every remaining budgeted attempt then draws that same index, funding repeated duplicate sends of it. Clamp the remaining budget down whenever the peer's current missing count drops below it; never raise it back up. Adds regression tests for both: a 6-part pass ticked across catchupResendInterval to show the deadline is measured from the pass's last send, and a 5-part pass whose bitmap shrinks mid-pass to show the budget clamps to the peer's current report. Both fail against the pre-fix code. Addresses thepastaclaw findings on PR #1418. <sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub> Co-Authored-By: Claude Sonnet 5 <[email protected]> * perf(consensus): avoid a full bit-array copy to count missing catch-up parts beginCatchupAttempt derived the peer's missing-part count via Not().CountTrueBits(), which allocates and copies the whole (peer-controlled, up to MaxBlockPartsCount) bit-array on every gossip tick just to count it. sendCatchupBlockPart already performs its own Not().PickRandom() when a send actually happens, so this was a second, avoidable full-array allocation on every tick regardless of whether a send occurs. Derive the same count as size minus set bits instead. Addresses a copilot review comment on PR #1418. <sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub> Co-Authored-By: Claude Sonnet 5 <[email protected]> * fix(consensus): honor catch-up send failures, close height-advance evasion Layers on top of review-stream's retryAt-at-close and downward-clamp fix in beginCatchupAttempt. Distinct fixes: - syncProposalBlockPart (pre-existing, untouched elsewhere in this PR) unconditionally returned nil, so a failed send never reached endCatchupPass despite the caller's contract assuming it would. sendCatchupBlockPart now reports success as a bool instead of an error nobody was meant to inspect, and its "no missing part" branch can no longer be hit (the comment claiming otherwise was already false: prs is a fresh per-tick deep copy nothing else can mutate). - A peer's height advancing reset the retry deadline as well as the budget, granting a free pass on every height step; only the budget resets now. - The three catch-up fields were guarded only by a comment claiming a single caller, despite the same *msgGossiper being shared across three concurrent handler goroutines; a mutex now guards them structurally. - Documented the rate limit's actual scope (per gossip worker, not per peer -- a reconnect gets a fresh one) on the Gossiper interface and the actual tick-to-interval relationship on catchupResendInterval, both previously undocumented. Co-Authored-By: Claude Sonnet 5 <[email protected]> * docs(consensus): fix stale catch-up comment in dataGossipHandler GossipBlockPartsForCatchup is rate-limited and returns without sending on most ticks, so "block parts already delivered" no longer describes what happened before the unconditional GossipCommit call on the same branch. Co-Authored-By: Claude Sonnet 5 <[email protected]> * fix(consensus): propagate the real send error from syncProposalBlockPart syncProposalBlockPart unconditionally returned nil regardless of the underlying send's actual result, so sendCatchupBlockPart's error check against it (added in the prior commit) was dead code: a send that never reached the peer was indistinguishable from one that did, and endCatchupPass never fired for that failure mode -- the pass kept spending its budget one failed attempt per tick instead of ending on the first one, exactly the spin endCatchupPass exists to prevent. Fix at the source: return g.sync's result directly and drop the now-redundant local log, since both callers already log a non-nil error themselves. The other caller, GossipProposalBlockParts, only ever logged this error and took no other action, so propagating it for real is behavior-preserving there. Regression test advances a fake clock across many ticks with every send forced to fail and asserts exactly one block-part read per catchupResendInterval, not one per tick; confirmed failing (5 reads instead of 1) against the pre-fix code. Co-Authored-By: Claude Sonnet 5 <[email protected]> * fix(consensus): arm catch-up retry deadline when a peer's height advance interrupts a live pass A peer that advances its reported height mid-pass (before the pass exhausts its own budget) reset catchupRemaining to 0 without arming catchupRetryAt, since the deadline was only ever armed when a pass ran its budget down naturally. A peer whose height ticks forward every gossip tick therefore got a fresh full-budget pass every tick forever, completely bypassing catchupResendInterval for the common multi-part-block case. Arm the deadline on the height-change branch too whenever a pass was actually in flight, matching the same invariant beginCatchupAttempt's normal exhaustion path already upholds. Document that invariant on the struct fields it protects. Also, while re-auditing this function for the same iteration: - stop re-deriving the budget from a peer-controlled bit-array once a pass is open (now g.catchupRemaining = min(g.catchupRemaining, missing), replacing an equivalent but more verbose branch) - de-duplicate the block-store-failure error logs in sendCatchupBlockPart; blockRepository.loadMeta/loadPart already log the failure, so the caller's second log was pure noise - correct sendCatchupBlockPart's doc (it reports handoff to the p2p channel, not peer delivery) and give its error log a distinct message from GossipProposalBlockParts's - correct the Gossiper interface, catchupResendInterval, and endCatchupPass doc comments, which described a flat one-send-per- interval bound that does not hold for multi-part blocks Co-Authored-By: Claude Sonnet 5 <[email protected]> * test(consensus): pin the height-advance throttle bug and fix stale/weak catch-up assertions - Add TestGossipBlockPartsForCatchupHeightAdvanceInterruptingPassIsThrottled, a regression test for the height-advance bug fixed in gossiper.go: confirmed RED (20 sends) against the pre-fix code via git stash, GREEN (1 send) after the fix. - Rename/rewrite TestGossipBlockPartsForCatchupBudgetIsFixedAtPassOpen to TestGossipBlockPartsForCatchupBudgetIsNeverRaisedMidPass: the old sequence never actually drove catchupRemaining below the reported missing count it then 'raised', so the raise-attempt it claimed to guard against was a no-op the test would pass on regardless. The new version forces a real clamp (5-part block, drop to 1 missing after two sends) before attempting to raise the count back up, and asserts the raise is not honored before the interval elapses. - Strengthen TestGossipBlockPartsForCatchupPeerHasEveryPart with an explicit AssertNotCalled, so it fails loudly instead of silently if a send is ever wired in for a peer that already has every part. - Update the two wantLog assertions in TestGossipBlockPartsForCatchup that still expected the removed 'couldn't find a block meta/part' caller-side logs; the block-store-failure messages they should match are now blockRepository's own 'failed to load block meta'/'failed to load block part'. Co-Authored-By: Claude Sonnet 5 <[email protected]> * fix(consensus): share one clock between msgGossiper and its peerGossipWorker newPeerGossipWorker constructed two independent clockwork.NewRealClock() instances for what is meant to be one gossip worker's shared notion of time. They agree in practice (both wrap wall-clock time), but nothing enforces that, and it defeats point-in-time comparisons in tests that inject a single fake clock expecting both call sites to observe it. Construct one clock and pass it to both. Co-Authored-By: Claude Sonnet 5 <[email protected]> * docs(consensus): correct dataGossipHandler's stale catch-up rate-limit comment The comment described GossipBlockPartsForCatchup as rate-limited and a no-op on most ticks, which held before this PR's changes but not after: a pass now spends one send per tick for as many ticks as the peer reports parts missing, and the quiet gap applies only between passes, not on most individual ticks. Reword to match. Co-Authored-By: Claude Sonnet 5 <[email protected]> * docs(config): cross-reference PeerGossipSleepDuration's coupling to the catch-up throttle PeerGossipSleepDuration sets the tick rate that internal/consensus/gossiper.go's catchupResendInterval throttle is metered against: configuring it above that fixed interval silently disables the throttle. Document the coupling at both the struct field and the generated TOML template so an operator tuning gossip cadence sees the side effect. Co-Authored-By: Claude Sonnet 5 <[email protected]> * perf(consensus): skip the missing-part scan while a catch-up pass is backed off beginCatchupAttempt computed missing (Size() - CountTrueBits(), an O(bits) scan of the peer-controlled ProposalBlockParts array) unconditionally, even on ticks that are going to return false immediately because the pass is still within catchupRetryAt's backoff. At production defaults most gossip ticks land in backoff (a pass's quiet interval is ~5x the gossip cadence), so this scanned a bit-array up to MaxBlockPartsCount long on nearly every tick for no reason. Move the backoff check ahead of the scan: when no pass is open and the retry deadline hasn't elapsed, return early without touching ProposalBlockParts at all. The scan still runs whenever it can affect the outcome - opening a new pass, or clamping an active one's budget down to a shrunk missing count. Addresses a copilot review comment on PR #1418. <sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub> Co-Authored-By: Claude Sonnet 5 <[email protected]> * fix(consensus): close an open catch-up pass when the peer reports it complete beginCatchupAttempt returned early on missing == 0 without touching catchupRemaining/catchupRetryAt. When that happened mid-pass (catchupRemaining > 0, budget not yet exhausted), the pass stayed open indefinitely: noOpenPass would keep evaluating false forever, so the backoff check above it — which only runs while no pass is open — was skipped on every later tick regardless of elapsed time. A peer could freeze catchupRemaining above zero by reporting a complete part set whenever it liked, then resume sending immediately the next time it reported parts missing, with no retry interval honored at all. Close the pass in that case too: zero the remaining budget and arm the retry deadline, matching what happens when a send fails or a height change interrupts a pass. Only do this when a pass was actually open; a peer that has simply always reported a complete set must not have a wait imposed on it. Also corrects a stale doc comment on PeerGossipSleepDuration added by the same throttle: catchupResendInterval is a fixed quiet gap that does not scale with the gossip tick duration, it only fits more ticks into that same window. Adds a regression test that opens a pass, spends one send, has the peer report complete, then report missing again on the same simulated instant - asserting no send until the retry interval elapses. Fails against the pre-fix code (an immediate second send). Addresses copilot review comments on PR #1418. <sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub> Co-Authored-By: Claude Sonnet 5 <[email protected]> * docs(consensus): reclassify the missing==0 mid-pass fix as CPU-amplification, not a throttle bypass df8a6057c's commit message and code comments described the missing==0 mid-pass fix as letting a peer "resume sending... with no retry interval honored at all", which reads as a flooding/throttle-bypass concern. On closer trace (independently by team-lead and grumpy-stream) that's not accurate: catchupRemaining only ever counts down, never up, so total sends per pass are identically bounded by the budget fixed at pass open whether or not this fix exists. Nothing here lets a peer exceed that budget or the one-send-per-tick ceiling. The actual defect is CPU amplification: leaving a pass open indefinitely (via alternating missing==0 reports) keeps noOpenPass false forever, which permanently defeats 3b9463dd0's backoff-skip check - the O(bits) scan of the peer-controlled, up-to-MaxBlockPartsCount bit-array then runs on every single gossip tick instead of being skipped during backoff, for as long as the peer holds the pass open this way. It also predates this PR: grumpy traced the same missing==0 short-circuit in the 5978b27 baseline and both its parent commits, so this isn't new here - it only started costing more once 3b9463dd0 added a backoff-skip path for it to defeat. Also records a deliberate behavior change for honest peers: closing the pass on missing==0 means a peer that legitimately completes its part set and later falls behind again now waits out one catchupResendInterval before catch-up resumes, rather than resuming on its very next report. Accepted: a peer that just reported complete is not starving, and the wait is negligible against block time. No functional change from df8a6057c - comments only, on both the fix and its regression test. <sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub> Co-Authored-By: Claude Sonnet 5 <[email protected]> * fix(consensus): end a catch-up pass when a block-store read panics GossipBlockPartsForCatchup only called endCatchupPass() on a normal false return from sendCatchupBlockPart. But sendCatchupBlockPart's block-store reads (blockRepository.loadMeta/loadPart, wrapping LoadBlockMeta/ LoadBlockPart) panic deliberately on a decode or read failure rather than returning an error - runGossipHandler recovers that panic per gossip tick, logs a full stack, and keeps ticking, same as it does for every other peer-facing panic path in the node. A panic there unwinds straight past the if-check, so endCatchupPass() never runs and the pass stays open with its remaining budget intact. Since the peer controls both the height and the missing bitmap a pass is budgeted on, a peer that names a height whose stored record is corrupt or unreadable gets a fresh attempt - and a fresh panic, and a fresh full-stack log - on every tick for the rest of the pass's budget (up to ~160s for a maximum-size 1,601-part report at the default cadence) instead of ending on the first failed attempt like every other failure mode this PR's earlier commits already cover. Settle the attempt in a defer instead of an if-check on the return value, so panic unwinding also reaches it. sendCatchupBlockPart's own return value still selects the fast path (success needs no settlement); the defer only changes what happens when it doesn't get the chance to return at all. Adds a regression test using a block-store mock that panics on LoadBlockMeta, asserting exactly one read (and thus one panic) per pass rather than one per tick for the whole budget - mirrors TestGossipBlockPartsForCatchupSendFailureEndsPass's structure for the already-covered normal-failure case. Confirmed failing (2+ reads instead of 1) against the pre-fix code. Addresses a thepastaclaw blocking finding on PR #1418. <sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub> Co-Authored-By: Claude Sonnet 5 <[email protected]> * fix(consensus): don't throttle a genuinely-advancing peer's next catch-up pass 25da4c2 removed the unconditional catchupRetryAt clear from the height-change branch to close a bypass, and ea2b81498 later armed it properly for a pass genuinely interrupted mid-flight (catchupRemaining > 0). The catchupRemaining == 0 case was never revisited: a deadline armed by the OLD height (by exhausting its own budget, or by the peer reporting complete) silently carried forward and throttled the NEW height's first pass by up to catchupResendInterval, for a peer that isn't replaying anything and owes nothing - it's genuinely further along. Catch-up is the only path offered to a peer at a different height than ours (regular gossip requires equal heights), so this taxes every honestly-advancing lagging peer once per height. This throttle does not exist on origin/v1.7-dev; it's a cost this PR's own commits introduced. Naively clearing catchupRetryAt whenever catchupRemaining == 0 at a height change (the obvious fix) reopens a worse gap than intended, though: it cannot tell "the previous pass genuinely finished" apart from "an INTERMEDIATE height in a rapid chain never got a chance to open a pass at all, and is still serving an earlier interruption's penalty" - both look identical (remaining == 0) at the moment of the next height change. Verified by writing TestGossipBlockPartsForCatchupHeightAdvanceInterruptingPassIsThrottled first: a naive version of this fix turns its pinned 1 send across 20 rapid height-hops into 10, because every OTHER hop's remaining == 0 came from the previous hop being blocked, not from a pass finishing. Track WHY catchupRetryAt is currently armed instead: catchupRetrySticky is true when the deadline covers unrendered service (a pass interrupted before exhausting its own budget, or a failed attempt via endCatchupPass) and must survive a height change - including a chain of several - and false when the pass closed because it had genuinely nothing left to do (spent its own budget in full, or the peer reported complete). The height-change branch only clears catchupRetryAt when it's non-sticky (or already elapsed); otherwise it's left untouched, whatever height change caused it to be checked. This does still leave a bounded gap in the non-sticky case, stated explicitly in the code rather than glossed: a peer can open a pass, let it close cleanly (one real send, e.g. by reporting a single missing part), then immediately claim a new height and repeat, getting one send per gossip tick indefinitely instead of one pass per interval. Bounded to at most 1 send/PeerGossipSleepDuration tick (10/s, ~640KB/s of block parts at production defaults), because CompareHRS enforces monotonic height only (no replay or ping-ponging) and ensurePeerPartSetHeader requires the real, currently-stored PartSetHeader for each claimed height (a mismatch ends the pass via the now-sticky endCatchupPass, costing a full interval rather than a send). Sustaining it requires marching forward through genuine, still-retained history, capped by blockStoreBase - no worse than the pre-#1365 catch-up rate this codebase already tolerated in production. Accepted as strictly cheaper than taxing every honestly-advancing lagging peer by up to 500ms per height; a verified-progress-gated redesign that closes it for real is tracked as follow-up, not done here. Two new regression tests, both proven against the pre-fix code: - TestGossipBlockPartsForCatchupCleanHeightAdvanceIsNotThrottled: a single-part pass closes cleanly, the peer immediately claims a new height with a fresh block - asserts an immediate send, not a catchupResendInterval wait. RED before this fix. - TestGossipBlockPartsForCatchupHeightAdvanceInterruptingPassIsThrottled (existing, extended doc comment): still asserts full throttling across 20 rapid, always-interrupted height hops - GREEN before this fix, and the guard that caught the naive version's regression above. <sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub> Co-Authored-By: Claude Sonnet 5 <[email protected]> * fix(consensus): start the catch-up quiet gap after the send, not before it beginCatchupAttempt armed catchupRetryAt from a timestamp taken on entry, before the caller had even reached sendCatchupBlockPart. The p2p channel applies backpressure on that very goroutine, so a slow send burned its own duration out of the quiet gap it was supposed to precede - the slower the peer's channel, the weaker the throttle. It now reports the pass's last slot to the caller instead of arming the deadline itself, and GossipBlockPartsForCatchup settles the pass from a fresh clock reading once the send returns. endCatchupPass and the new completeCatchupPass share settleCatchupPass, keeping one place where a drawn attempt closes a pass. The window where the pass is spent but its deadline is not yet armed keeps the documented invariant (a stale deadline with catchupRemaining == 0 is legal) and is unobservable: the single per-peer goroutine is inside the send for all of it, so no further attempt and no height change can run before it settles. Co-Authored-By: Claude Opus 5 <[email protected]> --------- Co-authored-by: Claude Opus 5 <[email protected]>
* fix(consensus): bound catch-up block-part resends and restore round timeouts in reactor test (#1418) * test(consensus): restore real timeout ticker in TestReactorValidatorSetChanges The test drove its 7-node network with newMockTickerFunc(true), which forwards only RoundStepNewHeight timeouts and only the first one; every other scheduled timeout is discarded. That leaves the network without timeoutPropose, without timeoutPrevoteWait/timeoutPrecommitWait and, after the first height, without timeoutNewHeight — so consensus has no way to change round and no way to start a height it committed without receiving a peer commit. Any perturbation is therefore permanent, and the test hangs until its 2-minute context deadline. Both observed CI failure shapes follow from this. A proposal delayed past MessageDelay+Precision makes every validator prevote nil, and the round change that would recover never fires. Separately, a node that applies a commit itself sits at RoundStepNewHeight forever; when it is the next proposer, nobody proposes and nobody times out waiting. Restore the real ticker, which "chore(consensus): stabilize consensus algorithm (#284)" had already established before #1204 reverted it, and give rounds enough wall clock to complete on a loaded runner. Round timeouts only fire when the network stalls, so larger values cost nothing on the healthy path, while 2s/1s makes a starved CI runner abandon rounds it would have completed, leaving it to churn instead of converge. Verified with go test -race -count=10: the old code fails 1/10 on an idle 16-core host, reproducing the CI signature exactly (all seven nodes report a waitForAndValidateBlock deadline, one with "subscription terminated by publisher"); the new code passes 20/20 over two such runs. Under three concurrent copies of the test the pass rate rises from 10/18 to 14/15. Refs #1405 <sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub> Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01RoXmbFrVf1BqVW1BHZv6Va * fix(consensus): bound catch-up block-part resends to one pass per interval GossipBlockPartsForCatchup never marks catch-up parts as delivered, so prs.ProposalBlockParts.Not().PickRandom() keeps finding the same index missing and the part is re-sent on every gossip tick. The loop ends only when our own view of the peer's height advances, and the traffic it generates delays exactly the NewRoundStep messages that would advance it. Measured in a 7-node race-enabled reactor test: 1091 height-11 block parts pushed at a node that had already reached height 12, every one discarded, against 9 completed proposal blocks in the same window. The live round cannot assemble its proposal, every validator prevotes nil, and the height churns rounds until the test deadline. The same loop drives the part-set-header mismatch branch, which logs at error level on every tick without sending anything. Bound it to one part-set pass per catchupResendInterval. A pass spends one send per part; once complete, further ticks are skipped until the interval elapses, then a new pass begins. A peer that silently dropped its parts is therefore still served repeatedly for as long as it stays behind, so the wedge fixed in #1365 stays fixed, while a peer we only believe to be lagging costs one pass rather than one send per tick. Parts are still never marked delivered, keeping that guarantee independent of PeerState bookkeeping — which is unreliable here, since SetHasProposalBlockPart ignores updates whose round differs from the peer's current round and catch-up passes the committed block's round. At 4 concurrent race-enabled copies of TestReactorValidatorSetChanges, where the unbounded loop passes 2/16, this passes 16/16 — matching a full revert of the resend behaviour while keeping its protection. Also 18/18 at 3 concurrent copies and 10/10 unloaded. Wasted catch-up parts drop from 164592 to 2845 per batch (a revert scores 2736), and the wedge precondition "Commit came in before proposal" occurs 632 times across those runs with zero wedges. The two tests from #1365 now assert the bounded contract: parts are still never marked delivered, no resend occurs inside the interval, and a resend follows once the clock advances past it. <sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub> Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01RoXmbFrVf1BqVW1BHZv6Va * fix(consensus): budget catch-up passes by missing parts, not bit-array size beginCatchupAttempt sized a catch-up pass with prs.ProposalBlockParts.Size(), the length of the peer's bit-array, while GossipBlockPartsForCatchup draws indices from prs.ProposalBlockParts.Not().PickRandom() — the unset bits alone. A peer reporting all but one part present therefore had every draw in the pass return that same index, so the one missing part was re-sent once per entry in the array before the interval pause. That bit-array arrives from the network. NewValidBlockMessage. ValidateBasic checks only that its length equals BlockPartSetHeader.Total, never the bit pattern, and PeerState.ApplyNewValidBlockMessage installs it wholesale. A peer can thus pick the amplification factor, up to MaxBlockPartsCount (1601) sends of a single part per interval, which largely defeats the bound. Budget on the number of parts the peer reports missing instead, and return early when none are. CountTrueBits has no nil receiver guard, unlike Size, so the nil bit-array is rejected first; the sole production caller already checks it, but the previous Size call was nil-safe and that property is worth keeping. The bound can now only tighten: missing is at most the array length, and is equal to it in the common case where a lagging peer holds none of the parts, so catch-up throughput for genuinely lagging peers is unchanged. Adds a regression case for a bit-array with a single unset bit, which draws 3 sends per pass before this change and 1 after, plus a case for a peer that reports the complete part set, which must open no pass at all. <sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub> Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01RoXmbFrVf1BqVW1BHZv6Va * fix(consensus): fix the catch-up pass budget against peer bitmap swaps beginCatchupAttempt derived the pass threshold from prs.ProposalBlockParts on every call while catchupAttempts and catchupRetryAt persisted across calls, so the peer that owns that bit-array could move the threshold out from under the counter. Two ways, both reachable through NewValidBlockMessage, whose ValidateBasic checks only the array's length: Lowering the reported missing count to the number of sends already made takes the "pass spent" branch while catchupRetryAt is still zero, because that field was only assigned once the counter reached the earlier, larger threshold. The wait is then measured against the zero time, the counter resets and sending continues. Repeating one decrement at a time telescopes into roughly N^2/2 sends before any wait applies. Raising it afterwards is simpler still: the counter no longer meets the threshold, so the branch holding the deadline check is skipped entirely and a deadline already set is stepped over. Draw from a remaining-budget counter instead. Opening a pass fixes both the budget and the deadline together, and the budget only counts down, so neither can be re-derived from anything the peer sends mid-pass. There is no longer a state where a pass is spent but no deadline exists. The height reset stays: ApplyNewRoundStepMessage drops any message that does not advance the peer's height/round/step, so a peer cannot replay it to reopen passes, and it can only keep doing so by advancing out of the catch-up window. Removing it would instead make every legitimately advancing peer wait an interval per height. Sends per interval remain bounded by the block's real part count: ensurePeerPartSetHeader rejects a fabricated part-set header, so a peer inflating the count buys early exits rather than sends. The regression test drops the reported count to the sends already made and then raises it again, drawing 5 sends from a 3-send pass before this change and 3 after. TestGossiper, TestPeerGossipWorker and TestReactorValidatorSetChanges pass; 16/16 at 4 concurrent race-enabled copies with wasted catch-up parts at 3002 against 2845 before, so the storm bound is unchanged. <sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub> Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01RoXmbFrVf1BqVW1BHZv6Va * fix(consensus): end a catch-up pass that cannot send beginCatchupAttempt charged a budget slot before loadMeta, the part-set header check and loadPart, none of which ended the pass when they failed. The peer supplies both the missing bit-array a pass is budgeted from and the part-set header those checks run against, and ValidateBasic accepts any well-formed pair, so it could open a maximum-size pass under a header matching no stored block. That bought two things. A pass that can never send charged a block-store read and an error log to every gossip tick for its whole budget - roughly 160s at the production 100ms cadence - and since the retry deadline was armed when the pass opened, it had long expired by the time the budget ran out, so the next pass began immediately and the interval never throttled anything. The same inflated budget also survived the peer replacing its state, at the same height, with the stored block's real header and a single missing part: the budget is deliberately not re-derived once a pass is open, so the remainder landed as duplicate sends of that one part. Move the send into sendCatchupBlockPart and abandon the pass, arming a fresh retry deadline, whenever it reports that no part reached the peer. A pass now costs at most one failed attempt per interval, and only a pass that got as far as sending keeps its budget. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01RoXmbFrVf1BqVW1BHZv6Va * fix(consensus): close catch-up pass gaps thepastaclaw flagged as still exploitable Two gaps let a peer defeat the catch-up throttle this PR is adding: - beginCatchupAttempt armed catchupRetryAt when a pass opened. A pass with enough missing parts to span more gossip ticks than catchupResendInterval takes longer than the interval to exhaust its budget, so the deadline had already elapsed by the time the pass finished - the next tick reopened a fresh pass with no quiet gap at all. Arm the deadline when the pass's last attempt is spent instead. - The pass budget was fixed at open and never revisited downward. A peer fully controls ProposalBlockParts over the wire (NewValidBlockMessage. ValidateBasic checks only length, ApplyNewValidBlockMessage installs it wholesale) and can open a pass reporting many parts missing, then swap in a bit-array with only one unset bit — every remaining budgeted attempt then draws that same index, funding repeated duplicate sends of it. Clamp the remaining budget down whenever the peer's current missing count drops below it; never raise it back up. Adds regression tests for both: a 6-part pass ticked across catchupResendInterval to show the deadline is measured from the pass's last send, and a 5-part pass whose bitmap shrinks mid-pass to show the budget clamps to the peer's current report. Both fail against the pre-fix code. Addresses thepastaclaw findings on PR #1418. <sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub> Co-Authored-By: Claude Sonnet 5 <[email protected]> * perf(consensus): avoid a full bit-array copy to count missing catch-up parts beginCatchupAttempt derived the peer's missing-part count via Not().CountTrueBits(), which allocates and copies the whole (peer-controlled, up to MaxBlockPartsCount) bit-array on every gossip tick just to count it. sendCatchupBlockPart already performs its own Not().PickRandom() when a send actually happens, so this was a second, avoidable full-array allocation on every tick regardless of whether a send occurs. Derive the same count as size minus set bits instead. Addresses a copilot review comment on PR #1418. <sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub> Co-Authored-By: Claude Sonnet 5 <[email protected]> * fix(consensus): honor catch-up send failures, close height-advance evasion Layers on top of review-stream's retryAt-at-close and downward-clamp fix in beginCatchupAttempt. Distinct fixes: - syncProposalBlockPart (pre-existing, untouched elsewhere in this PR) unconditionally returned nil, so a failed send never reached endCatchupPass despite the caller's contract assuming it would. sendCatchupBlockPart now reports success as a bool instead of an error nobody was meant to inspect, and its "no missing part" branch can no longer be hit (the comment claiming otherwise was already false: prs is a fresh per-tick deep copy nothing else can mutate). - A peer's height advancing reset the retry deadline as well as the budget, granting a free pass on every height step; only the budget resets now. - The three catch-up fields were guarded only by a comment claiming a single caller, despite the same *msgGossiper being shared across three concurrent handler goroutines; a mutex now guards them structurally. - Documented the rate limit's actual scope (per gossip worker, not per peer -- a reconnect gets a fresh one) on the Gossiper interface and the actual tick-to-interval relationship on catchupResendInterval, both previously undocumented. Co-Authored-By: Claude Sonnet 5 <[email protected]> * docs(consensus): fix stale catch-up comment in dataGossipHandler GossipBlockPartsForCatchup is rate-limited and returns without sending on most ticks, so "block parts already delivered" no longer describes what happened before the unconditional GossipCommit call on the same branch. Co-Authored-By: Claude Sonnet 5 <[email protected]> * fix(consensus): propagate the real send error from syncProposalBlockPart syncProposalBlockPart unconditionally returned nil regardless of the underlying send's actual result, so sendCatchupBlockPart's error check against it (added in the prior commit) was dead code: a send that never reached the peer was indistinguishable from one that did, and endCatchupPass never fired for that failure mode -- the pass kept spending its budget one failed attempt per tick instead of ending on the first one, exactly the spin endCatchupPass exists to prevent. Fix at the source: return g.sync's result directly and drop the now-redundant local log, since both callers already log a non-nil error themselves. The other caller, GossipProposalBlockParts, only ever logged this error and took no other action, so propagating it for real is behavior-preserving there. Regression test advances a fake clock across many ticks with every send forced to fail and asserts exactly one block-part read per catchupResendInterval, not one per tick; confirmed failing (5 reads instead of 1) against the pre-fix code. Co-Authored-By: Claude Sonnet 5 <[email protected]> * fix(consensus): arm catch-up retry deadline when a peer's height advance interrupts a live pass A peer that advances its reported height mid-pass (before the pass exhausts its own budget) reset catchupRemaining to 0 without arming catchupRetryAt, since the deadline was only ever armed when a pass ran its budget down naturally. A peer whose height ticks forward every gossip tick therefore got a fresh full-budget pass every tick forever, completely bypassing catchupResendInterval for the common multi-part-block case. Arm the deadline on the height-change branch too whenever a pass was actually in flight, matching the same invariant beginCatchupAttempt's normal exhaustion path already upholds. Document that invariant on the struct fields it protects. Also, while re-auditing this function for the same iteration: - stop re-deriving the budget from a peer-controlled bit-array once a pass is open (now g.catchupRemaining = min(g.catchupRemaining, missing), replacing an equivalent but more verbose branch) - de-duplicate the block-store-failure error logs in sendCatchupBlockPart; blockRepository.loadMeta/loadPart already log the failure, so the caller's second log was pure noise - correct sendCatchupBlockPart's doc (it reports handoff to the p2p channel, not peer delivery) and give its error log a distinct message from GossipProposalBlockParts's - correct the Gossiper interface, catchupResendInterval, and endCatchupPass doc comments, which described a flat one-send-per- interval bound that does not hold for multi-part blocks Co-Authored-By: Claude Sonnet 5 <[email protected]> * test(consensus): pin the height-advance throttle bug and fix stale/weak catch-up assertions - Add TestGossipBlockPartsForCatchupHeightAdvanceInterruptingPassIsThrottled, a regression test for the height-advance bug fixed in gossiper.go: confirmed RED (20 sends) against the pre-fix code via git stash, GREEN (1 send) after the fix. - Rename/rewrite TestGossipBlockPartsForCatchupBudgetIsFixedAtPassOpen to TestGossipBlockPartsForCatchupBudgetIsNeverRaisedMidPass: the old sequence never actually drove catchupRemaining below the reported missing count it then 'raised', so the raise-attempt it claimed to guard against was a no-op the test would pass on regardless. The new version forces a real clamp (5-part block, drop to 1 missing after two sends) before attempting to raise the count back up, and asserts the raise is not honored before the interval elapses. - Strengthen TestGossipBlockPartsForCatchupPeerHasEveryPart with an explicit AssertNotCalled, so it fails loudly instead of silently if a send is ever wired in for a peer that already has every part. - Update the two wantLog assertions in TestGossipBlockPartsForCatchup that still expected the removed 'couldn't find a block meta/part' caller-side logs; the block-store-failure messages they should match are now blockRepository's own 'failed to load block meta'/'failed to load block part'. Co-Authored-By: Claude Sonnet 5 <[email protected]> * fix(consensus): share one clock between msgGossiper and its peerGossipWorker newPeerGossipWorker constructed two independent clockwork.NewRealClock() instances for what is meant to be one gossip worker's shared notion of time. They agree in practice (both wrap wall-clock time), but nothing enforces that, and it defeats point-in-time comparisons in tests that inject a single fake clock expecting both call sites to observe it. Construct one clock and pass it to both. Co-Authored-By: Claude Sonnet 5 <[email protected]> * docs(consensus): correct dataGossipHandler's stale catch-up rate-limit comment The comment described GossipBlockPartsForCatchup as rate-limited and a no-op on most ticks, which held before this PR's changes but not after: a pass now spends one send per tick for as many ticks as the peer reports parts missing, and the quiet gap applies only between passes, not on most individual ticks. Reword to match. Co-Authored-By: Claude Sonnet 5 <[email protected]> * docs(config): cross-reference PeerGossipSleepDuration's coupling to the catch-up throttle PeerGossipSleepDuration sets the tick rate that internal/consensus/gossiper.go's catchupResendInterval throttle is metered against: configuring it above that fixed interval silently disables the throttle. Document the coupling at both the struct field and the generated TOML template so an operator tuning gossip cadence sees the side effect. Co-Authored-By: Claude Sonnet 5 <[email protected]> * perf(consensus): skip the missing-part scan while a catch-up pass is backed off beginCatchupAttempt computed missing (Size() - CountTrueBits(), an O(bits) scan of the peer-controlled ProposalBlockParts array) unconditionally, even on ticks that are going to return false immediately because the pass is still within catchupRetryAt's backoff. At production defaults most gossip ticks land in backoff (a pass's quiet interval is ~5x the gossip cadence), so this scanned a bit-array up to MaxBlockPartsCount long on nearly every tick for no reason. Move the backoff check ahead of the scan: when no pass is open and the retry deadline hasn't elapsed, return early without touching ProposalBlockParts at all. The scan still runs whenever it can affect the outcome - opening a new pass, or clamping an active one's budget down to a shrunk missing count. Addresses a copilot review comment on PR #1418. <sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub> Co-Authored-By: Claude Sonnet 5 <[email protected]> * fix(consensus): close an open catch-up pass when the peer reports it complete beginCatchupAttempt returned early on missing == 0 without touching catchupRemaining/catchupRetryAt. When that happened mid-pass (catchupRemaining > 0, budget not yet exhausted), the pass stayed open indefinitely: noOpenPass would keep evaluating false forever, so the backoff check above it — which only runs while no pass is open — was skipped on every later tick regardless of elapsed time. A peer could freeze catchupRemaining above zero by reporting a complete part set whenever it liked, then resume sending immediately the next time it reported parts missing, with no retry interval honored at all. Close the pass in that case too: zero the remaining budget and arm the retry deadline, matching what happens when a send fails or a height change interrupts a pass. Only do this when a pass was actually open; a peer that has simply always reported a complete set must not have a wait imposed on it. Also corrects a stale doc comment on PeerGossipSleepDuration added by the same throttle: catchupResendInterval is a fixed quiet gap that does not scale with the gossip tick duration, it only fits more ticks into that same window. Adds a regression test that opens a pass, spends one send, has the peer report complete, then report missing again on the same simulated instant - asserting no send until the retry interval elapses. Fails against the pre-fix code (an immediate second send). Addresses copilot review comments on PR #1418. <sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub> Co-Authored-By: Claude Sonnet 5 <[email protected]> * docs(consensus): reclassify the missing==0 mid-pass fix as CPU-amplification, not a throttle bypass df8a6057c's commit message and code comments described the missing==0 mid-pass fix as letting a peer "resume sending... with no retry interval honored at all", which reads as a flooding/throttle-bypass concern. On closer trace (independently by team-lead and grumpy-stream) that's not accurate: catchupRemaining only ever counts down, never up, so total sends per pass are identically bounded by the budget fixed at pass open whether or not this fix exists. Nothing here lets a peer exceed that budget or the one-send-per-tick ceiling. The actual defect is CPU amplification: leaving a pass open indefinitely (via alternating missing==0 reports) keeps noOpenPass false forever, which permanently defeats 3b9463dd0's backoff-skip check - the O(bits) scan of the peer-controlled, up-to-MaxBlockPartsCount bit-array then runs on every single gossip tick instead of being skipped during backoff, for as long as the peer holds the pass open this way. It also predates this PR: grumpy traced the same missing==0 short-circuit in the 5978b27 baseline and both its parent commits, so this isn't new here - it only started costing more once 3b9463dd0 added a backoff-skip path for it to defeat. Also records a deliberate behavior change for honest peers: closing the pass on missing==0 means a peer that legitimately completes its part set and later falls behind again now waits out one catchupResendInterval before catch-up resumes, rather than resuming on its very next report. Accepted: a peer that just reported complete is not starving, and the wait is negligible against block time. No functional change from df8a6057c - comments only, on both the fix and its regression test. <sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub> Co-Authored-By: Claude Sonnet 5 <[email protected]> * fix(consensus): end a catch-up pass when a block-store read panics GossipBlockPartsForCatchup only called endCatchupPass() on a normal false return from sendCatchupBlockPart. But sendCatchupBlockPart's block-store reads (blockRepository.loadMeta/loadPart, wrapping LoadBlockMeta/ LoadBlockPart) panic deliberately on a decode or read failure rather than returning an error - runGossipHandler recovers that panic per gossip tick, logs a full stack, and keeps ticking, same as it does for every other peer-facing panic path in the node. A panic there unwinds straight past the if-check, so endCatchupPass() never runs and the pass stays open with its remaining budget intact. Since the peer controls both the height and the missing bitmap a pass is budgeted on, a peer that names a height whose stored record is corrupt or unreadable gets a fresh attempt - and a fresh panic, and a fresh full-stack log - on every tick for the rest of the pass's budget (up to ~160s for a maximum-size 1,601-part report at the default cadence) instead of ending on the first failed attempt like every other failure mode this PR's earlier commits already cover. Settle the attempt in a defer instead of an if-check on the return value, so panic unwinding also reaches it. sendCatchupBlockPart's own return value still selects the fast path (success needs no settlement); the defer only changes what happens when it doesn't get the chance to return at all. Adds a regression test using a block-store mock that panics on LoadBlockMeta, asserting exactly one read (and thus one panic) per pass rather than one per tick for the whole budget - mirrors TestGossipBlockPartsForCatchupSendFailureEndsPass's structure for the already-covered normal-failure case. Confirmed failing (2+ reads instead of 1) against the pre-fix code. Addresses a thepastaclaw blocking finding on PR #1418. <sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub> Co-Authored-By: Claude Sonnet 5 <[email protected]> * fix(consensus): don't throttle a genuinely-advancing peer's next catch-up pass 25da4c2 removed the unconditional catchupRetryAt clear from the height-change branch to close a bypass, and ea2b81498 later armed it properly for a pass genuinely interrupted mid-flight (catchupRemaining > 0). The catchupRemaining == 0 case was never revisited: a deadline armed by the OLD height (by exhausting its own budget, or by the peer reporting complete) silently carried forward and throttled the NEW height's first pass by up to catchupResendInterval, for a peer that isn't replaying anything and owes nothing - it's genuinely further along. Catch-up is the only path offered to a peer at a different height than ours (regular gossip requires equal heights), so this taxes every honestly-advancing lagging peer once per height. This throttle does not exist on origin/v1.7-dev; it's a cost this PR's own commits introduced. Naively clearing catchupRetryAt whenever catchupRemaining == 0 at a height change (the obvious fix) reopens a worse gap than intended, though: it cannot tell "the previous pass genuinely finished" apart from "an INTERMEDIATE height in a rapid chain never got a chance to open a pass at all, and is still serving an earlier interruption's penalty" - both look identical (remaining == 0) at the moment of the next height change. Verified by writing TestGossipBlockPartsForCatchupHeightAdvanceInterruptingPassIsThrottled first: a naive version of this fix turns its pinned 1 send across 20 rapid height-hops into 10, because every OTHER hop's remaining == 0 came from the previous hop being blocked, not from a pass finishing. Track WHY catchupRetryAt is currently armed instead: catchupRetrySticky is true when the deadline covers unrendered service (a pass interrupted before exhausting its own budget, or a failed attempt via endCatchupPass) and must survive a height change - including a chain of several - and false when the pass closed because it had genuinely nothing left to do (spent its own budget in full, or the peer reported complete). The height-change branch only clears catchupRetryAt when it's non-sticky (or already elapsed); otherwise it's left untouched, whatever height change caused it to be checked. This does still leave a bounded gap in the non-sticky case, stated explicitly in the code rather than glossed: a peer can open a pass, let it close cleanly (one real send, e.g. by reporting a single missing part), then immediately claim a new height and repeat, getting one send per gossip tick indefinitely instead of one pass per interval. Bounded to at most 1 send/PeerGossipSleepDuration tick (10/s, ~640KB/s of block parts at production defaults), because CompareHRS enforces monotonic height only (no replay or ping-ponging) and ensurePeerPartSetHeader requires the real, currently-stored PartSetHeader for each claimed height (a mismatch ends the pass via the now-sticky endCatchupPass, costing a full interval rather than a send). Sustaining it requires marching forward through genuine, still-retained history, capped by blockStoreBase - no worse than the pre-#1365 catch-up rate this codebase already tolerated in production. Accepted as strictly cheaper than taxing every honestly-advancing lagging peer by up to 500ms per height; a verified-progress-gated redesign that closes it for real is tracked as follow-up, not done here. Two new regression tests, both proven against the pre-fix code: - TestGossipBlockPartsForCatchupCleanHeightAdvanceIsNotThrottled: a single-part pass closes cleanly, the peer immediately claims a new height with a fresh block - asserts an immediate send, not a catchupResendInterval wait. RED before this fix. - TestGossipBlockPartsForCatchupHeightAdvanceInterruptingPassIsThrottled (existing, extended doc comment): still asserts full throttling across 20 rapid, always-interrupted height hops - GREEN before this fix, and the guard that caught the naive version's regression above. <sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub> Co-Authored-By: Claude Sonnet 5 <[email protected]> * fix(consensus): start the catch-up quiet gap after the send, not before it beginCatchupAttempt armed catchupRetryAt from a timestamp taken on entry, before the caller had even reached sendCatchupBlockPart. The p2p channel applies backpressure on that very goroutine, so a slow send burned its own duration out of the quiet gap it was supposed to precede - the slower the peer's channel, the weaker the throttle. It now reports the pass's last slot to the caller instead of arming the deadline itself, and GossipBlockPartsForCatchup settles the pass from a fresh clock reading once the send returns. endCatchupPass and the new completeCatchupPass share settleCatchupPass, keeping one place where a drawn attempt closes a pass. The window where the pass is spent but its deadline is not yet armed keeps the documented invariant (a stale deadline with catchupRemaining == 0 is legal) and is unobservable: the single per-peer goroutine is inside the send for all of it, so no further attempt and no height change can run before it settles. Co-Authored-By: Claude Opus 5 <[email protected]> --------- Co-authored-by: Claude Opus 5 <[email protected]> (cherry picked from commit 9bf9a0b) * fix(consensus): check that a proposal's block ID describes its block A Proposal carries a BlockID and a proposer signature over it. The BlockID has three fields, and until the block arrives none of them can be checked against anything: PartSetHeader is validated implicitly, because the parts have to assemble under it, but Hash and StateID are taken on the proposer's word. RoundState.BlockID() then hands that BlockID, unexamined, to the prevote signer. So a proposer can gossip a genuine block and sign a BlockID that does not describe it. Every node that receives the block assembles it, finds nothing that disagrees, and signs a prevote for the proposer's value. A commit forms over a BlockID no node ever verified. The height that commit seals is fine: finalization derives the BlockID from the block itself, so the committed state records the real one. The next height is not. Its LastCommit carries the BlockID the votes actually signed, and validation compares that against the previous height's recorded value. They differ, and neither can be revised -- one is persisted state, the other is sealed by a threshold signature over a finalized height. Every proposer at every subsequent round fails the same comparison. The chain does not recover, and restarting does not help. An honest proposer derives its BlockID from the block and the parts it is gossiped in, so once the block is assembled the claim is exactly checkable. Two changes, at the two points that matter: - When the part set completes, compare the Proposal's BlockID against the one derived from the block just assembled. On disagreement the block is kept -- it is the bytes, and they are what they are -- and the Proposal is dropped with its receive time, which leaves the proposal incomplete so the round prevotes nil and moves on. A round is a cheap price; the alternative is signing the value that ends the chain. - RoundState.BlockID() returns the BlockID derived from the block and parts whenever it holds them, and falls back to the Proposal's only when there is no block to derive from. The check above is what reports the lie; this is what keeps an unexamined claim from reaching a signature by some other route. Honest operation is unaffected, and that is measured rather than argued. An instrumented build that compared the two values at every block completion, without acting on the result, recorded 767 agreements and no disagreement across the consensus suite, replay included. Forging one StateID byte in the derived value turned all 778 of them into disagreements, so the comparison was in a position to report one. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_019gAC8rAzQagn5sgDxUJNjj (cherry picked from commit 2c2a8f6) * fix(consensus): check a commit's state ID against the block it commits A commit names a block by hash, part set header and state ID. Before applying one, a node checks that the block it holds matches the first two and never looks at the third. A commit that agrees on hash and part set header while naming a different state ID is therefore applied against this block, and then recorded carrying its own BlockID. That record is what the next height is validated against. Its LastCommit holds the BlockID the votes signed; the previous height's committed state holds the one derived from the block. They disagree, and neither side can be revised: one is sealed by a threshold signature over a finalized height, the other is persisted state. Every proposer at every subsequent round fails the same comparison, and restarting changes nothing. Ask the third field. It is asked separately from the other two, rather than as one comparison over the whole BlockID, so an operator is told which field disagreed instead of only that something did. The three checks move into verifyCommitBlock. That is an extraction made for testability and worth naming as such: reaching them previously required an ABCI client, because the surrounding function hands the block to the application immediately afterwards. Separated, each field's rejection is tested directly, with a nil executor so that a test which stops rejecting panics rather than passing quietly. Making the new comparison tautological fails exactly one subtest across the package, and nothing else notices. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_019gAC8rAzQagn5sgDxUJNjj (cherry picked from commit 665ff68) * fix(consensus): drop a disagreeing proposal instead of rejecting the block Two checks in addProposalBlockPart detect the same condition -- a Proposal that disagrees with the block just assembled -- and they disagreed about the remedy. The block ID check drops the proposal and keeps the block. The core chain locked height comparison returned an error, which discards the block. Discarding it is terminal. AddPart consumes the part before either check runs, and PartSet.AddPart returns (false, nil) for a part it already holds (types/part_set.go), so the completion branch is guarded by `added && IsComplete()` and is never re-entered. The part that completed the set is spent, the block is never assigned, and nothing assembles it again. Replay feeds the same sequence to the same rejection, so restarting does not clear it. Make the two agree: on disagreement the proposal is dropped and the block is kept. That is what gives the round its way back, and the mechanism is not tidiness. Proposaler.Set returns early while rs.Proposal is non-nil, so a second proposal for the same height and round is discarded unread -- clearing the field is the only thing that lets the honest copy be accepted. Re-delivery is ordinary behaviour rather than luck: shouldProposalBeGossiped sends when `!prs.Proposal`, and that flag is set only by the sender in updatePeerProposal after its own send, so every honest validator that lost the race still believes we lack the proposal and keeps offering it. Dropping is safe because the block is checked without reference to any proposal. StateData.isValidForPrevote calls sm.ValidateBlockChainLock before the node prevotes, comparing the block's own core chain locked height against state, and it guards Proposal == nil explicitly, so a cleared proposal makes the round prevote nil and advance rather than panic. The remedy does not depend on knowing what caused the disagreement, which is the property worth having: a proposer can build the value wrongly, and any peer relaying the message can raise it, because CanonicalizeProposal omits the dash fields from what the proposer signs while state_proposaler.go enforces only a lower bound. One test covers both because the code cannot distinguish them and is not required to. The part set header, not the block hash, decides whether the proposal describes these bytes: CoreChainLockedHeight reaches Header.Hash() through cdcEncode, which has no uint32 case and contributes an empty leaf for every value, so two blocks differing only in that field share a hash. That predicate selects which diagnosis is reported rather than the outcome, and it is commented as such. An earlier version of this change gated the comparison and left it terminal. That closes the cases where the proposal describes different bytes and does nothing when a relayed proposal names this block with the field altered, since the part set header still matches. It is recorded here so the narrower shape is not reintroduced as an obvious hardening. Measured over the consensus suite: the two values agree 778 times and disagree 3, all at height one and off by one. Every disagreement was attributed by capturing a stack at the comparison. One comes from the reactor test that installs a proposer proposing an incorrect chain lock height; the other two are the tests added here, which construct the disagreement deliberately -- including the reversed case, a proposal claiming a higher chain lock than the block it names, which is this commit's own fixture rather than anything arising at genesis. So the pre-existing suite contains exactly one disagreement, produced by a deliberately byzantine proposer, and none from an honest flow. The suite also passes with the mismatch made non-fatal, so nothing depended on the rejection. Dropping discards ProposalReceiveTime with the proposal, so timeliness is re-evaluated against the re-delivered copy and a slow re-delivery can still cost that round. That cost is per round and self-clearing, and keeping the two paths identical is worth more than softening it here. The proposal is cleared inline rather than through a helper shared with the block ID check above. The duplication is deliberate: that check is a cherry pick, and keeping it byte-comparable with the branch it came from is worth more on a release branch than removing four lines. The helper belongs where the code is native. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_019gAC8rAzQagn5sgDxUJNjj * test(p2p): draw distinct addresses in TestConnTracker loops TestConnTracker/BaseSmall/AddingMany failed in CI with "expected: 100, actual: 99". It is not a timing flake: randLocalIPv4 returns 127.<r>.<r>.<r> where randByte is rand.Intn(math.MaxUint8), so the three random octets span 255^3 = 16,581,375 addresses. connTrackerImpl.Len is len(rat.cache) and the cache is keyed by address, so two equal draws collapse into one entry and the count comes up short. AddConn also returns an error for the duplicate, but the loop discards it with `_ =`, so nothing reports the real cause. Measured over 1,000,000 simulated runs of the 100-draw loop: 298 collided, i.e. once in ~3,356 runs, matching the analytic 100*99/(2*255^3). Four loops in this test draw that way (AddingMany and Cycle, each under both the BaseSmall and BaseLarge factories), so the observed rate is closer to once in ~840 CI runs. Cycle is the worse of the two — a collision re-adds an address inside the window, so AddConn errors and trips require.NoError directly rather than only skewing a count. VeryShort draws ten and is exposed the same way. The fix already exists in this file: seqIPv4 ("deterministic, distinct IPv4 address for the given index") was added alongside the tests in #1356, which draw 21,000 addresses and would collide with near-certainty, but it was never applied to the pre-existing loops. Use it in all three loops that need distinct addresses. randLocalIPv4 stays for RepeatedAdding and Window, which each need exactly one address and are collision-immune, and its doc comment now states when it is safe to use so the next reader does not reintroduce the defect. Verified by mutation rather than by re-running until green: collapsing the address space to 3^3 = 27 (below the 100 drawn, so a collision is forced by pigeonhole) reproduces the exact CI signature on the pre-fix code — AddingMany "expected: 100, actual: 27" under both factories, plus Cycle and VeryShort — while the post-fix code passes ten consecutive runs at that same collapsed space. Run in an isolated module containing only conn_tracker.go and its test, since the package's BLS cgo dependency is not buildable in this environment. Not changed, but noted: randByte is rand.Intn(math.MaxUint8), which yields 0..254 and never 255. It is inert for the two remaining single-address callers and is left alone to keep this change scoped. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_019gAC8rAzQagn5sgDxUJNjj * fix(consensus): validate block IDs across message ordering Check commits against assembled blocks before application and persistence, including commit-first and locally assembled commit paths. Propagate apply errors before broadcasting a commit or advancing the round. Validate late proposals against retained blocks while allowing matching replacements. Add failing-first regressions with signed commits and proposal controls. Co-Authored-By: Codex GPT-6 <[email protected]> <sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub> --------- Co-authored-by: Claude Opus 5 <[email protected]>
Why this PR exists
Problem. Consensus catch-up block-part gossip optimistically marks a part as delivered the moment it is sent (
updatePeerProposalBlockPart). A peer that is catching up can legitimately be at a step where it is not yet expecting block parts (RoundStepNewHeight/Propose with a nilProposalBlockParts) and silently drops the part it receives (state_add_prop_block.go, "received a block part when we are not expecting any"). Because the sender now believes the peer has the part,GossipBlockPartsForCatchup'sprs.ProposalBlockParts.Not().PickRandom()finds nothing missing and never resends it. When the catch-up commit then arrives ahead of the proposal, the node stores the commit and builds an empty part set from the commit header (state_data.go, "Commit came in before proposal") and waits forever for a part that is never resent — the node wedges permanently at that height.What breaks without it. Under timing pressure a lagging node freezes (observed at height ~17 and ~19 in repro) while the rest of the network advances. This surfaces as the flaky CI test
TestReactorValidatorSetChanges, which intermittently times out at 120s. In production this normally self-heals via propose/round timeouts (which reset peer round state and re-trigger gossip) and via blocksync; the consensus-only test harness — with its one-shot mock ticker (no round timeouts) and no blocksync — disables both recovery paths and so exposes the latent bug as a hard hang.What was done
internal/consensus/gossiper.go: the catch-up block-part path no longer optimistically records the part as delivered, so it keeps resending the missing part each gossip tick until the peer applies the block and advances its height. This mirrors the "resend until acked" behavior already used for catch-up commits and removes catch-up's dependency on timeouts to recover a dropped part.syncProposalBlockPartgained amarkPeerHasPart bool; regular same-height block-part gossip is unchanged (still marks optimistically, for efficiency).TestGossipBlockPartsForCatchupResendsasserting catch-up does not mark the peer as having the part and resends on the next tick.Testing
-racestress sample (nodes frozen at heights 17 and 19, with the "Commit came in before proposal" signature after ~100 blocks produced).-raceruns (single-instance 25/25, 6-way 144/144, plus 10–12-way runs) and 600 plain runs. The only residual failures under heavy parallelism were CPU-starvation artifacts (whole instance produces 0 blocks) from oversubscribing the host — identical for baseline and fixed, and unrelated to this change.TestGossipBlockPartsForCatchupResendspasses; fullTestGossipersuite passes.gofmt/go vet/golangci-lint(changed files) clean.Breaking changes
None.
Known tradeoff / follow-up
For multi-part blocks, catch-up may redundantly resend parts (there is no per-part dedup/ack on the catch-up path). This is bounded — O(gossip_ticks × parts × peers) until the lagging peer executes the block and advances — and is fine for a fallback path (blocksync covers large gaps). It is strictly better than a permanent wedge. A per-part acknowledgement is a possible future optimization, not a correctness issue.
Scope
This fixes one source of shard-01 CI flakiness — the consensus reactor valset-change wedge. Other shard-01 flakes are separate and not addressed here (e.g.
TestHandshakeReplayNonet.TempDir()teardown race; a still-open evidence-reactor propagation flake).🤖 Co-authored by Claudius the Magnificent AI Agent