Skip to content

validation: prefetch blocks while connecting - #36000

Open
l0rinc wants to merge 10 commits into
bitcoin:masterfrom
l0rinc:l0rinc/block-read-ahead
Open

l0rinc wants to merge 10 commits into
bitcoin:masterfrom
l0rinc:l0rinc/block-read-ahead

Conversation

@l0rinc

@l0rinc l0rinc commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Problem: Connecting a block already on disk requires reading and deserializing it.
Doing this on the validation thread stalls validation and slows reindexing and initial block download.

This is a follow-up to #35295, which parallelized input prevout fetching during block connection.

Fix: Add a Chainstate-owned block fetcher that reads later blocks from disk while the current block is connected.
Start with synchronous 1-block read-ahead, then move reads to an eagerly started worker pool that persists across activations.
Keep caller-provided blocks on the direct path and refill a sliding read-ahead window.
During reorgs, start reading the first sibling while disconnecting the old tip.
Retry speculative failures synchronously when the block is needed.

-blockfetchthreads=<n> selects readers per chainstate, with a default of 2 and a cap of 16.
Setting it to 0 disables read-ahead. The window retains up to two blocks per reader, giving 4 by default.
Measurements favor 2 readers with a window of 4 or 8 blocks, so the default uses the smaller window.

Credit: The idea comes from bitcoindev1337, who had already implemented a similar design and reported comparable results.

Benchmark results

---- reindex-chainstate ----

1d6656c6b0 refactor: prepare block fetcher wiring
3547915bfb doc: add block read-ahead release note

2026-09-02 | reindex-chainstate | 964469 blocks | dbcache 2000 | i7-hdd | x86_64 | Intel(R) Core(TM) i7-7700 CPU @ 3.60GHz | 8 threads | 62Gi RAM | HDD

Benchmark 1: COMPILER=gcc ./build/bin/bitcoind -datadir=/mnt/my_storage/BitcoinData -stopatheight=964469 -dbcache=2000 -reindex-chainstate -assumevalid=00000000000000000000ccebd6d74d9194d8dcdc1d177c478e094bfad51ba5ac -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = 1d6656c6b024578db910f45f4a131f18d75a2ed0)
  Time (abs ≡):        30017.350 s               [User: 44516.820 s, System: 1392.820 s]

Benchmark 2: COMPILER=gcc ./build/bin/bitcoind -datadir=/mnt/my_storage/BitcoinData -stopatheight=964469 -dbcache=2000 -reindex-chainstate -assumevalid=00000000000000000000ccebd6d74d9194d8dcdc1d177c478e094bfad51ba5ac -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = 3547915bfb240f280188954c7c5b60ec90145ac5)
  Time (abs ≡):        19609.006 s               [User: 46710.915 s, System: 1466.050 s]

Relative speed comparison
        1.53          COMPILER=gcc ./build/bin/bitcoind -datadir=/mnt/my_storage/BitcoinData -stopatheight=964469 -dbcache=2000 -reindex-chainstate -assumevalid=00000000000000000000ccebd6d74d9194d8dcdc1d177c478e094bfad51ba5ac -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = 1d6656c6b024578db910f45f4a131f18d75a2ed0)
        1.00          COMPILER=gcc ./build/bin/bitcoind -datadir=/mnt/my_storage/BitcoinData -stopatheight=964469 -dbcache=2000 -reindex-chainstate -assumevalid=00000000000000000000ccebd6d74d9194d8dcdc1d177c478e094bfad51ba5ac -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = 3547915bfb240f280188954c7c5b60ec90145ac5)
ed7dd7cf4e Merge bitcoin/bitcoin#34371: wallet: allow importprunedfunds for spending transactions
c5aafe2557 doc: add block read-ahead release note

2026-09-29 | reindex-chainstate | 968869 blocks | dbcache 2000 | ssd-ryzen | x86_64 | AMD Ryzen 7 3700X 8-Core Processor | 16 threads | 62Gi RAM | SSD

Benchmark 1: COMPILER=gcc ./build/bin/bitcoind -datadir=/mnt/my_storage/BitcoinData -stopatheight=968869 -dbcache=2000 -reindex-chainstate -assumevalid=00000000000000000000ccebd6d74d9194d8dcdc1d177c478e094bfad51ba5ac -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = ed7dd7cf4e1561a97edf72eba29a67b14e28c717)
  Time (abs ≡):        12430.900 s               [User: 36689.125 s, System: 2521.533 s]

Benchmark 2: COMPILER=gcc ./build/bin/bitcoind -datadir=/mnt/my_storage/BitcoinData -stopatheight=968869 -dbcache=2000 -reindex-chainstate -assumevalid=00000000000000000000ccebd6d74d9194d8dcdc1d177c478e094bfad51ba5ac -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = c5aafe25576d341451d679816ae0d1f8c8405c7e)
  Time (abs ≡):        9562.801 s               [User: 37275.991 s, System: 2185.462 s]

Relative speed comparison
        1.30          COMPILER=gcc ./build/bin/bitcoind -datadir=/mnt/my_storage/BitcoinData -stopatheight=968869 -dbcache=2000 -reindex-chainstate -assumevalid=00000000000000000000ccebd6d74d9194d8dcdc1d177c478e094bfad51ba5ac -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = ed7dd7cf4e1561a97edf72eba29a67b14e28c717)
        1.00          COMPILER=gcc ./build/bin/bitcoind -datadir=/mnt/my_storage/BitcoinData -stopatheight=968869 -dbcache=2000 -reindex-chainstate -assumevalid=00000000000000000000ccebd6d74d9194d8dcdc1d177c478e094bfad51ba5ac -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = c5aafe25576d341451d679816ae0d1f8c8405c7e)

---- IBD ----

ed7dd7cf4e Merge bitcoin/bitcoin#34371: wallet: allow importprunedfunds for spending transactions
7c4efd1174 doc: add block read-ahead release note

2026-09-29 | IBD | 968869 blocks | dbcache 4000 | ssd-ryzen | x86_64 | AMD Ryzen 7 3700X 8-Core Processor | 16 threads | 62Gi RAM | ext4 | SSD

Benchmark 1: COMPILER=gcc ./build/bin/bitcoind -datadir=/mnt/my_storage/BitcoinData -stopatheight=968869 -dbcache=4000 -blocksonly  -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -printtoconsole=0 (COMMIT = ed7dd7cf4e1561a97edf72eba29a67b14e28c717)
  Time (mean ± σ):     19273.259 s ± 504.339 s    [User: 25801.170 s, System: 3635.246 s]                                                                                                                          
  Range (min … max):   18916.638 s … 19629.881 s    2 runs                                               
                                                    
Benchmark 2: COMPILER=gcc ./build/bin/bitcoind -datadir=/mnt/my_storage/BitcoinData -stopatheight=968869 -dbcache=4000 -blocksonly  -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -printtoconsole=0 (COMMIT = 7c4efd1174070eba967fb0803c2080500b77ee10)
  Time (mean ± σ):     16766.243 s ± 323.458 s    [User: 25575.079 s, System: 2691.147 s]                                                                                                                          
  Range (min … max):   16537.523 s … 16994.962 s    2 runs                                               
                                                    
Relative speed comparison                           
        1.15 ±  0.04  COMPILER=gcc ./build/bin/bitcoind -datadir=/mnt/my_storage/BitcoinData -stopatheight=968869 -dbcache=4000 -blocksonly  -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -printtoconsole=0 (COMMIT = ed7dd7cf4e1561a97edf72eba29a67b14e28c717)
        1.00          COMPILER=gcc ./build/bin/bitcoind -datadir=/mnt/my_storage/BitcoinData -stopatheight=968869 -dbcache=4000 -blocksonly  -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -printtoconsole=0 (COMMIT = 7c4efd1174070eba967fb0803c2080500b77ee10)

@DrahtBot

DrahtBot commented Aug 17, 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
ACK arejula27, w0xlt, andrewtoth

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:

  • #36946 (scripted-diff: [test] Add util/check.h includes for assertions by maflcko)
  • #36861 (Configuration argument handling improvements. by jlopp)
  • #36603 (Improve loadtxoutset performance by ajtowns)
  • #36548 (net: serve MSG_BLOCK by stripping witnesses in place by l0rinc)
  • #36066 (validation: Separate check-only version of ConnectBlock by optout21)
  • #35731 (Indexes: Harden the flush-error notification invariant by arejula27)
  • #35071 (Reindex: save progress to continue after interruption by pinheadmz)
  • #35003 (validation: improve block data I/O error handling in P2P paths by furszy)

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.

@fanquake

Copy link
Copy Markdown
Member

Note that this spams blockread.* thread start/exit debug logs to the point that rate-limiting kicks:

2026-08-18T10:20:43Z blockread.02 thread exit
2026-08-18T10:20:43Z blockread.03 thread exit
2026-08-18T10:20:43Z blockread.01 thread exit
[*] 2026-08-18T10:20:43Z [warning] Excessive logging detected from ./util/thread.cpp:19 (TraceThread): >1048576 bytes logged during the last time window of 3600s. Suppressing logging to disk from this source location until time window resets. Console logging unaffected. Last log entry.
[*] 2026-08-18T10:20:43Z blockread.00 thread start
[*] 2026-08-18T10:20:43Z UpdateTip: new best=00000000000002376bd10d0e9734df8894b2628dce1aacb9f86169dfd890eb0f height=198324 version=0x00000001 log2_work=68.682795 tx=6990764 date='2012-09-11T15:33:52Z' progress=0.005005 cache=336.1MiB(2535259txo)

Comment thread src/validation.cpp Resolved

@andrewtoth andrewtoth left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Concept ACK.

The benchmarks look promising. I am still trying to reproduce the benchmarks locally, but my usual IBD from a single local peer does not produce any speedup. This makes sense because all blocks will be downloaded in-order from the single peer, so the next block to connect will always be the one in memory.

I am trying to simulate out-of-order IBD by having my local node bind to 10 different ports and then -connect=ing to each of the ports. I am still working on getting consistent results with this, but will report back when I get this working properly.

A reindex-chainstate should show the highest theoretical speedup, since every block will be read ahead in-order.

This will also not show any improvement for connecting new blocks to tip at steady-state, since the new block will always be the one in memory. However, I think we can modify this to improve reorgs at steady-state. We can prefetch the blocks on the new fork that will be connected, while we read the blocks to disconnect.

Comment thread src/validation.cpp Resolved
Comment thread src/validation.cpp Resolved
Comment thread src/validation.cpp Resolved
@andrewtoth

Copy link
Copy Markdown
Contributor

While I figure out how to do out-of-order IBD, I can share reindex-chainstate benchmarks I did on my laptop. I tried variants with 2 threads and queue depth of 4, as well as the sliding-window change with queue depth of 2 and 4. The results are very impressive! The sliding-window with 2 depth had the best time.

Done on an i9-14900HX, default dbcache, stopatheight=961000.

Reindex Time Speedup
master 2h 33m 27s 1.00x
PR 1h 56m 19s 1.32x
sliding-window 1 thread, queue of 4 1h 52m 19s 1.37x
PR 2 threads, queue of 4 1h 51m 58s 1.37x
sliding-window 1 thread, queue of 2 1h 50m 44s 1.39x

@l0rinc
l0rinc force-pushed the l0rinc/block-read-ahead branch from d8b14e9 to b5e4845 Compare August 26, 2026 19:08

@l0rinc l0rinc left a comment •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for the review! I took all your suggestions (rebased separately to keep the diff focused).

The provided block is already decoded and selected by ActivateBestChain(), so it now stays on that path instead of being stored in BlockFetcher. This simplified the fetcher state: it only owns followups now, while read_ahead_tip stops at the provided block's parent to avoid rereading it. Accordingly, m_pending/PopPending() became m_followups/PopFollowup(), Prefetch() became FillQueue(), and the new argument is provided_block.

Also switched to a sliding 1-worker/depth-2 queue, added sibling prefetch during reorg disconnection, fixed the final followup being skipped when no block is provided, and removed futures before calling get().
feature_reindex.py now checks exact cache-hit counts, worker reuse, submitblock results, and reorg read-ahead.

I'll experiment further with different threads and queue sizes and whether we can call the context-free checks here.

Comment thread src/validation.cpp Resolved
Comment thread src/validation.cpp Resolved
Comment thread src/validation.cpp Resolved
Comment thread src/validation.cpp Resolved
@l0rinc
l0rinc force-pushed the l0rinc/block-read-ahead branch 2 times, most recently from 200ce58 to 398859b Compare August 28, 2026 18:06
@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task test ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/33196171834/job/98933744258
LLM reason (✨ experimental): CI failed because ctest hit a runtime symbol lookup error in test_kernel (libbitcoinkernel.so undefined symbol: node::BlockFetcher::FillQueue(...)).

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • An intermittent issue.

Leave a comment here, if you need help tracking down a confusing failure.

@andrewtoth andrewtoth left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Still working on out-of-order IBD benchmarks, but this is looking good.
Left some minor suggestions.

Comment thread doc/release-notes-36000.md Resolved
Comment thread src/node/blockfetcher.cpp Resolved
Comment thread src/node/blockfetcher.cpp Resolved
Comment thread src/node/blockfetcher.h Resolved
Comment thread src/node/blockfetcher.cpp Resolved
@l0rinc
l0rinc force-pushed the l0rinc/block-read-ahead branch from aaf3283 to 3547915 Compare September 1, 2026 21:51

@l0rinc l0rinc left a comment •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks, addressed most of your concerns, rebased and updated the defaults to 2 workers and queue size of 4 (current SSD and especially HDD measurements indicate that to be the optimum).

Comment thread doc/release-notes-36000.md Resolved
Comment thread src/validation.cpp Resolved

@andrewtoth andrewtoth left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ACK 81006fa

Comment thread src/node/blockfetcher.cpp
return std::shared_ptr<CBlock>{};
});
}
if (auto followups{m_pool.Submit(std::move(tasks))}) std::ranges::move(*followups, std::back_inserter(m_followups));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I ran this again twice, and it seems the slowdown was an anomaly. I got 1h 42m and 1h 44m, both faster than pushing single tasks.

Comment thread src/node/blockfetcher.h Outdated

//! Discard unneeded read-ahead results without cancelling submitted reads
void Clear() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
//! Supply a prefetched block for connection, or nullptr to fall back to synchronous reading

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I don't think we need to mention connection or falling back to synchronous reading here. These things seem unrelated to this class on its own.

Suggested change
//! Supply a prefetched block for connection, or nullptr to fall back to synchronous reading
//! Returns the block with the specified hash if it had been previously queued, otherwise nullptr.

Comment thread src/node/blockfetcher.h Outdated
void Clear() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
//! Supply a prefetched block for connection, or nullptr to fall back to synchronous reading
std::shared_ptr<const CBlock> Load(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
//! Queue upcoming blocks so disk reads overlap block connection

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Same here, the block connection is an external use case for this class.

Suggested change
//! Queue upcoming blocks so disk reads overlap block connection
//! Queue upcoming blocks to be read and deserialized asynchronously.

l0rinc and others added 10 commits November 18, 2026 19:49
Record cache use during reindexing, reconnection and a competing fork before introducing read-ahead.
Separate disk reads from block connection to prepare for overlapping I/O and validation.
The reader callback avoids a dependency cycle with block storage and validation.
Keep caller-provided blocks on the direct path and stop read-ahead at their parent to avoid reading them twice.
Discard results after invalid blocks or when the read-ahead range ends.
Speculative read failures fall back to the existing synchronous path.
Include loading time in the existing BENCH measurements.

Co-authored-by: Andrew Toth <[email protected]>
Use a worker pool with one retained read and one worker by default so disk I/O can overlap block connection.
`Chainstate` owns the fetcher and reuses the worker across activation calls.
Limit each chainstate to 16 readers, including callers that set kernel options directly.
Keep deterministic fuzz fixtures at zero workers so AFL can fork without inherited thread handles.

Co-authored-by: bitcoindev1337
Co-authored-by: Andrew Toth <[email protected]>
Queue the first sibling before disconnecting the old tip so its disk read can overlap `DisconnectTip()`.
Discard the previous candidate's results so the new branch can be queued immediately.

Co-authored-by: Andrew Toth <[email protected]>
A single followup can leave the reader idle between block connections.
Keep a sliding window of two retained reads per thread, with two threads by default.
Measurements favor a window of four or eight reads, so use the smaller window.
Submit the missing reads together so the pool takes its queue lock once and notifies all workers.

Co-authored-by: Andrew Toth <[email protected]>
Expose `-blockfetchthreads=<n>` so systems with limited memory can reduce or disable read-ahead.
The read-ahead window retains up to two blocks per reader, and zero disables read-ahead.
Clamp higher values to the existing limit of 16 readers per chainstate, limiting the window to 32 blocks.

Co-authored-by: Andrew Toth <[email protected]>
Avoid taking the worker-pool lock when there are no block reads to submit.
Describe the queue operations in terms of the fetcher API.

Suggested in bitcoin#36000 (comment)
bitcoin#36000 (comment)
> Why do we repeat this line here?

Reply: I added a check that invalidating block 1 leaves only genesis.
The final height check verifies that reconsidering block 1 restores the
chain after that rollback.
@l0rinc
l0rinc force-pushed the l0rinc/block-read-ahead branch from 81006fa to d62c4b5 Compare November 18, 2026 19:28
@arejula27

Copy link
Copy Markdown
Contributor

ACK d62c4b5

I did not run benchmarks, the existing ones in the PR look sufficient

@DrahtBot
DrahtBot requested review from andrewtoth and w0xlt November 19, 2026 17:34

@w0xlt w0xlt left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

reACK d62c4b5

@andrewtoth

Copy link
Copy Markdown
Contributor

reACK d62c4b5

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.

6 participants