utxo split/5 coins store

willcl-ark/bitcoin: PR #44

4 minor findings · 6 suggestions

Findings

Link

[minor] · BeginWriteOut() accepts another run after write-out failure

A direct retry after failed write-out can close the recovery marker over unwritten changes, although abandonment is shutdown-only and no current retrying caller was found.

Location: src/coinsstore.cpp:1290 (head).

Details and suggested fix

AbandonWriteOut() clears m_run_in_flight and sets m_flush_failed, but BeginWriteOut() checks only the former; only Flush() and Sync() enforce the latch. For a dirty confirmed coin held in an open block's spend record, CollectRecords() clears its write flags and installs or updates a pending marker before WriteRun() succeeds. If that write fails, a new run is accepted and forced final by m_fell_below_written, but collection skips the now-clean record and the non-owed pending marker. Its final WriteRun() can remove DB_HEAD_BLOCKS and set DB_BEST_BLOCK without that confirmed coin, preventing startup replay. Reject m_flush_failed at the start of BeginWriteOut(), before any state transfer, and extend failed_run_ends_all_writes to retry the direct API after a record-write failure.


Link

[minor] · byte_ledger_tests shifts a 32-bit size_t by 40 bits

size_t{1} << 40 is undefined on supported 32-bit targets and would fail the warnings-as-errors i686/ARM test builds; this is inferred from source, not an observed build failure.

Location: src/test/byte_ledger_tests.cpp:47 (head).

Details and suggested fix

an_account_without_a_limit_is_counted_and_admits_everything evaluates this expression three times. On the 32-bit targets allowed by compat/assumptions.h, it triggers -Wshift-count-overflow. The new file is part of test_bitcoin, and the i686 and ARM CI configurations use CMAKE_COMPILE_WARNING_AS_ERROR=ON. Include <limits>, define a representable large value such as std::numeric_limits<size_t>::max() / 2, and reuse it in all three expressions.


Link

[minor] · CoinsStore::Sync() does not dispatch through the cache interface

Sync() through a CCoinsViewCache& bound to CoinsStore uses the inherited cache and can assert instead of persisting; no current caller using that substitution was found.

Location: src/coinsstore.h:161 (head).

Details and suggested fix

coins.h advertises that the store can stand in for CCoinsViewCache, but Sync() remains non-virtual. The base implementation passes its unused cacheCoins and m_block_hash directly to BatchWrite(). CoinsStore::SetBestBlock() updates m_tier_block_hash instead, leaving the inherited hash null and causing a database-backed call to assert in CCoinsViewDB::BatchWrite(). It also bypasses the store's write-out and failure latch. CoinsTip().Sync() already uses this reference type for non-wiping flushes. Provide virtual dispatch for the cache's sync path and override it in the store, adjusting the overlay's deleted Sync() declaration while preserving its restriction during fetching. Add a regression test that syncs a store through CCoinsViewCache&.


Link

[minor] · The nullopt guard does not ensure a consistent stats cursor

With concurrent write-out, the pre-existing separate reads in Cursor() can label a partial UTXO snapshot with a valid block hash; no current node caller creates this overlap.

Location: src/kernel/coinstats.cpp:124 (head).

Details and suggested fix

CCoinsViewDB::Cursor() obtains GetBestBlock() separately from the sequence fixed by NewIterator(). If the best-block read happens first, a run's first batch can land before iterator creation, pairing the previous head with partially updated coins. In the opposite evaluation order, finalisation can pair a partial iterator snapshot with the new head. Both hashes can resolve to a non-null pindex, so this check accepts them. cs_main does not exclude WriteRun() batches. For the overlap anticipated by the new comment, read DB_BEST_BLOCK and DB_HEAD_BLOCKS through the iterator's own snapshot before seeking to DB_COIN, and add controlled-interleaving tests at run start and finalisation.


Optional improvements

Link

[suggestion] · Open-block record writes bypass the one-chunk memory bound

Record collection copies all eligible coins before writing, so peak preparation memory follows the open window's records rather than batch_bytes, despite the one-chunk contract.

Location: src/coinsstore.cpp:1639 (head).

Details and suggested fix

After chunking the shard entries, StreamWriteOut() calls CollectRecords() without a limit. That function gathers all eligible candidates and copies each dirty confirmed record coin into writes before returning to write_chunk(). Flush() similarly builds all of from_records before calling WriteRun(). Database-side batch splitting happens after these allocations, so this is a window-sized duplicate rather than one chunk of coins. Extend chunking to both record candidates and their coin payloads, preserving shard-before-slot locking and live-record rerouting. Extend streamed_run_in_chunks_of_one_change with confirmed coins spent by still-open blocks, which its current confirmed-only setup does not exercise.


Link

[suggestion] · EffectsExecutor leaves its hook's locking restriction unstated

The documented lock-held waits can deadlock if on_completion blocks on the requester's lock, because the hook runs on the only I/O worker.

Location: src/kernel/effects.h:31 (head).

Details and suggested fix

Loop() invokes m_on_completion() synchronously between effects. If a thread holds the requester lock while waiting for two queued effects, a hook that blocks on that lock after the first effect prevents the second from running. The earlier notification does not help because WaitForIO() still sees queued work; the same problem applies to a backlog wait whose threshold has not been reached. Document that the hook must not block on locks held across these waits, using try-lock-and-defer so the existing retry path can apply completions later. Add a test that holds the requester lock across a wait with several effects and a deferring hook.


Link

[suggestion] · Sync() can discard an unhandled restored-coin payload

If a caller violates the documented Sync() precondition, a release build discards its restored payload without writing it; no current caller supplies that payload, and database loss is unproven.

Location: src/coinsstore.cpp:1942 (head).

Details and suggested fix

BeginWriteOut() moves m_restored into WriteOutRun::restored, but StreamWriteOut() never consumes that field. The field comment requires writing it before the marker, and KeepWritten() says the next run writes it first, without the direct-run documentation explicitly assigning that operation to the owner. The Flush() and Sync() comments do assign restored writes to their caller, but their Assume(m_restored.empty()) checks do not stop an ordinary release build. Sync() then takes the payload into a run that eventually destroys it. Document the owner's required WriteCoins(run->restored) step before streaming and its failure handling. Enforce the wrappers' empty-payload precondition with Assert, and add coverage with a non-empty restored payload.


Link

[suggestion] · CoinsStore crash-prefix coverage bypasses ReplayBlocks()

The crash-prefix test checks fixed marker values but manually replays one chain, leaving marker-derived fork selection and rollback after a bounded run untested.

Location: src/test/coinsstore_tests.cpp:975 (head).

Details and suggested fix

streamed_run_cut_at_any_write_is_completed_by_a_replay calls Sync() at synthetic height 2, builds through height 6, and cuts a bounded run before manually reapplying heights 3 through 6. ReplayBlocks() instead reads the persisted heads, finds their common ancestor, disconnects the old branch, and rolls forward the new branch. The separate settled-head test checks successful marker advancement, not recovery from that marker. Add a chainstate-level case with real blocks and undo data: commit a bounded run, change branch, cut the following run at each write, recover through ReplayBlocks(), and compare the resulting UTXO set with an uninterrupted run.


Link

[suggestion] · Busy-pool fallback and late flush helpers lack deterministic coverage

The flush tests do not keep helpers queued after Flush() returns, so they miss deterministic coverage of busy-pool progress and late-task lifetime safety.

Location: src/coinsstore.cpp:1875 (head).

Details and suggested fix

The helper tasks capture this, &wipe, and &workers. Their shared claimed check lets a late task return without touching those captures after the calling thread has written its range. All three helper-flush tests use FlushHelpers() with available workers, so they do not force that path. Add a test that blocks every pool worker behind a latch and verifies that a flush actually queues helpers for multiple ranges, accounting for concurrent base writes, dirty volume, batch size, and the hardware-concurrency cap. Check that Flush() completes with correct database contents while the workers remain blocked. Keep the pool alive independently, destroy the store, then release the latch and drain the queued tasks.


Link

[suggestion] · The CoinsStore commit mixes an independent live prefetch change

The independently active prefetch scheduling change shares the large, not-yet-used CoinsStore commit, making its behavior harder to review and bisect in isolation.

Location: src/coins.cpp:414 at 944454ba2aa0 (commit) (commit).

Details and suggested fix

Commit 944454ba2aa024f5b0f0a6a728432c5264ea0dcc adds the unused store but also changes CoinsViewOverlay::StartFetching() from one task per worker to at most one per eight external inputs. The node already calls this path during block connection. Although the commit message discloses the adjustment, a scheduling or performance bisect would still land on the whole store addition. Extract only this task-count hunk and its rationale into a commit between its direct parent, the primitives commit deea5b437c7ea335ed5656e333be10a44d943a76, and the store commit. It depends only on existing inputs and worker counts, not on the store, so this preserves the final tree without an intermediate dependency. Keep the ComputeUTXOStats() change with WriteRun(), which introduces the open-marker state it handles.


Coverage details