This PR makes IBD (and -reindex and -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 cacheCoins map 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 other CCoinsViewCache instances 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:
| hardware | wall-clock improvement |
|---|---|
| Raspberry Pi 4, USB SSD (UAS off), to height 600k | −12.6% (54.6 h vs 62.4 h) |
| Raspberry Pi 4, USB SSD (UAS), to height 600k | −14.7% (7.9 h vs 9.2 h) |
| SATA HDD, to height 974k | −5.3% (8:14 vs 8:42) [^1] |
| NVMe SSD, to height 974k | −2.1% (2:22 vs 2:25) |
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 each BatchWrite(). feature_dbcrash.py caught 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.
[^1]: Master was run twice (8:45 and 8:39, a 1.2% difference). The master time shown is the mean. [^2]: full benchmark results