mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 12:41:38 +00:00
wallet: parallel fast rescan #34400
No reviewers
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!34400
Loading…
Reference in a new issue
No description provided.
Delete branch "new-rescan"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
This PR speeds up wallet fast-rescan by executing the filter checks in parallel while ensuring that the filters are updated properly so that no output scripts are missed. Benchmarks, outlined below, show considerable improvement that slows down around
8threads.Prerequisite PRs
CWallet::ScanForWalletTransactionsto prepare for the work in this PR.Benchmarks
Prepare
pyperf system tune.blockfilterindex=1in your bitcoin.conf file and sync your node to the tip.chain.isInitialBlockDownload()istrue. Ensure your node is synced before shutting down and running the mainnet benchmark commands.Using the following command on mainnet with a wallet with no scripts and hyperfine version
1.20.0:Table 1 was obtained on a machine with the following specifications
Table 1. Table of results of a mainnet benchmark of scanning 200,000 blocks on a wallet with no scripts. An empty wallet is not representative of a typical wallet; the next benchmark tries to simulate more "interesting" scenarios.
This Python script patch python script creates custom chains designed with payments at specified intervals to observe the performance of parallel fast rescan.
Fig 1 shown below was produced using this patch on a machine with the following specifications
Fig 1. Time to scan a 2000-block chain on Regtest with payments at varying intervals, comparing parallel Fast Rescan against serial Fast Rescan (baseline). These benchmarks use the -walletpar commit as a baseline instead of master, since master lacks the
-walletparconfig parameter. All materials for this custom benchmark are available here.The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.
External sites
Reviews
See the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste
<!--meta-tag:bot-skip-->into the comment that the bot should ignore.Conflicts
Reviewers, this pull request conflicts with the following ones:
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.
🚧 At least one of the CI tasks failed.
Task
test max 6 ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/21320629356/job/61369934184LLM reason (✨ experimental): Compilation failed due to an unused private member (m_thread_pool) in wallet.h being treated as an error under -Werror.
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.
I would have expected rescanning to be I/O bound rather than CPU, in which case parallelization could make things worse (more random seeking). Have you benchmarked this on a non-SSD?
Fast rescan checks block filters, which involves considerable hashing. This PR parallelises the checking of block filters, and my benchmarks show considerable improvements in rescan speeds with block filters. Slow rescan, which is I/O bound, remains the same. I expect the speedup to be transferable to non-SSD machines, but I haven't benchmarked this.
This slows down the scanning no? All workers already process submit task in its own
WorkThreadjust randomly trying to acquire mutex from scanning thread is non sense to me.Are you referring to the
ThreadPool::m_mutex? This mutex is not held during task processing. It is only briefly held to access the work queue. CallingProcessTask()from the main thread does not slow down scanning; it gives the main thread work to do instead of wasting cycles waiting for results.Yep it's not held during task execution, but if main thread do a task, it cannot put new tasks to queue i.e. workers "fight" itself to read something and do nothing. The idea is main thread submit tasks faster than workers could finish to keep all of them busy otherwise there is no difference between 3 and 16 thread (~13 threads do nothing).
The main thread intentionally submits only up to
WORKERS_COUNTtasks before waiting, rather than continuously submitting. This allows it to pause and update filters whenever a payment is found, preventing unnecessary work on wallets with many transactions packed into a short block range.https://github.com/bitcoin/bitcoin/pull/33689 has been merged; the cherry-picked Threadpool commit has been removed.
I like the PR conceptually but I think it would be nice to first improve the current scanning code structure, then land the parallelization feature. The current code mixes a lot responsibilities.
Similar to what you did in 633531614f69de49733642fd19cc9eba830fbdea, but into a separate PR so we can first land some good building blocks for this to happen.
Some quick pseudo-code structuring how I imagine it, which is similar to yours:
Concept ACK
I moved the test change into https://github.com/bitcoin/bitcoin/pull/34667 and the
ScanForWalletTransactionsrefactor into https://github.com/bitcoin/bitcoin/pull/34681.I'll be putting this PR in draft while those PRs are open.
Concept ACK
I attempted to reproduce the benchmarks for this
But I did not use hyperfine, I used time
System: AMD Ryzen 7 7700, 16 cores, 64GB RAM, mainnet, blocks 500000–900000, 3 runs averaged.
Baseline (881ebc4730ad15bd26e3e32ee3c9ba9d6e05552d): single-threaded fast rescan,
-walletparhas no effect — consistently ~283s regardless of thread count.Parallel scan (48154b87e2fb303ca0f3d46da29a3fbbf8758a06): fast rescan with threadpool parallelism enabled via
-walletpar.Steps to reproduce
-blockfilterindex=1till it's done.testbench_script.shscript
chmod +x bench_script.sh./bench_script.shThe current steps to reproduce in the description are stale because the commit hashes have changed since your force pushes.
I've looked only at the 48154b8 "wallet: check blockfilters in parallel" commit partially.
In 48154b8 "wallet: check blockfilters in parallel"
It appears that
current_block_index + 1is equal tocompleteddue to aint current_block_index = completed - 1;above.In 48154b87e2fb303ca0f3d46da29a3fbbf8758a06 "wallet: check blockfilters in parallel"
These two conditions in this check seem redundant with the same two conditions in the following for loop.
In 48154b87e2fb303ca0f3d46da29a3fbbf8758a06 "wallet: check blockfilters in parallel"
So it appears this is a flow where multiple tasks can be submitted in one go. There is an overload method of
Submitthat accepts a range of tasks & pushes all of them in the queue within one acquisition of queue lock, while notifying all the waiting workers. I think this workflow can be benefitted with this method, an untested code snippet is below because this branch is not rebased over master that contains the ranged overload.github.com/bitcoin/bitcoin@ff7cdf633e/src/util/threadpool.h (L199-L220)In 48154b8 "wallet: check blockfilters in parallel"
I'm doubtful that putting the controller (non-worker) thread to process the threadpool tasks is helpful.
This threadpool is shared across wallets. It could be the case that multiple RPCs of different wallets could be called simultaneously. ProcessTask picks the first item from a shared queue in the threadpool. Can't it happen that this controller thread picks up the task of another RPC of another wallet, thereby distorting results (from a RPC latency point of view) of this one?
It is helpful. I had better results when I put the thread to work vs when I didn't.
True, this creates an argument to ditch the shared threadpool and create one at the begining of the scan process; the same way we initialise script threads in
ConnectBlockI was doubtful of the helpfulness of using processtask because of this cross-wallet/rpc operation.
Interesting, I had thought of not using the processtask function in the current thread pool setup as a way.
But an intra-wallet scan operation specific threadpool seems like a good alternative to consider.
I wll think of its implications.
I will check this when I rebase on master.
Fixed.
Fixed.
Done.
I have changed the implementation substantially. I have moved away from a shared ThreadPool to one that is initialized before scanning and discarded after.
ProcessTask()is now only used when the main thread needs to complete the queued up jobs before the processing the selected blocks.I have changed the implementation so that the main thread only joins task processing when it needs to clear the work queue (after a range of blocks to fetch and scan has been determined) before processing blocks. The number of blocks that can be submitted at once has been raised to
2 * WORKERS_COUNT, it is still kept low intentionally to reduce wasted work.I have measured it on an
Intel(R) Core(TM) i7-7700 CPUwith 8 cores, 64Gi RAM and a HDD:rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 1)rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 1)rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 2)rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 2)rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 3)rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 3)rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 4)rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 4)rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 5)rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 5)rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 6)rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 6)rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 7)rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 7)rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 8)rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 8)rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 9)rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 9)rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 16)rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 16)Hyperfine relative speed comparison
🐙 This pull request conflicts with the target branch and needs rebase.
I've made some improvements which have increased the speedup from 5x at 8 threads to 8x at 8 threads. 8x speedup seems to be the peak for now. The results have been updated in the PR description, https://github.com/bitcoin/bitcoin/pull/34400#issue-3851923967
I re-ran my script with the recent changes.
Rescan of blocks 500000-900000 (mean of 3 runs).
b36c2d7(master)I got a 6× speedup relative to master.
🐙 This pull request conflicts with the target branch and needs rebase.
Strong Concept ACK ae888e0, forgot to share it in the prior review.
I will get around to re-reviewing the prerequisite #34681 so that this can be moved forward.
4 additional verified findings in the Review report.
Earlier concerns neither republished nor resolved: 3 suggestions. See the Run archive linked from the Review report for their assessments.
🟠 Minor · Read-ahead retains stale successors after a reorg
A reorg within parallel read-ahead can turn a previously successful fast rescan into a rescan error or failed wallet load; retrying after the reorg recovers.
Location:
src/wallet/scan.cpp:432(head).🟠 Minor · Cached
NoMatchdelivery misses concurrent descriptor growthA notification-driven top-up during an unlocked parallel rescan can leave later cached
NoMatchresults stale, widening the pre-existing race and allowing a successful scan to omit a transaction.Location:
src/wallet/scan.cpp:450(head).🔵 Suggestion · The
-walletparthread limit is ambiguous for concurrent rescansConcurrent rescans of different wallets each receive up to 16 threads, but the release note does not make the per-rescan scope explicit.
Location:
src/wallet/scan.cpp:557(head).🔵 Suggestion · Cancellation still drains queued read-ahead filter checks
After an abort or shutdown request, parallel rescan teardown still executes every outstanding filter lookup, bounded by two read-ahead windows.
Location:
src/wallet/scan.cpp:218(head).🔵 Suggestion · Parallel tests do not distinguish the wallet tip from the node tip
The parallel tests do not exercise stopping at the wallet's processed tip while read-ahead can still obtain newer active-chain blocks.
Location:
src/wallet/test/rescan_tests.cpp:839(head).🔵 Suggestion · Abort coverage never tears down an active parallel scan
No rescan test aborts with parallel filter checks in flight, leaving the script-set lifetime and worker-join integration unexercised.
Location:
src/wallet/scan.cpp:180(head).Review coverage was incomplete.
Reviewed:
67940dc7573b· Review report · Previous reportspermalink
🐙 This pull request conflicts with the target branch and needs rebase.
🐙 This pull request conflicts with the target branch and needs rebase.
Putting in draft while I finalize some changes.
concept ACK
Will review when you force push and open it again :)
We replaced the previous implementation with a much simpler sliding-window implementation. New benchmark results are in https://github.com/bitcoin/bitcoin/pull/34400#issue-3851923967.
reviewed
15fa337407will review the other 4 commits tomorrow :)
in
c1b97000bcwallet/scan: combine block iteration and filtering in NextBlocksSerialnit: in many places you use
QueuedBlockand in others you use a pair of{block_hash, block_height}. I think you could just useQueuedBlockalways as it represents the same pair.diff
<\details>
in
c1b97000bcwallet/scan: combine block iteration and filtering in NextBlocksSerialThis is in fact a behavior change :)
in
fdb49a2b72wallet/scan: check block is active under cs_wallet before syncingAs a small nit, I think there were some discussions about not creating more "result" enum types, and start using
Expected. I think it would be cleaner to have aScanBlockErrortype and return those ifUnexpectedhappens.diff
in
15fa337407wallet: add -walletpar optionMaybe we should just throw here if
m_wallet_paris negative? I think we should require-walletparto be bigger than-GetNumCores()and smaller thanGetNumCores() + 1.Also
GetIntArgreturns an int64 whilem_wallet_paris a normal int you can overflow the integers and trick a bit the result. This obviously is weird and not critic, but I think is worth addressing as is easy to fix:Done.
Done.
reviewed
db2d769ff2I've just reviewed code, I've skipped tests.
There are a few ralph comments that I would say they are worth addressing. Specially in commit
5441a57e59where there are some edge cases that can make the rescan skip payments.I couldn't personally find anything else wrong in the behavior of
5441a57e59, and my LLM scan found the same as Ralph.in
5441a57e59wallet/scan: check block filters in parallelnit:
This shouldn't be uppercase. See https://github.com/bitcoin/bitcoin/blob/master/doc/developer-notes.md: "
Enumerator constants may be snake_case, or PascalCase. They should not be ALL_CAPS, according to the [C++ Core Guidelines](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#renum-caps), to avoid clashing with macros."Also should probably use an
enum classinstead of just anenumper developer notes: "Prefer enum class (scoped enumerations) over enum (traditional enumerations) where possible."in
ca3136699bwallet: don't rescan in parallel during IBDIn the case of IBD, if
m_wallet_par > 1probably should log that the value ofm_wallet_parwas ignored.I updated the commit message to mention this second lookup. I also updated the comment.
I've fixed the overflow issue, but the code still doesn't throw. I'm not convinced we need to throw here. I think silently using the maximum or minimum number of threads is good enough, rather than forcing the user to enter the correct num cores.
Done.
Done.
CI failure seems unrelated. See https://github.com/bitcoin/bitcoin/issues/36913
Is there a reason to drop the anonymous namespace around FastWalletRescanFilter? The class is still only used inside scan.cpp. Keeping it preserves internal linkage and removes an unrelated change from this commit.
nit: this can be simplified for readability.
Now that S
canContextholds the per-scan state,LoopStateseems redundant.LoopState's fields can be moved intoScanContext.UpdateProgressandUpdateTipIfChangedcan takectx, like the other helpers.That removes a struct and keeps all scan state in one place.
diff
nit:
nit:
🐙 This pull request conflicts with the target branch and needs rebase.
Done.
Done.
Done.
Done.
Done.
I am close to acking it :)
reviewed
cdbdfd8e93There are some Ralph comments interesting to address.
For example the one regarding
Reorg tests miss disconnection between lookup and transaction sync.Maybe something like, the diff below would do the job. (The test is ai so may have some errors, but just to give an idea)
It fails in master and passes on top of commit1.
test diff
faa01f0766wallet/scan: check block filters in parallelnit: PascalCase (also in the commit message)
in
5fbcd6331awallet/scan: check block is active under cs_wallet before syncingnit:
ReadFailedandNotActive.in
cdbdfd8e93test: cover serial and parallel fast rescan in wallet_fast_rescanthe debug log assert checks for
fast variant block filterbut that matches both for parallel and serial scan. Adding the(...)characters to the check would explicitly search for the serial one.Thanks, I missed this.
Done.
Done.
Done.
Sorry for the noise.
The test you suggested works; I added it and fixed the following issues raised by Ralph:
and I added a release note for -walletpar
From the remaining Ralph reports I think only this one is worth fixing.
It is a weird case, but I don't think it is a pretty behavior to have. IIUC a failure to create a thread would lock the wallet and would make it even unable to unload or try to re-load, you would need to restart the node.
A simple fix would be to fallback to serial if threads cannot be created:
Got a clanker to code a functional test to trigger it:
test
@polespinasa re: https://github.com/bitcoin/bitcoin/pull/34400#issuecomment-7408450566
Done.
ACK
67940dc757Nit: I think there is no need to create another test file for the thread failure casen, it can fit inside the wallet rescan one.