wallet: parallel fast rescan

bitcoin/bitcoin: PR #34400

3 minor findings · 5 suggestions

Earlier concerns neither republished nor resolved: 2 suggestions. See the Run archive for their assessments.

Findings

Link

[minor] · Parallel delivery can commit stale NO_MATCH verdicts after notification-driven top-ups

Parallel delivery widens a pre-existing top-up race: an unlocked rescan can report SUCCESS while skipping a historical payment to a newly derived script; no production occurrence was identified.

Location: src/wallet/scan.cpp:447 (head).

Details and suggested fix

NextBlocksParallel calls UpdateFilter() once before waiting and delivering verdicts. Consider two queued negatives, A and B, where A is unrelated and B pays a script just beyond the old descriptor range. During a rescanblockchain call, which releases cs_wallet before scanning, a notification paying an unused in-range address can top up the keypool while RecordSkipped(A) waits for that lock. The delivery loop then commits B's stale NO_MATCH without checking NeedsUpdate() again. The base refreshed the filter before checking B, so it would inspect B after that same notification. Once B is popped, subsequent delta checks cannot repair the omission, and the final mempool pass does not revisit its historical block.

Before committing each NO_MATCH, check for range changes under cs_wallet and retain the verdict for UpdateFilter() if the range changed. Keep the check and skip ordered against notification-driven top-ups. Add a regression test that completes a notification-driven top-up between two queued skips. AttachChain does not have this interleaving because it holds cs_wallet throughout; an affected unlocked scan requires another rescan to recover the omitted transaction.


Link

[minor] · Skipped-block batches can suppress GUI progress and cancellation

An all-skip parallel scan from an even height can omit all intermediate ShowProgress updates, leaving the GUI at 0% and preventing its Cancel button from requesting an abort.

Location: src/wallet/scan.cpp:586 (head).

Details and suggested fix

Without top-ups, Wait() collects one two-block task and the delivery loop consumes both negatives. Scan reports progress only for the last skipped height, while UpdateProgress emits ShowProgress only at exact multiples of 100. Complete batches starting at an even height therefore report only odd heights. A final one-block task may produce a notification, but only when that final height is divisible by 100. The base reported progress for every block. WalletView::showProgress checks wasCanceled() and calls abortRescan() only for intermediate notifications, so omitting them also prevents GUI cancellation from reaching the scanner. RPC progress and abortrescan remain available. Report progress when a batch crosses a 100-block boundary, and add an all-skip parallel test that starts at an even height and expects an intermediate notification.


Link

[minor] · Read-ahead retains stale successors across reorgs

Read-ahead widens the reorg window where rescans fail or end on stale blocks; notifications cover replacements only with scripts known when delivered, so later-derived payments can remain missing. Production frequency is unconfirmed.

Location: src/wallet/scan.cpp:429 (head).

Details and suggested fix

fill_queue resolves successors up to roughly two windows ahead, at most about 128 queued blocks with 16 threads. If a reorg forks ahead of the processed position but inside that range, the queue still contains the old branch. The base's one-block lookahead can reach the still-active common ancestor and obtain its replacement-chain successor. Here, a stale MATCH reaches ScanBlock, returns NOT_ACTIVE, and causes an RPC rescan error or wallet-load failure. Stale NO_MATCH entries are recorded as scanned; after delivery, successor lookup from the stale ctx.block_hash finds nothing.

Replacement blockConnected notifications ordinarily recover those blocks. During an unlocked rescan, however, they can run before processing a common-ancestor block derives the scripts needed for replacement payments. The serial scan subsequently revisits the replacements with those scripts, while this path ends on the old branch. Another rescan recovers the omitted history. Check activity before delivering queued blocks; on detecting a stale block, discard speculative work and resume successor lookup from the last processed active block. Add a serial/parallel regression test with the fork point inside the read-ahead range.


Optional improvements

Link

[suggestion] · Release notes omit -walletpar and the new parallel default

Eligible fast rescans now use up to 16 threads automatically, but no release note documents the resource change or explains that -walletpar=1 retains single-threaded scanning.

Location: src/wallet/init.cpp:79 (head).

Details and suggested fix

DEFAULT_WALLETPAR=0 resolves to GetNumCores(), clamped to 16 total threads including the calling thread. With a block-filter index and IBD finished, this changes the default CPU use of wallet rescans, including scans during wallet loading. Add a release-note snippet describing -walletpar, automatic sizing, the calling-thread accounting, and -walletpar=1 as the single-threaded setting. This gives operators controlling CPU use a discoverable explanation of the new default.


Link

[suggestion] · Reorg tests miss disconnection between lookup and transaction sync

The existing stale-block cases cannot distinguish the new locked activity check from the earlier lookup-time check.

Location: src/wallet/scan.cpp:513 (head).

Details and suggested fix

scan_for_wallet_transactions_reorged_block invalidates its target before calling Scan, so either check placement rejects the matching stale block. The new ordering matters when disconnection and its blockDisconnected notification occur after successor lookup but before transaction synchronization. Add a test using the ShowProgress hook pattern from scan_for_wallet_transactions_resume_after_tip: arrange a matching block at a height divisible by 100 in a nondegenerate scan range, invalidate it and deliver blockDisconnected from the intermediate hook, then assert that its transactions are not left confirmed in the stale block. Run it with serial and parallel filtering. This exercises the ordering that the check under cs_wallet protects.


Link

[suggestion] · -walletpar help leaves its per-scan resource scope unclear

Each parallel scan creates a private pool, so N concurrent rescans of different wallets can start up to N × 15 workers rather than sharing one -walletpar budget.

Location: src/wallet/scan.cpp:259 (head).

Details and suggested fix

Scan constructs a new ParallelFilterChecker, whose private pool starts num_threads - 1 workers. Reservations serialize scans only within one wallet, so concurrent multiwallet rescans each receive the full configured allowance and can oversubscribe the machine. The help text, “Set the number of wallet threads”, does not explain this scope. State explicitly that the limit applies per scan if that is intended. If it is meant to bound aggregate wallet concurrency instead, use a shared pool while retaining each scan's separate filter state and ordered verdict queue.


Link

[suggestion] · Optional worker creation can prevent a serial-capable rescan

If worker creation fails under thread limits, the rescan or wallet load fails instead of using the existing serial fast path; no triggering environment was identified.

Location: src/wallet/scan.cpp:550 (head).

Details and suggested fix

ParallelFilterChecker calls ThreadPool::Start, where std::thread construction can throw std::system_error. The uncaught exception escapes Scan, and startup wallet loading reports an initialization error. The automatic default can request 15 additional workers for an optimization that already has a serial implementation. Although existing pools also propagate startup failures, these workers are optional for completing the rescan. Catch the thread-creation exception around checker construction, log the fallback, and leave ctx.checker unset so NextBlocksSerial is selected. Unwinding the pool member already joins workers created before the failure.


Link

[suggestion] · Serial filter-update refactoring is mixed into the concurrency commit

The parallel-checking commit also rewrites the serial top-up path, making serial equivalence harder to validate independently of the new concurrency machinery.

Location: src/wallet/scan.cpp:119 at faa01f0766b2 (commit) (commit).

Details and suggested fix

In the commit tree of 635da2524406a6ba1281b904231e8b0e04e159f3, the preparatory iteration/filtering refactor still defines UpdateIfNeeded() and calls it from NextBlocksSerial. The parallel commit, faa01f0766b2c84796a2c79313dcfbc82cff4ff5, replaces that implementation with Update(), changes the range-end mutation and script insertion, and switches the serial caller while also adding the thread pool. Move the serial-only UpdateIfNeeded() to Update() rewrite and caller change into the preparatory commit, or a small refactor immediately afterward. Keep NeedsUpdate(), GetElementSet(), and the added delta parameter with their parallel consumer in faa01f0766b2c84796a2c79313dcfbc82cff4ff5. This leaves the final tree unchanged while allowing the serial behavior-preserving portion to be checked on its own.


Coverage details

Earlier concerns

Earlier reports raised these, with the titles and severities shown there. This review neither republished nor resolved them.

Background

Ralph's summary of historical context for the behaviour affected by this change. The historical record reviewed here is incomplete.

Documented decisions

Fast rescan's safety argument is conditional on checking the relevant script set: filter false positives only cost extra inspection, whereas negative results permit skipping blocks. The original descriptor-wallet proposal explicitly identified a fixed, once-created script set as insufficient because processing transactions can trigger keypool top-ups. It therefore refreshed newly derived scripts after descriptor ranges grew, while including fixed non-ranged scripts once.

The base refreshes scripts before each block-filter check. Parallel checks move that check ahead of transaction processing, so preserving the historical argument requires accounting for scripts derived after queued verdicts were computed. This concerns discovering wallet transactions, not merely maintaining the same filter hit rate.

Source 1

The wallet's last-processed height is a consistency boundary, not simply the node's current tip. Historical PR #31629 explains that scanning newly connected blocks before updating that wallet state could temporarily make the wallet inconsistent and crash the GUI. With cs_wallet held throughout AttachChain, new blocks belong to pending blockConnected notifications after lock release. Without the permanent lock, those blocks may be scanned again once blockConnected has advanced the wallet's last-processed state.

Batch production and read-ahead do not themselves authorize wallet synchronization beyond this boundary. The head's StopAtWalletTip retains the distinction between locked wallet-load scans and scans that allow notifications to interleave. AttachChain registers notifications before scanning so connections during the scan are not lost.

Source 1

Reorg recovery has historically relied on ordinary wallet notifications as well as the explicit rescan. In #12275, Ryan Ofsky explained dropping a proposed rescan retry loop because reorg notifications should scan the replacement blocks; ending early at a reorg therefore need not itself indicate missing wallet history.

This explains why rescan completion is not a claim that the scanner alone traversed every replacement block. The pinned base and head distinguish a filtered-out stale block from a stale block requiring transaction inspection, while relying on blockConnected for replacement-chain processing. The historical rationale assumes notifications remain registered and are eventually delivered.

Source 1 · Source 2 · Source 3

The saved best-block locator exists to resume wallet synchronization from its last known point, including after restoring an older wallet. Later checkpoint history explicitly rejected treating a chainstate flush as evidence that the wallet processed that block: those events need not coincide, and recording the flushed block could cause wallet blocks to be skipped.

Saved progress must be tied to wallet processing rather than filter submission, worker completion, or the node's tip. In both pinned versions, intermittent locator writes occur after synchronizing a readable block's transactions when save_progress is enabled. AttachChain additionally saves the final successful scan position; a filter skip updates ScanResult but does not itself perform that intermittent database write.

Source 1 · Source 2

Avoiding a permanent wallet/chain lock during ordinary rescans was motivated by responsiveness: historical #11281 noted that rescans could take hours and that holding the locks obstructed GUI rescan abort. A later passive-startup proposal also identified the cost of wallet-load locking: pending notification delivery could delay other wallets, RPCs, and the GUI.

Parallel draining interacts with an existing responsiveness tradeoff, especially when wallet loading already holds cs_wallet. These sources motivate examining bounded outstanding work and eventual notification delivery, but do not establish a particular acceptable drain time or queue size.

Source 1 · Source 2

Ralph's inferences

Parallel filter execution can be speculative, but committing skips remains dependent on earlier wallet processing. A batch of blocks already requiring inspection can be synchronized in order; a subsequent negative verdict cannot be treated as final until earlier matches have had the opportunity to expand descriptor lookahead. Because the script set grows by addition, an old negative needs checking against the added scripts, whereas an existing positive still requires inspection.

This derives the constraint behind ordered verdict delivery, stopping a returned match batch before the next nonmatch, and rechecking undelivered NO_MATCH results after top-ups. The head's UpdateFilter drains old checks, adds the script delta, and patches queued negatives. Wallet transaction processing calls MarkUnusedAddresses, which can call TopUp.

Source 1

Notification-based correction requires an ordering relationship with rescan writes, not just an earlier observation that a block was active. Holding cs_wallet across the active-chain check and transaction synchronization ensures that a subsequent blockDisconnected handler cannot run between them: it must run afterward and undo confirmation. If disconnection was already handled, the active-chain check can reject synchronization.

The head places this check inside ScanBlock after reading block data and while holding cs_wallet. Both notification handlers also take that lock. Thus queued filter verdicts and previously read block data are not themselves authority to mark transactions confirmed; the synchronization-time check supplies the relevant ordering.

Finding no successor is a time-specific observation, not necessarily completion of an unbounded scan. When notifications can interleave, a new block may be processed before the rescan derives the script needed to recognize its payment. Once the wallet's notified tip has advanced beyond the processed scan position, retrying successor lookup allows that block to be revisited with the expanded script set.

The head retries lookup when no work remains, the scan has not reached its wallet-tip boundary, and no explicit maximum height applies. This follows from combining dynamic lookahead with the unlocked notification regime. With cs_wallet permanently held, the wallet-tip boundary instead leaves the extension for pending notifications after the rescan.

Source 1 · Source 2

Draining parallel work has separate correctness and resource roles. Workers referencing a shared script set must finish before that set is mutated or destroyed; delta checks must finish before their temporary delta is destroyed, including exception paths. Separately, stopping the scan does not imply cancellation of already submitted work: the existing thread pool completes queued tasks and joins workers on destruction.

The head drains before updating the filter, waits for all delta-check futures before retrieving potentially throwing results, and destroys the checker before its referenced filter. Workers perform chain filter checks rather than wallet synchronization, which matters when the caller holds cs_wallet during loading. Bounded read-ahead limits outstanding work to finish or redo, but is not a wall-clock shutdown guarantee.

Unresolved disagreements

The historical #31629 discussion agreed on the need to avoid inconsistent wallet tip state but contained competing approaches to the handoff. One objection favored advancing m_last_processed_block or using an explicit maximum height. The response warned that queued notifications could subsequently move that state backward and that unlocked callers also needed protection. The inspected, partly truncated record does not establish a general resolution of those architectural preferences.

This is context for why scan progress, the wallet's notification-maintained tip, and an explicit scan limit are distinct concepts. It does not establish that one handoff architecture is universally required or assess the current parallel implementation.

Source 1 · Source 2 · Source 3 · Source 4