Skip to content

perf(blocksync): remove redundant work from the block apply path - #1394

Merged
shumkov merged 7 commits into
v1.6-devfrom
perf/blocksync-apply-path
Aug 8, 2026
Merged

shumkov merged 7 commits into
v1.6-devfrom
perf/blocksync-apply-path

Conversation

@QuantumExplorer

@QuantumExplorer QuantumExplorer commented Jul 25, 2026 •

Copy link
Copy Markdown
Member

Stacked on #1393. Base is fix/blocksync-duplicate-block-peer-punishment;
GitHub will retarget to v1.6-dev once that merges. Review only the second
commit.

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 of
applying 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

  • 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. Now built once and passed 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 for
    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, off the
    serial path — and the metric reuses partSet.ByteSize(), which is exactly
    len(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.

Net: roughly five full block→protobuf conversions per block down to one, and the
survivor moved off the serial goroutine.

p2p

  • receivePeer recomputed proto.Size on every received message purely to feed
    a 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:

block sync rate  height=… blocks/s=… partset_ms=… verify_ms=… save_ms=… abci_ms=…

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=false change

This is the hunk worth scrutinising, so stating the reasoning explicitly:

  • FinalizeBlock calls ValidateBlockWithRoundState(ctx, state, uncommittedState, block) as its first statement, before SaveABCIResponses and before the
    ABCI FinalizeBlock call — so nothing is persisted or delivered ahead of
    validation.
  • The arguments are identical: ApplyBlock passes ProcessProposal's returned
    stateChanges straight through as uncommittedState.
  • Both wrap failures in ErrInvalidBlock, and both return the original state,
    so the error type and returned state are unchanged.
  • The only other FinalizeBlock caller, consensus/blockExecutor.finalize, is
    preceded by an explicit mustValidate in state_apply_commit.go.
  • BlockReplayer.replayBlock uses ProcessProposal(verify=false) but does not
    call FinalizeBlock at all, so it is unaffected.

No validation is removed; it just stops running twice.

Dropped: caching BlockStore.Height/Base

An earlier revision of this PR cached those two values in memory, since each one
opens a DB iterator and they are read twice per SaveBlock plus once per block
by pruneBlocks. It was removed: it broke e2e-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. full01 is configured with state_sync = "p2p" and
retain_blocks = 10, so statesync backfill writes block metas at low heights via
SaveSignedHeader while pruning runs every block — precisely that window. The
node 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 looked
tempting but is unsafe: CurrentRoundState.UpdateBlock assigns AppHash,
ResultsHash, NextValidatorsHash and CoreChainLockedHeight directly on a
live *types.Block during proposal construction, so a cached header hash could
go 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's deps stage (Go 1.26.4, BLS
prebuilt).

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, state Save, plus pruning), untouched here.

Breaking Changes

None to the wire protocol or on-disk format. One internal signature change:
consensus.Metrics.RecordConsMetrics now takes the block size as a parameter
rather than deriving it; it has a single caller.

Checklist:

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have added or updated relevant unit/integration/functional/e2e tests
  • I have made corresponding changes to the documentation

For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

🤖 Generated with Claude Code

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]>
@QuantumExplorer
QuantumExplorer requested a review from lklimek as a code owner July 25, 2026 10:00
@coderabbitai

coderabbitai Bot commented Jul 25, 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: e99b2f6c-a006-47e6-8df8-55a8a805d412

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

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch perf/blocksync-apply-path

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

Block sync applies blocks on a single goroutine, so sync rate is bounded
by the cost of applying one block. That path repeated several expensive
operations:

- The part set was built twice per block, once inside BlockID(nil) and
  once explicitly for SaveBlock. Each build serializes the whole block
  and computes a Merkle tree over its parts. Build it once and pass it to
  both; BlockID(partSet) is identical to BlockID(nil) for a part set made
  with BlockPartSizeBytes.
- Block.Size() converted the whole block to protobuf twice more, once to
  feed the peer flow monitor and once for the block size metric. The size
  is now measured once while decoding the response, on a worker
  goroutine, and the metric reuses partSet.ByteSize(), which is exactly
  the length of the serialized block.
- ApplyBlock validated every block twice: ProcessProposal(verify=true)
  and then FinalizeBlock, which calls ValidateBlockWithRoundState with
  the same arguments and wraps failures in the same ErrInvalidBlock.
  Each pass costs a threshold signature verification of block.LastCommit.
  ApplyBlock now passes verify=false; FinalizeBlock validates before any
  persistence or ABCI call, so no check is lost.
- The p2p receive path recomputed proto.Size on every message purely to
  feed a byte counter, walking the whole decoded message again. len(bz)
  is the exact wire size and is already in hand.

Also records per-stage timings of the apply pipeline and reports them
alongside the existing block sync rate log line, so a slow sync can be
attributed to serialization, signature verification, disk or the ABCI
application without a profiler.

Co-Authored-By: Claude Opus 5 <[email protected]>
@QuantumExplorer
QuantumExplorer force-pushed the perf/blocksync-apply-path branch from 13be8ad to 8038497 Compare July 25, 2026 11:22
@QuantumExplorer

Copy link
Copy Markdown
Member Author

CI follow-up

e2e-test (rotate) — fixed by dropping a change

TestBlock_Range/full01 failed with "An error is expected but got nil" — the
assertion that blocks below the node's reported earliest height are gone.

This was caused by this PR, specifically the (now removed) in-memory cache of
BlockStore.Height/Base. Each mutating path invalidated the cache before its
write committed, leaving a window in which a concurrent Base() rescans the
pre-write database and re-caches a value that goes stale the instant the write
lands. full01 is configured with state_sync = "p2p" and
retain_blocks = 10, so statesync backfill writes block metas at low heights via
SaveSignedHeader while pruning runs every block — exactly that window. The node
reported an earliest height above blocks it still held, and the assertion failed.

Confirming it was this and not a flake: e2e-test (rotate) passes on #1393,
which is the same branch point without the store change.

The bounds cache has been removed from this PR. Everything else is unchanged.
Doing it correctly needs a generation counter (refuse to cache a scan that raced
a mutation) or holding the mutex across the write; that deserves its own PR and
its own e2e run. It was the smallest win in this set anyway.

govulncheck — pre-existing, not from this PR

GO-2026-5856 in the Go standard library crypto/[email protected], fixed in
go1.26.5. It is reached through dash/core/client.go, rpc/jsonrpc/... and
internal/libs/autofile/... — none of which either PR touches, and it fails
identically on #1393. It needs a toolchain bump (go.mod, DOCKER/Dockerfile,
CI) which is a repo-wide decision, so I have deliberately not made it here.

🤖 Addressed by Claude Code

@QuantumExplorer

Copy link
Copy Markdown
Member Author

e2e-test (rotate) is green on the re-run (17m34s), as is e2e-test (dashcore)
and all six unit shards. Removing the BlockStore.Height/Base cache was the fix,
which confirms the diagnosis above.

Remaining red: govulncheck only, which is the pre-existing Go stdlib advisory and
not from this PR. A separate toolchain-bump PR is on the way to clear it.

🤖 Addressed by Claude Code

@lklimek

lklimek commented Jul 28, 2026

Copy link
Copy Markdown
Collaborator

🧐 Grumpy Review — PR #1394

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

Agent Model Lens
security-engineer-smythe opus OWASP / concurrency / DoS
project-reviewer-adams opus cross-artifact consistency, code quality
qa-engineer-marvin sonnet adversarial correctness, execution-verified

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 — CODE-006 is a false positive (its premise requires monitorInterval <= 0, which is unreachable at 3 independent points in synchronizer.go) and is reported below as disputed, not as a finding.

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 merge

0 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 ApplyBlock callers still get exactly one validation pass, not zero. Nothing here is unsafe and the diff introduces no new attack surface. Merge it; the items below are fast-follow.

Both genuine redundant-serialization removals are real: the double part-set construction, and collapsing ApplyBlock's double ValidateBlockWithRoundState pass to one.

What the review did find is a cluster of accuracy and completeness gaps around the PR's own claims and its own new instrumentation:

  • The PR body's "five conversions down to one" is actually four down to two — one full block→protobuf conversion survives inside SaveBlock, and it's a two-line fix from a value this PR already computes for another purpose.
  • A new code comment asserts an ordering invariant ("validate before anything is persisted or delivered to the application") that is false on the very blocksync path this PR touches.
  • The new applyStats/Timings instrumentation — the PR's stated justification for shipping without a measurement — ships with zero test coverage, despite the checklist ticking "tests added".
  • .Milliseconds() truncation means the two stages this PR most wants to show improvement on (partset_ms, verify_ms) will plausibly log 0 both before and after, defeating the instrumentation's own purpose.

Suggested order: fix the misleading FinalizeBlock comment, correct (or close) the conversion count, and fold in the missing applyStats/Timings tests — QA already wrote and validated exactly that coverage (TestApplyStatsTakeEmpty, TestApplyStatsTakeAveragesAndResets, TestBlockApplierTimingsWiredToApply, all passing under -race), so folding it in is close to free.


Findings

Severity: 🔴 CRITICAL · 🟠 HIGH · 🟡 MEDIUM · 🔵 LOW · ⚪ INFO

Non-blocking (9) — address as fast-follow

ID Sev Tags Location Finding
SEC-001 🟠 HIGH OWASP-A04 OWASP-A08 CWE-1173 CWE-754 internal/state/execution.go:558-572 ApplyBlock's only block validation now lives implicitly inside FinalizeBlock with no regression test guarding the invariant — confirmed non-exploitable today by two independent audits; the risk is structural fragility, not a live gap.
PROJ-001 🟡 MEDIUM comment-vs-code misleading-invariant internal/state/execution.go:491-493 The new FinalizeBlock comment makes three claims and all three are false on the blocksync path — the app already got the block via ProcessProposal, SaveBlock already persisted it, and applier.verify already validated once. A load-bearing comment that is wrong is worse than no comment.
PROJ-002 🟡 MEDIUM perf-claim-accuracy missed-optimization internal/blocksync/applier.go:84 "Five conversions down to one" is wrong — SaveBlock → NewBlockMeta → block.Size() still does a full conversion on the same serial path. Fix is two lines: BlockSize: int(blockParts.ByteSize()) in types/block_meta.go:29.
CODE-001 🟡 MEDIUM naming observability operator-ux internal/blocksync/synchronizer.go:405 The log key abci_ms blames the ABCI app for work that is mostly Tenderdash's own — the span also covers SaveABCIResponses, state.Update, flushMempool, store.Save and most of the PR's own "3-9 fsyncs per block". Rename to exec_ms/apply_ms.
SEC-003 🔵 LOW OWASP-A04 CWE-20 CWE-1188 CWE-400 internal/blocksync/synchronizer.go:505-529 BlockResponse.Size is an unvalidated exported field defaulting to 0 that feeds peer flow-rate eviction. Latent, not live — but a future construction path that omits it silently evicts honest peers. Several tests already omit it.
SEC-004 🔵 LOW OWASP-A09 CWE-1240 internal/p2p/router.go:849-859 PeerReceiveBytesTotal switched to raw wire length — the more honest number, but attacker-inflatable relative to decoded content. No enforcement reads it today; note the semantic shift in release notes so dashboards get recalibrated.
CODE-002 🔵 LOW dry reinvented-wheel internal/blocksync/applier.go:150-206 57 hand-rolled lines re-implement a worse histogram, while metrics *consensus.Metrics is already injected into the applier. Four Prometheus histograms delete applyStats, applyTimings, take() and the reset-on-read contract entirely — and yield quantiles instead of means.
CODE-003 🔵 LOW testing coverage-gap claim-vs-reality internal/blocksync/applier.go:99-137 New applyStats/Timings averaging logic ships with zero test coverage despite the checklist ticking "tests added" — verified by execution: no _test.go in the diff, and the timings log branch is unreachable in the existing suite.
CODE-004 🔵 LOW observability precision-loss internal/blocksync/synchronizer.go:402-405 .Milliseconds() truncates — the instrumentation cannot demonstrate the improvement it was added to demonstrate. partset_ms=0 verify_ms=0 before and after. Log the time.Duration directly and the logger gives you 312µs for free. Averaging also hides the tail, and stalls are what operators chase.

🔍 Disputed (1) — refuted by adversarial validation, no action needed

CODE-006 (LOW — "instrumentation adds unconditional per-block work, never drained when monitoring is off") was refuted as a false positive (confidence 0.75). Its premise requires monitorInterval <= 0, which the validation pass showed is unreachable at three independent points in synchronizer.go. Recorded for transparency; not an action item.

📋 Pre-existing / outside this diff (5) — for the backlog, not this PR

ID Sev Location Finding
SEC-002 🟡 MEDIUM internal/blocksync/applier.go:87-93 Pre-existing peer-triggerable panic on the apply path is preserved verbatim while the failure it catches has moved. Net reachability identical — requires a quorum-signed-but-invalid block or ABCI non-determinism, not a hostile peer. Worth a follow-up to split ErrInvalidBlock (drop the peer) from internal failures (fatal). Do not expand scope here.
PROJ-003 🔵 LOW docs/nodes/metrics.md:42,56 Stale for both metrics this PR touches: consensus_block_size_bytes is documented as Gauge but is a Histogram, and p2p_peer_receive_bytes_total is missing the message_type label. Two cell edits — cheap while in the area.
CODE-005 🔵 LOW metrics.go:145-149, router.go:852-858, synchronizer.go:146-147,531-553 Three independent "cheaper value equals the expensive one I removed" byte-size assumptions, none pinned by a test. Verified equal today by inspection; a future codec change could skew all three silently.
CODE-007 🔵 LOW internal/blocksync/synchronizer.go:387-390 maxPeerHeight is still computed on every block though used only at reporting points — and the "before locking to avoid deadlock" comment now explains a constraint this refactor removed.
CALL-001 🔵 LOW internal/state/execution.go:561-565 The redundancy is removed from the cold path and left on the hot one: the consensus path still validates 2-3× per block, paying the same threshold-signature verification this PR identifies as the cost worth eliminating. Not caused by this PR. Worth one line stating whether that's deliberate defence-in-depth or just out of scope — do not change it here, the consensus path is the wrong place for an unmeasured refactor.

👍 What holds up

  • CALL-002 — call-tree walk clean (INFO, praise-only): RecordConsMetrics's signature change has exactly two hits repo-wide — the declaration and its single updated caller. No test callers, no mocks, no interface declares it, internal/consensus isn't importable outside the module. Timings() likewise has one caller against a concrete type, and updateMonitor's signature is intact. The PR body's "one internal signature change… it has a single caller" is accurate. No breakage surface anywhere.
  • The two headline removals are real and correctly scoped, and the equivalence argument for dropping verify=true was independently re-derived from both ends before either reviewer wrote it up.
  • Both ApplyBlock callers were verified by execution to still get exactly one validation pass — not zero.
  • The applyTimings.Exec struct field doc is honest about covering the state-store writes; only the log key drifted (CODE-001).
  • Three of the four PR-body conversion-removal claims check out exactly as stated.

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

@thepastaclaw

thepastaclaw commented Jul 30, 2026 •

Copy link
Copy Markdown

✅ Final review complete — no blockers (commit 2282281)

@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 — 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]>
@QuantumExplorer

Copy link
Copy Markdown
Member Author

Thanks — genuinely useful review, especially catching that the PR body's own claim was wrong. Addressed in 94f8292.

Fixed

PROJ-001 — you're right on all three counts, and the comment was mine. On the block sync path ProcessProposal has already delivered the block to the app and blockApplier.Apply has already written it, so "before anything is persisted or delivered" was false. Rewritten to say what the call actually guards (the state and ABCI responses written below it) and why it must not be removed.

PROJ-002 — confirmed and fixed, not just corrected in prose. NewBlockMeta → block.Size() was a full conversion on the serial path. blockParts is already a parameter and holds the serialized block, so blockParts.ByteSize() is exact. Both callers pass a non-nil part set; kept a block.Size() fallback for nil rather than silently recording 0. So the count is now genuinely lower, and I've corrected the PR body rather than leaving the claim.

CODE-004 — agreed, and this one defeated the instrumentation's purpose. Now logs time.Duration directly, so sub-millisecond stages render as 312µs. Added a test that pins this: it asserts PartSet survives at 300µs and that .Milliseconds() on it is 0, so the reason for the choice can't be quietly undone.

CODE-001 — renamed abci_ms → exec. Correct that the span covers SaveABCIResponses, state.Update, flushMempool and store.Save; blaming the app for our own fsyncs would have sent operators the wrong way.

CODE-003 — fair hit, and the checklist tick was wrong. Added TestApplyStatsTakeEmpty, TestApplyStatsTakeAveragesAndResets and TestApplyStatsSubMillisecondPreserved.

SEC-001 — added TestApplyBlockValidatesBlock. I verified it's a real guard rather than a vacuous one: with FinalizeBlock's ValidateBlockWithRoundState removed, it fails with "ApplyBlock must reject a block that fails validation"; restored, it passes.

CODE-007 — maxPeerHeight now read only at reporting points, and the stale "before locking to avoid deadlock" comment is gone.

Not doing here

CODE-002 (replace applyStats with Prometheus histograms) — reasonable, but the deliverable is the sync-rate log line an operator reads while watching a node sync, not a scrape target; quantiles don't help there and it's a design change rather than a fix. Worth doing in addition later.

SEC-003 — agreed it's latent. BlockResponse is only constructed by BlockResponseFromProto in production, which always sets Size; the zero-value paths are tests. Left as-is rather than adding validation to a struct with one real constructor.

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 CODE-006

Your adversarial pass was right to refute it, and for a stronger reason than stated: stats.take() is only reached when recordSyncRate reports a reporting point, so the drain isn't gated on monitorInterval <= 0 at all.

Verified on the rebased branch (your merge of v1.6-dev + #1393): build clean, -race -tags=deadlock green across blocksync, state, store, consensus, p2p, statesync and types, and golangci-lint v2.12 reports nothing on any line this branch touches.

🤖 Addressed by Claude Code

Base automatically changed from fix/blocksync-duplicate-block-peer-punishment to v1.6-dev August 8, 2026 13:31
shumkov and others added 2 commits August 8, 2026 21:09
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]>
@shumkov
shumkov merged commit d3baf3f into v1.6-dev Aug 8, 2026
16 checks passed
@shumkov
shumkov deleted the perf/blocksync-apply-path branch August 8, 2026 14:52
shumkov added a commit that referenced this pull request Aug 8, 2026
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]>
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.

4 participants