validation: prefetch blocks while connecting #36000

Open
l0rinc wants to merge 10 commits from l0rinc/block-read-ahead into master AGit
l0rinc commented 2026-08-17 22:31:46 +00:00 (Migrated from github.com)

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)
**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](https://github.com/bitcoin/bitcoin/pull/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](https://bitcoin-irc.chaincode.com/bitcoin-core-dev/2026-08-11#1245429), who had already implemented a similar design and reported comparable results. <details><summary>Benchmark results</summary> ---- reindex-chainstate ---- ```python 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) ``` ```python 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 ---- ```python 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) ``` </details>
DrahtBot commented 2026-08-17 22:31:54 +00:00 (Migrated from github.com)

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.

<!--e57a25ab6845829454e8d69fc972939a--> The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. <!--006a51241073e994b41acfe9ec718e94--> ### External sites * Code coverage & benchmarks: https://corecheck.dev/bitcoin/bitcoin/pulls/36000 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/36000.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/36000#author-ralph <!--021abf342d371248e50ceaed478a90ca--> ### Reviews See [the guideline](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#code-review) and [AI policy](https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md) for information on the review process. | Type | Reviewers | | ---- | --------- | | ACK | [arejula27](https://github.com/bitcoin/bitcoin/pull/36000#issuecomment-7016909410), [w0xlt](https://github.com/bitcoin/bitcoin/pull/36000#pullrequestreview-5981320800), [andrewtoth](https://github.com/bitcoin/bitcoin/pull/36000#issuecomment-7044477336) | If your review is incorrectly listed, please copy-paste <code>&lt;!--meta-tag:bot-skip--&gt;</code> into the comment that the bot should ignore. <!--174a7506f384e20aa4161008e828411d--> ### Conflicts Reviewers, this pull request conflicts with the following ones: * [#36946](https://github.com/bitcoin/bitcoin/pull/36946) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36946.svg"></sub> (scripted-diff: [test] Add util/check.h includes for assertions by maflcko) * [#36861](https://github.com/bitcoin/bitcoin/pull/36861) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36861.svg"></sub> (Configuration argument handling improvements. by jlopp) * [#36603](https://github.com/bitcoin/bitcoin/pull/36603) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36603.svg"></sub> (Improve loadtxoutset performance by ajtowns) * [#36548](https://github.com/bitcoin/bitcoin/pull/36548) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36548.svg"></sub> (net: serve `MSG_BLOCK` by stripping witnesses in place by l0rinc) * [#36066](https://github.com/bitcoin/bitcoin/pull/36066) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36066.svg"></sub> (validation: Separate check-only version of ConnectBlock by optout21) * [#35731](https://github.com/bitcoin/bitcoin/pull/35731) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35731.svg"></sub> (Indexes: Harden the flush-error notification invariant by arejula27) * [#35071](https://github.com/bitcoin/bitcoin/pull/35071) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35071.svg"></sub> (Reindex: save progress to continue after interruption by pinheadmz) * [#35003](https://github.com/bitcoin/bitcoin/pull/35003) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35003.svg"></sub> (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. <!--5faf32d7da4f0f540f40219e4f7537a3-->
fanquake commented 2026-08-18 10:24:12 +00:00 (Migrated from github.com)

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)
Note that this spams ` blockread.* thread start/exit` debug logs to the point that rate-limiting kicks: ```bash 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) ```
andrewtoth (Migrated from github.com) reviewed 2026-08-18 18:18:44 +00:00
andrewtoth (Migrated from github.com) commented 2026-08-18 18:18:44 +00:00

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. The BlockFetcher or at least a shared pointer to a ThreadPool that can be passed to it should be owned by the Chainstate, so it can keep the fetcher threads alive throughout IBD.

This works fine for -reindex-chainstate, because it is one long ActivateBestChain call. But for IBD this gets called many times.

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. The `BlockFetcher` or at least a shared pointer to a `ThreadPool` that can be passed to it should be owned by the `Chainstate`, so it can keep the fetcher threads alive throughout IBD. This works fine for `-reindex-chainstate`, because it is one long `ActivateBestChain` call. But for IBD this gets called many times.
l0rinc (Migrated from github.com) reviewed 2026-08-18 18:38:31 +00:00
l0rinc (Migrated from github.com) commented 2026-08-18 18:38:31 +00:00

Yes, thanks @fanquake and @andrewtoth, I also just noticed that BlockFetcher was indeed recreated on every ActivateBestChain() call: I’ve pushed a fix that keeps it alive on Chainstate, 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:
image

Also removed configurability to make the patch even simpler - we can add it back later if needed.

Yes, thanks @fanquake and @andrewtoth, I also just noticed that `BlockFetcher` was indeed recreated on every `ActivateBestChain()` call: I’ve pushed a fix that keeps it alive on `Chainstate`, 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: <img width="235" height="201" alt="image" src="https://github.com/user-attachments/assets/3225e3ad-a924-46bb-89b4-6124cb4862b9" /> Also removed configurability to make the patch even simpler - we can add it back later if needed.
andrewtoth (Migrated from github.com) reviewed 2026-08-23 14:38:25 +00:00
andrewtoth (Migrated from github.com) left a comment

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.

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.
andrewtoth (Migrated from github.com) commented 2026-08-23 14:30:54 +00:00

Should we just pass in height here, and internally start at height + 1? We are adding the + 1 to callsites, so this would probably be cleaner to handle it in here instead.

    void Prefetch(const CBlockIndex& index_most_work, int height) EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
Should we just pass in height here, and internally start at `height + 1`? We are adding the `+ 1` to callsites, so this would probably be cleaner to handle it in here instead. ```suggestion void Prefetch(const CBlockIndex& index_most_work, int height) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) ```
andrewtoth (Migrated from github.com) commented 2026-08-23 14:29:23 +00:00

We can make this useful for reorgs here by checking if the pindexFork is 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 in DisconnectTip.

We can make this useful for reorgs here by checking if the `pindexFork` is 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 in `DisconnectTip`.
andrewtoth (Migrated from github.com) reviewed 2026-08-24 18:41:49 +00:00
andrewtoth (Migrated from github.com) commented 2026-08-24 18:41:49 +00:00

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 (m_pending.size() < QUEUE_SIZE) {
            auto* next{index_most_work.GetAncestor(next_height + static_cast<int>(m_pending.size()))};
            if (!next || !Enqueue(*next)) break;
        }
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. ```suggestion while (m_pending.size() < QUEUE_SIZE) { auto* next{index_most_work.GetAncestor(next_height + static_cast<int>(m_pending.size()))}; if (!next || !Enqueue(*next)) break; } ```
andrewtoth commented 2026-08-25 16:30:58 +00:00 (Migrated from github.com)

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
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 (Migrated from github.com) reviewed 2026-08-26 19:39:33 +00:00
l0rinc (Migrated from github.com) left a comment

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.

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](https://github.com/l0rinc/bitcoin/pull/287/commits) with different threads and queue sizes and whether we can call the context-free checks here.
l0rinc (Migrated from github.com) commented 2026-08-25 04:57:22 +00:00

I think next_height is 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.

I think `next_height` is 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.
l0rinc (Migrated from github.com) commented 2026-08-25 04:43:12 +00:00

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_pending doesn't get updated in the loop) I used a bounded loop.

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_pending` doesn't get updated in the loop) I used a bounded loop.
l0rinc (Migrated from github.com) commented 2026-08-26 18:58:42 +00:00

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().

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()`.
andrewtoth (Migrated from github.com) reviewed 2026-08-28 16:05:47 +00:00
andrewtoth (Migrated from github.com) commented 2026-08-28 16:05:47 +00:00

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
diff --git a/src/index/base.cpp b/src/index/base.cpp
index 5820448bb7..4225796fc0 100644
--- a/src/index/base.cpp
+++ b/src/index/base.cpp
@@ -11,6 +11,7 @@
 #include <interfaces/types.h>
 #include <kernel/types.h>
 #include <node/abort.h>
+#include <node/blockfetcher.h>
 #include <node/blockstorage.h>
 #include <node/context.h>
 #include <node/database_args.h>
@@ -209,6 +210,7 @@ void BaseIndex::Sync()
 {
     const CBlockIndex* pindex = m_best_block_index.load();
     if (!m_synced) {
+        node::BlockFetcher fetcher{m_chainstate->m_blockman, m_thread_name};
         auto last_log_time{NodeClock::now()};
         auto last_locator_write_time{last_log_time};
         while (true) {
@@ -249,8 +251,14 @@ void BaseIndex::Sync()
             }
             pindex = pindex_next;
 
-
-            if (!ProcessBlock(pindex)) return; // error logged internally
+            std::shared_ptr<const CBlock> loaded;
+            WITH_LOCK(::cs_main, {
+                loaded = fetcher.Load(pindex->GetBlockHash());
+                if (const auto* tip{m_chainstate->m_chain.Tip()}) {
+                    fetcher.FillQueue(*tip, pindex->nHeight + 1);
+                }
+            });
+            if (!ProcessBlock(pindex, loaded.get())) return; // error logged internally
 
             auto current_time{NodeClock::now()};
             if (current_time - last_log_time >= SYNC_LOG_INTERVAL) {

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).

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) <details><summary>Index patch</summary> ```diff diff --git a/src/index/base.cpp b/src/index/base.cpp index 5820448bb7..4225796fc0 100644 --- a/src/index/base.cpp +++ b/src/index/base.cpp @@ -11,6 +11,7 @@ #include <interfaces/types.h> #include <kernel/types.h> #include <node/abort.h> +#include <node/blockfetcher.h> #include <node/blockstorage.h> #include <node/context.h> #include <node/database_args.h> @@ -209,6 +210,7 @@ void BaseIndex::Sync() { const CBlockIndex* pindex = m_best_block_index.load(); if (!m_synced) { + node::BlockFetcher fetcher{m_chainstate->m_blockman, m_thread_name}; auto last_log_time{NodeClock::now()}; auto last_locator_write_time{last_log_time}; while (true) { @@ -249,8 +251,14 @@ void BaseIndex::Sync() } pindex = pindex_next; - - if (!ProcessBlock(pindex)) return; // error logged internally + std::shared_ptr<const CBlock> loaded; + WITH_LOCK(::cs_main, { + loaded = fetcher.Load(pindex->GetBlockHash()); + if (const auto* tip{m_chainstate->m_chain.Tip()}) { + fetcher.FillQueue(*tip, pindex->nHeight + 1); + } + }); + if (!ProcessBlock(pindex, loaded.get())) return; // error logged internally auto current_time{NodeClock::now()}; if (current_time - last_log_time >= SYNC_LOG_INTERVAL) { ``` </details> 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).
DrahtBot commented 2026-08-28 18:06:50 +00:00 (Migrated from github.com)

🚧 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.

<!--85328a0da195eb286784d51f73fa0af9--> 🚧 At least one of the CI tasks failed. <sub>Task `test ancestor commits`: https://github.com/bitcoin/bitcoin/actions/runs/33196171834/job/98933744258</sub> <sub>LLM reason (✨ experimental): CI failed because `ctest` hit a runtime symbol lookup error in `test_kernel` (`libbitcoinkernel.so` undefined symbol: `node::BlockFetcher::FillQueue(...)`).</sub> <details><summary>Hints</summary> 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. </details>
l0rinc (Migrated from github.com) reviewed 2026-08-28 18:48:49 +00:00
l0rinc (Migrated from github.com) commented 2026-08-28 18:48:49 +00:00

Thanks, I like this approach. I moved BlockFetcher into src/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, and ReadBlock introduced 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: ThreadPool adds a .xx suffix, so the current blkfltbscidx, coinstatsidx, and txospenderidx names would exceed the limit accepted by ThreadRename() before it adds b-.
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.

Thanks, I like this approach. I moved `BlockFetcher` into `src/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, and `ReadBlock` introduced 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: `ThreadPool` adds a `.xx` suffix, so the current `blkfltbscidx`, `coinstatsidx`, and `txospenderidx` names would exceed the limit accepted by `ThreadRename()` before it adds `b-`. 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.
andrewtoth (Migrated from github.com) reviewed 2026-08-31 16:41:40 +00:00
andrewtoth (Migrated from github.com) left a comment

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

Still working on out-of-order IBD benchmarks, but this is looking good. Left some minor suggestions.
andrewtoth (Migrated from github.com) commented 2026-08-31 16:25:14 +00:00

Does this warrant a release note? It is covered already by "performance improvements" in every release note.

Does this warrant a release note? It is covered already by "performance improvements" in every release note.
andrewtoth (Migrated from github.com) commented 2026-08-31 16:25:34 +00:00

nit: we can remove the dates altogether. same for header file.

// Copyright (c) The Bitcoin Core developers
nit: we can remove the dates altogether. same for header file. ```suggestion // Copyright (c) The Bitcoin Core developers ```
andrewtoth (Migrated from github.com) commented 2026-08-31 16:28:37 +00:00

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.

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.
andrewtoth (Migrated from github.com) commented 2026-08-31 16:31:34 +00:00

We should call Clear here, since on a miss we have gotten out of sync of the fetching.

We should call `Clear` here, since on a miss we have gotten out of sync of the fetching.
andrewtoth (Migrated from github.com) commented 2026-08-31 16:29:52 +00:00

Could we pass these as default parameters to the constructor, and call ThreadPool::Start on 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.

Could we pass these as default parameters to the constructor, and call `ThreadPool::Start` on 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.
andrewtoth (Migrated from github.com) reviewed 2026-08-31 17:13:48 +00:00
andrewtoth (Migrated from github.com) commented 2026-08-31 17:13:48 +00:00

I don't think there's a circular dependency. We don't need the ReadBlockFn (so we also don't need BlockFetcher to be wrapped in a std::unique_ptr):

Patch
diff --git a/src/node/blockfetcher.cpp b/src/node/blockfetcher.cpp
index cc8c65e182..0528622606 100644
--- a/src/node/blockfetcher.cpp
+++ b/src/node/blockfetcher.cpp
@@ -5,12 +5,11 @@
 #include <node/blockfetcher.h>
 
 #include <chain.h>
-#include <flatfile.h>
 #include <kernel/cs_main.h>
+#include <node/blockstorage.h>
 #include <primitives/block.h>
 #include <sync.h>
 #include <uint256.h>
-#include <util/expected.h>
 #include <util/threadpool.h>
 
 #include <cstddef>
@@ -31,9 +30,9 @@ std::shared_ptr<const CBlock> BlockFetcher::PopFollowup()
 bool BlockFetcher::Enqueue(const CBlockIndex& index)
 {
     if (m_pool.WorkersCount() == 0) m_pool.Start(WORKER_COUNT);
-    auto followup{m_pool.Submit([&read_block = m_read_block, hash = index.GetBlockHash(), pos = index.GetBlockPos()]() -> std::shared_ptr<const CBlock> {
+    auto followup{m_pool.Submit([&blockman = m_blockman, hash = index.GetBlockHash(), pos = index.GetBlockPos()]() -> std::shared_ptr<const CBlock> {
         auto block{std::make_shared<CBlock>()};
-        if (!read_block(*block, pos, hash)) return nullptr;
+        if (!blockman.ReadBlock(*block, pos, hash)) return nullptr;
         // TODO The block is owned by the worker until its future is consumed, so CheckBlock() may safely set its memoization flags.
         return block;
     })};
diff --git a/src/node/blockfetcher.h b/src/node/blockfetcher.h
index 88290a39af..40e489f328 100644
--- a/src/node/blockfetcher.h
+++ b/src/node/blockfetcher.h
@@ -5,33 +5,30 @@
 #ifndef BITCOIN_NODE_BLOCKFETCHER_H
 #define BITCOIN_NODE_BLOCKFETCHER_H
 
+#include <attributes.h>
 #include <kernel/cs_main.h>
 #include <sync.h>
 #include <util/threadpool.h>
 
 #include <cstdint>
 #include <deque>
-#include <functional>
 #include <future>
 #include <memory>
-#include <string>
-#include <utility>
 
 class CBlock;
 class CBlockIndex;
-struct FlatFilePos;
 class uint256;
 
 namespace node {
+class BlockManager;
+
 /** Supplies blocks to validation. Destruction waits for any queued reads. */
 class BlockFetcher
 {
-    using ReadBlockFn = std::function<bool(CBlock&, const FlatFilePos&, const uint256&)>;
-
     static constexpr uint32_t WORKER_COUNT{1};
     static constexpr uint32_t QUEUE_SIZE{2};
 
-    const ReadBlockFn m_read_block;
+    const BlockManager& m_blockman;
     ThreadPool m_pool{"blockread"};
     std::deque<std::future<std::shared_ptr<const CBlock>>> m_followups GUARDED_BY(::cs_main);
 
@@ -40,7 +37,7 @@ class BlockFetcher
     bool Enqueue(const CBlockIndex& index) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
 
 public:
-    explicit BlockFetcher(ReadBlockFn read_block) : m_read_block{std::move(read_block)} {}
+    explicit BlockFetcher(const BlockManager& blockman LIFETIMEBOUND) : m_blockman{blockman} {}
 
     void Clear() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
     std::shared_ptr<const CBlock> Load(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
diff --git a/src/validation.cpp b/src/validation.cpp
index abb2a612be..be006fdd0d 100644
--- a/src/validation.cpp
+++ b/src/validation.cpp
@@ -29,7 +29,6 @@
 #include <kernel/types.h>
 #include <kernel/warning.h>
 #include <logging/timer.h>
-#include <node/blockfetcher.h>
 #include <node/blockstorage.h>
 #include <node/utxo_snapshot.h>
 #include <policy/ephemeral_policy.h>
@@ -1876,17 +1875,13 @@ Chainstate::Chainstate(
     BlockManager& blockman,
     ChainstateManager& chainman,
     std::optional<uint256> from_snapshot_blockhash)
-    : m_block_fetcher{std::make_unique<node::BlockFetcher>([blockman = &blockman](CBlock& block, const FlatFilePos& pos, const uint256& hash) {
-          return blockman->ReadBlock(block, pos, hash);
-      })},
+    : m_block_fetcher{blockman},
       m_mempool(mempool),
       m_blockman(blockman),
       m_chainman(chainman),
       m_assumeutxo(from_snapshot_blockhash ? Assumeutxo::UNVALIDATED : Assumeutxo::VALIDATED),
       m_from_snapshot_blockhash(from_snapshot_blockhash) {}
 
-Chainstate::~Chainstate() = default;
-
 fs::path Chainstate::StoragePath() const
 {
     fs::path path{m_chainman.m_options.datadir / "chainstate"};
@@ -3222,8 +3217,8 @@ bool Chainstate::ActivateBestChainStep(BlockValidationState& state, CBlockIndex&
     const CBlockIndex* pindexFork = m_chain.FindFork(index_most_work);
     const CBlockIndex* read_ahead_tip{provided_block ? index_most_work.pprev : &index_most_work}; // Avoid rereading the provided block
     if (pindexFork && pindexFork != pindexOldTip) {
-        m_block_fetcher->Clear();
-        if (read_ahead_tip) m_block_fetcher->FillQueue(*read_ahead_tip, pindexFork->nHeight + 1);
+        m_block_fetcher.Clear();
+        if (read_ahead_tip) m_block_fetcher.FillQueue(*read_ahead_tip, pindexFork->nHeight + 1);
     }
 
     // Disconnect active blocks which are no longer in the best chain.
@@ -3263,8 +3258,8 @@ bool Chainstate::ActivateBestChainStep(BlockValidationState& state, CBlockIndex&
 
         // Connect new blocks.
         for (CBlockIndex* pindexConnect : vpindexToConnect | std::views::reverse) {
-            auto block_to_connect{provided_block && pindexConnect == &index_most_work ? provided_block : m_block_fetcher->Load(pindexConnect->GetBlockHash())};
-            if (read_ahead_tip) m_block_fetcher->FillQueue(*read_ahead_tip, pindexConnect->nHeight + 1);
+            auto block_to_connect{provided_block && pindexConnect == &index_most_work ? provided_block : m_block_fetcher.Load(pindexConnect->GetBlockHash())};
+            if (read_ahead_tip) m_block_fetcher.FillQueue(*read_ahead_tip, pindexConnect->nHeight + 1);
             if (!ConnectTip(state, pindexConnect, std::move(block_to_connect), connected_blocks, disconnectpool)) {
                 if (state.IsInvalid()) {
                     // The block violates a consensus rule.
diff --git a/src/validation.h b/src/validation.h
index 2c67d1aa32..2793ccb92b 100644
--- a/src/validation.h
+++ b/src/validation.h
@@ -18,6 +18,7 @@
 #include <kernel/chainparams.h>
 #include <kernel/chainstatemanager_opts.h>
 #include <kernel/cs_main.h> // IWYU pragma: export
+#include <node/blockfetcher.h>
 #include <node/blockstorage.h>
 #include <policy/feerate.h>
 #include <policy/packages.h>
@@ -63,7 +64,6 @@ namespace kernel {
 struct ChainstateRole;
 } // namespace kernel
 namespace node {
-class BlockFetcher;
 class SnapshotMetadata;
 } // namespace node
 namespace Consensus {
@@ -562,7 +562,7 @@ protected:
     Mutex m_chainstate_mutex;
 
     //! Reads blocks ahead during chain activation.
-    std::unique_ptr<node::BlockFetcher> m_block_fetcher;
+    node::BlockFetcher m_block_fetcher;
 
     //! Optional mempool that is kept in sync with the chain.
     //! Only the active chainstate has a mempool.
@@ -594,7 +594,6 @@ public:
         node::BlockManager& blockman,
         ChainstateManager& chainman,
         std::optional<uint256> from_snapshot_blockhash = std::nullopt);
-    ~Chainstate();
 
     //! Return path to chainstate leveldb directory.
     fs::path StoragePath() const;
I don't think there's a circular dependency. We don't need the `ReadBlockFn` (so we also don't need `BlockFetcher` to be wrapped in a `std::unique_ptr`): <details><summary>Patch</summary> ```diff diff --git a/src/node/blockfetcher.cpp b/src/node/blockfetcher.cpp index cc8c65e182..0528622606 100644 --- a/src/node/blockfetcher.cpp +++ b/src/node/blockfetcher.cpp @@ -5,12 +5,11 @@ #include <node/blockfetcher.h> #include <chain.h> -#include <flatfile.h> #include <kernel/cs_main.h> +#include <node/blockstorage.h> #include <primitives/block.h> #include <sync.h> #include <uint256.h> -#include <util/expected.h> #include <util/threadpool.h> #include <cstddef> @@ -31,9 +30,9 @@ std::shared_ptr<const CBlock> BlockFetcher::PopFollowup() bool BlockFetcher::Enqueue(const CBlockIndex& index) { if (m_pool.WorkersCount() == 0) m_pool.Start(WORKER_COUNT); - auto followup{m_pool.Submit([&read_block = m_read_block, hash = index.GetBlockHash(), pos = index.GetBlockPos()]() -> std::shared_ptr<const CBlock> { + auto followup{m_pool.Submit([&blockman = m_blockman, hash = index.GetBlockHash(), pos = index.GetBlockPos()]() -> std::shared_ptr<const CBlock> { auto block{std::make_shared<CBlock>()}; - if (!read_block(*block, pos, hash)) return nullptr; + if (!blockman.ReadBlock(*block, pos, hash)) return nullptr; // TODO The block is owned by the worker until its future is consumed, so CheckBlock() may safely set its memoization flags. return block; })}; diff --git a/src/node/blockfetcher.h b/src/node/blockfetcher.h index 88290a39af..40e489f328 100644 --- a/src/node/blockfetcher.h +++ b/src/node/blockfetcher.h @@ -5,33 +5,30 @@ #ifndef BITCOIN_NODE_BLOCKFETCHER_H #define BITCOIN_NODE_BLOCKFETCHER_H +#include <attributes.h> #include <kernel/cs_main.h> #include <sync.h> #include <util/threadpool.h> #include <cstdint> #include <deque> -#include <functional> #include <future> #include <memory> -#include <string> -#include <utility> class CBlock; class CBlockIndex; -struct FlatFilePos; class uint256; namespace node { +class BlockManager; + /** Supplies blocks to validation. Destruction waits for any queued reads. */ class BlockFetcher { - using ReadBlockFn = std::function<bool(CBlock&, const FlatFilePos&, const uint256&)>; - static constexpr uint32_t WORKER_COUNT{1}; static constexpr uint32_t QUEUE_SIZE{2}; - const ReadBlockFn m_read_block; + const BlockManager& m_blockman; ThreadPool m_pool{"blockread"}; std::deque<std::future<std::shared_ptr<const CBlock>>> m_followups GUARDED_BY(::cs_main); @@ -40,7 +37,7 @@ class BlockFetcher bool Enqueue(const CBlockIndex& index) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); public: - explicit BlockFetcher(ReadBlockFn read_block) : m_read_block{std::move(read_block)} {} + explicit BlockFetcher(const BlockManager& blockman LIFETIMEBOUND) : m_blockman{blockman} {} void Clear() EXCLUSIVE_LOCKS_REQUIRED(::cs_main); std::shared_ptr<const CBlock> Load(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); diff --git a/src/validation.cpp b/src/validation.cpp index abb2a612be..be006fdd0d 100644 --- a/src/validation.cpp +++ b/src/validation.cpp @@ -29,7 +29,6 @@ #include <kernel/types.h> #include <kernel/warning.h> #include <logging/timer.h> -#include <node/blockfetcher.h> #include <node/blockstorage.h> #include <node/utxo_snapshot.h> #include <policy/ephemeral_policy.h> @@ -1876,17 +1875,13 @@ Chainstate::Chainstate( BlockManager& blockman, ChainstateManager& chainman, std::optional<uint256> from_snapshot_blockhash) - : m_block_fetcher{std::make_unique<node::BlockFetcher>([blockman = &blockman](CBlock& block, const FlatFilePos& pos, const uint256& hash) { - return blockman->ReadBlock(block, pos, hash); - })}, + : m_block_fetcher{blockman}, m_mempool(mempool), m_blockman(blockman), m_chainman(chainman), m_assumeutxo(from_snapshot_blockhash ? Assumeutxo::UNVALIDATED : Assumeutxo::VALIDATED), m_from_snapshot_blockhash(from_snapshot_blockhash) {} -Chainstate::~Chainstate() = default; - fs::path Chainstate::StoragePath() const { fs::path path{m_chainman.m_options.datadir / "chainstate"}; @@ -3222,8 +3217,8 @@ bool Chainstate::ActivateBestChainStep(BlockValidationState& state, CBlockIndex& const CBlockIndex* pindexFork = m_chain.FindFork(index_most_work); const CBlockIndex* read_ahead_tip{provided_block ? index_most_work.pprev : &index_most_work}; // Avoid rereading the provided block if (pindexFork && pindexFork != pindexOldTip) { - m_block_fetcher->Clear(); - if (read_ahead_tip) m_block_fetcher->FillQueue(*read_ahead_tip, pindexFork->nHeight + 1); + m_block_fetcher.Clear(); + if (read_ahead_tip) m_block_fetcher.FillQueue(*read_ahead_tip, pindexFork->nHeight + 1); } // Disconnect active blocks which are no longer in the best chain. @@ -3263,8 +3258,8 @@ bool Chainstate::ActivateBestChainStep(BlockValidationState& state, CBlockIndex& // Connect new blocks. for (CBlockIndex* pindexConnect : vpindexToConnect | std::views::reverse) { - auto block_to_connect{provided_block && pindexConnect == &index_most_work ? provided_block : m_block_fetcher->Load(pindexConnect->GetBlockHash())}; - if (read_ahead_tip) m_block_fetcher->FillQueue(*read_ahead_tip, pindexConnect->nHeight + 1); + auto block_to_connect{provided_block && pindexConnect == &index_most_work ? provided_block : m_block_fetcher.Load(pindexConnect->GetBlockHash())}; + if (read_ahead_tip) m_block_fetcher.FillQueue(*read_ahead_tip, pindexConnect->nHeight + 1); if (!ConnectTip(state, pindexConnect, std::move(block_to_connect), connected_blocks, disconnectpool)) { if (state.IsInvalid()) { // The block violates a consensus rule. diff --git a/src/validation.h b/src/validation.h index 2c67d1aa32..2793ccb92b 100644 --- a/src/validation.h +++ b/src/validation.h @@ -18,6 +18,7 @@ #include <kernel/chainparams.h> #include <kernel/chainstatemanager_opts.h> #include <kernel/cs_main.h> // IWYU pragma: export +#include <node/blockfetcher.h> #include <node/blockstorage.h> #include <policy/feerate.h> #include <policy/packages.h> @@ -63,7 +64,6 @@ namespace kernel { struct ChainstateRole; } // namespace kernel namespace node { -class BlockFetcher; class SnapshotMetadata; } // namespace node namespace Consensus { @@ -562,7 +562,7 @@ protected: Mutex m_chainstate_mutex; //! Reads blocks ahead during chain activation. - std::unique_ptr<node::BlockFetcher> m_block_fetcher; + node::BlockFetcher m_block_fetcher; //! Optional mempool that is kept in sync with the chain. //! Only the active chainstate has a mempool. @@ -594,7 +594,6 @@ public: node::BlockManager& blockman, ChainstateManager& chainman, std::optional<uint256> from_snapshot_blockhash = std::nullopt); - ~Chainstate(); //! Return path to chainstate leveldb directory. fs::path StoragePath() const; ``` </details>
l0rinc (Migrated from github.com) reviewed 2026-09-01 21:53:28 +00:00
l0rinc (Migrated from github.com) left a comment

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).

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).
l0rinc (Migrated from github.com) commented 2026-09-01 21:41:27 +00:00

I expect this to land in a future release, so for now I'd keep it

I expect this to land in a future release, so for now I'd keep it
l0rinc (Migrated from github.com) commented 2026-09-01 21:43:15 +00:00

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?

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?
l0rinc commented 2026-09-02 02:55:34 +00:00 (Migrated from github.com)

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:

image

If we add context-independent CheckBlock calls in a followup (to do partial validation before returning the blocks), the optimum shifts slightly to 4 threads and queue length of 8.

image image
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: <img width="2534" height="799" alt="image" src="https://github.com/user-attachments/assets/9ea194be-b614-49a9-b353-d40fcd842743" /> If we add context-independent `CheckBlock` calls in a followup (to do partial validation before returning the blocks), the optimum shifts slightly to 4 threads and queue length of 8. <img width="2534" height="799" alt="image" src="https://github.com/user-attachments/assets/2c0b3bde-2318-4627-a8f7-0f99a38d1a36" /> <img width="2534" height="802" alt="image" src="https://github.com/user-attachments/assets/96d20155-5f21-421a-bdca-8b6d6df3ceea" />
andrewtoth (Migrated from github.com) reviewed 2026-09-03 15:11:47 +00:00
andrewtoth (Migrated from github.com) commented 2026-09-03 15:11:47 +00:00

Since we have multiple worker threads now, maybe we can take advantage of the multi-Submit overload whenever we have an empty m_followups? That would awaken all threads at once. This would happen on every ActivateBestChainStep call, 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.

Since we have multiple worker threads now, maybe we can take advantage of the multi-`Submit` overload whenever we have an empty `m_followups`? That would awaken all threads at once. This would happen on every `ActivateBestChainStep` call, 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.
andrewtoth (Migrated from github.com) reviewed 2026-09-03 16:56:28 +00:00
andrewtoth (Migrated from github.com) commented 2026-09-03 16:56:28 +00:00

Ahh I did not use the linter, I just compiled. Indeed, my patch fails lint. Thanks!

Ahh I did not use the linter, I just compiled. Indeed, my patch fails lint. Thanks!
andrewtoth (Migrated from github.com) approved these changes 2026-09-08 18:53:02 +00:00
andrewtoth (Migrated from github.com) left a comment

ACK 3547915bfb

Managed 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.

Workload Machine Base elapsed PR elapsed Less elapsed time
IBD i7 5h 39m 4h 53m 13.4%
IBD i5 7h 12m 6h 56m 3.8%
reindex-chainstate i7 3h 44m 2h 24m 35.8%
reindex-chainstate i5 4h 40m 4h 04m 12.7%
ACK 3547915bfb240f280188954c7c5b60ec90145ac5 Managed 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. | Workload | Machine | Base elapsed | PR elapsed | Less elapsed time | |---|---|---|---|---| | IBD | i7 | 5h 39m | 4h 53m | 13.4% | | IBD | i5 | 7h 12m | 6h 56m | 3.8% | | reindex-chainstate | i7 | 3h 44m | 2h 24m | 35.8% | | reindex-chainstate | i5 | 4h 40m | 4h 04m | 12.7% |
andrewtoth (Migrated from github.com) commented 2026-09-08 18:32:43 +00:00

The release notes are stale. There are now multiple threads.

The release notes are stale. There are now multiple threads.
andrewtoth (Migrated from github.com) commented 2026-09-08 18:37:46 +00:00

This comment is not very helpful IMO. Why would anyone care about destruction waiting on queued reads? Something like this would be better.

/**
 * Reads and deserializes blocks in parallel starting from a requested block index.
 * Useful for improving performance when scanning blocks.
 **/
This comment is not very helpful IMO. Why would anyone care about destruction waiting on queued reads? Something like this would be better. ```suggestion /** * Reads and deserializes blocks in parallel starting from a requested block index. * Useful for improving performance when scanning blocks. **/ ```
andrewtoth (Migrated from github.com) commented 2026-09-08 18:40:02 +00:00

This comment is a bit cryptic.

    // If we have a provided block, we don't need to read it so we can stop reading ahead at the previous block.
    const CBlockIndex* read_ahead_tip{provided_block ? index_most_work.pprev : &index_most_work};
This comment is a bit cryptic. ```suggestion // If we have a provided block, we don't need to read it so we can stop reading ahead at the previous block. const CBlockIndex* read_ahead_tip{provided_block ? index_most_work.pprev : &index_most_work}; ```
w0xlt (Migrated from github.com) reviewed 2026-09-16 16:22:26 +00:00
w0xlt (Migrated from github.com) commented 2026-09-16 16:22:26 +00:00

When a block was rejected, blocks read ahead for its branch could remain in memory indefinitely.

diff --git a/src/validation.cpp b/src/validation.cpp
index 86a2c8a2a4..0a14db9e9b 100644
--- a/src/validation.cpp
+++ b/src/validation.cpp
@@ -3256,7 +3256,8 @@ bool Chainstate::ActivateBestChainStep(BlockValidationState& state, CBlockIndex&
             if (read_ahead_tip) m_block_fetcher->FillQueue(*read_ahead_tip, pindexConnect->nHeight + 1);
             if (!ConnectTip(state, pindexConnect, std::move(block_to_connect), connected_blocks, disconnectpool)) {
                 if (state.IsInvalid()) {
-                    // The block violates a consensus rule.
+                    // The block violates a consensus rule. Discard any prefetched descendants.
+                    m_block_fetcher->Clear();
                     if (state.GetResult() != BlockValidationResult::BLOCK_MUTATED) {
                         InvalidChainFound(vpindexToConnect.front());
                     }
When a block was rejected, blocks read ahead for its branch could remain in memory indefinitely. ```diff diff --git a/src/validation.cpp b/src/validation.cpp index 86a2c8a2a4..0a14db9e9b 100644 --- a/src/validation.cpp +++ b/src/validation.cpp @@ -3256,7 +3256,8 @@ bool Chainstate::ActivateBestChainStep(BlockValidationState& state, CBlockIndex& if (read_ahead_tip) m_block_fetcher->FillQueue(*read_ahead_tip, pindexConnect->nHeight + 1); if (!ConnectTip(state, pindexConnect, std::move(block_to_connect), connected_blocks, disconnectpool)) { if (state.IsInvalid()) { - // The block violates a consensus rule. + // The block violates a consensus rule. Discard any prefetched descendants. + m_block_fetcher->Clear(); if (state.GetResult() != BlockValidationResult::BLOCK_MUTATED) { InvalidChainFound(vpindexToConnect.front()); } ```
DrahtBot commented 2026-09-24 05:44:54 +00:00 (Migrated from github.com)

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

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
l0rinc commented 2026-09-24 23:59:15 +00:00 (Migrated from github.com)

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. BENCH timings 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.

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. `BENCH` timings 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.
andrewtoth (Migrated from github.com) reviewed 2026-09-25 15:26:35 +00:00
andrewtoth (Migrated from github.com) commented 2026-09-25 15:26:35 +00:00

@l0rinc just wondering if you had any thoughts on these suggestions?

@l0rinc just wondering if you had any thoughts on these suggestions?
l0rinc (Migrated from github.com) reviewed 2026-09-26 01:20:28 +00:00
l0rinc (Migrated from github.com) commented 2026-09-26 01:20:28 +00:00

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 of 2*n blocks. Setting it to 0 disables read-ahead. Thanks for the reminder.

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 of `2*n` blocks. Setting it to `0` disables read-ahead. Thanks for the reminder.
l0rinc commented 2026-09-26 01:26:02 +00:00 (Migrated from github.com)

Pushed a few versions again, since 3547915, BENCH block-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, with 0 disabling read-ahead). I also restored helper and loop code changed in intermediate pushes, so this range-diff shows the net changes:

git range-diff --creation-factor=95 dc0395c585..3547915bfb ed7dd7cf4e..7c4efd1174
Pushed a few versions again, since 3547915, `BENCH` block-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`, with `0` disabling read-ahead). I also restored helper and loop code changed in intermediate pushes, so this range-diff shows the net changes: ```bash git range-diff --creation-factor=95 dc0395c585..3547915bfb ed7dd7cf4e..7c4efd1174 ```
andrewtoth (Migrated from github.com) reviewed 2026-09-28 01:44:58 +00:00
andrewtoth (Migrated from github.com) left a comment

Code review 7c4efd1174

I measured reindex-chainstate again with this latest commit and it's a blistering 1h 48m.

Left a few suggestions on the latest revision.

Code review 7c4efd1174070eba967fb0803c2080500b77ee10 I measured reindex-chainstate again with this latest commit and it's a blistering 1h 48m. Left a few suggestions on the latest revision.
andrewtoth (Migrated from github.com) commented 2026-09-28 01:11:14 +00:00

Should we also add this to the reduce memory usage docs?

Should we also add this to the reduce memory usage docs?
andrewtoth (Migrated from github.com) commented 2026-09-28 01:10:54 +00:00

We should bound this to a max value, no?

We should bound this to a max value, no?
andrewtoth (Migrated from github.com) commented 2026-09-28 01:42:43 +00:00

Instead of passing a time_point, could we pass const CBlockIndex* read_ahead_tip? Then we could do

if (!block_to_connect) {
    block_to_connect = m_block_fetcher->Load(pindexNew->GetBlockHash());
}
if (read_ahead_tip) {
    m_block_fetcher->FillQueue(*read_ahead_tip, pindexNew->nHeight + 1);
}

inside ConnectTip instead, and not have to adjust any of the timing variables?

Instead of passing a `time_point`, could we pass `const CBlockIndex* read_ahead_tip`? Then we could do ```C++ if (!block_to_connect) { block_to_connect = m_block_fetcher->Load(pindexNew->GetBlockHash()); } if (read_ahead_tip) { m_block_fetcher->FillQueue(*read_ahead_tip, pindexNew->nHeight + 1); } ``` inside `ConnectTip` instead, and not have to adjust any of the timing variables?
andrewtoth (Migrated from github.com) commented 2026-09-28 01:19:50 +00:00

I don't see the purpose of this line. Seems like it will always be a no-op. I think it should be removed.

I don't see the purpose of this line. Seems like it will always be a no-op. I think it should be removed.
First-time contributor

Earlier concerns remain unresolved; see the Run archive linked from the Review report.

🔴 Major · ChainMan releases its context before joining block readers

ChainMan teardown can free chain parameters before outstanding kernel block readers finish when it owns the last Context reference; 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 · ReadBlockFn leaves its worker lock contract undocumented

The current callback is safe, but ReadBlockFn does not state that concurrent callbacks must avoid cs_main, which Load() 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 · BlockFetcher lifecycle tests never hold a read in progress

The 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 reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:3f89681de11a6729a084d29fd96adfa42e3f319bf8f5c8ad91552cdeb231adb4:1ed10c4979af6fc548d6b8d4534d505e02e84ac4b0aa4f8633555b2ba75119e8 --> <!-- ralph-base:d55f55eda79a98ddaad7f7bec9faca8beb097b99 --> <!-- ralph-head:d62c4b54799a29fe33e45bc9d0b7462398c6b020 --> <!-- ralph-case:689418cd957da5ca371f8366363f67790abcd3c48942d4907967f305f8a1c439 --> Earlier concerns remain unresolved; see the Run archive linked from the Review report. **🔴 Major · `ChainMan` releases its context before joining block readers** `ChainMan` teardown can free chain parameters before outstanding kernel block readers finish when it owns the last `Context` reference; no current in-tree caller using this release order was found. Location: [`src/validation.cpp:1862`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/d62c4b54799a29fe33e45bc9d0b7462398c6b020/src/validation.cpp#L1862>) (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`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/d62c4b54799a29fe33e45bc9d0b7462398c6b020/test/functional/feature_reindex.py#L49>) (head). **🔵 Suggestion · `ReadBlockFn` leaves its worker lock contract undocumented** The current callback is safe, but `ReadBlockFn` does not state that concurrent callbacks must avoid `cs_main`, which `Load()` holds while waiting for them. Location: [`src/node/blockfetcher.h:28`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/d62c4b54799a29fe33e45bc9d0b7462398c6b020/src/node/blockfetcher.h#L28>) (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`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/d62c4b54799a29fe33e45bc9d0b7462398c6b020/src/node/blockfetcher.cpp#L58>) (head). **🔵 Suggestion · `BlockFetcher` lifecycle tests never hold a read in progress** The existing fetcher unit test consumes both reads, leaving nonblocking `Clear()` and callback lifetime during destruction unchecked. Location: [`src/node/blockfetcher.cpp:35`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/d62c4b54799a29fe33e45bc9d0b7462398c6b020/src/node/blockfetcher.cpp#L35>) (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. <!-- Review tier: sensitive --> --- Reviewed: [`d62c4b54799a`](<https://git.fish.foo/bitcoin/bitcoin/commit/d62c4b54799a29fe33e45bc9d0b7462398c6b020>) · [Review report](<https://review.fish.foo/report/36000-d62c4b54799a29fe33e45bc9d0b7462398c6b020-2818-6.html>) · [Previous reports](<https://review.fish.foo/traces/36000/>) [permalink](<https://review.fish.foo/report/36000-d62c4b54799a29fe33e45bc9d0b7462398c6b020-2818-6.html>)
l0rinc (Migrated from github.com) reviewed 2026-09-29 00:36:38 +00:00
l0rinc (Migrated from github.com) left a comment

Added retry coverage and stronger reconnection checks, batched read-ahead submissions, unified thread naming with a 16-reader cap and a 2*n queue, and moved loading into ConnectTip to preserve the existing BENCH timers.

Added retry coverage and stronger reconnection checks, batched read-ahead submissions, unified thread naming with a 16-reader cap and a `2*n` queue, and moved loading into `ConnectTip` to preserve the existing `BENCH` timers.
l0rinc (Migrated from github.com) commented 2026-09-29 00:23:13 +00:00

It was already there, but I updated it in the latest push to cover the cap and queue capacity.

It was already there, but I updated it in the latest push to cover the cap and queue capacity.
l0rinc (Migrated from github.com) commented 2026-09-29 00:25:10 +00:00

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 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.
l0rinc (Migrated from github.com) commented 2026-09-29 00:23:28 +00:00

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.

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.
l0rinc (Migrated from github.com) commented 2026-09-29 00:17:25 +00:00

Thanks, this minimizes the diff, I like the outcome. Loading and refilling now happen inside ConnectTip, keeping the existing timing variables. FillQueue handles the guard internally, so its callers don't need one.

Thanks, this minimizes the diff, I like the outcome. Loading and refilling now happen inside `ConnectTip`, keeping the existing timing variables. `FillQueue` handles the guard internally, so its callers don't need one.
l0rinc (Migrated from github.com) commented 2026-09-29 00:23:01 +00:00

I'm not sure whether it wasn't needed before, but FillQueue now handles cleanup when the read-ahead range ends, so it isn't needed anymore.

I'm not sure whether it wasn't needed before, but `FillQueue` now handles cleanup when the read-ahead range ends, so it isn't needed anymore.
andrewtoth (Migrated from github.com) reviewed 2026-09-29 03:24:15 +00:00
andrewtoth (Migrated from github.com) commented 2026-09-29 03:24:15 +00:00

Well without this guard the application could spawn millions of threads if misconfigured?

Well without this guard the application could spawn millions of threads if misconfigured?
l0rinc (Migrated from github.com) reviewed 2026-09-29 03:32:37 +00:00
l0rinc (Migrated from github.com) commented 2026-09-29 03:32:37 +00:00

Sure, but we don't usually guard against user error like -dbcache=-1 or similar - and I did apply it, I was just hesitant because of the reasons above.

Sure, but we don't usually guard against user error like `-dbcache=-1` or similar - and I did apply it, I was just hesitant because of the reasons above.
l0rinc (Migrated from github.com) reviewed 2026-09-29 16:51:19 +00:00
l0rinc (Migrated from github.com) commented 2026-09-29 16:51:19 +00:00

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
for DBCACHE in 2000; do
  COMMITS="ed7dd7cf4e1561a97edf72eba29a67b14e28c717 7c4efd1174070eba967fb0803c2080500b77ee10 c5aafe25576d341451d679816ae0d1f8c8405c7e"
  STOP=968869; CC=gcc; CXX=g++
  BASE_DIR="/mnt/my_storage"; DATA_DIR="$BASE_DIR/BitcoinData"; LOG_DIR="$BASE_DIR/logs"
  (echo ""; for c in $COMMITS; do git fetch -q origin "$c" 2>/dev/null || true; git log -1 --pretty='%h %s' "$c" || exit 1; done) &&
  (echo "" && echo "$(date -I) | reindex-chainstate | ${STOP} blocks | dbcache ${DBCACHE} | $(hostname) | $(uname -m) | $(lscpu | grep 'Model name' | head -1 | cut -d: -f2 | xargs) | $(nproc) threads | $(free -h | awk '/^Mem:/{print $2}') RAM | $(lsblk -no ROTA $(df --output=source $BASE_DIR | tail -1) | grep -q 1 && echo HDD || echo SSD)"; echo "") &&
  hyperfine   --sort command   --runs 1   --export-json "$BASE_DIR/rdx-$(sed -E 's/([a-f0-9]{8})[a-f0-9]* ?/\1-/g;s/-$//'<<<"$COMMITS")-$STOP-$DBCACHE-$CC.json"   --parameter-list COMMIT ${COMMITS// /,}   --prepare "killall -9 bitcoind 2>/dev/null; rm -f ./build/bin/bitcoind; git clean -fxd; git reset --hard {COMMIT} && \
CC=$CC CXX=$CXX cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Release && ninja -C build bitcoind -j1 && \
./build/bin/bitcoind -datadir=$DATA_DIR -stopatheight=$STOP -printtoconsole=0; sleep 20 && rm -f $DATA_DIR/debug.log && rm -rfd $DATA_DIR/chainstate $DATA_DIR/indexes"     --conclude "killall bitcoind || true; sleep 100; sync; echo 3 | sudo tee /proc/sys/vm/drop_caches; \
grep -q 'height=0' $DATA_DIR/debug.log && \
grep -q 'height=$STOP' $DATA_DIR/debug.log && \
grep 'Bitcoin Core version' $DATA_DIR/debug.log | grep -q \"\$(git rev-parse --short=12 {COMMIT})\" && \
cp $DATA_DIR/debug.log $LOG_DIR/debug-{COMMIT}-\$(date +%s).log"   "COMPILER=$CC ./build/bin/bitcoind -datadir=$DATA_DIR -stopatheight=$STOP -dbcache=$DBCACHE -reindex-chainstate -assumevalid=00000000000000000000ccebd6d74d9194d8dcdc1d177c478e094bfad51ba5ac -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0"; done

ed7dd7cf4e Merge bitcoin/bitcoin#34371: wallet: allow importprunedfunds for spending transactions
7c4efd1174 doc: add block read-ahead release note
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 = 7c4efd1174070eba967fb0803c2080500b77ee10)
  Time (abs ≡):        9641.134 s               [User: 37300.454 s, System: 2003.075 s]

Benchmark 3: 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.01          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 = 7c4efd1174070eba967fb0803c2080500b77ee10)
        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)
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). <details><summary>master vs single-submit vs multi-submit</summary> ```bash for DBCACHE in 2000; do COMMITS="ed7dd7cf4e1561a97edf72eba29a67b14e28c717 7c4efd1174070eba967fb0803c2080500b77ee10 c5aafe25576d341451d679816ae0d1f8c8405c7e" STOP=968869; CC=gcc; CXX=g++ BASE_DIR="/mnt/my_storage"; DATA_DIR="$BASE_DIR/BitcoinData"; LOG_DIR="$BASE_DIR/logs" (echo ""; for c in $COMMITS; do git fetch -q origin "$c" 2>/dev/null || true; git log -1 --pretty='%h %s' "$c" || exit 1; done) && (echo "" && echo "$(date -I) | reindex-chainstate | ${STOP} blocks | dbcache ${DBCACHE} | $(hostname) | $(uname -m) | $(lscpu | grep 'Model name' | head -1 | cut -d: -f2 | xargs) | $(nproc) threads | $(free -h | awk '/^Mem:/{print $2}') RAM | $(lsblk -no ROTA $(df --output=source $BASE_DIR | tail -1) | grep -q 1 && echo HDD || echo SSD)"; echo "") && hyperfine --sort command --runs 1 --export-json "$BASE_DIR/rdx-$(sed -E 's/([a-f0-9]{8})[a-f0-9]* ?/\1-/g;s/-$//'<<<"$COMMITS")-$STOP-$DBCACHE-$CC.json" --parameter-list COMMIT ${COMMITS// /,} --prepare "killall -9 bitcoind 2>/dev/null; rm -f ./build/bin/bitcoind; git clean -fxd; git reset --hard {COMMIT} && \ CC=$CC CXX=$CXX cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Release && ninja -C build bitcoind -j1 && \ ./build/bin/bitcoind -datadir=$DATA_DIR -stopatheight=$STOP -printtoconsole=0; sleep 20 && rm -f $DATA_DIR/debug.log && rm -rfd $DATA_DIR/chainstate $DATA_DIR/indexes" --conclude "killall bitcoind || true; sleep 100; sync; echo 3 | sudo tee /proc/sys/vm/drop_caches; \ grep -q 'height=0' $DATA_DIR/debug.log && \ grep -q 'height=$STOP' $DATA_DIR/debug.log && \ grep 'Bitcoin Core version' $DATA_DIR/debug.log | grep -q \"\$(git rev-parse --short=12 {COMMIT})\" && \ cp $DATA_DIR/debug.log $LOG_DIR/debug-{COMMIT}-\$(date +%s).log" "COMPILER=$CC ./build/bin/bitcoind -datadir=$DATA_DIR -stopatheight=$STOP -dbcache=$DBCACHE -reindex-chainstate -assumevalid=00000000000000000000ccebd6d74d9194d8dcdc1d177c478e094bfad51ba5ac -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0"; done ed7dd7cf4e Merge bitcoin/bitcoin#34371: wallet: allow importprunedfunds for spending transactions 7c4efd1174 doc: add block read-ahead release note 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 = 7c4efd1174070eba967fb0803c2080500b77ee10) Time (abs ≡): 9641.134 s [User: 37300.454 s, System: 2003.075 s] Benchmark 3: 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.01 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 = 7c4efd1174070eba967fb0803c2080500b77ee10) 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) ``` </details>
w0xlt commented 2026-09-29 20:06:09 +00:00 (Migrated from github.com)

nit: feature_proxy.py disables prevout fetching with -prevoutfetchthreads=0 (added in f82043af50) to avoid starting a thread pool for each of its 7 nodes. With this PR, util.py sets blockreadahead=1 for 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:

        # This test launches many nodes; disable prevout prefetching and block read-ahead
        # so we don't spin up thread pools for each one.
        args = [a + ['-prevoutfetchthreads=0', '-blockreadahead=0'] for a in args]
nit: `feature_proxy.py` disables prevout fetching with `-prevoutfetchthreads=0` (added in f82043af50) to avoid starting a thread pool for each of its 7 nodes. With this PR, `util.py` sets `blockreadahead=1` for 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: ```py # This test launches many nodes; disable prevout prefetching and block read-ahead # so we don't spin up thread pools for each one. args = [a + ['-prevoutfetchthreads=0', '-blockreadahead=0'] for a in args] ```
w0xlt (Migrated from github.com) reviewed 2026-09-29 20:12:48 +00:00
w0xlt (Migrated from github.com) commented 2026-09-29 20:12:48 +00:00

nit: Assert() aborts here instead of throwing, so if the retry path regresses, test_bitcoin dies with no Boost report and the remaining blockmanager_tests cases don't run. This file already uses BOOST_REQUIRE(block) for this at lines 169 and 197:

suggestion:

     const auto loaded{fetcher.Load(hash)};
     BOOST_REQUIRE(loaded);
     BOOST_CHECK_EQUAL(loaded->GetHash(), hash);
nit: `Assert()` aborts here instead of throwing, so if the retry path regresses, test_bitcoin dies with no Boost report and the remaining `blockmanager_tests` cases don't run. This file already uses `BOOST_REQUIRE(block)` for this at lines 169 and 197: suggestion: ```py const auto loaded{fetcher.Load(hash)}; BOOST_REQUIRE(loaded); BOOST_CHECK_EQUAL(loaded->GetHash(), hash); ```
w0xlt commented 2026-09-29 20:19:08 +00:00 (Migrated from github.com)

Bikeshed: -blockreadahead=<n> reads like a block count, but it sets the number of reader threads, and the window is 2*n blocks. For example, someone setting -blockreadahead=4 to limit memory to 4 blocks would actually keep 8. Since options are hard to rename after a release, would -blockreadaheadthreads be clearer, matching -prevoutfetchthreads?

Bikeshed: `-blockreadahead=<n>` reads like a block count, but it sets the number of reader threads, and the window is `2*n blocks`. For example, someone setting `-blockreadahead=4` to limit memory to 4 blocks would actually keep 8. Since options are hard to rename after a release, would `-blockreadaheadthreads` be clearer, matching `-prevoutfetchthreads`?
l0rinc (Migrated from github.com) reviewed 2026-09-29 22:55:11 +00:00
l0rinc (Migrated from github.com) left a comment

Thanks, the leftover blockreadahead name 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.

Thanks, the leftover `blockreadahead` name 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.
l0rinc (Migrated from github.com) commented 2026-09-29 22:38:31 +00:00

I consider the loaded block a precondition for the hash comparison, so I used Assert() deliberately to keep it a simple one-liner.

I consider the loaded block a precondition for the hash comparison, so I used `Assert()` deliberately to keep it a simple one-liner.
DrahtBot commented 2026-10-08 16:20:46 +00:00 (Migrated from github.com)

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

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
w0xlt (Migrated from github.com) reviewed 2026-10-09 06:54:03 +00:00
w0xlt (Migrated from github.com) left a comment
ACK 495d50ae0ca75b605495fe825f4034ffdea06544
andrewtoth (Migrated from github.com) reviewed 2026-10-10 00:13:22 +00:00
andrewtoth (Migrated from github.com) commented 2026-10-09 15:47:29 +00:00

I also find this comment cryptic. I'm not sure it's useful.

            } catch (std::exception&) {}
I also find this comment cryptic. I'm not sure it's useful. ```suggestion } catch (std::exception&) {} ```
andrewtoth (Migrated from github.com) commented 2026-10-10 00:13:04 +00:00

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?

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?
andrewtoth (Migrated from github.com) commented 2026-10-10 00:12:05 +00:00

Maybe something like this is more clear:

    //! Clear queued reads. Queued block reads will no longer be returned via Load, but will still complete asynchronously.
Maybe something like this is more clear: ```suggestion //! Clear queued reads. Queued block reads will no longer be returned via Load, but will still complete asynchronously. ```
andrewtoth (Migrated from github.com) commented 2026-10-09 15:39:55 +00:00

nit: this can now be util::NotNullUniquePtr<node::BlockFetcher>.

nit: this can now be `util::NotNullUniquePtr<node::BlockFetcher>`.
andrewtoth (Migrated from github.com) commented 2026-10-09 23:33:48 +00:00
    """Returns the number of blocks ConnectTip() did not have to read from disk since log_start."""
```suggestion """Returns the number of blocks ConnectTip() did not have to read from disk since log_start.""" ```
andrewtoth (Migrated from github.com) commented 2026-10-09 23:36:37 +00:00
    """Returns the startup lines logged by the block read-ahead workers, one per worker thread."""
```suggestion """Returns the startup lines logged by the block read-ahead workers, one per worker thread.""" ```
andrewtoth (Migrated from github.com) commented 2026-10-09 23:38:31 +00:00

I'm not sure what this comment is here for? I think it should be removed.

I'm not sure what this comment is here for? I think it should be removed.
andrewtoth (Migrated from github.com) commented 2026-10-09 23:55:28 +00:00

Why do we repeat this line here? Seems like a redundant assertion that can be removed?

Why do we repeat this line here? Seems like a redundant assertion that can be removed?
andrewtoth (Migrated from github.com) commented 2026-10-10 00:10:11 +00:00

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.

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.
l0rinc (Migrated from github.com) reviewed 2026-10-10 13:04:20 +00:00
l0rinc (Migrated from github.com) left a comment

Thanks @andrewtoth, applied most of your suggestions.

Thanks @andrewtoth, applied most of your suggestions.
l0rinc (Migrated from github.com) commented 2026-10-10 12:22:33 +00:00

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.

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.
l0rinc (Migrated from github.com) commented 2026-10-10 12:30:23 +00:00

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.

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.
l0rinc (Migrated from github.com) commented 2026-10-10 12:31:05 +00:00

Thanks, clarified that clearing results doesn't cancel submitted reads and documented Load() and FillQueue().

Thanks, clarified that clearing results doesn't cancel submitted reads and documented Load() and FillQueue().
l0rinc (Migrated from github.com) commented 2026-10-10 12:19:49 +00:00

Indeed, rebased & switched.

Indeed, rebased & switched.
l0rinc (Migrated from github.com) commented 2026-10-10 12:23:22 +00:00

Removed

Removed
l0rinc (Migrated from github.com) commented 2026-10-10 12:24:50 +00:00

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.

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.
l0rinc (Migrated from github.com) commented 2026-10-10 12:31:49 +00:00

Thanks, removed the height assertion and its saved value

Thanks, removed the height assertion and its saved value
arejula27 (Migrated from github.com) reviewed 2026-10-10 20:36:40 +00:00
arejula27 (Migrated from github.com) left a comment

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 writes: only blocks with BLOCK_HAVE_DATA are queued, and that flag is set after WriteBlock() closes the file, so a block that is still being written is never prefetched.
  • Pruning: files holding blocks above the tip are never pruned.
  • Indexes: they read blocks below the tip, while the fetcher reads above it.
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 writes: only blocks with `BLOCK_HAVE_DATA` are queued, and that flag is set after `WriteBlock()` closes the file, so a block that is still being written is never prefetched. - Pruning: files holding blocks above the tip are never pruned. - Indexes: they read blocks below the tip, while the fetcher reads above it.
arejula27 (Migrated from github.com) commented 2026-10-10 20:24:31 +00:00

nit: when tasks is empty, could we return early here?

nit: when tasks is empty, could we return early here?
l0rinc (Migrated from github.com) reviewed 2026-10-14 08:35:51 +00:00
l0rinc (Migrated from github.com) commented 2026-10-14 08:35:51 +00:00

Maybe it is worth reverting to single task submission

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
diff --git a/src/node/blockfetcher.cpp b/src/node/blockfetcher.cpp
index 5e7465cbce..518086d4e0 100644
--- a/src/node/blockfetcher.cpp
+++ b/src/node/blockfetcher.cpp
@@ -17,10 +17,8 @@
 #include <algorithm>
 #include <cstddef>
 #include <exception>
-#include <iterator>
 #include <memory>
 #include <utility>
-#include <vector>
 
 namespace node {
 BlockFetcher::BlockFetcher(ReadBlockFn read_block, int32_t thread_count)
@@ -54,17 +52,15 @@ void BlockFetcher::FillQueue(const CBlockIndex* last_index, int next_height)
         Clear();
         return;
     }
-    std::vector<ReadTask> tasks;
     for (size_t i{m_followups.size()}; i < m_thread_count * BLOCKS_PER_READ_AHEAD_THREAD; ++i) {
         const auto* next{last_index->GetAncestor(next_height + i)};
         if (!next || !(next->nStatus & BLOCK_HAVE_DATA)) break;
-        tasks.emplace_back([this, hash = next->GetBlockHash(), pos = next->GetBlockPos()] {
+        if (auto followup{m_pool.Submit([this, hash = next->GetBlockHash(), pos = next->GetBlockPos()]() -> std::shared_ptr<const CBlock> {
             try {
                 if (auto block{std::make_shared<CBlock>()}; m_read_block(*block, pos, hash)) return block;
             } catch (std::exception&) {} // ConnectTip() retries failed read-ahead synchronously
-            return std::shared_ptr<CBlock>{};
-        });
+            return nullptr;
+        })}) m_followups.emplace_back(std::move(*followup));
     }
-    if (auto followups{m_pool.Submit(std::move(tasks))}) std::ranges::move(*followups, std::back_inserter(m_followups));
 }
 } // namespace node
diff --git a/src/node/blockfetcher.h b/src/node/blockfetcher.h
index e158132322..7d53b25317 100644
--- a/src/node/blockfetcher.h
+++ b/src/node/blockfetcher.h
@@ -26,7 +26,6 @@ namespace node {
 class BlockFetcher
 {
     using ReadBlockFn = std::function<bool(CBlock&, const FlatFilePos&, const uint256&)>;
-    using ReadTask = std::function<std::shared_ptr<const CBlock>()>;
 
     const ReadBlockFn m_read_block;
     const int32_t m_thread_count;
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
for DBCACHE in 3000; do \
  COMMITS="81006fa18ce7177ba36046ae35ee3198b48b5501 dcf775943e168813d898cbdb2092c654dfbf383b"; \
  STOP=968869; export CC=gcc CXX=g++; \
  BASE_DIR="/mnt/my_storage"; DATA_DIR="$BASE_DIR/BitcoinData"; LOG_DIR="$BASE_DIR/logs"; \
  mkdir -p "$DATA_DIR" "$LOG_DIR" && \
  python3 -c 'import fcntl, sys; f = open(sys.argv[1], "a"); fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB)' "$DATA_DIR/.lock" && \
  (echo ""; for c in $COMMITS; do git fetch -q origin "$c" 2>/dev/null || true; git log -1 --pretty='%h %s' "$c" || exit 1; done) && \
  (echo "" && echo "$(date -I) | reindex-chainstate | ${STOP} blocks | dbcache ${DBCACHE} | $(hostname) | $(uname -m) | $(lscpu | grep 'Model name' | head -1 | cut -d: -f2 | xargs) | $(nproc) threads | $(free -h | awk '/^Mem:/{print $2}') RAM | $(lsblk -snro NAME,TYPE,ROTA,TRAN "$(findmnt -nvo SOURCE -T "$BASE_DIR")" 2>/dev/null | awk '\
    $2 == "disk" { k=$1 ~ /^mmcblk/ ? "SD/MMC" : $1 ~ /^(vd|xvd|nbd)/ ? "unknown (virtual)" : $3 == 1 ? "HDD" : $4 == "usb" ? "unknown (USB flash/SSD/SD)" : $3 == 0 ? "SSD (reported nonrotational)" : "unknown"; seen[k]=1 } \
    END { for (k in seen) { n++; result=k } print (n > 1 ? "mixed media" : n == 1 ? result : "unknown") }')"; echo "") && \
  hyperfine --shell 'bash -euo pipefail' \
  --sort command \
  --runs 1 \
  --export-json "$BASE_DIR/rdx-$(printf '%.8s-' $COMMITS)$STOP-$DBCACHE-$CC.json" \
  --parameter-list COMMIT "${COMMITS// /,}" \
  --setup "git clean -fxd; git reset --hard {COMMIT} && \
    cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Release && ninja -C build bitcoind -j1" \
  --prepare "./build/bin/bitcoind -datadir=\"$DATA_DIR\" -stopatheight=$STOP -printtoconsole=0 && sleep 20 && rm -f \"$DATA_DIR\"/debug.log && sync && echo 3 | sudo tee /proc/sys/vm/drop_caches >/dev/null" \
    --conclude "cp \"$DATA_DIR\"/debug.log \"$LOG_DIR/debug-{COMMIT}-\$(date +%s).log\"; sleep 5; \
      grep -Eq 'height=0([^0-9]|$)' \"$DATA_DIR\"/debug.log && \
      grep -Eq 'height=$STOP([^0-9]|$)' \"$DATA_DIR\"/debug.log && \
      grep -Fq \"version \$(./build/bin/bitcoind -version | sed -En '1s/.* version ([^ ]+).*/\1/p') \" \"$DATA_DIR\"/debug.log" \
  "./build/bin/bitcoind -datadir=\"$DATA_DIR\" -stopatheight=$STOP -dbcache=$DBCACHE -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0"; \
done

81006fa18c doc: add block read-ahead release note
dcf775943e 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

Benchmark 1: ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=3000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = 81006fa18ce7177ba36046ae35ee3198b48b5501)
  Time (abs ≡):        8209.909 s               [User: 20215.701 s, System: 1796.500 s]
 
Benchmark 2: ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=3000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = dcf775943e168813d898cbdb2092c654dfbf383b)
  Time (abs ≡):        8253.195 s               [User: 20154.134 s, System: 1596.314 s]
 
Relative speed comparison
        1.00          ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=3000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = 81006fa18ce7177ba36046ae35ee3198b48b5501)
        1.01          ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=3000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = dcf775943e168813d898cbdb2092c654dfbf383b)

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
for DBCACHE in 1000 3000; do \                                                                                                                                                                                                                                                                      
  COMMITS="99252a0a4a89c39820663d66c4765d7b53bcc821 81006fa18ce7177ba36046ae35ee3198b48b5501"; \                                                                                                                                                                                                                                          
  STOP=968869; export CC=gcc CXX=g++; \                                                                                                                                                                                                                                                                                                   
  BASE_DIR="/mnt/my_storage"; DATA_DIR="$BASE_DIR/BitcoinData"; LOG_DIR="$BASE_DIR/logs"; \                                                                                                                                                                                                                                               
  mkdir -p "$DATA_DIR" "$LOG_DIR" && \                                                                                                                                                                                                                                                                                                    
  python3 -c 'import fcntl, sys; f = open(sys.argv[1], "a"); fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB)' "$DATA_DIR/.lock" && \                                                                                                                                                                                                        
  (echo ""; for c in $COMMITS; do git fetch -q origin "$c" 2>/dev/null || true; git log -1 --pretty='%h %s' "$c" || exit 1; done) && \                                                                                                                                                                                                    
  (echo "" && echo "$(date -I) | reindex-chainstate | ${STOP} blocks | dbcache ${DBCACHE} | $(hostname) | $(uname -m) | $(lscpu | grep 'Model name' | head -1 | cut -d: -f2 | xargs) | $(nproc) threads | $(free -h | awk '/^Mem:/{print $2}') RAM | $(lsblk -snro NAME,TYPE,ROTA,TRAN "$(findmnt -nvo SOURCE -T "$BASE_DIR")" 2>/dev/null | awk '\                                                                         
    $2 == "disk" { k=$1 ~ /^mmcblk/ ? "SD/MMC" : $1 ~ /^(vd|xvd|nbd)/ ? "unknown (virtual)" : $3 == 1 ? "HDD" : $4 == "usb" ? "unknown (USB flash/SSD/SD)" : $3 == 0 ? "SSD (reported nonrotational)" : "unknown"; seen[k]=1 } \                                                                                                          
    END { for (k in seen) { n++; result=k } print (n > 1 ? "mixed media" : n == 1 ? result : "unknown") }')"; echo "") && \                                          
  hyperfine --shell 'bash -euo pipefail' \                                        
  --sort command \                                                                
  --runs 1 \                                                                      
  --export-json "$BASE_DIR/rdx-$(printf '%.8s-' $COMMITS)$STOP-$DBCACHE-$CC.json" \                                                                                  
  --parameter-list COMMIT "${COMMITS// /,}" \                                     
  --setup "git clean -fxd; git reset --hard {COMMIT} && \                         
    cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Release && ninja -C build bitcoind -j1" \                                                                             
  --prepare "./build/bin/bitcoind -datadir=\"$DATA_DIR\" -stopatheight=$STOP -printtoconsole=0 && sleep 20 && rm -f \"$DATA_DIR\"/debug.log && sync && echo 3 | sudo tee /proc/sys/vm/drop_caches >/dev/null" \                                                                                                                           
    --conclude "cp \"$DATA_DIR\"/debug.log \"$LOG_DIR/debug-{COMMIT}-\$(date +%s).log\"; sleep 5; \                                                                  
      grep -Eq 'height=0([^0-9]|$)' \"$DATA_DIR\"/debug.log && \                                                                                                     
      grep -Eq 'height=$STOP([^0-9]|$)' \"$DATA_DIR\"/debug.log && \                                                                                                 
      grep -Fq \"version \$(./build/bin/bitcoind -version | sed -En '1s/.* version ([^ ]+).*/\1/p') \" \"$DATA_DIR\"/debug.log" \                                                                                                                                                                                                         
  "./build/bin/bitcoind -datadir=\"$DATA_DIR\" -stopatheight=$STOP -dbcache=$DBCACHE -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0"; \                                                                   
done                                                                              

99252a0a4a test: characterize block connection cache use                          
81006fa18c doc: add block read-ahead release note                                 

2026-10-13 | reindex-chainstate | 968869 blocks | dbcache 1000 | i9-ssd | x86_64 | Intel(R) Core(TM) i9-9900K CPU @ 3.60GHz | 16 threads | 62Gi RAM | SSD (reported nonrotational)                                                                                                                                                        

Benchmark 1: ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=1000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = 99252a0a4a89c39820663d66c4765d7b53bcc821)                                                                              
  Time (abs ≡):        14120.107 s               [User: 29406.097 s, System: 1603.310 s]                                                                             
                                                                                  
Benchmark 2: ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=1000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = 81006fa18ce7177ba36046ae35ee3198b48b5501)                                                                              
  Time (abs ≡):        8860.643 s               [User: 31706.561 s, System: 1674.162 s]                                                                              
                                                                                  
Relative speed comparison                                                         
        1.59          ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=1000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = 99252a0a4a89c39820663d66c4765d7b53bcc821)                                                                     
        1.00          ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=1000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = 81006fa18ce7177ba36046ae35ee3198b48b5501)                                                                     

99252a0a4a test: characterize block connection cache use                          
81006fa18c doc: add block read-ahead release note                                 

2026-10-13 | reindex-chainstate | 968869 blocks | dbcache 3000 | i9-ssd | x86_64 | Intel(R) Core(TM) i9-9900K CPU @ 3.60GHz | 16 threads | 62Gi RAM | SSD (reported nonrotational)                                                                                                                                                        

Benchmark 1: ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=3000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = 99252a0a4a89c39820663d66c4765d7b53bcc821)                                                                              
  Time (abs ≡):        14186.928 s               [User: 23973.212 s, System: 1048.147 s]
  
Benchmark 2: ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=3000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = 81006fa18ce7177ba36046ae35ee3198b48b5501)                                                                              
  Time (abs ≡):        8741.336 s               [User: 25051.586 s, System: 1068.567 s]
  
Relative speed comparison
        1.62          ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=3000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = 99252a0a4a89c39820663d66c4765d7b53bcc821)                                                                     
        1.00          ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=3000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = 81006fa18ce7177ba36046ae35ee3198b48b5501)
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
for DBCACHE in 1000 3000; do \                                                                                                                                                                                                                                     
  COMMITS="99252a0a4a89c39820663d66c4765d7b53bcc821 81006fa18ce7177ba36046ae35ee3198b48b5501"; \                                                                                                                                                                                                         
  STOP=968869; export CC=gcc CXX=g++; \                                                                                                                                                                                                                                                                  
  BASE_DIR="/mnt/my_storage"; DATA_DIR="$BASE_DIR/BitcoinData"; LOG_DIR="$BASE_DIR/logs"; \                                                                                                                                                                                                              
  mkdir -p "$DATA_DIR" "$LOG_DIR" && \                                                                                                                                                                                                                                                                   
  python3 -c 'import fcntl, sys; f = open(sys.argv[1], "a"); fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB)' "$DATA_DIR/.lock" && \                                                                                                                                                                       
  (echo ""; for c in $COMMITS; do git fetch -q origin "$c" 2>/dev/null || true; git log -1 --pretty='%h %s' "$c" || exit 1; done) && \                                                                                                                                                                   
  (echo "" && echo "$(date -I) | reindex-chainstate | ${STOP} blocks | dbcache ${DBCACHE} | $(hostname) | $(uname -m) | $(lscpu | grep 'Model name' | head -1 | cut -d: -f2 | xargs) | $(nproc) threads | $(free -h | awk '/^Mem:/{print $2}') RAM | $(lsblk -snro NAME,TYPE,ROTA,TRAN "$(findmnt -nvo SO
URCE -T "$BASE_DIR")" 2>/dev/null | awk '\                                                                                                                                                                                                                                                               
    $2 == "disk" { k=$1 ~ /^mmcblk/ ? "SD/MMC" : $1 ~ /^(vd|xvd|nbd)/ ? "unknown (virtual)" : $3 == 1 ? "HDD" : $4 == "usb" ? "unknown (USB flash/SSD/SD)" : $3 == 0 ? "SSD (reported nonrotational)" : "unknown"; seen[k]=1 } \                                                                         
    END { for (k in seen) { n++; result=k } print (n > 1 ? "mixed media" : n == 1 ? result : "unknown") }')"; echo "") && \                                                                                                                                                                              
  hyperfine --shell 'bash -euo pipefail' \                                                                                                                                                                                                                                                               
  --sort command \                                                                                                                                                                                                                                                                                       
  --runs 1 \                                                                                                                                                                                                                                                                                             
  --export-json "$BASE_DIR/rdx-$(printf '%.8s-' $COMMITS)$STOP-$DBCACHE-$CC.json" \                                                                                                                                                                                                                      
  --parameter-list COMMIT "${COMMITS// /,}" \                                                                                                                                                                                       
  --setup "git clean -fxd; git reset --hard {COMMIT} && \                                                                                                                                                                           
    cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Release && ninja -C build bitcoind -j1" \                                                                                                                                            
  --prepare "./build/bin/bitcoind -datadir=\"$DATA_DIR\" -stopatheight=$STOP -printtoconsole=0 && sleep 20 && rm -f \"$DATA_DIR\"/debug.log && sync && echo 3 | sudo tee /proc/sys/vm/drop_caches >/dev/null" \                     
    --conclude "cp \"$DATA_DIR\"/debug.log \"$LOG_DIR/debug-{COMMIT}-\$(date +%s).log\"; sleep 5; \                                                                                                                                                     
      grep -Eq 'height=0([^0-9]|$)' \"$DATA_DIR\"/debug.log && \                                                                                                                                                                    
      grep -Eq 'height=$STOP([^0-9]|$)' \"$DATA_DIR\"/debug.log && \                                                                                                                                                                
      grep -Fq \"version \$(./build/bin/bitcoind -version | sed -En '1s/.* version ([^ ]+).*/\1/p') \" \"$DATA_DIR\"/debug.log" \                                                                                                   
  "./build/bin/bitcoind -datadir=\"$DATA_DIR\" -stopatheight=$STOP -dbcache=$DBCACHE -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0"; \
done                                                                                                                                                                                                                                
                                                                                                                                                                                                                                    
99252a0a test: characterize block connection cache use                                                                                                                                                                                                  
81006fa1 doc: add block read-ahead release note                                                                                                                                                                                     
                                                                                                                                                                                                                                    
2026-10-13 | reindex-chainstate | 968869 blocks | dbcache 1000 | i7-hdd | x86_64 | Intel(R) Core(TM) i7-7700 CPU @ 3.60GHz | 8 threads | 62Gi RAM | HDD                                                                             
                                                                                                                  
Benchmark 1: ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=1000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = 9925
2a0a4a89c39820663d66c4765d7b53bcc821)                                                                                                                                                                                                                                                    
  Time (abs ≡):        28121.273 s               [User: 32327.904 s, System: 1700.115 s]                                                                                                                                            
                                                                                                                  
Benchmark 2: ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=1000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = 8100
6fa18ce7177ba36046ae35ee3198b48b5501)                                                                                                                                                                                                                   
  Time (abs ≡):        19444.230 s               [User: 35364.384 s, System: 1814.729 s]                                                            
                                                                                                                                                                                                                                                        
Relative speed comparison                                                                                                                                                                                                           
        1.45          ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=1000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMM
IT = 99252a0a4a89c39820663d66c4765d7b53bcc821)                                                                                                                                                                                      
        1.00          ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=1000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMM
IT = 81006fa18ce7177ba36046ae35ee3198b48b5501)                                                                    
                                                                                                                  
99252a0a test: characterize block connection cache use                                                                      
81006fa1 doc: add block read-ahead release note                                                                                                                                                                                     
                                                                                                                            
2026-10-14 | reindex-chainstate | 968869 blocks | dbcache 3000 | i7-hdd | x86_64 | Intel(R) Core(TM) i7-7700 CPU @ 3.60GHz | 8 threads | 62Gi RAM | HDD                                                                             
                                                                                                                  
Benchmark 1: ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=3000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = 9925
2a0a4a89c39820663d66c4765d7b53bcc821)                                                                             
  Time (abs ≡):        27015.804 s               [User: 26895.784 s, System: 1210.885 s]                                                                                                                                            
                                                                                                                  
Benchmark 2: ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=3000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = 8100
6fa18ce7177ba36046ae35ee3198b48b5501)                    
  Time (abs ≡):        16243.500 s               [User: 27838.870 s, System: 1222.553 s]                                                            
                                                                                                                                                                                                                                    
Relative speed comparison                                                                                                                                                                                                           
        1.66          ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=3000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMM
IT = 99252a0a4a89c39820663d66c4765d7b53bcc821)                                                                                                                                                                                      
        1.00          ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=3000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMM
IT = 81006fa18ce7177ba36046ae35ee3198b48b5501)
> Maybe it is worth reverting to single task submission 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. <details><summary>temp: use single-task block read-ahead submission</summary> ```diff diff --git a/src/node/blockfetcher.cpp b/src/node/blockfetcher.cpp index 5e7465cbce..518086d4e0 100644 --- a/src/node/blockfetcher.cpp +++ b/src/node/blockfetcher.cpp @@ -17,10 +17,8 @@ #include <algorithm> #include <cstddef> #include <exception> -#include <iterator> #include <memory> #include <utility> -#include <vector> namespace node { BlockFetcher::BlockFetcher(ReadBlockFn read_block, int32_t thread_count) @@ -54,17 +52,15 @@ void BlockFetcher::FillQueue(const CBlockIndex* last_index, int next_height) Clear(); return; } - std::vector<ReadTask> tasks; for (size_t i{m_followups.size()}; i < m_thread_count * BLOCKS_PER_READ_AHEAD_THREAD; ++i) { const auto* next{last_index->GetAncestor(next_height + i)}; if (!next || !(next->nStatus & BLOCK_HAVE_DATA)) break; - tasks.emplace_back([this, hash = next->GetBlockHash(), pos = next->GetBlockPos()] { + if (auto followup{m_pool.Submit([this, hash = next->GetBlockHash(), pos = next->GetBlockPos()]() -> std::shared_ptr<const CBlock> { try { if (auto block{std::make_shared<CBlock>()}; m_read_block(*block, pos, hash)) return block; } catch (std::exception&) {} // ConnectTip() retries failed read-ahead synchronously - return std::shared_ptr<CBlock>{}; - }); + return nullptr; + })}) m_followups.emplace_back(std::move(*followup)); } - if (auto followups{m_pool.Submit(std::move(tasks))}) std::ranges::move(*followups, std::back_inserter(m_followups)); } } // namespace node diff --git a/src/node/blockfetcher.h b/src/node/blockfetcher.h index e158132322..7d53b25317 100644 --- a/src/node/blockfetcher.h +++ b/src/node/blockfetcher.h @@ -26,7 +26,6 @@ namespace node { class BlockFetcher { using ReadBlockFn = std::function<bool(CBlock&, const FlatFilePos&, const uint256&)>; - using ReadTask = std::function<std::shared_ptr<const CBlock>()>; const ReadBlockFn m_read_block; const int32_t m_thread_count; ``` </details> <details><summary>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</summary> ```python for DBCACHE in 3000; do \ COMMITS="81006fa18ce7177ba36046ae35ee3198b48b5501 dcf775943e168813d898cbdb2092c654dfbf383b"; \ STOP=968869; export CC=gcc CXX=g++; \ BASE_DIR="/mnt/my_storage"; DATA_DIR="$BASE_DIR/BitcoinData"; LOG_DIR="$BASE_DIR/logs"; \ mkdir -p "$DATA_DIR" "$LOG_DIR" && \ python3 -c 'import fcntl, sys; f = open(sys.argv[1], "a"); fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB)' "$DATA_DIR/.lock" && \ (echo ""; for c in $COMMITS; do git fetch -q origin "$c" 2>/dev/null || true; git log -1 --pretty='%h %s' "$c" || exit 1; done) && \ (echo "" && echo "$(date -I) | reindex-chainstate | ${STOP} blocks | dbcache ${DBCACHE} | $(hostname) | $(uname -m) | $(lscpu | grep 'Model name' | head -1 | cut -d: -f2 | xargs) | $(nproc) threads | $(free -h | awk '/^Mem:/{print $2}') RAM | $(lsblk -snro NAME,TYPE,ROTA,TRAN "$(findmnt -nvo SOURCE -T "$BASE_DIR")" 2>/dev/null | awk '\ $2 == "disk" { k=$1 ~ /^mmcblk/ ? "SD/MMC" : $1 ~ /^(vd|xvd|nbd)/ ? "unknown (virtual)" : $3 == 1 ? "HDD" : $4 == "usb" ? "unknown (USB flash/SSD/SD)" : $3 == 0 ? "SSD (reported nonrotational)" : "unknown"; seen[k]=1 } \ END { for (k in seen) { n++; result=k } print (n > 1 ? "mixed media" : n == 1 ? result : "unknown") }')"; echo "") && \ hyperfine --shell 'bash -euo pipefail' \ --sort command \ --runs 1 \ --export-json "$BASE_DIR/rdx-$(printf '%.8s-' $COMMITS)$STOP-$DBCACHE-$CC.json" \ --parameter-list COMMIT "${COMMITS// /,}" \ --setup "git clean -fxd; git reset --hard {COMMIT} && \ cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Release && ninja -C build bitcoind -j1" \ --prepare "./build/bin/bitcoind -datadir=\"$DATA_DIR\" -stopatheight=$STOP -printtoconsole=0 && sleep 20 && rm -f \"$DATA_DIR\"/debug.log && sync && echo 3 | sudo tee /proc/sys/vm/drop_caches >/dev/null" \ --conclude "cp \"$DATA_DIR\"/debug.log \"$LOG_DIR/debug-{COMMIT}-\$(date +%s).log\"; sleep 5; \ grep -Eq 'height=0([^0-9]|$)' \"$DATA_DIR\"/debug.log && \ grep -Eq 'height=$STOP([^0-9]|$)' \"$DATA_DIR\"/debug.log && \ grep -Fq \"version \$(./build/bin/bitcoind -version | sed -En '1s/.* version ([^ ]+).*/\1/p') \" \"$DATA_DIR\"/debug.log" \ "./build/bin/bitcoind -datadir=\"$DATA_DIR\" -stopatheight=$STOP -dbcache=$DBCACHE -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0"; \ done 81006fa18c doc: add block read-ahead release note dcf775943e 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 Benchmark 1: ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=3000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = 81006fa18ce7177ba36046ae35ee3198b48b5501) Time (abs ≡): 8209.909 s [User: 20215.701 s, System: 1796.500 s] Benchmark 2: ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=3000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = dcf775943e168813d898cbdb2092c654dfbf383b) Time (abs ≡): 8253.195 s [User: 20154.134 s, System: 1596.314 s] Relative speed comparison 1.00 ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=3000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = 81006fa18ce7177ba36046ae35ee3198b48b5501) 1.01 ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=3000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = dcf775943e168813d898cbdb2092c654dfbf383b) ``` </details> ---- Edit: I also checked general speedup, it's still blazing fast for reindexes, 50-60% faster: <details><summary>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 </summary> ```bash for DBCACHE in 1000 3000; do \ COMMITS="99252a0a4a89c39820663d66c4765d7b53bcc821 81006fa18ce7177ba36046ae35ee3198b48b5501"; \ STOP=968869; export CC=gcc CXX=g++; \ BASE_DIR="/mnt/my_storage"; DATA_DIR="$BASE_DIR/BitcoinData"; LOG_DIR="$BASE_DIR/logs"; \ mkdir -p "$DATA_DIR" "$LOG_DIR" && \ python3 -c 'import fcntl, sys; f = open(sys.argv[1], "a"); fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB)' "$DATA_DIR/.lock" && \ (echo ""; for c in $COMMITS; do git fetch -q origin "$c" 2>/dev/null || true; git log -1 --pretty='%h %s' "$c" || exit 1; done) && \ (echo "" && echo "$(date -I) | reindex-chainstate | ${STOP} blocks | dbcache ${DBCACHE} | $(hostname) | $(uname -m) | $(lscpu | grep 'Model name' | head -1 | cut -d: -f2 | xargs) | $(nproc) threads | $(free -h | awk '/^Mem:/{print $2}') RAM | $(lsblk -snro NAME,TYPE,ROTA,TRAN "$(findmnt -nvo SOURCE -T "$BASE_DIR")" 2>/dev/null | awk '\ $2 == "disk" { k=$1 ~ /^mmcblk/ ? "SD/MMC" : $1 ~ /^(vd|xvd|nbd)/ ? "unknown (virtual)" : $3 == 1 ? "HDD" : $4 == "usb" ? "unknown (USB flash/SSD/SD)" : $3 == 0 ? "SSD (reported nonrotational)" : "unknown"; seen[k]=1 } \ END { for (k in seen) { n++; result=k } print (n > 1 ? "mixed media" : n == 1 ? result : "unknown") }')"; echo "") && \ hyperfine --shell 'bash -euo pipefail' \ --sort command \ --runs 1 \ --export-json "$BASE_DIR/rdx-$(printf '%.8s-' $COMMITS)$STOP-$DBCACHE-$CC.json" \ --parameter-list COMMIT "${COMMITS// /,}" \ --setup "git clean -fxd; git reset --hard {COMMIT} && \ cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Release && ninja -C build bitcoind -j1" \ --prepare "./build/bin/bitcoind -datadir=\"$DATA_DIR\" -stopatheight=$STOP -printtoconsole=0 && sleep 20 && rm -f \"$DATA_DIR\"/debug.log && sync && echo 3 | sudo tee /proc/sys/vm/drop_caches >/dev/null" \ --conclude "cp \"$DATA_DIR\"/debug.log \"$LOG_DIR/debug-{COMMIT}-\$(date +%s).log\"; sleep 5; \ grep -Eq 'height=0([^0-9]|$)' \"$DATA_DIR\"/debug.log && \ grep -Eq 'height=$STOP([^0-9]|$)' \"$DATA_DIR\"/debug.log && \ grep -Fq \"version \$(./build/bin/bitcoind -version | sed -En '1s/.* version ([^ ]+).*/\1/p') \" \"$DATA_DIR\"/debug.log" \ "./build/bin/bitcoind -datadir=\"$DATA_DIR\" -stopatheight=$STOP -dbcache=$DBCACHE -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0"; \ done 99252a0a4a test: characterize block connection cache use 81006fa18c doc: add block read-ahead release note 2026-10-13 | reindex-chainstate | 968869 blocks | dbcache 1000 | i9-ssd | x86_64 | Intel(R) Core(TM) i9-9900K CPU @ 3.60GHz | 16 threads | 62Gi RAM | SSD (reported nonrotational) Benchmark 1: ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=1000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = 99252a0a4a89c39820663d66c4765d7b53bcc821) Time (abs ≡): 14120.107 s [User: 29406.097 s, System: 1603.310 s] Benchmark 2: ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=1000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = 81006fa18ce7177ba36046ae35ee3198b48b5501) Time (abs ≡): 8860.643 s [User: 31706.561 s, System: 1674.162 s] Relative speed comparison 1.59 ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=1000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = 99252a0a4a89c39820663d66c4765d7b53bcc821) 1.00 ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=1000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = 81006fa18ce7177ba36046ae35ee3198b48b5501) 99252a0a4a test: characterize block connection cache use 81006fa18c doc: add block read-ahead release note 2026-10-13 | reindex-chainstate | 968869 blocks | dbcache 3000 | i9-ssd | x86_64 | Intel(R) Core(TM) i9-9900K CPU @ 3.60GHz | 16 threads | 62Gi RAM | SSD (reported nonrotational) Benchmark 1: ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=3000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = 99252a0a4a89c39820663d66c4765d7b53bcc821) Time (abs ≡): 14186.928 s [User: 23973.212 s, System: 1048.147 s] Benchmark 2: ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=3000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = 81006fa18ce7177ba36046ae35ee3198b48b5501) Time (abs ≡): 8741.336 s [User: 25051.586 s, System: 1068.567 s] Relative speed comparison 1.62 ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=3000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = 99252a0a4a89c39820663d66c4765d7b53bcc821) 1.00 ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=3000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = 81006fa18ce7177ba36046ae35ee3198b48b5501) ``` </details> <details><summary>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</summary> ```bash for DBCACHE in 1000 3000; do \ COMMITS="99252a0a4a89c39820663d66c4765d7b53bcc821 81006fa18ce7177ba36046ae35ee3198b48b5501"; \ STOP=968869; export CC=gcc CXX=g++; \ BASE_DIR="/mnt/my_storage"; DATA_DIR="$BASE_DIR/BitcoinData"; LOG_DIR="$BASE_DIR/logs"; \ mkdir -p "$DATA_DIR" "$LOG_DIR" && \ python3 -c 'import fcntl, sys; f = open(sys.argv[1], "a"); fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB)' "$DATA_DIR/.lock" && \ (echo ""; for c in $COMMITS; do git fetch -q origin "$c" 2>/dev/null || true; git log -1 --pretty='%h %s' "$c" || exit 1; done) && \ (echo "" && echo "$(date -I) | reindex-chainstate | ${STOP} blocks | dbcache ${DBCACHE} | $(hostname) | $(uname -m) | $(lscpu | grep 'Model name' | head -1 | cut -d: -f2 | xargs) | $(nproc) threads | $(free -h | awk '/^Mem:/{print $2}') RAM | $(lsblk -snro NAME,TYPE,ROTA,TRAN "$(findmnt -nvo SO URCE -T "$BASE_DIR")" 2>/dev/null | awk '\ $2 == "disk" { k=$1 ~ /^mmcblk/ ? "SD/MMC" : $1 ~ /^(vd|xvd|nbd)/ ? "unknown (virtual)" : $3 == 1 ? "HDD" : $4 == "usb" ? "unknown (USB flash/SSD/SD)" : $3 == 0 ? "SSD (reported nonrotational)" : "unknown"; seen[k]=1 } \ END { for (k in seen) { n++; result=k } print (n > 1 ? "mixed media" : n == 1 ? result : "unknown") }')"; echo "") && \ hyperfine --shell 'bash -euo pipefail' \ --sort command \ --runs 1 \ --export-json "$BASE_DIR/rdx-$(printf '%.8s-' $COMMITS)$STOP-$DBCACHE-$CC.json" \ --parameter-list COMMIT "${COMMITS// /,}" \ --setup "git clean -fxd; git reset --hard {COMMIT} && \ cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Release && ninja -C build bitcoind -j1" \ --prepare "./build/bin/bitcoind -datadir=\"$DATA_DIR\" -stopatheight=$STOP -printtoconsole=0 && sleep 20 && rm -f \"$DATA_DIR\"/debug.log && sync && echo 3 | sudo tee /proc/sys/vm/drop_caches >/dev/null" \ --conclude "cp \"$DATA_DIR\"/debug.log \"$LOG_DIR/debug-{COMMIT}-\$(date +%s).log\"; sleep 5; \ grep -Eq 'height=0([^0-9]|$)' \"$DATA_DIR\"/debug.log && \ grep -Eq 'height=$STOP([^0-9]|$)' \"$DATA_DIR\"/debug.log && \ grep -Fq \"version \$(./build/bin/bitcoind -version | sed -En '1s/.* version ([^ ]+).*/\1/p') \" \"$DATA_DIR\"/debug.log" \ "./build/bin/bitcoind -datadir=\"$DATA_DIR\" -stopatheight=$STOP -dbcache=$DBCACHE -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0"; \ done 99252a0a test: characterize block connection cache use 81006fa1 doc: add block read-ahead release note 2026-10-13 | reindex-chainstate | 968869 blocks | dbcache 1000 | i7-hdd | x86_64 | Intel(R) Core(TM) i7-7700 CPU @ 3.60GHz | 8 threads | 62Gi RAM | HDD Benchmark 1: ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=1000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = 9925 2a0a4a89c39820663d66c4765d7b53bcc821) Time (abs ≡): 28121.273 s [User: 32327.904 s, System: 1700.115 s] Benchmark 2: ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=1000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = 8100 6fa18ce7177ba36046ae35ee3198b48b5501) Time (abs ≡): 19444.230 s [User: 35364.384 s, System: 1814.729 s] Relative speed comparison 1.45 ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=1000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMM IT = 99252a0a4a89c39820663d66c4765d7b53bcc821) 1.00 ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=1000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMM IT = 81006fa18ce7177ba36046ae35ee3198b48b5501) 99252a0a test: characterize block connection cache use 81006fa1 doc: add block read-ahead release note 2026-10-14 | reindex-chainstate | 968869 blocks | dbcache 3000 | i7-hdd | x86_64 | Intel(R) Core(TM) i7-7700 CPU @ 3.60GHz | 8 threads | 62Gi RAM | HDD Benchmark 1: ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=3000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = 9925 2a0a4a89c39820663d66c4765d7b53bcc821) Time (abs ≡): 27015.804 s [User: 26895.784 s, System: 1210.885 s] Benchmark 2: ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=3000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMMIT = 8100 6fa18ce7177ba36046ae35ee3198b48b5501) Time (abs ≡): 16243.500 s [User: 27838.870 s, System: 1222.553 s] Relative speed comparison 1.66 ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=3000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMM IT = 99252a0a4a89c39820663d66c4765d7b53bcc821) 1.00 ./build/bin/bitcoind -datadir="/mnt/my_storage/BitcoinData" -stopatheight=968869 -dbcache=3000 -reindex-chainstate -assumevalid=00000000000000000000748969ec33043c0e52a763c6dd5193861f559f2c72e3 -blocksonly -disablewallet -connect=0 -listen=0 -dnsseed=0 -printtoconsole=0 (COMM IT = 81006fa18ce7177ba36046ae35ee3198b48b5501) ``` </details>
andrewtoth (Migrated from github.com) approved these changes 2026-10-18 19:01:31 +00:00
andrewtoth (Migrated from github.com) left a comment
ACK 81006fa18ce7177ba36046ae35ee3198b48b5501
andrewtoth (Migrated from github.com) commented 2026-10-18 18:57:09 +00:00

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.

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.
andrewtoth (Migrated from github.com) commented 2026-10-18 18:59:23 +00:00

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.

    //! Returns the block with the specified hash if it had been previously queued, otherwise nullptr.
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. ```suggestion //! Returns the block with the specified hash if it had been previously queued, otherwise nullptr. ```
andrewtoth (Migrated from github.com) commented 2026-10-18 19:00:16 +00:00

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

    //! Queue upcoming blocks to be read and deserialized asynchronously.
Same here, the block connection is an external use case for this class. ```suggestion //! Queue upcoming blocks to be read and deserialized asynchronously. ```
arejula27 commented 2026-11-19 17:34:11 +00:00 (Migrated from github.com)

ACK d62c4b5479

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

ACK d62c4b5479 I did not run benchmarks, the existing ones in the PR look sufficient
w0xlt (Migrated from github.com) reviewed 2026-11-19 18:55:30 +00:00
w0xlt (Migrated from github.com) left a comment

reACK d62c4b5479

reACK d62c4b54799a29fe33e45bc9d0b7462398c6b020
andrewtoth commented 2026-11-20 16:14:22 +00:00 (Migrated from github.com)

reACK d62c4b5479

reACK d62c4b54799a29fe33e45bc9d0b7462398c6b020
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
bitcoin/bitcoin!36000
No description provided.