mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 12:20:38 +00:00
validation: prefetch blocks while connecting #36000
No reviewers
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!36000
Loading…
Reference in a new issue
No description provided.
Delete branch "l0rinc/block-read-ahead"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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 ----
---- IBD ----
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.
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:
MSG_BLOCKby stripping witnesses in place by l0rinc)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.
Note that this spams
blockread.* thread start/exitdebug logs to the point that rate-limiting kicks:This is creating a new ThreadPool on each invocation of
ActivateBestChain. This is what's causing the logs in https://github.com/bitcoin/bitcoin/pull/36000#issuecomment-5326868873. TheBlockFetcheror at least a shared pointer to aThreadPoolthat can be passed to it should be owned by theChainstate, so it can keep the fetcher threads alive throughout IBD.This works fine for
-reindex-chainstate, because it is one longActivateBestChaincall. But for IBD this gets called many times.Yes, thanks @fanquake and @andrewtoth, I also just noticed that
BlockFetcherwas indeed recreated on everyActivateBestChain()call: I’ve pushed a fix that keeps it alive onChainstate, and will remeasure IBD performance. Added you both as coauthors, thanks for the tests!I’ve also reduced the default queue size from 4 to 2, since the results so far indicate that 4 isn’t worthwhile and single threaded for now for simplicity - proper HDD measurements may change this again later:

Also removed configurability to make the patch even simpler - we can add it back later if needed.
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.
Should we just pass in height here, and internally start at
height + 1? We are adding the+ 1to callsites, so this would probably be cleaner to handle it in here instead.We can make this useful for reorgs here by checking if the
pindexForkis not our current tip, then clearing the prefetch queue and start fetching from the fork index. We would then be fetching the sibling while we read the current tip synchronously inDisconnectTip.I think this method might be more efficient as a sliding window rather than just adding all pending tasks only when the validation thread has emptied the queue. The current way has the worker thread go idle once it hits the max queue size and waits until validation catches up, whereas we can make sure the worker thread is always either working or bumping up against the max queue size.
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.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 inBlockFetcher. This simplified the fetcher state: it only owns followups now, whileread_ahead_tipstops at the provided block's parent to avoid rereading it. Accordingly,m_pending/PopPending()becamem_followups/PopFollowup(),Prefetch()becameFillQueue(), and the new argument isprovided_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.pynow checks exact cache-hit counts, worker reuse,submitblockresults, and reorg read-ahead.I'll experiment further with different threads and queue sizes and whether we can call the context-free checks here.
I think
next_heightis clearer here because the argument is the first height to enqueue: there's no "current" height here, it doesn't make sense to give an unrelated block height to the fetcher.But the names should be consolidated (pending vs queued vs followups vs provided vs saved), I kept renaming these and they don't match anymore.
Thanks, implemented.
FillQueue()(renamed) now starts from the number of queued followups and fills every missing slot.I originally waited for the queue to empty so adjacent reads would be submitted together (from the same file probably), which I thought might improve file-cache locality, but your measurements indicate that's not the case, so I'll remeasure. Instead of the while loop above (which might be infinite if
m_pendingdoesn't get updated in the loop) I used a bounded loop.Thanks, implemented. Before disconnecting the current tip, activation now clears followups for the previous candidate and fills the queue from the first sibling. This overlaps that read with
DisconnectTip().What if we moved this out into a header in
src/node/blockfetcher.h, and allowed passing the thread name in the constructor? Then with a simple commit on top (and shortening index thread names)Index patch
we could have parallelism for all indexes. With this patch I measured speedups of 30% for txindex, 50% for blockfilterindex, and 6% for coinstatsindex. We could improve the latter two even more with an optional prefetch of the undo data as a follow-up.
cc @furszy what do you think of this approach to parallelizing the indexing code? It would stack easily with https://github.com/bitcoin/bitcoin/pull/34489 for txospenderindex and txindex; it should be as simple as increasing the threadcount and queue depth of the blockfetcher (since each append would no longer be writing so the bottleneck would just be reading/deserializing blocks).
🚧 At least one of the CI tasks failed.
Task
test ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/33196171834/job/98933744258LLM reason (✨ experimental): CI failed because
ctesthit a runtime symbol lookup error intest_kernel(libbitcoinkernel.soundefined 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.
Thanks, I like this approach. I moved
BlockFetcherintosrc/node/blockfetcher.{h,cpp}in this push and added you as a co-author - although I initially forgot to add it to the Kernel build, andReadBlockintroduced a circular dependency.Since the extraction is useful independently of the index follow-up and makes the diff simpler, I also wired it into
BaseIndex::Sync()locally to make sure the interface works.Your results make index prefetching worth doing, but I left the index wiring and configurable thread name out so we can finish the validation path in this PR first.
One detail for the follow-up is thread naming:
ThreadPooladds a.xxsuffix, so the currentblkfltbscidx,coinstatsidx, andtxospenderidxnames would exceed the limit accepted byThreadRename()before it addsb-.Since we just shortened these names in this release, maybe we should leave room for the worker suffix now, even if index prefetching remains a follow-up, to avoid renaming the threads again later (assuming each index will get their own
ThreadPool, which would kind of defeat the purpose of handling shared resources).And about the index parallelization work: this change is independent of batching index writes or parallelizing
MuHash, so @furszy's ideas can still make sense on top.Before batching or adding more index concurrency, I think we should fix the concrete
Stop()/Init()reader issue and account for pre-genesis sync and flush callbacks, stale-tip rewind after a disconnect, and blockfilter/coinstats crash-reorg recovery (I found several of these issues by repeatedly crashing during sync, and while some paths are theoretical and can wait, we should account for these states first).There is also a separate follow-up for context-free validation: the prefetched block is owned by the worker until its future is consumed, so
CheckBlock()can safely populate its memoization flags there, and I left a TODO at that point.So I agree index block prefetching should be a follow-up, but before batching or parallelizing the indexes, I'd like to harden them to be more crash-safe.
Still working on out-of-order IBD benchmarks, but this is looking good.
Left some minor suggestions.
Does this warrant a release note? It is covered already by "performance improvements" in every release note.
nit: we can remove the dates altogether. same for header file.
Not sure we should have this TODO here. I don't know if there is consensus for this yet. Changing the validation ordering is a different beast than just parallelizing reading a block from disk and deserializing.
We should call
Clearhere, since on a miss we have gotten out of sync of the fetching.Could we pass these as default parameters to the constructor, and call
ThreadPool::Starton construction? That way we can inject different values.Why do we wait to start the threadpool later? IMO it's cleaner/more RAII to start in constructor.
I don't think there's a circular dependency. We don't need the
ReadBlockFn(so we also don't needBlockFetcherto be wrapped in astd::unique_ptr):Patch
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).
I expect this to land in a future release, so for now I'd keep it
The full patch still introduces the exact cycle: node/blockfetcher -> node/blockstorage -> validation -> node/blockfetcher, can you please check it with lint-circular-dependencies.py?
Took about a week, but the measurements are in and 2 threads and a queue of 4 blocks (already the current values of the PR) seem to be the sweet spot:
If we add context-independent
CheckBlockcalls in a followup (to do partial validation before returning the blocks), the optimum shifts slightly to 4 threads and queue length of 8.Since we have multiple worker threads now, maybe we can take advantage of the multi-
Submitoverload whenever we have an emptym_followups? That would awaken all threads at once. This would happen on everyActivateBestChainStepcall, so could show some improvement?Also, if we have multiple threads and queue depth, we might want to allow disabling this mechanism for low memory systems. Maybe worth it to just be an on/off toggle (that defaults to on)? Or maybe a configuration of threads only and the queue depth is 2*threads? Just trying to think of ways to make it simple instead of adding all kinds of configuration options.
Ahh I did not use the linter, I just compiled. Indeed, my patch fails lint. Thanks!
ACK
3547915bfbManaged to see speedup in IBD benchmarks by having one local node bind to 10 ports and the other connect to all 10. I did this and reindex-chainstate with an i7 and i5 machine. Nice speedups, especially for reindex-chainstate. This will also be good for the typical single block reorg during tip, and we can use it almost verbatim for speeding up our optional index syncing in a follow-up.
The release notes are stale. There are now multiple threads.
This comment is not very helpful IMO. Why would anyone care about destruction waiting on queued reads? Something like this would be better.
This comment is a bit cryptic.
When a block was rejected, blocks read ahead for its branch could remain in memory indefinitely.
🐙 This pull request conflicts with the target branch and needs rebase.
Thanks for the reviews, rebased because of a conflict and addressed the documentation and queue cleanup comments: the fetcher and provided-block comments are clearer, the release note says “threads,” and an invalid block clears prefetched descendants.
BENCHtimings now include waits for prefetched blocks. I also clear the queue after connecting a caller-provided tip and disable reader threads in deterministic fuzz fixtures.@l0rinc just wondering if you had any thoughts on these suggestions?
I started investigating your suggestions, then got pulled into a few issues for this release and forgot to follow up here. I prototyped batching when the queue is empty, but the extra task-building code was hard to justify without a measured speedup - I can measure them later. But I did add
-blockreadahead=<n>with a default of 2 readers and a queue capacity of2*nblocks. Setting it to0disables read-ahead. Thanks for the reminder.Pushed a few versions again, since
3547915,BENCHblock-load timing includes waits for prefetched blocks, stale queued reads are cleared after invalid blocks and caller-provided tips, and-blockreadahead=<n>controls the readers and queue capacity (2*n, with0disabling read-ahead). I also restored helper and loop code changed in intermediate pushes, so this range-diff shows the net changes:Code review
7c4efd1174I measured reindex-chainstate again with this latest commit and it's a blistering 1h 48m.
Left a few suggestions on the latest revision.
Should we also add this to the reduce memory usage docs?
We should bound this to a max value, no?
Instead of passing a
time_point, could we passconst CBlockIndex* read_ahead_tip? Then we could doinside
ConnectTipinstead, and not have to adjust any of the timing variables?I don't see the purpose of this line. Seems like it will always be a no-op. I think it should be removed.
Earlier concerns remain unresolved; see the Run archive linked from the Review report.
🔴 Major ·
ChainManreleases its context before joining block readersChainManteardown can free chain parameters before outstanding kernel block readers finish when it owns the lastContextreference; no current in-tree caller using this release order was found.Location:
src/validation.cpp:1862(head).🟠 Minor · Reader-startup assertions race with thread scheduling
An unusually delayed second reader can fail
feature_reindex.py's zero-timeout startup-log assertion on a correct node; no such failure has been observed.Location:
test/functional/feature_reindex.py:49(head).🔵 Suggestion ·
ReadBlockFnleaves its worker lock contract undocumentedThe current callback is safe, but
ReadBlockFndoes not state that concurrent callbacks must avoidcs_main, whichLoad()holds while waiting for them.Location:
src/node/blockfetcher.h:28(head).🔵 Suggestion · Cache-hit tests do not distinguish the sliding-window depth
A one-block read-ahead implementation would satisfy the existing cache-hit counts, leaving the four-result window and consume-one/refill-one behavior unprotected.
Location:
src/node/blockfetcher.cpp:58(head).🔵 Suggestion ·
BlockFetcherlifecycle tests never hold a read in progressThe existing fetcher unit test consumes both reads, leaving nonblocking
Clear()and callback lifetime during destruction unchecked.Location:
src/node/blockfetcher.cpp:35(head).🔵 Suggestion · Empty-batch handling is split across two commits
The batching commit changes shared
ThreadPool::Submit()behavior for empty batches, but a later fetcher guard removes its production use, obscuring which changes the feature actually needs.Location: src/node/blockfetcher.cpp:68 (commit).
Review coverage was incomplete.
Reviewed:
d62c4b54799a· Review report · Previous reportspermalink
Added retry coverage and stronger reconnection checks, batched read-ahead submissions, unified thread naming with a 16-reader cap and a
2*nqueue, and moved loading intoConnectTipto preserve the existingBENCHtimers.It was already there, but I updated it in the latest push to cover the cap and queue capacity.
I played with it a bit more and massaged it until I found a setup I liked.
I forgot that we already have a batch overload that avoids locking and notifying for each entry - missing reads now use it, including refills of a partly drained queue.
Let me know what you think, I’ll come back with the benchmarks tomorrow.
I know we usually do that. I didn’t see the need here, but I don’t mind. Pushed a cap of 16 readers per chainstate.
Thanks, this minimizes the diff, I like the outcome. Loading and refilling now happen inside
ConnectTip, keeping the existing timing variables.FillQueuehandles the guard internally, so its callers don't need one.I'm not sure whether it wasn't needed before, but
FillQueuenow handles cleanup when the read-ahead range ends, so it isn't needed anymore.Well without this guard the application could spawn millions of threads if misconfigured?
Sure, but we don't usually guard against user error like
-dbcache=-1or similar - and I did apply it, I was just hesitant because of the reasons above.Now that the code for multi-submit isn't more complicated than single-submit (which was the case in my original attempt), the 1% speedup is probably worth it (I should update the assumevalid in my benchmarks).
master vs single-submit vs multi-submit
nit:
feature_proxy.pydisables prevout fetching with-prevoutfetchthreads=0(added inf82043af50) to avoid starting a thread pool for each of its 7 nodes. With this PR,util.pysetsblockreadahead=1for every node, so each node now starts a reader thread that this test never uses. It runs on a clean chain and connects only the genesis block.Suggestion:
nit:
Assert()aborts here instead of throwing, so if the retry path regresses, test_bitcoin dies with no Boost report and the remainingblockmanager_testscases don't run. This file already usesBOOST_REQUIRE(block)for this at lines 169 and 197:suggestion:
Bikeshed:
-blockreadahead=<n>reads like a block count, but it sets the number of reader threads, and the window is2*n blocks. For example, someone setting-blockreadahead=4to limit memory to 4 blocks would actually keep 8. Since options are hard to rename after a release, would-blockreadaheadthreadsbe clearer, matching-prevoutfetchthreads?Thanks, the leftover
blockreadaheadname was indeed confusing. I renamed it to be consistent with the prevout fetcher and added it to the memory savings options in the mentioned test.I consider the loaded block a precondition for the hash comparison, so I used
Assert()deliberately to keep it a simple one-liner.🐙 This pull request conflicts with the target branch and needs rebase.
ACK
495d50ae0cI also find this comment cryptic. I'm not sure it's useful.
I ran a reindex-chainstate with the latest code here, and it was 14 minutes slower at 2h 02m. Maybe it is worth reverting to single task submission, which would make this a bit simpler?
Maybe something like this is more clear:
nit: this can now be
util::NotNullUniquePtr<node::BlockFetcher>.I'm not sure what this comment is here for? I think it should be removed.
Why do we repeat this line here? Seems like a redundant assertion that can be removed?
Not sure why we assert this here either? This isn't what's under test here. I think we can remove this line and
blockcount = node.getblockcount()above.Thanks @andrewtoth, applied most of your suggestions.
I over-compressed the comment, and I meant to explain why it's okay to swallow the exception.
I kept the rationale but clarified it:
ConnectTip()retries failed async read-ahead synchronously.My comparison favored the bulk version slightly. I'll run a few more tests a bit later and see if we need to revert this.
Thanks, clarified that clearing results doesn't cancel submitted reads and documented Load() and FillQueue().
Indeed, rebased & switched.
Removed
This checks restoration after invalidate/reconsider, which the earlier assertion doesn't cover.
We could also assert height 0 immediately after invalidation to make that transition explicit.
Thanks, removed the height assertion and its saved value
Concept ACK
I was curious whether this could open a window for race conditions, so I checked the following cases and didn't find any:
BLOCK_HAVE_DATAare queued, and that flag is set afterWriteBlock()closes the file, so a block that is still being written is never prefetched.nit: when tasks is empty, could we return early here?
I tested again against submitting each block read separately to compare single-task scheduling with bulk submission and it still shows a 1% speedup for me while the code isn't any more complicated so I think we should keep it now.
temp: use single-task block read-ahead submission
2026-10-14 | reindex-chainstate | 968869 blocks | dbcache 3000 | ssd-ryzen | x86_64 | AMD Ryzen 7 3700X 8-Core Processor | 16 threads | 62Gi RAM | SSD
Edit: I also checked general speedup, it's still blazing fast for reindexes, 50-60% faster:
2026-10-13 | reindex-chainstate | 968869 blocks | dbcache 1000/3000 | i9-ssd | x86_64 | Intel(R) Core(TM) i9-9900K CPU @ 3.60GHz | 16 threads | 62Gi RAM | SSD
2026-10-13 | reindex-chainstate | 968869 blocks | dbcache 1000/3000 | i7-hdd | x86_64 | Intel(R) Core(TM) i7-7700 CPU @ 3.60GHz | 8 threads | 62Gi RAM | HDD
ACK
81006fa18cI 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.
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.
Same here, the block connection is an external use case for this class.
ACK
d62c4b5479I did not run benchmarks, the existing ones in the PR look sufficient
reACK
d62c4b5479reACK
d62c4b5479