Skip to content

validation, net: Process blocks asynchronously and reduce cs_main contention - #36244

Draft
w0xlt wants to merge 20 commits into
bitcoin:masterfrom
w0xlt:validation/async-block-processing
Draft

w0xlt wants to merge 20 commits into
bitcoin:masterfrom
w0xlt:validation/async-block-processing

Conversation

@w0xlt

@w0xlt w0xlt commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

The shared P2P message thread currently waits for block processing to finish before it can process messages from other peers.

This PR moves block processing to a dedicated worker after the initial checks, following the approach of #18963 and #16324:

  • Initial checks still run on the P2P message thread and decide whether a block should enter the processing queue.
  • A single worker processes queued blocks one at a time, in the order they are added to the queue.
  • Each peer can have only one block queued or being processed at a time. The node handles the processing result and any required peer penalties before processing that peer’s next incoming message.
  • Tracking block requests and reconstructing blocks from compact-block transaction responses no longer require cs_main, the chain lock.
  • When cs_main is busy, SendMessages() defers work such as requesting headers, blocks or transactions and announcing new blocks or transactions. This allows the P2P message thread to move on to other peers.

A controlled 10,000-block IBD benchmark showed these response-time improvements, measured as the median of four per-run medians:

Probe Download connections Baseline → This branch Reduction
PING/PONG 1 41.8 → 0.77 ms 98%
Block serving 1 39.0 → 26.5 ms 32%
Block serving 4 107.0 → 58.5 ms 45%

With four download connections, the median time to download and validate the 10,000 tested blocks during IBD fell by approximately 5%, from 473.6 s to 450.3 s.

The comparison used matching Clang 18 Release builds of baseline 4519933391dd and this branch, mainnet blocks 910,489 - 920,488, one local source node, and -assumevalid=0 -blocksonly=1. Each setup ran four times per build. PINGs ran at 10/s; the block probe requested the same previously validated block after warmup, at most once per second, timing receipt of the full block.

These results apply to this controlled IBD workload; they do not establish gains for other services, hardware, or network conditions. Performance outside IBD was not measured.

Tests and test infrastructure account for approximately 67% of the diff. Production code and build integration account for 1,132 changed lines (883 additions and 249 deletions).

I’m opening this PR as a draft primarily to gather feedback on the overall approach.

@DrahtBot

DrahtBot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

External sites

Reviews

See the guideline and AI policy for information on the review process.

Type Reviewers
Concept ACK sedited

If your review is incorrectly listed, please copy-paste <!--meta-tag:bot-skip--> into the comment that the bot should ignore.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #36445 (net: Skip cs_main when a peer has no orphan work by w0xlt)
  • #36389 (refactor: deduplicate block validation state catcher by enirox001)
  • #36353 (kernel: don't reuse cached CheckBlock results across params by FlashWayne)
  • #36337 (fuzz: Cover block filter P2P messages by maflcko)
  • #36268 (refactor: prune unused semi-colons by fanquake)
  • #36167 ([RFC] Enable -Wunused by fanquake)
  • #36109 (test: fix coinbases built on arbitrary parents by l0rinc)
  • #36098 (fuzz: add corpus reachability checks by HowHsu)
  • #35936 (net: reject oversized locators before allocating by l0rinc)
  • #35911 (Warn on and add missing [[noreturn]] by fanquake)
  • #35906 (First steps towards a stateless, side-effect free validation library by purpleKarrot)
  • #35570 (refactor: Change some validation.cpp methods to return BlockValidationState by optout21)
  • #35561 (net: move some CNodeState fields to Peer by Crypt-iQ)
  • #35474 (node: move index ownership to NodeContext by w0xlt)
  • #35229 (refactor: Use CBlockIndex parameters as reference by optout21)
  • #34775 (kernel: allow only one global logging connection by stickies-v)
  • #34374 (kernel: use struct-based logging and simplify logging interface by stickies-v)
  • #33847 (kernel: Attach logging connections to contexts, per-connection log levels by ryanofsky)
  • #28690 (build: Introduce internal kernel library by sedited)
  • #24230 (indexes: Stop using node internal types and locking cs_main, improve sync logic by ryanofsky)

If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.

LLM Linter (✨ experimental)

Possible places where named args for integral literals may be used (e.g. func(x, /*named_arg=*/0) in C++, and func(x, named_arg=0) in Python):

  • ProcessNewBlock(block, state, true, true) in src/node/block_template_manager.cpp
  • ProcessNewBlock(block, state, true, true) in src/test/util/setup_common.cpp
  • ProcessNewBlock(block, state, true, true) in src/test/util/mining.cpp
  • ProcessNewBlock(block, state, true, true) in src/test/baseindex_tests.cpp
  • ProcessNewBlock(block, state, true, true) in src/test/blockfilter_index_tests.cpp
  • ProcessNewBlock(block, state, true, true) in src/test/coinstatsindex_tests.cpp
  • ProcessNewBlock(block, state, true, true) in src/test/txindex_tests.cpp
  • ProcessNewBlock(block, state, true, true) in src/test/txospenderindex_tests.cpp
  • ProcessNewBlock(..., true, true) in src/test/validation_chainstate_tests.cpp
  • ProcessNewBlock(..., true, true) in src/test/validation_block_tests.cpp
  • ProcessNewBlock(..., true, true) in src/test/validation_tests.cpp
  • ProcessNewBlock(..., true, true) in src/test/peerman_tests.cpp

Possible places where comparison-specific test macros should replace generic comparisons:

  • [src/test/validation_queue_tests.cpp] BOOST_CHECK_THROW(queue.Start(), std::logic_error); -> consider BOOST_CHECK_EXCEPTION(queue.Start(), std::logic_error, /*predicate on message*/) so the test verifies the specific failure reason, not just the exception type.
  • [src/test/validation_queue_tests.cpp] BOOST_CHECK_THROW(stopped.Start(), std::logic_error); -> consider BOOST_CHECK_EXCEPTION(stopped.Start(), std::logic_error, /*predicate on message*/) to assert the expected error detail.

2026-10-03 07:29:49

@w0xlt
w0xlt force-pushed the validation/async-block-processing branch from 821d4c2 to 34d9d3d Compare September 14, 2026 08:02
@w0xlt
w0xlt marked this pull request as draft September 14, 2026 12:25
@andrewtoth

Copy link
Copy Markdown
Contributor

The PR description describes IBD speedup. But, wouldn't the point of something like this be that we could process messages while validating at steady-state, so a block that takes a long time to validate does not hold up responding to compact block transaction requests or other messages? And eventually we could also process competing sibling blocks in parallel?

@w0xlt
w0xlt force-pushed the validation/async-block-processing branch from 34d9d3d to 5922474 Compare September 15, 2026 01:11
@w0xlt

w0xlt commented Sep 15, 2026

Copy link
Copy Markdown
Contributor Author

@andrewtoth Yes, keeping other peers responsive during block validation, including at the tip, is the main motivation. I used IBD as a repeatable workload with sustained validation to measure that benefit. The shorter IBD time was a secondary observation; the main measured gains were faster PING/PONG and block-serving responses, as shown in the table.

Your compact-block example fits. getblocktxn already has a path that serves missing transactions from the recent block cache without taking cs_main. This PR moves block processing onto a separate worker, allowing that handler to respond to other peers while validation continues. Other handlers that need cs_main can still wait.

Parallel validation of competing sibling blocks would require further work on shared chainstate and synchronization. This PR keeps a single worker processing blocks serially.

I see this separation of networking and block processing, along with fewer unnecessary waits for cs_main, as a starting point for further concurrency improvements.

w0xlt added 14 commits October 2, 2026 23:53
Pass a caller-owned BlockValidationState through ProcessNewBlock's
CheckBlock and AcceptBlock stages, keeping chain-activation states local.
Update callers to supply fresh states while preserving synchronous
BlockChecked delivery, processing success, and new_block semantics.

Cover initial rejection, valid and duplicate submissions, and a block
that passes admission but fails validation when connected. This prepares
callers to distinguish initial validation results from future completion,
following the API preparation in PR bitcoin#18963.
Move BlockProcessingResult from PeerManagerImpl into the validation API
and return it from ProcessNewBlock instead of returning bool and writing
new_block through an output parameter. Update all callers while keeping
validation, notifications, and peer completion synchronous.

Preserve both outcomes independently, including new_block remaining true
on a write failure. Neither field implies full consensus validity.
Extend the initial-state regression test to check both result fields and
exercise a real block-file write failure. Capture and assert its expected
error notification to keep successful test output clear.

This prepares the API for a future carrying both completion outcomes.
Wrap BlockProcessingResult in a future, fulfilling its promise at each
existing return. Keep validation synchronous and fulfill successful
completion after active and historical chainstate activation.

Update callers to consume the ready future before their existing
completion actions, preserving initial-state reporting, both result
fields, and notification ordering. Explicitly discard unused test
results for libc++ compatibility. Check future validity and immediate
readiness in the existing outcome regression scenarios.
Retain completion futures for full blocks, completed compact blocks,
and optimistic reconstruction. Poll without waiting, pausing new-message
dequeuing and the normal send loop for the submitting peer while its
completion is pending. Continue servicing previously queued getdata and
orphan work before checking for pending block processing.

Keep records in the peer manager by peer ID and poll them even when no
peers remain, so download cleanup survives source disconnection. Preserve
newer source attribution, check optimistic transaction validity at
completion, and apply punishment before dequeuing another message.
Handle failed futures without letting exceptions escape the message loop.

Add controlled-future coverage for peer pause/resumption, queued getdata
work, ordinary messages from other peers, disconnection, completion
ordering, and errors. Validation still executes synchronously and returns
ready futures.
Add a single-worker FIFO with owned blocks, processing callbacks, and
completion futures. Accept submissions while running and complete futures
with either a result or the callback's exception. Report inactive or
stopping queues without retaining the submitted work.

Make ChainstateManager own the queue. Support explicit startup, interruption,
and draining shutdown, and stop before node and test dependencies are
removed. Keep the kernel context alive throughout manager destruction.
Move BlockProcessingResult into the queue header without changing its API.

Add tests covering lifecycle, ownership, exceptions, FIFO processing,
concurrent producers and shutdown, and callback submission. Production
startup leaves the worker inactive and ProcessNewBlock remains synchronous;
validation admission, worker processing, and completion wakeups follow
separately.
Exclude received blocks awaiting processing completion from automatic
download selection and compact-block reconstruction. Avoid attributing
download stalls to peers when local processing holds back or advances the
download window.
Run initial validation and admission on the caller, then submit blocks needing
storage for persistence and chain activation. Retain inline execution before
the queue is started for kernel, fuzz, and other standalone callers.

Return initial errors directly and deferred cached-invalid outcomes through the
future so peer attribution remains tied to each submission. Notify listeners
when completions become available and adapt blocking callers to the split
result contract.
Start the block-processing queue during node and ordinary test setup. Keep fuzz
and kernel callers on the inline path, and stop the worker before its callback,
networking, mempool, and index dependencies are destroyed.

Add coverage for queued parent invalidation, duplicate rejection attribution,
pending downloads and stalling, disconnected sources, and worker-gate and
subscriber lifetimes.
Move mapBlockSource from cs_main to a PeerManager bookkeeping mutex,
following the source-attribution change in PR bitcoin#18963. Source insertion and
ordinary completion cleanup can run while validation holds cs_main.

Skip BlockChecked work for blocks with no peer source before acquiring
cs_main. This keeps local block processing from waiting unnecessarily when
BlockChecked notifications are subsequently moved to the callback queue.
Recheck the source after acquiring both locks for peer-supplied blocks.

Acquire cs_main before the new mutex where chain state is also needed,
matching the modern PeerManager lock order. Preserve source ownership,
compact-block punishment exceptions, and callback ordering. Add a
regression that completes source cleanup while another thread holds
cs_main.
Deliver BlockChecked through the validation task runner, retaining the
block and validation state until delivery. Keep peer completions pending
until a queued marker has run so validation feedback precedes source
cleanup and message processing resumption.

Wait for queued results before unregistering mining catchers. Adapt the
network fuzz targets to a scoped scheduler and serial runner, with
explicit callback and completion draining between messages, so callbacks
can acquire cs_main without blocking the emitter under that lock.

Cover queued ownership, callback ordering, peer teardown, and the fuzz
runner's deferred delivery.

Cover no-source BlockChecked callbacks completing while cs_main is held,
using the fast path installed by the preceding block-source mutex change.
Move per-peer in-flight blocks and download/stalling timers out of
CNodeState, following PR bitcoin#16324. Protect them, mapBlocksInFlight, and the
downloading-peer count with the block bookkeeping mutex.

Serialize request registration and cleanup with peer removal, retaining
the Peer until its request entries are cleared. Keep cs_main for chain
dependent reads and preserve request selection, limits, and timeouts.

When new_block is true, skip the redundant optimistic validity recheck
and its chain-lock acquisition after request cleanup. Retain the recheck
for completions with new_block=false.

Add a regression that registers and completes requests for both full
blocks and optimistic reconstructions while another thread holds
cs_main. Freeze its node clock so the completion timestamp assertion
cannot race a wall-clock second boundary.
Skip taking the chain lock when a peer has no orphan transactions to
reconsider. Defer the remaining send work when cs_main is unavailable so
the shared message handler can service other peers.

Keep fee-filter calculation inside the successful chain-lock scope so
block validation cannot acquire the mempool lock before the calculation.
Require cs_main in the helper's lock annotation.

Add a regression covering PING/PONG output, punishment, and deferred
header requests while another thread holds cs_main.
Use the validated header already stored with the download request to
determine SegWit activation. This lets BLOCKTXN bookkeeping and
reconstruction proceed under m_block_mutex while another block is being
validated. Release the lock before the existing admission checks.

Add a regression covering unexpected responses and reconstruction
failures while another thread holds cs_main, including full-block
fallback.
Clear other peers' requests after successful initial admission of an
optimistically reconstructed compact block, following bitcoin#16324. Pending
processing still suppresses automatic downloads and pauses the source
until its completion and validation callbacks have been handled.

Remove the optimistic flag from pending completions and the remaining
completion-time validity recheck under cs_main. Cover admission with a
parked worker, queued duplicates, source disconnection, initial rejection,
and interrupted submission.

Validation: 41 unit tests passed in regular and ThreadSanitizer builds;
six compact-block, invalid-block and unrequested-block functional tests
passed.
@DrahtBot

DrahtBot commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

🐙 This pull request conflicts with the target branch and needs rebase.

@sedited

sedited commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

Concept ACK

I think it would be great to finally get this rolling. However, I'm not sure if this should be one big pull request. Reviewing the pure validation changes with the net processing changes at once seems a bit much. A good candidate for a first pull request seems to me changing AcceptBlock to write blocks without holding cs_main in the meantime.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants