Review failed during the final assessment.
Provisional findings
The final assessment failed. These findings passed source verification but have not received final adjudication. Severity and publication suitability remain provisional. The review remains failed.
4 minor findings · 6 suggestions
Findings
[minor] · Drain staged connections of the snapshot chainstate before destroying its coins views
When background validation of a snapshot fails, its CoinsViews are destroyed while another thread may still hold a staged connection or running window workers that borrow those views. Holding cs_main no longer rules this out, because a connection now spans several lock holds.
Location: src/validation.cpp:8599 (head).
Details and suggested fix
StageConnectTip keeps staged.view as a raw pointer into m_coins_views->m_apply_views, and a FetchGuard that refers to it for the tip path. ActivateBestChain stages under one cs_main hold and publishes under a later one. In between it waits for the undo backlog and pinned blocks, and in the window, workers run ConnectBlock and ApplyChanges on the view with no lock held. The historical chainstate's PublishConnectTip calls MaybeValidateSnapshot. On a hash mismatch, failed stats or missing chainparams, handle_invalid_snapshot calls unvalidated_cs.InvalidateCoinsDBOnDisk(). That waits only for a write-out run in flight (SettleWriteOut()) and then runs m_coins_views.reset(). The source comment says another thread may have a block of this chainstate staged.
The activation lock is per chainstate (m_chainstate_mutex). So one thread can be activating the snapshot (active) chainstate, for example RPC submitblock, while another publishes the historical chainstate's target block, for example the message handler running ProcessNewBlock's background ABC. If that happens:
- In the window, BlockApplyView's destructor (StopFetching, UnwindBlock) races with a worker that is still using the same view, and the worker then uses freed memory.
- On the single-block path, the publishing hold calls PublishConnectTip, whose
assert(CoinsStoreTip()...)dereferences the resetm_coins_views. The StagedConnect's FetchGuard is also later destroyed against a destroyed view.
The publishing loop makes no assumeutxo or interrupt check before PublishConnectTip.
The base had a narrower window of the same kind. A snapshot ABC that released cs_main at the end of its hold would hit assert(CanFlushToDisk()) in the following periodic FlushStateToDisk. The head widens the window to whole stage-to-publish intervals and adds unsynchronised worker access, so the result can be undefined behaviour instead of a clean abort.
The path is already fatal: fatalError requests shutdown. The consequence is a crash or memory corruption where the code intends a controlled shutdown. Suggested fix: mark the snapshot unusable under cs_main and have its activating thread drain and unwind its in-flight connections before the views are destroyed, or keep CoinsViews alive until that drain. Do not wait for the other chainstate's activation while holding cs_main. No concrete production occurrence of this concurrent interleaving was identified, so the production impact is unconfirmed.
[minor] · The GUI's script-verification thread setting no longer limits CPU use during IBD
GUI users who lower 'Number of script verification threads' (for example to a negative value, to leave cores free) still get a connect pool sized to every core. That pool verifies the scripts of window blocks during initial block download.
Location: src/node/chainstatemanager_args.cpp:30 (head).
Details and suggested fix
OptionsDialog binds threadsScriptVerif to OptionsModel::ThreadsScriptVerif, which is saved only as the par setting. The tooltip still says negative values leave that many cores free. ApplyArgsManOptions derives worker_threads_num from -par, but defaults prevoutfetch_threads_num to DefaultPrevoutFetchThreads() (the core count, at least 2). ChainstateManager starts the connect pool with that count. ConnectWindow() defaults to twice the pool. RunConnectTask calls ConnectBlock with check_queue=nullptr, so scripts (where assumevalid does not skip them) and all other per-block work run on those workers.
During IBD, the main validation load is therefore bounded by a setting the GUI neither shows nor controls. The -par CLI help now says it does not bound this work, but the GUI text gives no such hint. To fix this, either derive the pool's default from the same resource-limit setting, add a GUI control for it, or update the GUI label and tooltip to say the setting does not apply to parallel IBD validation.
[minor] · Keep catching std::exception at the btck_chainstate_manager_import_blocks C boundary
Narrowing the catch to std::runtime_error lets std::bad_alloc and logic_error-derived exceptions escape an exported C function, where the call used to return -1.
Location: src/kernel/bitcoinkernel.cpp:1393 (head).
Details and suggested fix
At the base, btck_chainstate_manager_import_blocks ended with catch (const std::exception& e) { LogError(...); return -1; }. At the head this is catch (const std::runtime_error& e). The try block still calls import_files.reserve(block_file_paths_data_len), which throws std::length_error (a logic_error) or std::bad_alloc, and builds std::strings from caller data. It also runs ImportBlocks and the new SettleUndoWrites calls, which can allocate. Exceptions outside the runtime_error hierarchy now propagate out of a BITCOINKERNEL_API function. A C caller cannot handle them, and unwinding through FFI frames usually aborts. The other btck entry points in the same file (lines 1237, 1307, 1330, 1639) still catch std::exception.
Suggested fix: keep catch (const std::exception&) at this boundary, optionally with a more specific runtime_error handler before it. Allocation failure is the main realistic trigger. No in-tree host passing an oversized length was identified.
[minor] · Help text, reduce-memory.md and the O1 comment describe a receive-task path this PR does not have
Several texts say the connect pool processes received blocks, that blocks wait for a pool thread in memory, and that message handlers wait in PeerManagerImpl::WaitForPendingBlocks(). At this head, received blocks are still accepted and activated synchronously on the message handler.
Location: src/init.cpp:544 (head).
Details and suggested fix
The new -prevoutfetchthreads help says the pool threads "process the blocks received from peers". It also says that with zero or one thread received blocks are processed by the message handler, which implies they are not with more threads. reduce-memory.md says "Blocks received from peers wait for a thread in memory, up to one fewer than the number of threads".
In the code, PeerManagerImpl::ProcessBlock calls m_chainman.ProcessNewBlock(block, force_processing, min_pow_checked, &new_block) with no activate_async. ProcessNewBlock runs accept, write and finish on the caller, and FinishNewBlock calls ActivateBestChain directly unless activate_async is set. A tree search finds activate_async=*/true only in validation_chainstate_tests.cpp. ChainstateManager::LockTaskLimit() has no caller.
The ProcessNewBlock comment cites PeerManagerImpl::ProcessBlockInStages(). The O1 precondition in validation.h names PeerManagerImpl::WaitForPendingBlocks() and lists message handlers that call it. None of these exist. Only ChainstateManager::WaitForPendingBlocks exists, called from tests.
The PR description says blocks stay on the message handler until #46, and each part is meant to be reviewed and merged on its own. Until #46 lands, operators get wrong guidance for sizing threads and memory, and readers of O1 are pointed at an ordering barrier that does not exist. In this PR, describe only what the pool does here (window validation and prefetch at the tip) and keep O1 to the synchronous mechanism. Move the receive-task wording to #46.
Optional improvements
[suggestion] · Window memory estimate omits the scripts of spent coins kept in undo data and spend records
The window's byte account counts a fixed 512 bytes per input. Each spent coin is kept twice (in the store's spend record and in the undo data), and its scriptPubKey is sized by the earlier output, not the current block.
Location: src/validation.cpp:4085 (head).
Details and suggested fix
RunConnectTask sets staged.bytes = WindowBlockBytes(*in.block, result.num_inputs, block_bytes) + staged.view->DynamicMemoryUsage() after staged.view->ApplyChanges(). ApplyChanges ends with cacheCoins.clear(); cachedCoinsUsage = 0;, so the view term is close to zero. SpendLocked runs SubUsage(shard, entry.coin.DynamicMemoryUsage()); item.coin = std::move(entry.coin);, so the coin leaves the coins-cache accounting and lives in the window block's record. The block's CBlockUndo holds another copy until publication. Coin::DynamicMemoryUsage is the scriptPubKey's heap size, so a spend of a spendable output with a scriptPubKey of up to about 10 kB keeps roughly twice that, against a 512-byte allowance. Taking the max with the current block's size does not cover it, because those bytes belong to earlier blocks. Disk-backed blocks are admitted with tx_count * 512 before their worker runs.
reduce-memory.md tells operators the window's blocks "together ... hold up to an eighth of the coins cache in memory". On ordinary chains the constant is probably adequate. On input-heavy blocks spending large-script outputs, a full window can hold many times the documented share, whereas the serial base held one block's undo data at a time.
Options: add the measured undo and record script memory to staged.bytes, reserve conservatively before validation, or describe the bound as a typical-case estimate and give its worst-case factor. A small-dbcache test with such blocks would establish the permitted overshoot.
[suggestion] · Add a deterministic test where a higher window block applies before its parent
No deterministic test covers the main dependency path: a higher block applies first and defers a transaction, then its continuation is claimed when the lower block applies.
Location: src/test/validation_chainstate_tests.cpp:455 (head).
Details and suggested fix
OnWindowBlockApplied walks the slots from the lowest upwards, claims Deferred blocks whose lower blocks have all applied, and queues their continuations at the front of the pool. The publisher waits for IsComplete on the lowest slot, and DrainWindow unwinds from the highest slot down after waiting for continuations. The deterministic harness cannot reach the interleaving these mechanisms exist for. WindowStepper's comment says so, and RunLowestBlock only processes the next queued task. Existing coverage:
- the 'deferred transaction that fails' case, where the parent completed first and the input never exists;
- validation_core_tests'
deferred_transaction_completes_when_input_arrives, which supplies the parent's coin with AddCoin and bypasses the store and scheduler; - feature_connect_window's reindex, which logs a deferred count that may be zero.
A regression in the claim walk, for example one that only considers the block that just applied, could pass all of these. Suggestion: let the stepper run a chosen block's task, or gate the lower block's task. Then require a deferral in the higher block, release the parent, and assert that the continuation completes, that the tip and BlockConnected/UpdatedBlockTip stay in order, and that the UTXO hash matches serial connection. Also cover a lower-block failure while the higher block's continuation is pending.
[suggestion] · Move the consensus-check refactor of ConnectBlock into a commit before the window commit
a62f3e1 restructures how ConnectBlock checks each transaction and the coinbase, and adds deferred continuations that reuse those helpers, inside one commit of roughly 2,000 lines in validation.cpp. A behaviour-preserving preparatory commit would let reviewers check that the serial verdicts equal master's on their own.
Location: src/consensus/tx_verify.h:37 at a62f3e1cf28b (commit) (commit).
Details and suggested fix
In the parent 8a6e1936a341023788632bffef0479315b7b1ac8, ::ConnectBlock(block, ctx, view, ...) already exists and checks inline: CheckTxInputs, fee MoneyRange, BIP68, the sigop limit, CheckInputScripts into a block-wide txsdata vector, and the coinbase reward. Commit a62f3e1cf28b211d9eb598ce2b5e47e65f3b6da1 replaces this with CheckBlockTransaction(..., inputs_found), AddBlockSigOps and CheckCoinbaseAmount. It adds Consensus::CheckAvailableTxInputs, uses control ? txsdata[i] : own_txdata, and adds the deferral branch and FinishDeferredTransactions, which call the same helpers.
The PR's first invariant is that verdicts equal master's. Reviewers and bisect would be helped by a preceding commit that introduces the helpers and the per-transaction txdata with only the serial caller. It must keep block-lifetime txdata whenever a check queue control exists, and can be validated against the existing validation_core_tests. a62f3e1 would then only add defer_missing_inputs and the continuation caller. BlockValidationContext is already in the parent, so the split needs no new type.
[suggestion] · Split the window-independent behaviour changes out of a62f3e1
a62f3e1 also carries changes that do not need the window: the end of coins-DB cache resizing, the narrowed kernel import catch, and the coinstats cursor parameter. Each has its own user-visible effect and could be reviewed and bisected on its own.
Location: src/txdb.cpp:73 at 8a6e1936a341 (parent of a62f3e1cf28b) (commit).
Details and suggested fix
In a62f3e1cf28b211d9eb598ce2b5e47e65f3b6da1, txdb.cpp deletes ResizeCache, whose body resets m_db under m_db_mutex, and drops LOCK(m_db_mutex) from CompactFullAsync. As a result, an assumeutxo node no longer rebalances its database cache. bitcoinkernel.cpp changes catch (const std::exception&) to catch (const std::runtime_error&), which by itself changes the C API's error contract (see the separate finding). ComputeUTXOStats gains a cursor parameter.
The commit message lists these under 'Other changes in behaviour'. They cannot be bisected or reviewed separately from the window machinery, and the commit message says the kernel library was not compiled for this commit. Constraints on a split: the ResizeCache removal, with its callers and the mutex removal, should go in an earlier commit, because a later one would leave a DB reset racing off-lock readers. The cursor change may depend on write-out runs that the parent already has. The thread-default change sizes the window and can stay. Whether a62f3e1 actually fails to build the kernel library was not established.
[suggestion] · Kernel header says pinned blocks have no byte limit, contradicting the PinnedBlocks limit
btck_chainstate_manager_options_set_database_cache_bytes says the blocks whose notifications wait for an undo write have 'no limit in bytes'. The code limits them to an eighth of the coins cache, at least 64 MiB, except within reorganisation steps.
Location: src/kernel/bitcoinkernel.h:1308 (head).
Details and suggested fix
ActivateBestChain runs pinned_account.SetLimit(std::max(share, MIN_PINNED_BYTES)) with share = m_coinstip_cache_size_bytes / 8 in every step that is not a reorganisation. Before publishing, it waits while (!reorg_lock_main && !pinned_account.Admits()). byte_ledger.h describes this as 'the same eighth and 64 MiB at least for the blocks pinned by signals that wait for an undo write', and reduce-memory.md says the same. The new kernel header text tells library users this component is unbounded. Update it to state the bound and the reorganisation exception, so the three documents agree.
[suggestion] · Add a release note for the changed thread, memory and notification behaviour
Operators and kernel users have to change their configuration or expectations, but the PR adds no release-notes fragment.
Location: src/init.cpp:541 (head).
Details and suggested fix
ApplyArgsManOptions now defaults prevoutfetch_threads_num to DefaultPrevoutFetchThreads() (the core count, at least 2) and allows up to 1024. The -par help now says it does not bound the connect pool's script verification during IBD. The new -blockcache option defaults to up to 128 MiB on top of -dbcache. The kernel header now documents that block_connected may arrive after block_tip during IBD. -prevoutfetchthreads was introduced with a release note (doc/release-notes/release-notes-32.1.md), and doc/developer-notes.md asks for a release-notes file when an API or configuration model changes. A note should tell operators to use -prevoutfetchthreads rather than -par to limit IBD CPU, and give the new defaults, the new memory term and the new callback order. The maintainers may prefer one note for the whole stack.