utxo partial order split

willcl-ark/bitcoin: PR #47

10 suggestions

Earlier concerns neither republished nor resolved: 1 suggestion. See the Run archive for their assessments.

Optional improvements

Link

[suggestion] · Region headers bring first-touch faults under the shared depot lock

When NodeRegion() returns unprepared memory, the new header write can fault while holding the process-wide depot mutex, delaying other refills and returned lists; the latency is unmeasured.

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

Details and suggested fix

Below the 1 GiB threshold, or whenever no prepared region is available, Depot::Take() receives memory that the worker has not touched. The new std::memcpy(region, &number, sizeof(number)) touches its first page inside LOCK(mutex), potentially including a huge-page fault. At base, the explicit first touch occurred during list initialization after unlocking. Other threads needing Take() or Give() now wait for this fault, potentially while holding their own shard locks. Prefault a candidate region outside the depot critical section, then reacquire the lock and recheck before installing it, retaining or releasing an unused candidate safely. Write the region number before publishing any of its nodes. Also update the comment claiming that first touch happens outside the lock.


Link

[suggestion] · Node-number exhaustion has no diagnostic or cache-interface warning

Although no current workload is expected to reach it, exhausting the process-wide 256 GiB node-region space calls std::abort() without an explanatory log, while the 64-bit cache API accepts larger budgets without documenting that ceiling.

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

Details and suggested fix

For 104-byte cells, MAX_REGIONS allows 8192 regions of 32 MiB. Their numbers belong to the shared, never-destroyed depot and survive store recreation, so this is a process-wide node-backing limit rather than one chainstate's cache limit. Once another region is needed, Depot::Take() aborts without identifying the exhausted resource. Reaching this requires node demand on the order of billions of cells. Log an explanatory fatal message before aborting and document the ceiling beside btck_chainstate_manager_options_set_database_cache_bytes(), distinguishing node-region backing from script allocations and total process memory.


Link

[suggestion] · Uncache() copies scripts for a scalar-only tracepoint

Uncaching a clean entry now converts StoredCoin to Coin under the shard mutex, copying its script and allocating for scripts over 36 bytes even though TraceUncache() only needs metadata.

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

Details and suggested fix

The unchanged TraceUncache(outpoint, it->second.coin) call now binds its const Coin& parameter to a temporary created by operator Coin() and ToCoin(). Unlike the reference passed at base, this conversion copies the complete script before entering the trace helper, outside any tracepoint-active check. Mempool rejection cleanup reaches it through CoinsTip().Uncache(). Add a read-only amount accessor to StoredCoin and pass height, amount and coinbase status to the trace helper directly. That preserves the payload without constructing a CScript; the performance impact has not been measured.


Link

[suggestion] · coinsahead handoff and lifecycle lack focused unit coverage

The new allocator fixture does not force the worker's 1 GiB activation threshold or verify prepared-region handoff, shutdown during preparation, shared-store lifetime, or restart.

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

Details and suggested fix

node_numbers_span_regions inserts 700,000 cells, about 70 MiB, and checks node lookup and bookkeeping rather than worker state. NodeRegion() uses process-wide allocation history to activate the worker, while RegionAheadBytes() separately needs one store's live nodes to reach 1 GiB. Add a scoped test-only threshold override and synchronization hooks, keeping production defaults unchanged. Use them to verify single consumption of a prepared region, synchronous fallback while preparation is blocked, destruction of one of two stores, last-store join and reserve release, and restart after recreation. Include the per-store 32 MiB accounting charge. Synchronization rather than sleeps would make these lifecycle assertions deterministic.


Link

[suggestion] · Change::script creates bypass the compact-coin unit tests

Window commits supply scripts separately through Change::script, but the store unit tests never set that field and therefore do not exercise the new StoredCoin::AssignOutput() branch.

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

Details and suggested fix

CreateLocked() now calls AssignOutput() when the separate script pointer is non-null. The window caller builds a Coin containing only amount, height and coinbase status, whereas the test helper leaves Change::script null and the new tests construct complete coins. Accidentally taking the ordinary assignment branch would therefore leave these unit tests passing while storing an empty script for window creates. Add an ApplyConfirmed() test with a script-less Coin and a non-null script pointer. Cover both sides of the 35-byte boundary, including spending a heap-script coin and recreating it inline over the dirty spent entry. Compare all coin fields both in the store and after write-out and database reload.


Link

[suggestion] · Long-script coverage skips the collected-copy lifetime

The long-script test spends only after WriteOut() returns, while the existing in-flight spend test uses inline scripts, leaving heap-script ownership across an unlocked database write untested.

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

Details and suggested fix

CollectChunk() reconstructs a Coin under the shard lock, then StreamWriteOut() calls WriteRun() without that lock. A spend in between can clear the entry and release its original heap block, so the collected script must remain independently owned. Extend run_settles_only_unchanged_entries with a 100-byte script and use RunBase::m_in_flight to spend it after collection but before the database write. Assert that the first batch retains the original script byte for byte, that the later erase remains dirty, and that the next run writes that erase. The existing hook permits this without timing-dependent threads.


Link

[suggestion] · MayHave() requests entry cache lines for key-only probes

MayHave() selects whole-cell prefetching although its locked loop only reads keys and chain links, requesting entry-only cache lines on misses that the existing key-only mode would avoid.

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

Details and suggested fix

PrefetchNode(..., true) requests the cell's middle and last lines in addition to its first line. MayHave() only checks find(...) != end(), so it needs the chain link and complete key, which the false mode already covers even when the key straddles lines. HaveAnyOutput() asks for the actual coin only after a positive result and after this shard lock is released. Pass [](uint32_t) { return false; } here and correct the commit message's description of MayHave() as an entry reader. This removes unnecessary hints on misses without changing lookup results; any throughput effect is unmeasured.


Link

[suggestion] · RegionAheadBytes() gives an incorrect reason for excluding the region tail

The accounting comment says the uncarved tail has not been supplied by the system, but coinsahead touches every page before handoff, so that excluded tail can already consume physical memory.

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

Details and suggested fix

RegionAhead::Run() writes every 4 KiB page before publishing ready. When Depot::Take() consumes that region, it initially carves only 1024 cells, leaving nearly 32 MiB of already-touched backing outside the live-node total, independently of the next reserve being prepared. Excluding reusable backing may be intentional, but lack of first touch no longer explains that exclusion. State directly that uncarved and reusable backing remains outside the cache budget whether it has been prefaulted or not. This keeps the accounting documentation consistent with the worker without suggesting that DynamicMemoryUsage() bounds resident memory.


Link

[suggestion] · node_numbers_span_regions never evicts its clean entries

The final Sync() writes the remaining coins but retains them on the clean lists, so the cross-region fixture does not test the clean-list eviction promised by its comment.

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

Details and suggested fix

After the fresh spends remove every third entry, roughly 466,000 unspent entries remain. Sync() writes them and SettleNode() attaches them to the clean lists; CommitWriteOut() does not evict them. Store destruction eventually frees these nodes through bucket chains, which does not exercise EvictClean() walking and removing compact clean-list links across regions. After Sync(), call store.EvictClean(0), assert store.GetCacheSize() == 0, and run SanityCheck() again.


Link

[suggestion] · The cross-region spend phase deletes fresh nodes instead of relinking erases

node_numbers_span_regions spends only fresh entries, so SpendCoin() deletes them and the subsequent spent-coin assertions do not verify retained dirty erases across regions.

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

Details and suggested fix

Each AddCoin(..., false) creates a fresh entry, and no run clears that flag before the height-100 spends. SpendEntry() therefore takes its EraseDetached() branch and returns without clearing, transitioning or reattaching the entry. The later AccessCoin().IsSpent() assertion also passes for an absent entry backed by the empty database. Call Sync() before the spend phase to clear freshness. Then assert that the spent entries remain cached as dirty erases, run SanityCheck(), and verify that a subsequent run removes those coins from the database. This exercises compact-link relinking rather than only deletion.


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

Earlier Bitcoin Core work deliberately expanded inline script storage to avoid allocations for increasingly common 34-byte P2WSH and P2TR scripts. Its stated tradeoff was a larger base object versus fewer allocations, less fragmentation, and faster flushing; alignment made 36 bytes cost no more than 34 in that representation.

This supplies historical context for retaining common scripts inline rather than minimizing the fixed script buffer alone. The current StoredCoin uses a different packing arrangement: its 35-byte threshold preserves inline storage for those common scripts while reducing the stored coin to 48 bytes. The earlier measurements do not establish performance for this new representation.

Source 1

The upstream proposal explicitly sought parallel validation without additional trust assumptions and with assumevalid disabled. The series description requires consensus verdicts, undo data, and crash safety to remain equivalent to the existing implementation; the store accepts changes only after block validation, not as speculative block-owned entries.

Compact storage and allocator optimizations sit below this semantic boundary. They must preserve the coins used by validation, rollback, and database write-out rather than introduce a restricted script vocabulary or change what is published as confirmed state.

Source 1 · Source 2 · Source 3

Ralph's inferences

Process-lifetime retention addresses cross-thread reuse and destruction-order constraints, not permanent ownership of live coins. The base allocator already batches free nodes in thread-local lists and a shared depot, retains backing regions, returns lists when threads exit, and permits allocation or freeing after thread-local teardown.

A store's destruction cannot invalidate storage still held in another thread's allocator lists. The never-destroyed depot also supports static test-owned stores that free nodes after ordinary thread-local destruction. This explains why recreation reuses a process-wide allocator instead of starting a fresh per-store arena, and why retained backing memory differs from live coin/script ownership.

The preparation worker is intended to move first-touch memory-supply latency away from block-connection threads holding shard locks. It prepares one 32 MiB region after process node-region allocation reaches 1 GiB, touches every 4 KiB page, and falls back to synchronous allocation when preparation is unavailable.

The optimization changes who waits for memory, not whether huge pages are guaranteed. Sharing the worker follows the shared allocator's ownership: one reserve serves process-wide node supply rather than creating a reserve per chainstate. The threshold avoids making that reserve a large proportional overhead for a small allocator.

Worker lifetime is deliberately shorter than allocator-state lifetime. A store count keeps the worker usable across multiple stores; the last store stops and joins it and releases an unused prepared region, while the shared control state and depots survive. During stopping or with no stores, node allocation remains synchronous.

This separates shutdown/recreation from allocator reclamation. The worker handles only shared flags and raw region memory, not queued work referencing a chainstate. The stop interval prevents it from being restarted while an earlier last-store destructor is joining it; later allocation can start it again after that interval.

Per-store reserve charging is a budget allowance, not attribution of the globally prepared region. Only a store whose own live nodes reach 1 GiB adds 32 MiB to DynamicMemoryUsage. Free reusable nodes remain outside that live-byte total, and the ledger explicitly acknowledges retained memory outside the cache budget.

Snapshot operation gives one chainstate only 5% of the cache, potentially less than a region. Charging every store whenever the process-wide worker is active would burden that small chainstate with another store's allocator history. Conversely, the chosen accounting is not an exact RSS bound: a reserve can exist while no store charges it, and multiple large stores can each carry the allowance. Excluding free backing storage lets eviction reduce budgeted usage even though regions remain reusable.

The exact 35-byte threshold follows the compact layout: eight amount bytes, a four-byte height/coinbase word, one size byte, and 35 script bytes fit in 48 bytes aligned to four. Longer scripts retain their complete bytes in owned heap storage; copies duplicate that storage, moves transfer ownership, and lookups reconstruct ordinary Coins.

This is lossless storage packing, not script compression or a standardness restriction. It preserves amount, creation height, coinbase status, spent-state semantics, and arbitrary script bytes needed by validation and persistence. The round-trip tests exercise both sides of the inline boundary, large scripts, copies, moves, and clearing; the integration test follows heap scripts through write-out, eviction, reload, and spending.

Thirty-two-bit node numbers trade address-space capacity for smaller links and buckets while retaining nonmoving nodes. For 104-byte cells, the encoding uses 19 slot bits and 13 region bits: 8192 regions of 32 MiB, or 256 GiB of node-region backing. Reserving each region's first slot makes zero an unambiguous null link; aborting on exhaustion avoids wrapping into existing identifiers.

The ceiling concerns the process-lifetime node allocator, not total RSS, script heap memory, or an individual chainstate's dbcache. Region numbering survives store destruction and recreation. The compact coin's four-byte alignment permits the node to follow its four-byte chain link without padding, making representation and link-size choices interdependent.

The intended publication model preserves existing synchronization and value ownership rather than making node links independently lock-free. Prepared memory is handed over under the preparation mutex; region-table entries are written once and remain valid; depot and shard synchronization govern node distribution and access. Callers receive coin copies, while write-out retains stable node identities and copies values under shard locks.

The relaxed atomic region table is not itself an acquire/release publication protocol for mutable entries. Compact identifiers must continue to resolve to stable backing storage, and neither returned Coins nor database batches should borrow script storage that a concurrent spend can release. The store also retains owner-serialized commits/runs and shard-protected lookup/update boundaries.