Skip to content

fix(consensus): deliver and process a polka block for a validator left in its round - #1600

Merged
lklimek merged 17 commits into
devfrom
fix/consensus-serve-polka-block
Nov 27, 2026
Merged

lklimek merged 17 commits into
devfrom
fix/consensus-serve-polka-block

Conversation

@Claudius-Maginificent

@Claudius-Maginificent Claudius-Maginificent commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

TL;DR: A validator that fell behind can now get the block the network already agreed to vote on, and process it, so it can rejoin the round instead of leaving the network stuck.

User story

As a validator operator, I want a validator that missed a block to fetch and process it from its peers, to achieve continued block production after network trouble or validator outages.

Scenario

Base flow

In each round a proposer sends a block. Once more than two-thirds of validators prevote for it (a "polka"), validators precommit it. Precommits for a block carry vote extensions, which the application (Drive) checks before the vote is counted.

Actual behavior

Take a validator that saw a polka for a block but never received the block itself:

  • Its peers move on to the next round and stop sending that block's parts.
  • Even when the block does arrive late, the validator never hands it to the application.
  • The application therefore keeps rejecting the vote extensions in other validators' precommits for that block. Those votes are not counted, no timer starts, and the validator stays in the old round.

If the validators that went ahead cannot reach a two-thirds quorum without the stuck ones, the whole network stalls. Two ways to get there:

  • about one-third of validators stop voting after the polka;
  • about one-third crash at the same moment while another third is cut off from the block.

Expected behavior

Validators that still hold the agreed block send it to peers that ask for it. A validator that completes the block processes it, accepts the other validators' precommits, starts its timer and rejoins the round. With the round back at a two-thirds quorum, the network commits the block.

Detailed discussion

Stack: this PR is the bottom layer of native stack #1658 (#1600 → #1627 → #1515 → #1639 → #1641 → #1642 → #1654 → #1655), base dev. Each PR carries only its own changes.

What was done

  • Serving the polka block (gossip_handlers.go, heldBlockPartsFor):
    • Data gossip normally serves parts only from rs.ProposalBlockParts, which entering a new round clears. A node then still holds the polka block as ValidBlockParts and/or LockedBlockParts, but those were never served.
    • When the normal path sends nothing, a complete ValidBlockParts or LockedBlockParts is now served to a peer that meets all of these:
      • it is a validator,
      • it is at the same height, in an earlier round,
      • its requested ProposalBlockPartSetHeader equals the held one exactly (header equality is the block identity).
    • The handler repoints only its local snapshot copy (ProposalBlockParts, and Round to the peer's round so SetHasProposalBlockPart marks the parts) and calls the existing GossipProposalBlockParts.
    • Consensus state is never mutated. Same-round peers never reach this branch.
  • Processing the polka block (block_executor.go, blockExecutor.processPolkaBlock):
    • On dev, a block completed in the Prevote or Precommit steps is never passed to ProcessProposal.
    • When the round's held proposal block equals the non-nil +2/3 prevote majority of the node's current round and has not been processed for that round, it is processed via ensureProcess(rs, rs.Round). Three call sites:
      • ProposalCompletedAction (state_add_prop_block.go), when the block completes after its polka;
      • addVoteUpdateValidBlockMw (state_add_vote.go), when the polka forms in the Precommit step (including the precommit wait) after the block completed;
      • EnterPrecommitAction (state_enter_precommit.go), before a nil precommit: over a proposal timestamp the block does not match, or without a proposal while the polka block is held (e.g. a signed proposal dropped because its block ID does not describe the completed block).
    • No vote is cast or changed.
    • It runs once per block completion, once when the round's polka forms, and once on a nil precommit in EnterPrecommitAction; never per precommit.
  • Retrying the polka block after a transient failure (block_executor.go, tryPolkaBlock/retryPolkaBlock; state.go, receiveRoutine):
    • If ProcessProposal fails in processPolkaBlock with a recoverable error, the round would otherwise stay stuck: the validator already precommitted nil, nothing else processes the block, and the application keeps rejecting the peers' vote extensions.
    • A retry is scheduled on a dedicated timer (not the timeout ticker, which replaces step timers). receiveRoutine selects on its channel, so the retry runs on the consensus goroutine.
    • At most one retry is pending per height, round and full BlockID; repeated triggers coalesce. The delay starts at 100 ms and doubles up to 5 s.
    • No retry after a definitive rejection (ErrBlockRejected, ErrInvalidBlock), a stopped ABCI client (ErrClientStopped), or a cancelled context. A retry that fires after the height, round or polka target changed, the block is no longer complete, or the block was processed elsewhere is dropped without calling the application. The timer is stopped on exit, on a failed start and before WAL-repair replay.
    • The ensureOwnRound doc comment states which failures are retried.
    • ensureOwnRound then finds the round processed, and VerifyVoteExtension accepts the peers' precommits.
    • ProposalCompletedAction (state_controller.go) and addVoteUpdateValidBlockMw (state_add_vote.go) get the blockExec dependency.
  • Part set completeness under its mutex (types/part_set.go):
    • PartSet.IsComplete reads count under ps.mtx, since data gossip checks the completeness of the part set the consensus state is filling.
  • Precommit redelivery:

Testing

  • New tests:

    Test Kind
    TestGossipHandlerTestSuite/TestDataGossipHandlerServesHeldBlockToLaggingPeer Serves the valid block, the locked block, the valid block while the round proposes another, and the valid block while the round collects it incomplete. Negative cases: mismatched header, other height, same/later round, non-validator, incomplete part set.
    TestStatePolkaBlockCompletedInPrecommitIsProcessed Fails without the fix.
    TestStatePolkaBlockDeliveryEndsThePrecommitStall Fails without the fix. Ends with TriggeredTimeoutPrecommit.
    TestStatePolkaBlockRejectedByTheApplicationIsNotRetried Fails without the fix.
    TestStatePolkaBlockCompletedInPrevoteWaitIsProcessedOnce Fails without the fix.
    TestStatePolkaFormedAfterTheBlockCompletedInPrecommitIsProcessed Fails without the addVoteUpdateValidBlockMw hook.
    TestStatePolkaFormedAfterTheBlockCompletedInPrecommitWaitIsProcessed Fails without the addVoteUpdateValidBlockMw hook; asserts the step stays RoundStepPrecommit in the precommit wait.
    TestStatePolkaBlockPrecommittedNilOnATimestampMismatchIsProcessed Fails without the EnterPrecommitAction call.
    TestStatePolkaBlockWithDroppedProposalIsProcessedOnPrecommit Fails without the EnterPrecommitAction call on the no-proposal branch.
    types/TestPartSetIsCompleteConcurrentWithAddPart Fails under -race without the PartSet.IsComplete mutex.
    TestStatePolkaBlockCompletedInProposeVotesAndProcessesOnce Regression guard.
    TestStateCompletedBlockWithoutItsPolkaIsNotProcessed Regression guard.
    TestStateCompletedBlockOtherThanThePolkaBlockIsNotProcessed Regression guard; a mutation check confirms it catches removal of the block-identity check.
    TestStatePolkaBlockRetryEndsThePrecommitStall One transient ProcessProposal error, then the retry processes the block and the resent precommits arm the precommit wait. Fails without the retry.
    TestStatePolkaBlockRetryCoalescesDuplicateTriggers Duplicate triggers make no extra ProcessProposal calls; the delay doubles.
    TestStatePolkaBlockRetryIgnoresStaleTarget A due retry is dropped after the round, height or target changes, the block is incomplete, or it was processed elsewhere.
    TestStatePolkaBlockFailureNotWorthRetryingIsNotRetried No retry for an invalid block, a stopped client or a cancelled context; a mutation check confirms each case.
    TestStatePolkaBlockRetryDelayIsCapped The backoff stops at 5 s.
  • The tests use an application that accepts extensions only for a processed (height, round, hash), the strict same-round contract; Drive also accepts the same block processed in another round of the height.

  • The new tests also pass under -race. The full internal/consensus package passes with -tags deadlock, and golangci-lint reports 0 issues on the changed packages.

  • Independent reviews found, all addressed in this PR:

    • the v1 dependency on fix(consensus): resend same-round votes the peer never acknowledged #1599 (merged);
    • missing edge-case tests;
    • an unsynchronized read in PartSet.IsComplete;
    • log and doc wording that did not match every call site;
    • no recovery after a transient ProcessProposal failure on the polka-block path (now retried), and the retry timer's lifecycle on shutdown.

Breaking changes

None.

Prior work

Attribution

🤖 Generated with Claude Code

https://claude.ai/code/session_01WunYYgcoPDNh3uebhUCwig

🤖 Co-authored by Claudius the Magnificent AI Agent

PR Hygiene · 6260fed

  • Bots — thepastaclaw ✓
  • Self-review — not asked of a bot author
  • Build green
  • Approvals
    • files with no dedicated owner (internal/consensus/block_executor.go, internal/consensus/gossip_handlers.go, internal/consensus/gossip_handlers_test.go and 9 more) — approved by lklimek

When every merge requirement is met, the PR Hygiene check passes. Reviewer limits do not block merging; other required GitHub checks and protections still apply.

lklimek and others added 3 commits November 9, 2026 13:26
…t in its round

A validator that saw a polka for a block it never received precommits nil
and, once its peers move to a later round, can no longer obtain the block:
block parts are served only from the proposal part set, which entering a
new round clears, while the valid and locked part sets that still hold the
block are never gossiped. Even when the block does arrive, one completed in
the prevote or precommit step is not processed, so an application that
verifies vote extensions against its last processed proposal, like Drive,
rejects every precommit for the block. Rejected precommits are not stored
and do not count towards the +2/3 of any kind that start the precommit
wait, so the validator stays in its round for good and a network without
spare voting power stalls with it.

Serve a validator peer at this height, in an earlier round, the complete
valid or locked part set whose header it is collecting, from the gossip
snapshot. Process the round's polka block when it completes too late for
the round to vote on it, so that the precommits for it verify; the node
casts no vote again, and a failure is not retried.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
A polka block the application rejects is processed once and not retried
on the precommits for it or on its parts arriving again; a block completing
in the prevote wait is processed there and not again in the precommit step;
one completing in the propose step with its proposal takes the usual path
and is processed once; a block completing without being the round's polka
block is not processed; an incomplete held part set is not served.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
A block completing while the round's polka is for another block is not
processed; a nil polka alone let the identity check go unexercised. The
rejected-block test no longer redelivers parts the part set already holds,
which completes nothing.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@coderabbitai

coderabbitai Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

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

Run configuration

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

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@thepastaclaw

thepastaclaw commented Nov 9, 2026 •

Copy link
Copy Markdown

✅ Final review complete — no blockers (commit 6260fed) · triage: critical

@lklimek lklimek added this to the v2.1 milestone Nov 16, 2026
@lklimek
lklimek marked this pull request as ready for review November 17, 2026 09:12
@github-actions

Copy link
Copy Markdown

Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post /skip-bots to proceed without them; blocking findings still need addressing.
Full checklist in the description.

@github-actions github-actions Bot added the waiting-bots Waiting for the review bots to report on this head label Nov 17, 2026
@github-actions

github-actions Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post /skip-bots to proceed without them; blocking findings still need addressing.
Full checklist in the description.

@thepastaclaw thepastaclaw left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Final validation — Phase 1 + Phase 2

Updated after discussion: 2 finding(s) of this review were settled in the inline threads; 2 blocking finding(s) still stand.

  • ✅ Withdrawn: 🔴 Do not optimistically mark held-block parts after a failed send
  • ⏭️ Deferred (maintainer decision): 🟡 Consensus-v1 completion still depends on vote redelivery (tracked in #1599)

The PR addresses the intended liveness wedge, but three in-scope ordering and delivery issues remain. Held-block gossip can permanently suppress retries after a failed send, the completed-block path does not reprocess a block when its polka arrives later, and the held-block fallback is incorrectly suppressed for an incomplete same-header part set. CI also reports a timeout in tests (00), specifically TestReactorValidatorSetChanges after vote-set gossip deadline errors; the available log does not establish that this failure was caused by this diff, while lint, build, vet, and the other completed test shards passed.

🔴 3 2 blocking | 🟡 1 0 suggestion(s)

Review provenance

Source: reviewer 1: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.1-sol (agent: phase2-reviewer, role: tenderdash-consensus-security); reviewer 3: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)

  • Triage: critical by gpt-6.1-sol (effort low) — This is a large, intricate change to the consensus state machine and peer-facing block gossip, specifically ProposalCompletedAction.processPolkaBlock and gossip_handlers.go, directly affecting BFT block delivery, ProcessProposal handling, and vote acceptance.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-3.8-flash-high (antigravity quota lookup failed), glm-5.3-flash (not used above high effort; tier asks max)
  • Single stage: Phase 1 and Phase 2 reviewed this head side by side, with no blocker gate between them (triage tier)
  • Fresh verifier: gpt-6.1-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.1-sol — general (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — tenderdash-consensus-security (completed, effort xhigh); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.

In `internal/consensus/gossip_handlers.go`:
- [BLOCKING → WITHDRAWN in discussion; do not fix] internal/consensus/gossip_handlers.go:257-258: Do not optimistically mark held-block parts after a failed send
  This path reuses GossipProposalBlockParts after substituting a held part set into the local RoundState snapshot. The peer gossip worker constructs its gossiper with optimistic=true, and msgGossiper.sync invokes the peer-state update callback even when msgSender.send returns an error. As a result, a part can be recorded in the peer's ProposalBlockParts bit array although it was never enqueued or delivered. On a one-part block, or for each lost part of a multi-part block, later passes see no missing part and stop retrying, while the substituted held set is not consensus state that will be re-announced through the normal state refresh. Use an acknowledged/non-optimistic send for this fallback or otherwise ensure failed sends do not update the peer's held-part bookkeeping and remain retryable.
- [BLOCKING] internal/consensus/gossip_handlers.go:322-324: Serve held parts when the current same-header set is incomplete
  The guard suppresses held-block fallback whenever the current ProposalBlockParts has the peer's header, regardless of whether that current set is complete. A node can retain a complete ValidBlockParts or LockedBlockParts set, enter a later round that clears the proposal set, and then retarget to a new incomplete set with the same header after observing the polka. The normal path can only send parts present in that incomplete current set; if the peer is missing another part, no part is selected, and this guard prevents the complete held set from being served. The lagging peer can remain unable to complete the block. Suppress fallback only when the current same-header part set is complete.

In `internal/consensus/state_add_prop_block.go`:
- [BLOCKING] internal/consensus/state_add_prop_block.go:388-390: Reprocess a completed block when its polka arrives later
  The new processing call is triggered only from ProposalCompletedAction, which is dispatched when adding a block part makes the part set complete. If the block completes before the final authenticated prevote arrives, this condition sees hasTwoThirds=false and does not process the block. When the final prevote creates the polka, addVoteDispatchPrevoteMw transitions the state but does not emit another ProposalCompletedEvent because the part set was already complete. The node can therefore keep an unprocessed block while receiving non-nil precommits whose vote extensions are rejected by VerifyVoteExtension, leaving it stuck in the old round. Trigger the same once-per-round processing logic when a current-round non-nil prevote majority is observed for an already-complete matching block, not only when block completion follows the polka.
- [SUGGESTION → DEFERRED by a maintainer; not blocking, do not fix in this PR] internal/consensus/state_add_prop_block.go:388-391: Consensus-v1 completion still depends on vote redelivery
  The processing fix makes late precommits verifiable only after the block is processed; it does not recover precommits that were rejected and dropped before the block arrived. Consensus v2 has the existing earlier-round vote resend path, but consensus v1 still requires the tracked #1599 vote-redelivery change for this liveness fix to be complete. Keep #1599 included with this change rather than treating this PR as a standalone consensus-v1 fix.

Comment thread internal/consensus/gossip_handlers.go Resolved
Comment thread internal/consensus/gossip_handlers.go Resolved
@github-actions github-actions Bot added waiting-self-review Waiting for the author to post /self-reviewed and removed waiting-bots Waiting for the review bots to report on this head labels Nov 17, 2026
lklimek and others added 4 commits November 17, 2026 11:35
… set is incomplete

heldBlockPartsFor skipped the held-block fallback whenever the round's
ProposalBlockParts carried the peer's part set header, even when that set
was incomplete and had nothing left to send. A complete current set still
suppresses the fallback, which would send nothing new anyway.

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ommit step

A block that completed in the precommit step before its polka was never
processed: ProposalCompletedAction found no polka, and the prevote that
formed it later only updated the valid block, as the node had already
precommitted. The application then rejected every precommit for the block
and the node never started its precommit wait.

blockExecutor.processPolkaBlock now owns the condition (current-round
non-nil polka, matching proposal block, not yet processed) and is called
both on block completion and when the current round's polka forms in the
Precommit or PrecommitWait step. The polka path runs once per round, as
the valid round is set there, so a failed ProcessProposal is not retried.

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s nil for it

When the polka formed in the prevote steps and enterPrecommit precommitted
nil because the round's proposal was missing or its timestamp differed from
the block's, the held polka block was never processed: the valid round was
already set and the block had completed earlier. The application then
rejected every precommit for it and the node never started its precommit
wait. Both nil branches now call processPolkaBlock before signing; it is a
no-op unless the held block is the unprocessed polka block, and
enterPrecommit runs once per round.

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…h nil precommit

With no proposal held, a polka block can only be held unprocessed after
ProposalCompletedAction already tried and failed to process it, so the call in
that branch was a silent retry that contradicted the no-retry contract and was
not covered by any test. The timestamp-mismatch branch alone closes the stall.

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions

github-actions Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post /skip-bots to proceed without them; blocking findings still need addressing.
Full checklist in the description.

@github-actions github-actions Bot added waiting-bots Waiting for the review bots to report on this head and removed waiting-self-review Waiting for the author to post /self-reviewed labels Nov 17, 2026

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Re-review — Final validation — Phase 1 + Phase 2

Two blocking issues remain. The polka-formation hook still omits the case where a completed block is present before the non-nil polka forms while the node is in PrevoteWait or an earlier step, and the new gossip fallback checks mutable PartSet completeness without synchronization. CI is otherwise green, but tests (00) failed in TestReactorValidatorSetChanges after a 120-second timeout; the log shows a consensus livelock but does not independently establish that this diff caused it.

🔴 2 blocking

Review provenance

Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 3: gpt-6.1-sol (agent: phase2-reviewer, role: tenderdash-consensus-security); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)

  • Triage: critical by gpt-6.1-sol (effort low) — This is a large, intricate change to consensus state transitions and peer-facing block/vote gossip, including ProcessProposal and precommit handling in state_add_prop_block.go and gossip_handlers.go.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-3.8-flash-high (antigravity quota lookup failed), glm-5.3-flash (not used above high effort; tier asks max)
  • Single stage: Phase 1 and Phase 2 reviewed this head side by side, with no blocker gate between them (triage tier)
  • Fresh verifier: gpt-6.1-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.1-sol — general (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — tenderdash-consensus-security (completed, effort xhigh); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.

In `internal/consensus/state_add_vote.go`:
- [BLOCKING] internal/consensus/state_add_vote.go:176-177: Reprocess a completed block when its polka arrives later
  The new hook only calls processPolkaBlock in Precommit and PrecommitWait. It still misses the valid ordering where the block completes first while the node is in Propose, Prevote, or PrevoteWait, and the final prevote establishing the non-nil polka arrives afterward. ProposalCompletedAction returns without processing because no polka exists yet; when the later prevote forms the polka, this condition is false in PrevoteWait, and EnterPrecommit subsequently takes the no-proposal branch and precommits nil without processing the held block. The block's non-nil precommits therefore fail vote-extension verification and cannot advance the node. The existing Prevotewait regression test covers polka-before-block completion, not this block-before-polka ordering. Invoke processPolkaBlock for every step before ApplyCommit, or process it from the missing-proposal precommit path.

In `internal/consensus/gossip_handlers.go`:
- [BLOCKING] internal/consensus/gossip_handlers.go:323-329: Avoid racing on PartSet completeness in the gossip snapshot
  StateDataStore.Get returns a shallow RoundState copy, so the PartSet pointers in rs remain shared with the consensus state. heldBlockPartsFor now calls PartSet.IsComplete while the consensus path can concurrently call AddPart. IsComplete reads count without taking PartSet.mtx, whereas AddPart writes count under that mutex, creating a race in race-enabled execution and allowing an inconsistent completeness result. Use the lock-protected BitArray snapshot when checking completeness, or synchronize IsComplete itself.

Comment thread internal/consensus/state_add_vote.go Resolved
Comment thread internal/consensus/gossip_handlers.go Resolved
@github-actions github-actions Bot added waiting-self-review Waiting for the author to post /self-reviewed and removed waiting-bots Waiting for the review bots to report on this head labels Nov 17, 2026
@Claudius-Maginificent Claudius-Maginificent added the priority: medium Medium priority label Nov 24, 2026
lklimek and others added 4 commits November 25, 2026 11:01
PartSet.IsComplete read count without the part set mutex that AddPart
writes it under. Consensus gossip checks the completeness of the
proposal part set the consensus state is filling, so the read raced
with AddPart.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A block that completed before its polka must be processed when the
polka forms after +2/3 precommits started the precommit wait, so that
the precommits for it verify. The valid-block middleware test passes a
real block executor rather than nil to the polka processing it calls.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
processPolkaBlock also runs before the node votes, and on the nil
precommit over a mismatched proposal timestamp, so its doc and log
messages no longer say the block arrived too late to vote on. The debug
log drops the step, which on the timestamp path is the step before
precommit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The node's own step never becomes RoundStepPrecommitWait: entering the
precommit wait only sets TriggeredTimeoutPrecommit and leaves the step
at RoundStepPrecommit, which the polka-block hook already checks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@lklimek
lklimek added this pull request to stack #1650 November 26, 2026 12:59
@lklimek
lklimek removed this pull request from stack #1650 November 26, 2026 16:19
@lklimek
lklimek added this pull request to stack #1658 November 26, 2026 16:19
lklimek and others added 2 commits November 27, 2026 08:29
…ocessProposal error

A validator that precommitted nil and then completes the round's polka
block processes it once so peer precommit extensions verify. When that
ProcessProposal failed recoverably, nothing processed the block again:
ensureOwnRound restores only an already processed proposal, so every
peer precommit stayed rejected and precommit wait never started.

Schedule one pending retry per height, round and block ID on a dedicated
timer read by the consensus loop, with the delay doubling from 100ms up
to 5s. Duplicate triggers are coalesced. A due retry is dropped when the
node moved to another height, round or polka block, lost the complete
block, or has it processed already; no retry is scheduled after a
rejection, an invalid block, a stopped ABCI client or a canceled context.
The step timeout ticker is not used, so step timeouts are unaffected.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add clearPolkaRetry and call it when a retry is replaced or dropped as
stale, when the receive routine exits, when OnStart fails, and before
the WAL catchup replay runs again after a repair, so no timer outlives
the state that armed it.

Treat an error wrapping context.Canceled as not worth retrying, and
state in ensureOwnRound's comment that only processPolkaBlock failures
are retried.

Test that an invalid block, a stopped ABCI client, a canceled context
or a canceled ctx schedule no retry, and that the delay stops growing
at polkaRetryMaxDelay.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@lklimek
lklimek force-pushed the fix/consensus-serve-polka-block branch from 9ae88ca to 96ffd22 Compare November 27, 2026 08:55
@github-actions

github-actions Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post /skip-bots to proceed without them; blocking findings still need addressing.
Full checklist in the description.

@github-actions github-actions Bot added waiting-bots Waiting for the review bots to report on this head and removed ready-for-human PR Hygiene: bots done, author self-reviewed, awaiting human review labels Nov 27, 2026

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Re-review — Final validation — Phase 1 + Phase 2

Changes requested: 1 blocker

  • WAL repair can leave a restarted validator stuck in precommit after its application recovers — internal/consensus/state.go:562-563 (new)
    Impact: A validator restarting after an unclean shutdown can remain unable to count the precommits it needs even after its application recovers, stalling block production if the other online validators cannot form a quorum without it.

New on this head: The two new commits add a dedicated, backoff-based retry when processing a polka block fails, and check that the same block still needs processing before calling ABCI again. The build, all six test shards, both end-to-end jobs, lint, and vet passed; PastaClaw review and PR Hygiene are still pending.

🔴 1 blocking | 🟡 1 suggestion(s)

Review provenance

Source: reviewer 1: gpt-6.2-astra (agent: phase2-reviewer, role: general); reviewer 2: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 3: gpt-6.2-astra (agent: phase2-reviewer, role: tenderdash-consensus-security); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)

  • Triage: critical by gpt-6.2-sol (effort low) — The diff changes consensus behavior across multiple event orderings: blockExecutor.processPolkaBlock and its prevote and precommit call sites change when a late block reaches the application, which can determine whether precommits are counted and the round advances.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-3.8-flash-high (antigravity quota lookup failed), glm-5.3-flash (not used above high effort; tier asks max)
  • Single stage: Phase 1 and Phase 2 reviewed this head side by side, with no blocker gate between them (triage tier)
  • New since the last final review (9ae88cad): 1 new blocker(s) went to an independent confirmation pass (the final verifier's model in a fresh session, without its reasoning): 1 confirmed
  • Fresh verifier: gpt-6.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-astra — general (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — tenderdash-consensus-security (completed, effort high); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.

In `internal/consensus/state.go`:
- [BLOCKING] internal/consensus/state.go:562-563: WAL repair can leave a restarted validator stuck in precommit after its application recovers
  Impact: A validator restarting after an unclean shutdown can remain unable to count the precommits it needs even after its application recovers, stalling block production if the other online validators cannot form a quorum without it.
  A successful WAL repair can leave the validator holding the block with no retry to rebuild the application context needed to verify precommits. On an ordinary restart with WAL catch-up enabled, the intact prefix can reconstruct a round that precommitted nil while missing its polka block, then replay the late parts. If `ProcessProposal` fails transiently before the application accepts the block, the completion hook schedules a retry. `readReplayMessage` saves the completed part set and votes before `catchupReplay` reaches the damaged record. Repair clears the timer but starts the second pass from that same saved state: duplicate parts do not dispatch `ProposalCompletedEvent`, duplicate prevotes do not run the polka hook, and the same-round precommit entry is already guarded. The startup timeout is stale, and redelivered precommits do not themselves process the block. Preserve the pending retry across repair so the receive loop can recheck its target and run it; failed-start cleanup already stops the timer if repair fails. Add a restart regression that arms the retry from the intact WAL prefix and verifies it survives repair.

  _Confirmed by an independent pass: After an unclean shutdown, a validator restarting with WAL catch-up enabled can replay an intact prefix that records a nil precommit followed by the late arrival of the polka block, then encounter a torn WAL tail. If ABCI returns a transient ProcessProposal error during that replay, OnStart clears the pending retry before replaying the repaired WAL against the same saved state, so the block is not processed again. Even after ABCI recovers, it still rejects the redelivered precommits for the unprocessed block; without those votes or a later quorum to catch up to, the validator stays in precommit and can hold up block production._

In `internal/consensus/block_executor.go`:
- [SUGGESTION] internal/consensus/block_executor.go:227-235: A malformed ABCI response keeps the polka-block retry running
  Impact: If the application consistently returns an accepted response with a wrong-length app hash or the wrong number of transaction results, the lagging validator keeps calling `ProcessProposal` and logging warnings on the consensus loop after the backoff reaches five seconds.
  A persistent response-format error gets the same retry treatment as a temporary ABCI call failure. In `internal/state/execution.go`, `resp.Validate()` and `validateExecTxResults` return ordinary wrapped errors, so neither matches the terminal cases in `tryPolkaBlock`. The existing invalid-block test uses a correctly sized hash that disagrees with the block and reaches `ErrInvalidBlock`; it does not cover malformed responses. Distinguish response-validation errors from call failures in the state executor, where that distinction is known, and add a wrong-length hash case that pins down the intended retry policy.

Comment thread internal/consensus/state.go Resolved
Comment thread internal/consensus/block_executor.go Resolved
@github-actions github-actions Bot added waiting-self-review Waiting for the author to post /self-reviewed and removed waiting-bots Waiting for the review bots to report on this head labels Nov 27, 2026
lklimek and others added 2 commits November 27, 2026 11:21
OnStart cleared the pending polka block retry before replaying a repaired
WAL. The repaired WAL holds only the records the first replay already
applied, so the second replay cannot arm the retry again: duplicate block
parts complete no proposal and duplicate prevotes form no new polka. A
retry armed by a transient ProcessProposal failure during the first
replay was lost, and the node kept rejecting precommits for the block.

Keep the retry; a failed start still clears it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Claudius-Maginificent

Copy link
Copy Markdown
Collaborator Author

Re thepastaclaw's review:
Per maintainer decision, this is fixed in this pull request.

4d794a6

🤖 Co-authored by Claudius the Magnificent AI Agent

@github-actions

github-actions Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post /skip-bots to proceed without them; blocking findings still need addressing.
Full checklist in the description.

@github-actions github-actions Bot added waiting-bots Waiting for the review bots to report on this head and removed waiting-self-review Waiting for the author to post /self-reviewed labels Nov 27, 2026

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Re-review — Final validation — Phase 1 + Phase 2

New on this head: This revision preserves the pending polka-block retry across WAL repair and adds a torn-WAL regression test that checks processing succeeds after a transient ABCI failure during replay. GitHub reports that the Linux build, lint, vet, both end-to-end jobs, the protobuf and app checks, and two unit-test shards passed; four unit-test shards and the ABCI CLI check are pending.

🟡 1 suggestion(s)

Approved: nothing here blocks the merge. The non-blocking findings are optional: fix them forward, in this PR or a follow-up, without waiting for another review round.

Still open from earlier rounds (1)

  • 🟡 Suggestion: A malformed ABCI response keeps the polka-block retry running — internal/consensus/block_executor.go:227-235 (thread)
Review provenance

Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: gpt-6.2-astra (agent: phase2-reviewer, role: general); reviewer 3: gpt-6.2-astra (agent: phase2-reviewer, role: tenderdash-consensus-security); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)

  • Triage: critical by gpt-6.2-sol (effort low) — The diff intricately changes consensus state transitions: blockExecutor.processPolkaBlock and its callers alter when a +2/3-prevoted block reaches ABCI during prevote and precommit, affecting whether subsequent precommits can be counted.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-3.8-flash-high (antigravity quota lookup failed), glm-5.3-flash (not used above high effort; tier asks max)
  • Single stage: Phase 1 and Phase 2 reviewed this head side by side, with no blocker gate between them (triage tier)
  • Fresh verifier: gpt-6.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-astra — general (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — tenderdash-consensus-security (completed, effort high); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.

In `internal/consensus/block_executor.go`:
- [SUGGESTION] internal/consensus/block_executor.go:227-235: A malformed ABCI response keeps the polka-block retry running
  (carried; thread: https://github.com/dashpay/tenderdash/pull/1600#discussion_r4717797307)

Comment thread internal/consensus/state.go Resolved
Comment thread internal/consensus/block_executor.go Resolved
@github-actions github-actions Bot removed the waiting-bots Waiting for the review bots to report on this head label Nov 27, 2026
@Claudius-Maginificent

Copy link
Copy Markdown
Collaborator Author

Re thepastaclaw's review, suggestion "A malformed ABCI response keeps the polka-block retry running":
Per maintainer decision, this is addressed in #1662.

🤖 Co-authored by Claudius the Magnificent AI Agent

@github-actions

Copy link
Copy Markdown

Ready for review — files with no dedicated owner: lklimek or shumkov.
Full checklist in the description.

@github-actions github-actions Bot added the ready-for-human PR Hygiene: bots done, author self-reviewed, awaiting human review label Nov 27, 2026
@lklimek
lklimek enabled stacked auto-merge (squash) November 27, 2026 12:41
@github-actions

Copy link
Copy Markdown

Policy satisfied — this can merge.
Full checklist in the description.

@github-actions github-actions Bot removed the ready-for-human PR Hygiene: bots done, author self-reviewed, awaiting human review label Nov 27, 2026
@lklimek
lklimek merged commit b3f0500 into dev Nov 27, 2026
28 checks passed
@lklimek
lklimek deleted the fix/consensus-serve-polka-block branch November 27, 2026 12:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

priority: medium Medium priority

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants