Repository navigation
perf(blocksync): remove redundant work from the block apply path - #1394
Conversation
removePeer re-requested every block it had already received from the peer being removed, but left those responses in pendingToApply. When the re-requested block arrived from a different peer, addBlock rejected it as a duplicate and the synchronizer reported a PeerError against the peer that had served it correctly, evicting it. Under peer churn this cascades: each eviction re-requests more heights, each of those punishes another healthy peer, and block sync can stall long enough to hit the 60s syncTimeout and switch to consensus without being caught up. Delete the pending entry alongside the re-request so the re-fetched block is accepted, dedupe pushedBack so a height is not fetched twice concurrently, and treat a duplicate response as benign rather than as a peer fault. Co-Authored-By: Claude Opus 5 <[email protected]>
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
Block sync applies blocks on a single goroutine, so sync rate is bounded by the cost of applying one block. That path repeated several expensive operations: - The part set was built twice per block, once inside BlockID(nil) and once explicitly for SaveBlock. Each build serializes the whole block and computes a Merkle tree over its parts. Build it once and pass it to both; BlockID(partSet) is identical to BlockID(nil) for a part set made with BlockPartSizeBytes. - Block.Size() converted the whole block to protobuf twice more, once to feed the peer flow monitor and once for the block size metric. The size is now measured once while decoding the response, on a worker goroutine, and the metric reuses partSet.ByteSize(), which is exactly the length of the serialized block. - ApplyBlock validated every block twice: ProcessProposal(verify=true) and then FinalizeBlock, which calls ValidateBlockWithRoundState with the same arguments and wraps failures in the same ErrInvalidBlock. Each pass costs a threshold signature verification of block.LastCommit. ApplyBlock now passes verify=false; FinalizeBlock validates before any persistence or ABCI call, so no check is lost. - The p2p receive path recomputed proto.Size on every message purely to feed a byte counter, walking the whole decoded message again. len(bz) is the exact wire size and is already in hand. Also records per-stage timings of the apply pipeline and reports them alongside the existing block sync rate log line, so a slow sync can be attributed to serialization, signature verification, disk or the ABCI application without a profiler. Co-Authored-By: Claude Opus 5 <[email protected]>
13be8ad to
8038497
Compare
CI follow-up
|
|
Remaining red: 🤖 Addressed by Claude Code |
🧐 Grumpy Review — PR #1394Reviewed by: Claude Code with a 3-agent team:
Every finding was then independently re-validated by a 4th adversarial pass that tried to refute each one on its own evidence: 15 of 16 confirmed valid, 1 refuted — 19 raw findings → 16 after dedup (42% redundancy; three findings were raised independently by two agents each, which is the strongest signal in the set). Verdict: ✅ Approve with comments — safe to merge0 blocking findings. The core optimization is sound, correctly scoped, and independently verified from first principles rather than taken on the commit message's word — including proving by execution that both Both genuine redundant-serialization removals are real: the double part-set construction, and collapsing What the review did find is a cluster of accuracy and completeness gaps around the PR's own claims and its own new instrumentation:
Suggested order: fix the misleading FindingsSeverity: 🔴 CRITICAL · 🟠 HIGH · 🟡 MEDIUM · 🔵 LOW · ⚪ INFO Non-blocking (9) — address as fast-follow
🔍 Disputed (1) — refuted by adversarial validation, no action needed
📋 Pre-existing / outside this diff (5) — for the backlog, not this PR
👍 What holds up
Inline comments for the 9 non-blocking findings are attached as a pending review on the diff. 🤖 Co-authored by Claudius the Magnificent AI Agent |
|
✅ Final review complete — no blockers (commit 2282281) |
thepastaclaw
left a comment
There was a problem hiding this comment.
Final validation — Codex + Sonnet
Every finding from both Claude reviewer lanes is factually correct at head 2282281 (verified directly against types/block_meta.go, internal/blocksync/applier.go, internal/blocksync/synchronizer.go, and internal/state/execution.go), but each one is a duplicate of substance already delivered to the PR author in the pre-existing PR comment 5107503419 (PROJ-001, PROJ-002, CODE-001, CODE-003, CODE-004, SEC-001, SEC-003), which the Codex checkpoint already adjudicated and suppressed for the same reason. No new, previously-unreported issue survives verification, and no blocking or consensus-safety defect exists in this diff: the part-set reuse and the collapse of ApplyBlock's ProcessProposal(verify=true) pass down to a single ValidateBlockWithRoundState call inside FinalizeBlock are both correctly derived and preserve exactly one validation on the block-sync/replay path.
Source: reviewers codex/general=gpt-5.6-sol(completed); codex/tenderdash-consensus-security=gpt-5.6-sol(completed); claude/general=claude-sonnet-5(failed); claude/tenderdash-consensus-security=claude-sonnet-5(completed); claude/general=claude-sonnet-5(completed); verifier=claude/final-verifier=claude-sonnet-5(completed); coordinator=openclaw-agent/cliproxy/gpt-5.6-sol(orchestration-only).
Review provenance
- Codex reviewers:
gpt-5.6-sol— general (completed),gpt-5.6-sol— tenderdash-consensus-security (completed) - Verifier:
claude-sonnet-5— final-verifier - Sonnet reviewers:
claude-sonnet-5— general (failed),claude-sonnet-5— tenderdash-consensus-security (completed),claude-sonnet-5— general (completed)
- FinalizeBlock's new comment claimed the validation runs before the block reaches the app or the stores. That is false on the block sync path: ProcessProposal has already delivered the block and blockApplier.Apply has already written it. Say what the call actually guards, and why it must not be removed. - NewBlockMeta still converted the whole block to protobuf for its size, on the same serial path this change set is trying to shorten. The part set it already receives holds the serialized block, so its byte size is exactly the block size. - The timing log reported whole milliseconds, which truncates part set building and commit verification - routinely sub-millisecond - to 0 both before and after any improvement, defeating the point of adding the instrumentation. Log durations instead. - Renamed the abci_ms key to exec: the span also covers SaveABCIResponses, the state store write and the mempool update, which are ours rather than the application's. - updateMonitor read maxPeerHeight on every applied block for a line it prints once per interval, and carried a comment about a lock ordering the refactor had already removed. Adds the missing coverage: applyStats averaging, reset-on-read, and sub-millisecond retention, plus a regression test pinning that ApplyBlock still rejects an invalid block. ApplyBlock calls ProcessProposal with verify=false and relies solely on FinalizeBlock's validation, a coupling invisible from either function alone; the test was confirmed to fail when that validation is removed. Co-Authored-By: Claude Opus 5 <[email protected]>
|
Thanks — genuinely useful review, especially catching that the PR body's own claim was wrong. Addressed in FixedPROJ-001 — you're right on all three counts, and the comment was mine. On the block sync path PROJ-002 — confirmed and fixed, not just corrected in prose. CODE-004 — agreed, and this one defeated the instrumentation's purpose. Now logs CODE-001 — renamed CODE-003 — fair hit, and the checklist tick was wrong. Added SEC-001 — added CODE-007 — Not doing hereCODE-002 (replace SEC-003 — agreed it's latent. SEC-004 — noted in the PR body as a semantic shift so dashboards get recalibrated. The pre-existing five (SEC-002, PROJ-003, CODE-005, CODE-007-adjacent, CALL-001) I've left alone, agreeing with your framing — particularly CALL-001: the consensus path is the wrong place for an unmeasured refactor. On
|
Resolves the conflicts introduced when #1393 was squash-merged as a99ff2a. The squash dropped the shared ancestry between this branch and #1393, so the merge base fell back to 50f84e4 and every #1393 change resurfaced as a conflict against this branch's older copies of the same functions. Conflicts were in internal/blocksync/{block_fetch_job.go,synchronizer.go, synchronizer_test.go}, all between #1393's fixes and the pre-#1393 code this branch still carried. Resolved in favour of #1393 throughout: - block_fetch_job.go: taken from v1.6-dev unchanged. This branch needs no change here; keeping its copy would have reverted the sorted, single-pass pushBack and restored the quadratic scan and arrival-order retry. - synchronizer_test.go: taken from v1.6-dev unchanged. - synchronizer.go: keeps #1393's dropPeer batching, applyBlock returning the failing response so the supplying peer is charged, the addBlock floor guard for already-applied heights, and the context-cancellation carve-out; adds this branch's apply-path work on top (BlockResponse.Size, the per-stage timings in updateMonitor, and the RecordConsMetrics call). The resolved tree was verified byte-for-byte against a three-way merge of this branch with #1393's pre-squash tip, computed while that ancestry still existed. Net delta against v1.6-dev is this branch's apply-path work only. Co-Authored-By: Claude Opus 5 <[email protected]>
NewBlockMeta computed the fallback eagerly:
blockSize := block.Size()
if blockParts != nil {
blockSize = int(blockParts.ByteSize())
}
Go evaluates the initializer unconditionally, so block.Size() - which is
ToProto() plus a full walk of the result - ran on every call and was then
discarded whenever a part set was supplied. Both production callers
(store.SaveBlock and the block sync apply path through blockApplier.Apply)
always supply one, so the serialization this was meant to remove was still
being paid on every block.
Move the fallback into the branch that needs it. The nil case still reports
the real size rather than 0.
No behaviour change and no test: PartSet.ByteSize() is len(data) of the same
marshalling Block.Size() computes, so both branches produce identical values
and no assertion can tell the old code from the new. The change is only about
not doing the work. Verified by inspection; not compiled locally, as the BLS
native dependency is not built on this machine.
Co-Authored-By: Claude Opus 5 <[email protected]>
Resolves the conflicts introduced when #1394 was squash-merged as d3baf3f, the same way #1394 resolved the conflicts from #1393's squash as a99ff2a. Each squash drops the shared ancestry with the branch below it in the stack, so the merge base falls back past both parents and their changes resurface as conflicts against the older copies this branch still carries. Conflicts in internal/blocksync/{block_fetch_job.go,synchronizer.go, synchronizer_test.go} and types/block_meta.go, all between work already merged to v1.6-dev and this branch's stale copies. Resolved in favour of v1.6-dev throughout; this branch contributes no change to any of the four: - block_fetch_job.go, synchronizer_test.go: taken from v1.6-dev unchanged. - types/block_meta.go: taken from v1.6-dev unchanged. Keeping this branch's copy would have restored the eager block.Size() call, reintroducing the redundant serialization on the block sync apply path. - synchronizer.go: keeps #1393's dropPeer batching, applyBlock returning the failing response, and the addBlock floor guard, plus #1394's apply-path work, and layers this branch's failure-tracking and stall handling on top. The resolved tree was verified byte-for-byte against a three-way merge of this branch with #1394's pre-squash tip, computed while that ancestry still existed. Net delta against v1.6-dev is this branch's own seven files and nothing else. Co-Authored-By: Claude Opus 5 <[email protected]>
Issue being fixed or feature implemented
Block sync applies blocks on a single goroutine (
consumeJobResult→applyBlock→applier.Apply), so the sync rate is bounded by the cost ofapplying one block. Fetching is already wide (600-worker pool), so that serial
path is the ceiling — and it was repeating several expensive operations per
block.
What was done?
Redundant work removed from the apply path
BlockID(nil)andonce explicitly for
SaveBlock. Each build serializes the whole block andcomputes a Merkle tree over its parts. Now built once and passed to both.
BlockID(partSet)is identical toBlockID(nil)for a part set made withBlockPartSizeBytes.Block.Size()converted the whole block to protobuf twice more, once forthe peer flow monitor and once for the block size metric. The size is now
measured once while decoding the response — on a worker goroutine, off the
serial path — and the metric reuses
partSet.ByteSize(), which is exactlylen(serialized block).ApplyBlockvalidated every block twice:ProcessProposal(verify=true)and then
FinalizeBlock, which callsValidateBlockWithRoundStatewith thesame arguments and wraps failures in the same
ErrInvalidBlock. Each passcosts a threshold signature verification of
block.LastCommit.Net: roughly five full block→protobuf conversions per block down to one, and the
survivor moved off the serial goroutine.
p2p
receivePeerrecomputedproto.Sizeon every received message purely to feeda byte counter — a full extra pass over a block-sized message on the receive
hot path.
len(bz)is the exact wire size and already in hand.Instrumentation
Per-stage timings are recorded and reported alongside the existing rate line:
This is deliberately part of the PR: it says whether a slow sync is bound by
serialization, signature verification, disk or the ABCI app, without a profiler.
On the
verify=falsechangeThis is the hunk worth scrutinising, so stating the reasoning explicitly:
FinalizeBlockcallsValidateBlockWithRoundState(ctx, state, uncommittedState, block)as its first statement, beforeSaveABCIResponsesand before theABCI
FinalizeBlockcall — so nothing is persisted or delivered ahead ofvalidation.
ApplyBlockpasses ProcessProposal's returnedstateChangesstraight through asuncommittedState.ErrInvalidBlock, and both return the originalstate,so the error type and returned state are unchanged.
FinalizeBlockcaller,consensus/blockExecutor.finalize, ispreceded by an explicit
mustValidateinstate_apply_commit.go.BlockReplayer.replayBlockusesProcessProposal(verify=false)but does notcall
FinalizeBlockat all, so it is unaffected.No validation is removed; it just stops running twice.
Dropped: caching
BlockStore.Height/BaseAn earlier revision of this PR cached those two values in memory, since each one
opens a DB iterator and they are read twice per
SaveBlockplus once per blockby
pruneBlocks. It was removed: it brokee2e-test (rotate)(
TestBlock_Range/full01).The invalidation was ordered wrongly. Each mutating path invalidated the cache
before its write committed, which leaves a window where a concurrent
Base()rescans the pre-write database and re-caches a value that is stale the moment
the write lands.
full01is configured withstate_sync = "p2p"andretain_blocks = 10, so statesync backfill writes block metas at low heights viaSaveSignedHeaderwhile pruning runs every block — precisely that window. Thenode then reported an earliest height above blocks it still had, and the test's
"blocks below base must be gone" assertion failed.
Doing this correctly needs either a generation counter that refuses to cache a
scan that raced a mutation, or holding the mutex across the write. That belongs
in its own PR with its own e2e run, not bolted onto this one. It was also the
smallest win in this set, so nothing much is lost by deferring it.
Not done
Block.Hash()is still recomputed several times per block. Memoizing it lookedtempting but is unsafe:
CurrentRoundState.UpdateBlockassignsAppHash,ResultsHash,NextValidatorsHashandCoreChainLockedHeightdirectly on alive
*types.Blockduring proposal construction, so a cached header hash couldgo stale in consensus. Left alone deliberately.
How Has This Been Tested?
go build ./internal/... ./types/... ./node/... ./cmd/...go test -race -tags=deadlock -p 1 ./internal/blocksync/... ./internal/store/... ./internal/state/ ./internal/consensus/ ./internal/p2p/— all pass.golangci-lint: identical issue set to the base branch, nothing introduced.Built and tested against
DOCKER/Dockerfile'sdepsstage (Go 1.26.4, BLSprebuilt).
No measured sync-time improvement yet. Estimated 10–20% on the apply loop
from reading the code, but that is an estimate, not a measurement, and it is
conditional on the apply loop being the actual bottleneck rather than the
network or the ABCI app. The instrumentation above is what turns it into a
number. The larger remaining item is the 3–9
fsyncs per applied block(
SaveABCIResponses,SaveBlock, stateSave, plus pruning), untouched here.Breaking Changes
None to the wire protocol or on-disk format. One internal signature change:
consensus.Metrics.RecordConsMetricsnow takes the block size as a parameterrather than deriving it; it has a single caller.
Checklist:
For repository code-owners and collaborators only
🤖 Generated with Claude Code