1 major finding · 5 minor findings · 9 suggestions
Earlier concerns neither republished nor resolved: 1 minor finding. See the Run archive for their assessments.
Findings
[major] · Take-back undo reader calls a nonexistent ReadBlockUndo() overload
The three-argument ReadBlockUndo() call prevents validation.cpp from compiling, as also reported by the supplied build experiment.
Location: src/validation.cpp:6048 (head).
Details and suggested fix
This lambda is inside non-template ActivateBestChain(), so its call must resolve even if no take-back occurs. BlockManager declares and defines only ReadBlockUndo(CBlockUndo&, const CBlockIndex&), which obtains the undo position and parent hash itself. Use m_blockman.ReadBlockUndo(undo, index) here, preserving the null-position and parent guards.
[minor] · StagedConnect::bytes races with window-admission reads
During windowed IBD, RunWindowValidation() writes the non-atomic byte estimate without the mutex that protects concurrent WindowBytes() reads.
Location: src/validation.cpp:4958 (head).
Details and suggested fix
The connector can refill the window while earlier blocks are validating. WindowBytes() holds sync.mutex, but IsIndexed() includes Validating, so it already reads s.bytes before Finish. The worker overwrites that plain size_t outside the lock; taking the lock only for Transit(Finish) does not synchronize those accesses. Compute the new size locally and assign it inside the same locked section as the Finish transition.
[minor] · Pinned-block accounting omits witness-heavy blocks' measured size
During IBD, delayed BlockConnected callbacks can retain much more memory than the pinned allowance for valid, low-input, witness-heavy blocks; the practical excess has not been measured.
Location: src/validation.cpp:5152 (head).
Details and suggested fix
The completion captures the full block behind its undo write, but WindowBlockBytes(..., 0) charges only (transactions + inputs) * 512. Large witnesses can therefore leave a multi-megabyte block charged at only a few KiB. If the effects executor falls behind, the separate undo-byte limit does not cover that retained witness data, undermining the pinned allowance of one eighth of the coins cache, at least 64 MiB. Pass staged.parsed_bytes on the window path and measure the block equivalently on the serial path. Add a delayed-executor test using a large-witness, low-input block.
[minor] · An exception in a commit helper can strand a claimed group
A helper-side allocation failure can hang kernel embedders without a terminating allocation handler; bitcoind terminates on allocation failure, and no other current throwing path was identified.
Location: src/validation.cpp:6035 (head).
Details and suggested fix
The submitted helper drops its future and is not noexcept. After RunCommitWork() claims a group by changing its state from 0 to 1, CommitGroup() can allocate before marking it 2. If that allocation throws, std::packaged_task stores the exception in the discarded future, no worker reclaims the group, and the connector waits indefinitely for committed or commit_failed while holding cs_main. Make the helper entry point noexcept, matching the other validation worker entry points.
[minor] · Kernel import lets non-runtime_error exceptions escape the C API
btck_chainstate_manager_import_blocks() no longer converts std::length_error or std::bad_alloc into -1; no current in-tree oversized-count caller was found.
Location: src/kernel/bitcoinkernel.cpp:1396 (head).
Details and suggested fix
Changing the outer handler from std::exception to std::runtime_error excludes both exception types. import_files.reserve(block_file_paths_data_len) can throw std::length_error before reading any paths, and string or path allocation can throw std::bad_alloc in an embedder without a terminating allocation handler. These exceptions were previously caught at the boundary; now they escape an API intended for C callers and may terminate the application rather than return an error. Restore catch (const std::exception&) here.
[minor] · Shutdown logs the default window width as 1
With -connectwindow=0, the shutdown summary reports a width of 1 instead of the width used during IBD.
Location: src/validation.cpp:9353 (head).
Details and suggested fix
The destructor calls m_connect_pool->Stop() before logging ConnectWindow(). Stopping the pool empties its worker vector, so the default calculation becomes twice zero workers and is clamped to one. Capture ConnectWindow() before stopping the pool and log that value so the summary describes the configuration used during validation.
Optional improvements
[suggestion] · Explicit -par settings no longer constrain IBD script-check concurrency
When -prevoutfetchthreads is unset, windowed IBD ignores an explicit -par or GUI thread limit whenever scripts are checked, despite the existing request to leave cores free.
Location: src/node/chainstatemanager_args.cpp:91 (head).
Details and suggested fix
The new default sizes the connect pool from GetNumCores() independently of -par, and RunWindowValidation() verifies scripts inline with check_queue=nullptr. The updated help documents the split, but an operator upgrading with -par=1 or a negative value still gets the core-count-based pool, including above assumevalid or with -assumevalid=0. When -par is explicitly configured and -prevoutfetchthreads is not, derive the connect-pool default from the resolved -par value. This also preserves the purpose of the GUI control, which has no setting for the new pool.
[suggestion] · Kernel users cannot shrink or disable the new block cache
The kernel C API fixes the accepted-block cache budget at 128 MiB on top of configured caches, even for embedders using a small database cache.
Location: src/kernel/bitcoinkernel.h:1307 (head).
Details and suggested fix
The kernel options retain block_cache_bytes=DEFAULT_BLOCK_CACHE_BYTES, and no C API setter changes it. This is usable capacity, not an upfront allocation: out-of-order btck_chainstate_manager_process_block() submissions can populate the cache through the accept path. bitcoind already scales this budget with the coins cache and exposes -blockcache; the kernel header discloses the extra memory but provides no control. Add a block-cache byte-budget setter with 0 disabling the cache.
[suggestion] · Thread and memory configuration changes lack an upgrade note
The new -blockcache budget and changed -prevoutfetchthreads and -par semantics need release-note guidance, not just updated option help and doc/reduce-memory.md.
Location: src/init.cpp:544 (head).
Details and suggested fix
This PR adds memory beyond -dbcache, changes the connect-pool default from eight threads to the core count (at least two), and moves IBD script checking outside the -par limit. An upgrade note should identify -prevoutfetchthreads as the new IBD concurrency control and explain how to reduce or disable the accepted-block cache. Add a release-note fragment, or cover these changes in the series-level note before merge.
[suggestion] · Conflict test misses restoration of a netted output
The deterministic conflict test never nets a surviving block's output against a taken-back block's spend, so its assertions do not exercise TakeBackCommit()'s restoration loop.
Location: src/test/validation_chainstate_tests.cpp:928 (head).
Details and suggested fix
Both conflicting transactions currently spend m_coinbase_txns[0]:0, and the block above them contains only its coinbase. Thus no taken-back block spends lower_spend:0, and HaveCoin(lower_spend:0) would still pass if the separate DROPPED-item restoration loop were removed. Add a transaction spending lower_spend:0 to the upper block alongside the conflicting spend. Keep the existing shared-commit scheduling and check the restored coin's height and value after take-back.
[suggestion] · Window tests cannot force out-of-order validation completion
WindowStepper completes blocks in staging order, leaving the central rule that a finished upper block must wait for a lower one without deterministic coverage.
Location: src/test/validation_chainstate_tests.cpp:455 (head).
Details and suggested fix
The harness holds every pool worker and executes queued tasks one at a time; CacheStepBlocks() makes that queue follow block height. Production instead schedules eligible validations independently, so an upper block can finish first. Add a test-only gate before the lower block's Finish transition, let an upper block finish, and assert that the tip and BlockConnected/UpdatedBlockTip notifications do not advance. Release the gate and check ordered publication and the final UTXO state. The existing functional tests exercise real scheduling but do not force this interleaving.
[suggestion] · sync_mode test checks yielding only while idle
An always-false YieldHistoricalActivation() passes the new yield assertions because both run before any connector work is pending.
Location: src/test/sync_mode_tests.cpp:46 (head).
Details and suggested fix
After SignalConnector() returns inside the existing cs_main hold, m_connector_active_signals is ahead of m_connector_active_done, while the connector cannot finish activation. Assert that YieldHistoricalActivation(SyncMode::Tip) is true and the Download case remains false there. After tip.get(), assert that Tip no longer yields. This uses the existing synchronization and distinguishes the mode-dependent branch without adding a timing window.
[suggestion] · BIP30's call-site switch is separated from the lookup implementation
Moving the HaveAnyOutput() call-site switch into the commit that adds it would let reviewers validate the BIP30 lookup change before reviewing the window scheduler.
Location: src/coinsstore.cpp:1373 at 72d95e165fac (commit) (commit).
Details and suggested fix
Commit 72d95e165facc0d109bc6c0773ef700b6d3e0faa introduces CCoinsViewCache::HaveAnyOutput() and the BlockApplyView batching override, but its ConnectBlock() still uses the per-output HaveCoin() loop. Its direct child, c66f2288b8d59b18d9213a030af3a096105e4ceb, switches the call site inside the much larger window change. Move that switch into the parent commit and add a focused stub-WindowCoinSource test for named and unnamed IDs, spent-in-view coins and store-only coins. Without an installed overlay, the earlier switch retains the original loop semantics; leave WindowOutputs integration in the window commit.
[suggestion] · validation:block_connected duration stops before tip publication
The new tracing documentation describes publication latency, but the recorded duration excludes the pre-publication chainstate write, mempool update and SetTip().
Location: doc/tracing.md:168 (head).
Details and suggested fix
In FinishConnectBlock(), argument 6 is time_5 - result.time_start, with time_5 captured immediately after queuing undo data. PublishConnectTip() then confirms the commit, calls FlushStateToDisk(IF_NEEDED), updates the mempool and moves the tip. A profiler following the documentation would miss write-out stalls. Describe the endpoint as undo-write queueing, before the chainstate write and tip update, rather than publication.
[suggestion] · Message-handler ordering comments describe barriers not used here
The new comments describe ping and transaction barriers that no production caller invokes at this head.
Location: src/node/chainstatemanager_args.h:16 (head).
Details and suggested fix
The ConnectorSignals() comment says ProcessMessages() delays pongs, and WaitForPendingBlocks() says the message handler waits before processing a transaction. At this head the former has no callers and the latter is used only by tests. The rationale on MIN_DEFAULT_PREVOUTFETCH_THREADS likewise assumes the later hand-off. Move these message-handler claims into #46 with the code they describe, or mark them as planned behavior, so the comments do not imply ordering synchronization that this PR does not invoke.
Earlier concerns
Earlier reports raised these, with the titles and severities shown there. This review neither republished nor resolved them.
- [minor]: The kernel callback reentrancy ban excludes safe undo reads (earlier report)
Background
Ralph's summary of historical context for the behaviour affected by this change. The historical record reviewed here is incomplete.
Documented decisions
BIP30 protects chainstate against duplicate transaction identifiers, not merely redundant transactions. The original proposal prohibited overwriting transactions with unspent outputs and warned that leaving the behavior unfixed exposed the network to fork risk from attackers capable of causing reorganizations.
Window validation reads outputs from blocks not yet committed. Its BIP30 checks therefore concern consensus-visible state across the window, rather than only the durable store. The historical rule explains why output-overwrite checks remain necessary alongside input and script validation.
Skipping BIP30 after BIP34 was a database-access optimization with a narrower justification than initially understood. PR #12204 documented that pre-BIP34 coinbases could resemble later height-encoded coinbases, requiring BIP30 checks again from height 1,983,702.
The affected read path batches BIP30 output lookups across the window and store. This history distinguishes optimizing those lookups from eliminating the rule: the bypass depends on specific chain history and height bounds, which the pinned base explicitly preserves.
Notification ordering became an explicit locking requirement after concurrent block-processing threads delivered UpdatedBlockTip callbacks in reverse chain order. The historical diagnosis identified releasing cs_main before enqueueing as the race; PR #12988 addressed it by holding cs_main while sending the signal.
The head introduces worker completion and deferred effects while retaining ordered publication. This history explains why parallel validation completion cannot determine subscriber order: callback enqueueing must preserve the order in which the chain changes, even if execution happens later.
Source 1 · Source 2 · Source 3
Reorg notification timing has historically involved a distinction between block connection and completion of mempool repair. In PR #17562, moving BlockConnected earlier exposed an intermediate mempool state; the author noted that BlockConnected did not guarantee a consistent mempool and directed listeners needing that property to UpdatedBlockTip. The proposal was withdrawn because the ordering change was difficult to review.
The affected behavior delays IBD BlockConnected behind undo writes and separately handles steps that disconnect blocks. The historical discussion explains why block order alone does not describe the full subscriber contract: the position of notifications relative to reorg mempool reconciliation also matters.
Preserving a warm UTXO cache improves block connection, but frequent pruning flushes expose a competing cost. PR #28280 explained that simply retaining the cache could be slower when every sync scanned all entries; tracking dirty entries separately traded per-entry memory overhead for work proportional to changed entries.
The base already distinguishes syncing from emptying the cache. The head extends this performance concern to oldest-change write-out runs and avoids waiting for queued writes on automatic pruning checks that will select no files. The historical rationale is about retaining useful cached state without making frequent persistence operations increasingly expensive; it does not establish the performance of this implementation.
The preceding durability stage explicitly required block and undo bytes to be synced before the block index records them. Its stated motivation was that later stages write files from multiple threads, so durability could no longer depend on serial processing or syncing only the current file.
This PR queues undo writes and chainstate write-out effects. The pinned base already orders file sync before index persistence and coins persistence. That prior design intent explains why moving I/O off-lock introduces completion dependencies rather than removing the ordering requirement.
Database cache resizing has a lifetime-versus-locking tradeoff. The earlier proposal #35744 described UTXO cursors surviving release of cs_main while resizing replaced their underlying database. Its proposed lifetime locks protected cursors, but could make cache rebalancing hold cs_main while waiting for a long-running scan.
The patch removes database cache resizing and changes UTXO-statistics cursor acquisition. This history identifies the interaction between snapshot/background-chainstate cache allocation, stable database objects, and validation responsiveness. It does not establish that avoiding this interaction was the author's reason for removing resizing.
Ralph's inferences
The connect window separates speculative computation from authoritative chainstate transition. Because its output overlay does not account for lower blocks' spends, successful speculative validation is insufficient to establish that all spends can be committed. Conversely, a speculative failure is not necessarily the serial validation verdict.
The base validates and applies one block atomically under cs_main. The head instead commits in order, takes back a conflicting suffix, and retries window failures alone. These mechanisms appear intended to preserve serial consensus semantics while allowing expensive validation work to overlap.
A lagging coins database makes block and undo retention part of recoverability: files are not dispensable merely because the in-memory tip has passed them. Recovery must still be able to traverse the path from the written database head, including both branches after a reorg.
The head bounds pruning by the common ancestor of the written head and current chain, advances the written state when that blocks pruning, and permits automatic pruning to wait outside cs_main. This reflects a tradeoff between bounded disk usage and avoiding validation stalls, while retaining the data needed for recovery.