Skip to content

perf(state): skip the second LastCommit verification when the memo proves it ran - #1428

Merged
lklimek merged 1 commit into
perf/verify-commit-oncefrom
perf/skip-second-lastcommit-verify
Sep 2, 2026
Merged

lklimek merged 1 commit into
perf/verify-commit-oncefrom
perf/skip-second-lastcommit-verify

Conversation

@PastaPastaPasta

Copy link
Copy Markdown
Member

Stacked on #1427 — base is perf/verify-commit-once, so the diff here is the 8 lines this change adds. Review #1427 first.

ValidateBlockWithRoundState verifies block.LastCommit even though the ValidateBlock call at the top of the same function normally does it.

That second verification is load-bearing rather than plainly redundant: ValidateBlock short-circuits on blockExec.cache, which is keyed on the block hash alone and carries no promise about the state the earlier validation ran against. Deleting it outright breaks TestStateProposalTime.

So gate it on the memo #1427 introduces instead of on the cache. The skip fires only when this exact commit was already verified against identical inputs — same chain ID, height, block ID, quorum type, quorum hash, threshold public key and byte-identical marshalled commit. That is a property of the data rather than of the cache, so it holds regardless of which path populated the cache.

Measurements

Same 3,000-block window at mainnet height 190k, on top of #1427:

ms/block fb_validate
#1427 alone 10.31 1.977 ms
with this change 8.36 0.010 ms

A further −18.9% off the block. Against v1.7-dev the pair is 12.81 → 8.36 ms/block, −34.7%: block sync now performs one threshold verification per block instead of three.

Same caveat as #1427 on the measurement method — tenderdash's per-block fsync is removed so macOS F_FULLFSYNC does not swamp the result.

Tests

internal/state/..., internal/blocksync/..., internal/consensus all pass, TestStateProposalTime included.

🤖 Generated with Claude Code

…oves it ran

ValidateBlockWithRoundState verifies block.LastCommit even though the ValidateBlock
call at the top of the same function normally does it. That second verification is
load-bearing rather than redundant: ValidateBlock short-circuits on blockExec.cache,
which is keyed on the block hash alone and carries no promise about the state the
earlier validation ran against. Removing it outright breaks TestStateProposalTime.

So gate it on the memo added in the previous change instead of on the cache. The
skip happens only when this exact commit was already verified against identical
inputs — same chain ID, height, block ID, quorum type, quorum hash, threshold
public key and byte-identical marshalled commit. That is a property of the data,
not of the cache, so it holds no matter which path populated the cache.

Replaying mainnet, this stage goes from 1.81 ms a block to 0.007 ms. Together with
the previous change block sync performs one threshold verification per block
instead of three.
@coderabbitai

coderabbitai Bot commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

Important

Review skipped

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

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 677dcde4-fd60-4e87-b1ca-2a464be65d75

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

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

❤️ Share

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

@thepastaclaw

thepastaclaw commented Aug 31, 2026 •

Copy link
Copy Markdown

⛔ Final review complete — 1 blocking finding(s) (commit ad721f2)

@PastaPastaPasta

Copy link
Copy Markdown
Member Author

CI: tests (01) failed on TestReactorValidatorSetChanges (120 s timeout, "context deadline exceeded" syncing vote sets). Pre-existing flake, not a regression from this change:

Re-running the failed job.


🤖 Posted autonomously by Claude on behalf of pasta.

@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 — Sol-only technical fallback

The new guard is unsafe because the memo is created after mutable commit buffers have crossed the in-process ABCI boundary, allowing it to attest to bytes that were never verified. The consensus-critical bypass also lacks direct regression coverage for exact matches and mismatched verification inputs.

Source: reviewer 1: gpt-5.6-sol (agent: sol-fallback-reviewer, role: general); reviewer 2: gpt-5.6-sol (agent: sol-fallback-reviewer, role: tenderdash-consensus-security); final verifier: gpt-5.6-sol (agent: sol-verifier, role: final-verifier)

One or more required Phase-1 GLM Flash lanes remained technically unusable after the bounded exact-model retry. Their evidence was discarded as authoritative, and the complete selected role cohort was rerun fresh on exact gpt-5.6-sol before this fresh Sol verifier produced the final decision. No additional Phase-2 reviewer pass ran.

Review provenance

  • Phase 1 GLM evidence: technically unusable after bounded retry; discarded from the decision
  • GLM failure attempts: codex-general-ff851787b4fc4df8a63f33a39c843add (failed), codex-general-64e85bf1713045619c2426b9fe6a2e33 (failed), codex-tenderdash-consensus-security-c6a769eb62a84018ade176bd17ff3fda (failed), codex-tenderdash-consensus-security-cc29103b379842f6ade92619621b5695 (failed)
  • Sol-only fallback reasons: launch_transport_or_nonzero_exit, launch_transport_or_nonzero_exit
  • Sol-only fallback reviewers: gpt-5.6-sol — general (completed); agent sol-fallback-reviewer, gpt-5.6-sol — tenderdash-consensus-security (completed); agent sol-fallback-reviewer
  • Fresh verifier (Sol): gpt-5.6-sol — final-verifier; agent sol-verifier
  • Additional Phase 2 pass: not run; the Sol-only fallback is final

🔴 1 blocking | 🟡 1 suggestion(s)

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

🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

In `internal/state/execution.go`:
- [BLOCKING] internal/state/execution.go:537-542: Post-verification ABCI mutation can forge the verification memo
  `NoteVerifiedCommit` is called only after `ApplyBlock` returns, but before that call `execBlock` passes `commit.ToCommitInfo()` to the application. `ToCommitInfo` directly aliases `ThresholdBlockSignature`, `QuorumHash`, and nested vote-extension buffers, and the local ABCI client passes the request object in-process without serialization. An application can therefore replace commit H's valid signature after `blockApplier.verify` succeeds, causing the memo to record unverified bytes. At H+1, `ValidateBlock` first verifies and caches the original block, after which the same application can replace the shallow-aliased `ProposedLastCommit` signature with the memoized bytes. The cached block hash then bypasses validation here, and this new guard skips the only remaining `VerifyCommit`, so `FinalizeBlock` executes and events expose LastCommit data that was never cryptographically verified. Capture an immutable snapshot immediately after the successful verification and retain that snapshot until the memo is installed; until then, preserve this second verification.
- [SUGGESTION] internal/state/execution.go:537: Add regression coverage for the new verification bypass
  This PR changes consensus-critical validation without adding a test. The existing block-sync tests only verify that the mock `NoteVerifiedCommit` method is called, while the state tests never populate the memo before exercising `ValidateBlockWithRoundState`. Add direct coverage showing that an exact snapshot match takes the bypass and that changes to the commit bytes, chain ID, height, block ID, quorum type, quorum hash, or threshold public key fall through to `VerifyCommit` and reject an invalid commit. The fix for the mutation issue should also include an in-process application regression test that mutates FinalizeBlock's commit buffers and ProcessProposal's LastCommit buffers.

// commit was already verified against these exact inputs — same chain, height,
// block ID, quorum, threshold key and byte-identical commit — which is a
// property of the data rather than of the cache.
if block.Height > state.InitialHeight && !blockExec.lastCommitAlreadyVerified(state, block) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Suggestion: Add regression coverage for the new verification bypass

This PR changes consensus-critical validation without adding a test. The existing block-sync tests only verify that the mock NoteVerifiedCommit method is called, while the state tests never populate the memo before exercising ValidateBlockWithRoundState. Add direct coverage showing that an exact snapshot match takes the bypass and that changes to the commit bytes, chain ID, height, block ID, quorum type, quorum hash, or threshold public key fall through to VerifyCommit and reject an invalid commit. The fix for the mutation issue should also include an in-process application regression test that mutates FinalizeBlock's commit buffers and ProcessProposal's LastCommit buffers.

source: ['claude']

@lklimek lklimek left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

just add a test

@lklimek
lklimek merged commit f735774 into perf/verify-commit-once Sep 2, 2026
20 of 22 checks passed
@lklimek
lklimek deleted the perf/skip-second-lastcommit-verify branch September 2, 2026 11:35
lklimek added a commit that referenced this pull request Sep 11, 2026
…LastCommit (#1427)

* perf(blocksync): verify a commit once, not again as the next block's LastCommit

Block sync threshold-verifies the commit for block N in blockApplier.verify, and
one height later the same commit comes back as block N+1's LastCommit and is
verified a second time inside validateBlock. Every commit was verified twice, a
block apart, at roughly 1.9 ms each.

The applier now records what it verified through a new Executor.NoteVerifiedCommit
and validateBlock takes a lastCommitVerified hint. The skip fires only on an exact
match of every input ValidatorSet.verifyCommit reads: chain ID, height, block ID,
quorum type, quorum hash, threshold public key, and a byte-identical marshalled
commit. Marshalling rather than using Commit.Hash() matters, because that hash
only covers ThresholdBlockSignature and would miss Round and the vote extensions.
Anything short of a full match falls through to a real verification.

The note is stored after ApplyBlock returns, not before: both places that would
re-verify this commit run while the *next* block is applied, so writing it earlier
would overwrite the entry they are still reading for the current block and the
skip would never fire. The validator set is captured before ApplyBlock, which
reassigns e.state.

The consensus path never calls NoteVerifiedCommit, so the memo stays nil there and
nothing changes. It is an atomic.Pointer written and read whole, never
read-modify-write, and blockApplier.Apply is serialised under its own mutex.

Replaying mainnet, the applier's verify stage goes from 3.61 ms to 1.84 ms a block.

* perf(state): skip the second LastCommit verification when the memo proves it ran (#1428)

ValidateBlockWithRoundState verifies block.LastCommit even though the ValidateBlock
call at the top of the same function normally does it. That second verification is
load-bearing rather than redundant: ValidateBlock short-circuits on blockExec.cache,
which is keyed on the block hash alone and carries no promise about the state the
earlier validation ran against. Removing it outright breaks TestStateProposalTime.

So gate it on the memo added in the previous change instead of on the cache. The
skip happens only when this exact commit was already verified against identical
inputs — same chain ID, height, block ID, quorum type, quorum hash, threshold
public key and byte-identical marshalled commit. That is a property of the data,
not of the cache, so it holds no matter which path populated the cache.

Replaying mainnet, this stage goes from 1.81 ms a block to 0.007 ms. Together with
the previous change block sync performs one threshold verification per block
instead of three.

* test(state): cover the verified-commit memo directly

TestLastCommitAlreadyVerified checks the memo matches only on a full match of every input VerifyCommit reads, and falls through when the chain ID, height, block ID, quorum type, quorum hash, threshold key or any commit field differs. TestApplyBlockSkipsVerifiedLastCommit drives a real BlockExecutor with genuine BLS commits through ApplyBlock: a noted commit is not threshold-verified again, a forged commit that was never noted is rejected, and a memo for a different commit does not cover a forged one.

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

* test(state): fold the ApplyBlock drive into the memo fixture

Replace the blockAndID closure with a fixture method so each subtest reads as note-then-assert, use slices.Clone for the vote extensions, and move the cache comment above the call it explains.

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

* refactor(state): verify commits through the executor so the memo cannot be fed unverified ones

NoteVerifiedCommit took the caller's word that a commit had been verified. Replace it with Executor.VerifyCommit, which runs the threshold verification itself and remembers the result only on success. The block sync applier now verifies through it; nothing else can write the memo.

The memo keeps the two most recent commits instead of one: VerifyCommit for commit N runs before block N is validated, and block N's LastCommit is commit N-1, so both must be present. This also removes the ordering constraint that forced the applier to record the note only after ApplyBlock returned.

Every slice-backed field in the memo is now an owned copy, so mutation of the validator set, block ID or commit after verification cannot change what it matches. validateBlock takes the hint as a closure, so the memo is consulted only after ValidateBasic and the cheaper header checks. A new state_last_commit_verification_skipped counter makes the skip observable, and a marshal failure on the memo path is logged instead of swallowed.

* refactor(state): replace commit-verification memo with typed VerifiedCommit token (#1456)

* feat(types): add CommitVerification, a typed proof of commit verification

VerifyCommitSignatures verifies a commit exactly as ValidatorSet.VerifyCommit
does and, on success, returns a CommitVerification recording the chain,
height, block ID, quorum, threshold key and the signed digests and signatures
it checked. ValidatorSet.VerifyCommitUnlessVerified skips the threshold
verification only when a verification covers exactly those inputs. Anything
else, including the zero value, falls through to the unchanged verifyCommit,
so its typed errors (ErrInvalidCommitSignature versus the untyped
vote-extension count mismatch and budget exhaustion) are preserved.

verifyCommit is split into commitSignData and verifyCommitReportingSigns with
every error path unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>

* refactor(state): replace commit-verification memo with typed CommitVerification token

BlockExecutor.VerifyCommit returns a types.CommitVerification instead of
recording it in a private two-slot memo. ValidateBlock,
ValidateBlockWithRoundState, FinalizeBlock and ApplyBlock take the
verification of block.LastCommit explicitly. Block sync's applier threads the
verification of each commit one block forward; consensus and the replayer pass
the zero value and verify in full as before. The
state_last_commit_verification_skipped metric keeps its meaning.

Co-Authored-By: Claude Opus 5 <[email protected]>

* test(consensus): deflake TestWALRoundsSkipper

The WAL generator node is the only validator, so it proposes every round,
and replayPrevoter makes heights 3 to 5 commit only at round 10. The test
genesis gives round 10 a 30.5ms propose timeout. On a loaded runner (-race,
-coverprofile, several packages at once) that timer fires before the node's
own proposal is complete, so it prevotes nil and moves to round 11:
- at height 5, stopConsensusAtHeight(5, 11) halts consensus and the test
  times out after 60s ("waited too long for tendermint to produce 5
  blocks"), which is the failure seen on #1391, #1393 and #1410;
- at height 3 or 4, the commit lands past maxRound and the round assertion
  fails.

Give the generator a 10s propose timeout. With a single proposer, a round
moves on as soon as the proposal is complete, so a longer timeout only
removes the race. UnsafeProposeTimeoutOverride is node-local and not a
consensus parameter, so the blocks are unchanged.

TestWALRoundsSkipperSlowProposer pins this. Its app holds PrepareProposal at
round 10 for three times the genesis propose timeout. Without the override
it fails every run; with it, it passes every run.

Once the test survives load, a second pre-existing flake surfaces. The
replaying State and its WAL keep running after Stop/Wait: receiveRoutine
exits only when it sees its context cancelled, and the services' ctx
watchers log asynchronously. Their logs through NewTestingLogger then land
after the test completes and panic the binary ("Log in goroutine after
TestWALRoundsSkipper has completed"). The test now logs through a writer
that is muted, under a lock, by its first-registered cleanup.

Co-Authored-By: Claude Opus 5 <[email protected]>

* refactor(types): turn CommitVerification into VerifiedCommit

types.CommitVerification only carried proof metadata, checked against a
commit passed alongside it. It becomes types.VerifiedCommit: the commit
itself plus an optional proof.

    type VerifiedCommit struct {
        commit *Commit       // the caller's pointer, the subject only
        proof  *commitProof  // nil: no proof
    }

commitProof keeps the nine fields CommitVerification recorded, with their
doc comments.
- VerifyCommitSignatures keeps its signature, checks and errors. It returns
  the commit with a proof on success, and the zero VerifiedCommit on failure.
- NewUnverifiedCommit(commit) builds the no-proof variant. The zero value is
  NewUnverifiedCommit(nil).
- Commit() returns the embedded pointer. Its doc spells out that it is not
  evidence and must never be validated in place of the commit actually
  received.
- checkMatches moves to *commitProof and treats a nil receiver as "nothing
  was verified". It compares commit content only, never pointer identity.
- errCommitVerificationMismatch becomes errCommitProofMismatch.

Only the parameter types change at the call sites. block.LastCommit is
still read from the block, and the current-height commit parameter of
ApplyBlock/FinalizeBlock is untouched. Consensus (finalize, validate),
ProcessProposal and the replayer pass NewUnverifiedCommit(block.LastCommit);
the block-sync applier keeps the zero value where it holds no commit. Mocks
are regenerated with mockery v3.7.4.

Tests:
- the types tests are renamed to VerifiedCommit;
- the proof-mutation test pins with require.Same that the embedded commit
  aliases the caller's pointer;
- a new case shows that a VerifiedCommit without proof, even one holding
  the very commit being verified, never skips verification;
- the new TestBlockApplierSkipsTheLastCommitItVerified drives three blocks
  through a real executor and asserts LastCommitVerificationSkipped reaches
  0, 2 and 4. It fails if the applier hands the next block the commit
  without its proof;
- metricspy gains a Counter for it.

Co-Authored-By: Claude Opus 5 <[email protected]>

* chore: retrigger CI

GitHub Actions never picked up 0eccc06 (no check-suite created for it
after 45+ minutes, unlike every prior push on this branch) — pushing an
empty commit to force a fresh push event.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* refactor(types): drop NewUnverifiedCommit, the only way to fake a VerifiedCommit

NewUnverifiedCommit let any caller wrap an arbitrary commit into a value of
a type named VerifiedCommit while attaching no proof at all -- a naming
trap, and unused by anything that reads Commit(): nothing outside tests
ever called it. The four call sites that used it to signal "no proof held"
never read the commit back off the value either; they only pass it into
VerifyCommitUnlessVerified, which already falls through to a full
verification on any proof-less value, zero value included.

Remove the constructor. The zero value is now the only proof-less
VerifiedCommit that code outside types can produce, and it is the only one
that matters in practice: consensus, the replayer and block sync's
ProcessProposal path all switch to it. The still-exported Commit() and the
commit field stay -- VerifyCommitSignatures is still the only way to end up
with a VerifiedCommit that names a real commit, and it always pairs one
with its proof.

TestUnverifiedCommitMatchesNothing keeps its "holds the exact commit but no
proof" case as an in-package struct literal: a white-box test proving the
mismatch check would still refuse to skip verification even in that
stronger, no-longer-reachable-from-outside scenario.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

---------

Co-authored-by: Claude Opus 5 <[email protected]>

* perf(state): offer the verified LastCommit to ProcessProposal

Since block sync validates the app response through
ProcessProposal(verify=true), ValidateBlockWithRoundState runs there with
a hard-coded zero proof, so every synced block threshold-verified its
LastCommit once more even though the applier already held the proof.

ProcessProposal takes lastCommit and forwards it to the verify branch.
The block applier hands it the proof it carries forward; consensus and
the replayer hold none and pass the zero value. ApplyBlock passes its own
lastCommit through for uniformity; it is unread with verify unset.

TestBlockApplierSkipsTheLastCommitItVerified now expects three skips per
height after the first, and fails against the previous commit.

Co-Authored-By: Claude Opus 5 <[email protected]>

* test(state): trim the ApplyBlock LastCommit verification tests

- Count skipped verifications with metricspy.Counter instead of a local
  duplicate of it.
- Drop the subtest applying a forged commit with the verification
  VerifyCommit returned on rejecting it: that verification is the zero
  value, already pinned by "rejected commit yields no verification" and
  TestVerifiedCommitKeepsTheVerifyCommitErrors, and a forged LastCommit
  without proof is pinned by "unverified forged commit is rejected".
- TestApplyBlockSkipsVerifiedLastCommit covers ApplyBlock only; block sync
  no longer calls it, so point to the block sync pin instead.

Co-Authored-By: Claude Opus 5 <[email protected]>

---------

Co-authored-by: lklimek <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants