2 major findings · 1 minor finding · 6 suggestions
Findings
[major] · coinstatsindex saves a mismatched checkpoint on mid-range interruption
Interrupting coinstatsindex catch-up inside a range can save a MuHash that does not match the recovery locator, making the next startup fail even after a clean shutdown.
Location: src/index/base.cpp:276 (head).
Details and suggested fix
ProcessBlocks() checks m_interrupt before every block, so it can return after applying a non-empty prefix. This branch then discards db_batch without advancing the local pindex, but CoinStatsIndex::CustomAppend() has already changed m_muhash, its counters and current-block identity. When pindex is non-null, the shutdown handler commits that newer MuHash with the previous boundary's locator. For example, after completing [30,39] and applying blocks 40 through 45, interruption saves locator 39 with the accumulator for 45. On reopening, CustomInit() rejects the mismatch against block 39's stored digest, preventing startup with the index enabled until it is rebuilt or disabled. ChainStateFlushed() cannot repair this while m_synced is false. Interruption immediately after Rewind() can similarly checkpoint the pre-rewind local pindex with rewound subclass state.
Honor interruption only at completed range boundaries so the entries, retained subclass state and checkpoint tip remain aligned. Add a CoinStatsIndex interrupt-and-reopen test that checks the accumulator as well as the locator.
[major] · NextSyncRange() crashes when the active tip is an ancestor of the indexed tip
The trusted invalidateblock RPC can leave an index above the active tip, after which restarting with that index enabled crashes in NextSyncRange() if no replacement branch exists.
Location: src/index/base.cpp:181 (head).
Details and suggested fix
Let an index catch up to block B, invalidate B without an alternative branch, then restart. BaseIndex has no disconnect handler, so its best block remains B. The shutdown flush accepts the ancestor locator for T = B's parent but still checkpoints B. On restart, Init() restores B and starts unsynced. Here FindFork(B) returns T and Next(T) returns null, yet this function only returns std::nullopt when B equals the active tip. It therefore dereferences null at range.first->nHeight; enforcing Assume() would abort instead. Startup can keep failing while this chain/index relationship remains unchanged. The base returned null for the absent successor and handled it without crashing. Handle a null successor before computing the window, for example by returning no range as before, and add a restart test that shortens the chain without mining a replacement branch. No peer-only trigger is established.
[minor] · Sync() can overwrite callback progress during shutdown
A narrow shutdown race after m_synced becomes true lets Sync() overwrite callback progress and persist a mismatched coinstatsindex checkpoint.
Location: src/index/base.cpp:303 (head).
Details and suggested fix
The interrupt handler now runs outside the unsynced branch, including after the handoff and when Sync() starts already synced. Once the handoff publishes m_synced, a BlockConnected() callback can finish indexing P+1 while the sync thread retains local pindex P. If shutdown sets m_interrupt before this handler runs, it restores P and commits the accumulator for P+1 under locator P. A subsequent shutdown flush for P+1 is rejected because it is above the regressed best pointer, and CoinStatsIndex::CustomInit() rejects the checkpoint on restart. If the callback overlaps CustomCommit(), the accumulator access also races. The base performed no checkpoint after handing off. Keep interruption checkpointing inside the pre-handoff phase and return without touching index state once m_synced has been published.
Optional improvements
[suggestion] · initial_sync_reorg does not check multi-block rollback
initial_sync_reorg uses single-block ranges and a stateless simulator, so its final-tip assertions do not verify the rollback behavior introduced by multi-block processing.
Location: src/test/blockfilter_index_tests.cpp:486 (head).
Details and suggested fix
SetProcessingBatchSize(1) prevents a reorg inside a multi-block range. IndexBlockSim forwards appends to the no-op base hook and inherits the no-op removal hook, so omitting Rewind() would still allow the final summary assertions to pass. The real-filter batch-window test has no reorg. Keep the deterministic pause, but use a batch size greater than one and fork behind blocks already applied in that range. Give the simulator applied-block state and assert the exact reverse-order removals and replacement suffix, rather than only the final summary.
[suggestion] · 500-block batches lack a byte budget
All production indexes accumulate up to 500 blocks of writes outside -dbcache, although txindex and txospenderindex batch sizes vary with transaction and input counts.
Location: src/index/base.h:32 (head).
Details and suggested fix
SetProcessingBatchSize() is only called by tests, so no production index tunes the shared default. TxIndex queues one record per transaction and TxoSpenderIndex one per non-coinbase input. This increases pending storage from one block to an entire window, independently for each syncing index. Millions of transaction records require tens of MiB just for their transaction IDs, before positions and batch overhead; this is a size estimate, not a measured peak. Add a byte budget using CDBBatch::ApproximateSize() as an additional batch-ending condition between complete blocks, and advance pindex to the actual processed end. Keep the block-count cap and separate checkpointing so batching still reduces lock contention without making memory depend solely on the contents of 500 blocks.
[suggestion] · shutdown_during_initial_sync never observes batched entries
Because the simulator writes no entries, shutdown_during_initial_sync would still pass if writes happened per block or entries from an interrupted range reached the database.
Location: src/test/blockfilter_index_tests.cpp:468 (head).
Details and suggested fix
IndexBlockSim::CustomAppend() only pauses and calls the no-op base hook. The test therefore checks locator 39 after interruption and reopening without checking any indexed records. Have the simulator add height-to-hash records to the supplied batch, then check their visibility while paused, after interruption and after reopening. Under the current discard behavior, entries through 39 should exist and 40 through 44 should be absent; adjust that expectation to the chosen cancellation fix. Keep the locator checks and also let the reopened index finish syncing.
[suggestion] · 1628b10 promises batched writes before introducing them
1628b10 enables 500-block windows and changes interruption behavior, but the promised single-batch writes only arrive in e4b1fd0, splitting the processing unit's behavior across commits.
Location: src/index/base.cpp:185 at 1628b1005a74 (commit) (commit).
Details and suggested fix
At 1628b1005a74becbd82e128023bcdd70b86cc834, range.last becomes the window end, but ProcessBlocks() still writes each block directly and can stop between blocks without advancing local pindex. The message's claim that windows are flushed “in one go” only becomes true in e4b1fd09e49d2840317300fa6ad89a18aa094411, which supplies the shared CDBBatch. The shutdown-locator test follows in 1497086cdb0e64df861100e0715ffd975d4c41cf. Move e4b1fd0 before 1628b10, initially batching single-block ranges, so the window-enabling commit introduces its write unit and interruption semantics together. That ordering keeps the plumbing separate while making recovery review easier. It does not fix the partial-range checkpoint defect in the final tree.
[suggestion] · IndexBlockSim can hang while reporting a failed test
A unit-test assertion failure while the simulator is paused can leave its worker waiting on destroyed state, turning the failure into a hang or undefined behavior.
Location: src/test/blockfilter_index_tests.cpp:459 (head).
Details and suggested fix
In initial_sync_reorg, the BOOST_REQUIRE checks on BuildChain() and ProcessNewBlock() run after worker arrival but before allow_continue(). If one fails, unwinding destroys the simulator's latches and database before ~BaseIndex() interrupts and joins the worker. Interrupt() only sets a flag, so it cannot release m_continue_sync.wait(). The arrival wait can also block forever if the worker exits before reaching the requested height. Use a bounded arrival wait and failure-safe cleanup that releases the pause exactly once, interrupts, and joins while all simulator members are still alive.
[suggestion] · vPos adds avoidable temporary storage and a second traversal
The caller-owned CDBBatch lets TxIndex::CustomAppend() serialize positions directly, avoiding a per-block vector allocation and second traversal without changing the records.
Location: src/index/txindex.cpp:83 (head).
Details and suggested fix
WriteTxs() now only loops over vPos and writes into the supplied batch. Call batch.Write(std::make_pair(DB_TXINDEX, tx->GetHash().ToUint256()), pos) inside the existing transaction loop, before incrementing pos.nTxOffset, and remove the vector and helper. CDBBatch::Write() serializes the value immediately, so later offset updates do not change earlier records. This preserves the genesis exclusion, key encoding and caller-owned batch atomicity.
Background
Ralph's summary of historical context for the behaviour affected by this change. The historical record reviewed here is incomplete.
Documented decisions
Index-entry writes and progress checkpoints were deliberately separated to permit inexpensive forward processing while retaining a recoverable, potentially older restart point. The original rationale cites infrequent block-index flushing and avoiding cs_main acquisition to generate a locator on every BlockConnected call. Reprocessing entries after a crash is acceptable; corrupting the restart state is not.
The base writes entries per block but checkpoints periodically during Sync and through ChainStateFlushed after catch-up. The head changes entry writes to range batches while retaining the separate Commit path. Historically, writing entries does not by itself authorize advancing the recovery locator.
The full MuHash accumulator must be committed atomically with DB_BEST_BLOCK. #24138 explains that restoring an older locator with a newer accumulator causes replayed UTXOs to be accumulated twice, making subsequent results wrong. Independently written per-block records are different: replay can overwrite them safely.
Both pinned versions preserve this distinction: CustomAppend writes per-height results, while CustomCommit places DB_MUHASH in the locator's batch. Thus the recovery contract concerns the accumulator's logical block position, not merely atomicity of the entry-write batch.
A filter-index checkpoint also requires durable filter bytes and a saved flat-file position. The original design explicitly requires flushing the flat files before committing a new best block. A failed checkpoint may leave progress behind without corrupting the index, provided the preceding recovery state remains valid.
BlockFilterIndex::CustomCommit commits the current file before adding DB_FILTER_POS to the locator batch. CustomAppend separately changes the cached header, file position, and filter files. Batching LevelDB entries therefore does not encompass all state or durability effects of processing filters.
Recovery from a reorg must start from the exact block represented by the saved accumulator, then undo intervening blocks individually. #25193 replaced initialization directly at the active-chain fork point because changing the apparent tip without un-applying those blocks corrupts coinstatsindex.
The pinned initialization restores the locator's top block; Sync later invokes Rewind. CoinStatsIndex reverses UTXO contributions using block and undo data and restores associated counters from per-block records. The locator is a description of state, not a substitute for transforming that state.
The original requirement to commit at reorg fork points was superseded by a stronger recovery constraint: do not checkpoint state ahead of the flushed chainstate. #33212 explains that a crash can otherwise lose the block-index entries needed to undo the prematurely committed state, particularly for coinstatsindex. It consequently removed Commit from Rewind.
Both pinned versions retain this restriction. A reorg or completed entry batch is not independently sufficient reason to persist a new recovery locator. This history also means the 2019 fork-point-commit explanation must not be applied literally to the current Rewind contract.
Ralph's inferences
Discarding pending database writes is not equivalent to undoing a processed prefix. Any subsequent append, rewind, or checkpoint must use a logical tip consistent with the mutable state actually retained. A checkpoint must pair its locator with the corresponding MuHash, counters, current-block identity, and filter-header state; atomic entry batching alone does not establish that correspondence.
At the head, ProcessBlocks can stop within a range, while CustomAppend mutates subclass members and writes filter bytes as processing proceeds. The historical invariant applies to those effects as well as to the range's CDBBatch, without prescribing a particular cancellation implementation.
A reorg before the next checkpoint must preserve recovery from the still-persisted old checkpoint while transforming the actual applied suffix. Old-branch records must remain identifiable when height entries are replaced, and the block and undo data needed for accumulator rollback must remain available.
Both affected subclasses copy disconnected height entries to hash keys before replacement. CoinStatsIndex rollback reads per-block records and reverses the applied blocks. These dependencies concern all applied progress since the checkpoint, not just the persisted locator or the most recent batch boundary.
The filter-file position protects retained file references, so it is not simply another block-height counter. Rewinding logical chain progress does not necessarily permit rewinding the allocation position: filters retained under old-branch hash keys still reference their original bytes.
CustomRemove copies filter references and writes DB_FILTER_POS atomically with those copies, while restoring the previous cached header. Cancellation and reorg reasoning must therefore distinguish logical chain state from the file region occupied by retained references.
Unresolved disagreements
The inspected historical record leaves enforcement of flush ordering during initial index sync unresolved. In #33212, a reviewer noted that periodic and catch-up-completion commits could reach a tip not yet flushed; the author agreed this was possible when the chain advances during Sync and deferred further work.
The pinned base and head both retain periodic and completion/interruption checkpoint paths in Sync. The history establishes the intended recovery constraint, but does not establish that initial-sync commits automatically satisfy it. This is historical uncertainty, not an assessment of the current PR.