Repository navigation
coins: store spent dbcache entries compactly - #37038
LarryRuane wants to merge 6 commits into
Conversation
Currently, coins cache entries that are either DIRTY or FRESH (or both) are kept on a "flagged entry" linked list so they can be enumerated quickly (by `Sync()`/`Flush()`), without needing to enumerate the entire `cacheCoins` map. A later commit will need to identify only the spent entries in this list. To avoid having to enumerate the full list, this commit splits the list in two, unspents and spents. This is done by having two sentinels instead of one. Because these two sentinels are often needed at the same time, this commit packages them into a new struct, `CoinsSentinel`. The number of entries in the spent list is maintained in a new counter, `m_spent_count`. Most of this commit is the logic to keep the coins on the correct list, including by moving them when necessary (transitioning between spent and unspent states). When a cache's `BatchWrite()` runs, it iterates the child cache's flagged entries using the passed-in cursor's `Begin()`, `End()`, and `NextAndMaybeErase()` methods. Both unspent and spent entries must be returned (in any order). Implementing these methods is simpler if there's a single linked list, so this commit modifies the cursor's constructor to merge the spent list into the unspent list, which can then be iterated as before. (Merging the other way would work too. Either way, one list's name is briefly wrong. The distinction between unspent and spent is no longer needed, since the spents are all deleted anyway once the flush or sync completes.) `SanityCheck()` verifies both lists' integrity, that spent entries are DIRTY and not FRESH, and checks `m_spent_count`'s value. No change in behavior.
Add `m_compact_spents`, a vector of `COutPoint`s, to `CCoinsViewCache` to hold spent coins in a more memory-efficient way. It can be considered an extension of the existing `cacheCoins` map; a spent coin can be in either place. After a coin in the cache is spent, its `Coin` fields are unused (except its output's `nValue` is set to -1). So we only need to store a spent coin's outpoint. (The `CCoinsCacheEntry`'s flags are always `DIRTY` and `!FRESH`, so those don't need to be stored.) Using memory more efficiently means we can fit more coins in the cache, which increases the cache hit ratio and reduces the frequency of cache flushes. It's equivalent to increasing the size of the cache. Storing a spent coin as an element of a vector requires 36 bytes (the minimum possible), versus about 128 bytes for a `cacheCoins` map entry. When looking for a coin in the cache, we must now look in two places, first the map, and, if not found, the compact spents vector. (In reorg scenarios, it's possible the coin could be in both places; the map takes precedence. Similarly, the same spent coin could end up in the compact list more than once, which is harmless.) To speed up the compact spents lookup, we keep the vector sorted to enable binary search. (A later commit improves on this further.) It would be inefficient to re-sort the vector with every new spent coin. Instead, we store spent coins in the map, as in the past. When there's a significant number of them, we migrate them from the map to the vector, then sort the vector. This amortizes the overhead of the sort over many cache operations. This frees space in the map, more than the space used by the vector. We can gather these spent coins in the map efficiently because they're on a separate linked list. When the number of spents in the map again becomes significant, we migrate them to the vector. Optimization: Instead of adding this group of N new spents to the end of the sorted vector of E existing spents, and then sorting the entire vector, we use a two-step process. We write the new spents to a temporary vector, sort it, and then _merge_ the two vectors (one step of a merge sort), which has complexity O(N*log(N) + (E+N)), rather than O((E+N)*log(E+N)). The merge writes into a newly allocated vector, so memory use briefly exceeds the cache budget by about the size of the vector (as already happens when the map's bucket array is resized). This lasts only as long as the sort and merge (about 0.3 seconds on a desktop with a vector of 10M entries). It may push some unrelated memory out to swap, but that's very different from steadily using memory beyond the budget. `BatchWrite()` is given the compact spents list (`m_compact_spents`) in addition to the cursor (map). The map can also contain spent coins; spents from either source should be processed the same way. Before `BatchWrite()` is called (by `Flush()` or `Sync()`), the caller must remove all spent coins from the list that are also in the map, that is, that are "shadowed" by the map. (Shadowing rarely happens, but could following a reorg.) The method `RemoveShadowedSpents()` does this. This is needed because otherwise a stale spent in the list could delete the unspent coin the map holds for the same outpoint. A coin isn't marked FRESH if its outpoint is in the compact spents vector, for the same reason it isn't when a spent coin is in the map. Compaction is opt-in via `SetCompactSpentsThreshold()` (default: disabled). It's intended only for the main cache (not the per-block caches). It will be enabled in the next commit.
Set the compaction threshold in the coins fuzz targets (`coinscache_sim`, `coins_view`, `coins_view_db`, `coins_view_overlay` and `coins_view_stacked`) from the fuzz input, in the range 0 to 4. Small thresholds compact often but still leave some spent coins in the map between operations, and 0 disables compaction. The existing simulation unit tests (`SimulationTest` and `updatecoins_simulation_test`) now set a random threshold of 0 to 3 on each cache in their stack. This mixes compacting and non-compacting caches. Add three unit tests. `compact_spents_lookup` checks that compacted spent coins aren't found by any lookup, even though the base view still holds them unspent, and that a flush erases them from the base. `compact_spents_shadowed_purged` checks that a coin spent and then re-created isn't passed to the base's `BatchWrite()` as spent. `compact_spents_sync` checks that the cache stays consistent after a `Sync()`, which clears the vector but keeps unspent map entries.
Enable compaction for the main coins cache only, sized from the actual dbcache. For example, with dbcache=1024 (1 GiB, the usual default), compact when the cache has accumulated about 1M spent map entries (roughly 1/8th of the total cache capacity). This is scaled down proportionally on memory-constrained nodes and up with larger caches. The threshold is set in `InitCoinsCache()` and updated on `ResizeCoinsCaches()`. Every other `CCoinsViewCache` (mempool validation views, the per-block `ConnectBlock` overlay, RPC helpers, tests) doesn't set the threshold, and compaction is disabled by default. Also clamp `LargeCoinsCacheThreshold()` at 95% of total space. The fixed 10 MiB headroom assumed cache usage grows smoothly per block. But a compaction run can raise the measured usage by 36 bytes per compacted entry (up to ~3.5% of the cache) within a single block. So the headroom must scale with the cache. For caches below ~200 MiB, the pre-existing terms already provide at least this much headroom, so behavior there is unchanged. Without the clamp, benchmarked reindexes hit `CoinsCacheSizeState::CRITICAL` (cache over budget) up to 12 times. With it, zero (same as master). In debug builds, run `CCoinsViewCache::SanityCheck()` at every flush boundary (compiled out of release builds).
This commit is a performance-only improvement. Whenever a coin is looked up, there's a good chance we'll find it unspent in the cache, especially if the cache is large or the coin was recently created. But if it's not found in the cache, previous commits require a binary search of the compact spents list (vector). Only if it's not found there (which is almost always the case, or this would be a double-spend attempt) do we search for the coin on disk (base view), where there's a good chance it will be found (or else the input is invalid). A binary search of a large vector (the compact spents vector can have millions of entries) is bad from a CPU cache perspective, since almost every probe is a cache miss. To mitigate this problem, this commit adds `CompactSpentsFilter`, a blocked bloom filter, so that a negative lookup usually needs only a single 64-byte cache-line read. We only need to binary search if we get a positive bloom filter result (in practice, rarely). The false positive rate is at most about 0.1%, and the measured average was around 1 in 4,000. A bloom filter can't give false negatives, and correctness depends on that, so when a debug build gets a negative filter result, it verifies that the binary search fails. `CompactSpents()`, which moves all spent coins from the map to the vector, is the only place the vector is added to (or created), so it maintains the filter. The vector only grows within a flush cycle, so `CompactSpents()` inserts just the new entries unless the filter must grow. The filter doubles when it grows, so it's rebuilt only a few times per flush cycle, at the new size (known exactly). It's cleared along with the vector at each flush. We don't touch the filter when `RemoveShadowedSpents()` runs, because a stale filter entry can only cause a false positive. The filter takes about 2-4 bytes per 36-byte entry, which is counted in `DynamicMemoryUsage()`. The block and bit positions come from the outpoint (whose txid is already uniform) mixed with a per-instance salt. A peer that grinds txids could at worst raise the false positive rate, which degrades to the binary search. The hash's intentional integer wraparound is added to the ubsan suppressions, as `CBloomFilter::Hash` is. ; Conflicts: ; src/test/coins_tests.cpp ; src/validation.h
The `cache=` figure in the UpdateTip log line includes the pool memory resource's free lists. Map nodes freed by compaction stay there for reuse, so `cache=` doesn't drop when spents are compacted. It steps up instead, by the size of the vector. Add `cache_used=`, an estimate of the memory actually in use, so the effect of compaction is visible. The map node size is implementation defined, so it's estimated. `cache=` is unchanged.
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. External sites
ReviewsSee the guideline and AI policy for information on the review process. ConflictsReviewers, this pull request conflicts with the following ones:
If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first. LLM Linter (✨ experimental)Possible places where named args for integral literals may be used (e.g.
2026-12-01 23:58:55 |
Benchmark detailsAll runs: mainnet Desktop: AMD Ryzen 9 5950X, 64 GB RAM. NVMe SSD (Samsung 980 PRO 2 TB):
SATA HDD (Seagate ST4000DM004 4 TB), master run twice:
Raspberry Pi 4 (4 GB RAM), 1 TB SATA SSD (APS-SL3N-1T) in a USB 3 enclosure with UAS disabled:
The same Pi and SSD with UAS enabled, so the drive can queue many reads at once (queue depth 29 instead of 1), and the prevout fetch threads can overlap them. With UAS, the kernel picked a 64 MB readahead for this enclosure, which thrashed the page cache, so
Raspberry Pi 4, 4 TB HDD over USB. Master ran for 24 hours and reached height 449741, then the branch ran to the same height. Times are to the UpdateTip for that height:
Desktop NVMe SSD again, with
|
|
Non-required reading: Some of my earlier attempts to use cache memory more efficiently by optimizing spent coin representation. These didn't work out:
|
|
Hey Larry, welcome back. I checked out the code and took it for a spin: storing pending deletions separately from the main map could make sense if we can do it simply and safely. This version adds a lot of state to consensus-critical code for the gain I measured. It doesn't just depend on me of course, but if we can do this in a much simpler way (e.g. a separate map and dbcache hidden behind an interface) that doesn't affect anything else (and we can see meaningful improvements on weaker systems at least), I could be for this change. Issued flagged by my local AIs during review
|

This PR makes IBD (and
-reindexand-reindex-chainstate) faster and less resource-intensive.When a coin in the cache (dbcache) is spent and was created since the last flush to the chainstate database (disk), it can be erased from memory immediately. But if the coin had been flushed, it must be marked as spent in memory and retained until the next cache synchronization with the database (a flush or sync event), so the unspent version of the coin can be erased from the database.
Such a spent coin still occupies a full
cacheCoinsmap entry, about 128 bytes plus its share of the bucket array. During IBD, a large part of the cache holds spent coins. All that's needed to record a spent coin is its outpoint (the map key); the coin data isn't used.This PR periodically moves spent coin entries out of the map into a sorted vector of
COutPoints (36 bytes each), with a small blocked bloom filter in front of it (2-4 bytes per entry). This cuts the memory per spent coin from about 140 bytes to about 40. The cache can hold more total coins between flushes, so there are fewer cache-full flushes, fewer cache misses, and fewer chainstate (LevelDB) reads and writes. More coins are created and spent within a single flush cycle, so they never reach the chainstate database at all.Compaction runs when the number of spent entries in the map reaches a threshold, about 1M for default dbcache, scaled with the cache size. The spents are sorted and merged into a new vector as they're removed from the map. As the cache continues to fill, when the number of spent coins in the map reaches 20% of the vector size, we run another compaction cycle. Each cycle adds to the vector but frees space from the map, for a net space gain. The 20% choice balances avoiding many uncompacted spents in the map versus the overhead of updating (adding to) the vector. It's a fixed percentage because we want the space savings to scale with the overhead of vector growing and sorting. A minor tweak is that if the growth would exceed the initial threshold, we limit it to the threshold (we don't want the number of spents in the map to ever exceed the threshold). During a single flush cycle, compaction may run about 10 times (3 to 18 in my runs).
The downside of compacting spents is that when a coin isn't found in the map, we must now check the compacted spents list before looking in the chainstate (disk) database. Checking the spents list has two parts. First, we check the bloom filter. If the filter returns false (not found), then we go directly to disk. This happens most of the time. If the filter returns true, it could be a false positive (measured rate 0.025%), so we must binary-search the vector. (If found there, it's treated the same as finding a spent coin in the map. If not found, we go to disk.) This filter check is fast since it accesses a single CPU cache line (much faster than binary search of a large vector).
At flush or sync, the vector is passed to
BatchWrite()along with the cursor (used to iterate the map's dirty entries).BatchWrite()treats the vector's outpoints the same as spent coins in the map (they're erased from the chainstate).Compaction is enabled only for the main coins cache (
CoinsTip()). The per-block cache, mempool views, and otherCCoinsViewCacheinstances are unchanged. There's no new config option.Wall-clock time reduction isn't the only or even necessarily the biggest benefit of this patch. It reduces disk writes, which reduces SSD wear. The lower disk I/O and CPU use reduce resource competition with other services running on the same system. It's just a more efficient use of memory, and thus I/O bandwidth and CPU.
Results, mainnet
-reindex-chainstate, dbcache=1000:On the NVMe SSD, CPU time is 8% lower and SMART-measured device writes are 15% lower (678 vs 798 GB). On the desktop runs, flushes drop by about 30%. LevelDB reads drop 11% on the NVMe SSD and 6% (UAS off) and 12% (UAS) on the Pi. The wall-clock advantage is largest on the Pi, where both I/O and CPU are limited, since each avoided read costs more there. Details are in 2.
Crash safety: the erases are still part of the same atomic batch write, so the on-disk invariant is unchanged. If a compacted coin is re-created (in a reorg), the map entry takes precedence, and
RemoveShadowedSpents()removes the stale vector entry before eachBatchWrite().feature_dbcrash.pycaught this case in an earlier version.Concurrency with #35295's prevout fetchers: the new lookup paths are read-only, and the vector and filter are only modified after
StopFetching()has joined the workers.Summary of commits:
coins: track spent cache entries on a separate linked listlets spent entries be gathered without scanning the map. No behavior change.coins: add sorted outpoint vector to hold spent cache entriesis the core change: compaction, lookups, theBatchWrite()spents parameter, andRemoveShadowedSpents(). It's disabled by default.test, fuzz: exercise spent-coin compaction aggressively. The fuzz targets now read a compaction threshold from the input, so existing qa-assets seeds for these targets are interpreted differently.validation: enable spent-coin compaction for the coins tip cachesets the threshold from the dbcache size, and caps the large-cache flush trigger at 95% to leave room for a compaction.coins: add a blocked bloom filter in front of compact-spents lookupscuts the cost of a lookup for a coin that isn't in the map (avoids binary search).validation: log estimated in-use coins cache memory in UpdateTipis optional. With compaction, thecache=figure in the log steps up and then plateaus, because freed map nodes stay in the pool's free lists. This adds acache_used=estimate alongside it.Footnotes
Master was run twice (8:45 and 8:39, a 1.2% difference). The master time shown is the mean. ↩
full benchmark results ↩