utxo split/1 durability

willcl-ark/bitcoin: PR #39

8 suggestions

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

Optional improvements

Link

[suggestion] · m_sync_failed does not prevent further block connection

For a kernel caller that continues after flushError, an earlier recovered sync failure can lead to an existing coins/tip assertion; production occurrence is unconfirmed.

Location: src/node/blockstorage.cpp:575 (head).

Details and suggested fix

m_sync_failed can be set by an ignored file-switch or undo-finalization flush before another block is connected. Even after the file recovers, ConnectTip() applies view.Flush() to CoinsTip() before a critical-cache or pruning IF_NEEDED write-out fails on that latch. It then returns before m_chain.SetTip(). Retrying connection reaches assert(hashPrevBlock == view.GetBestBlock()) because the coins already describe that block. Reject further block processing with state.Error() when the latch is set, before applying another block, rather than relying solely on the documented stop requirement.

The coins-ahead-of-tip failure already existed when the connection's own flush failed; the latch extends it to earlier, recovered failures. This requires a caller to continue contrary to the new contract. bitcoind already requests shutdown on flushError, and no occurrence of the full failure-then-retry sequence was observed.


Link

[suggestion] · Pre-commit flush failures also disable shutdown persistence

If a transient open or truncate failure clears before shutdown, m_sync_failed still prevents saving cached progress that the base could have persisted by retrying.

Location: src/node/blockstorage.cpp:573 (head).

Details and suggested fix

FlatFileSeq::Flush() collapses open failures, finalize/truncate failures, failed FileCommit() calls and final fclose() failures into false. Consequently even an open failure caused by descriptor exhaustion sets m_sync_failed. If that condition clears before Shutdown(), both forced flushes still return before writing the index and coins. bitcoind already shuts down on flushError, so the additional cost is losing cached validation progress, not changing whether the node stops. Return the failing stage and error from Flush() so known-retryable pre-commit failures, such as EMFILE while opening the file, can remain pending in the unsynced sets until a later successful sync. Keep the permanent latch for failed commits and other failures whose durability is uncertain.


Link

[suggestion] · The snapshot flush guard has no distinguishing regression test

No test pins failed-flush snapshot completion, and the default fixture's interrupt can make an assertion of STATS_FAILED pass even if this guard is removed.

Location: src/validation.cpp:6191 (head).

Details and suggested fix

Add a snapshot-completion case with the validated CoinsDB() behind its in-memory target and notifications that do not interrupt on flushError(). The default fixture sets m_interrupt through AbortNode(), so hashing would throw StopHashingException and return STATS_FAILED even without the new guard. With interruption disabled and stale coins on disk, removing the guard can instead reach HASH_MISMATCH and invalidate the snapshot. Assert STATS_FAILED, retained UNVALIDATED status and target, an existing snapshot directory, and no _INVALID directory. Restore the faulty file and repeat completion to cover the remembered-failure path.


Link

[suggestion] · DurabilityState conflates file sync status with the failure latch

After a failed flush, a successful cursor flush can yield Synced while m_sync_failed still prevents recording, contrary to the header's claim that the block stays Unsynced.

Location: src/node/durability_machine.h:33 (head).

Details and suggested fix

FlushStateToDisk() calls FlushChainstateBlockFile() before checking the latch through SyncWrittenFiles(). A successful cursor flush removes the file from its unsynced set even when m_sync_failed is already set, and DataDurability() and UndoDurability() then return Synced. Reword this paragraph to describe the independent run-wide failure latch: later cursor flushes may change the derived state, but Synced does not authorize recording after a failure. The declaration in blockstorage.h already makes this distinction correctly.


Link

[suggestion] · File-switch failures are missing from durability regression coverage

The tests inject failures only at explicit write-outs, leaving the ignored rollover flush untested as a source of permanent write-out failure.

Location: src/test/durability_machine_tests.cpp:108 (head).

Details and suggested fix

FindNextBlockPos() continues after FlushBlockFile(..., fFinalize=true, ...) fails, so later protection depends on remembering the failure at that call, not only at explicit write-out boundaries. The existing failure tests cover explicit flushes, while the rollover test injects no fault. In the -fastprune fixture, persist a baseline, accept an unflushed block in the current file, replace that file with a directory, and accept a sufficiently large block to force rollover. Restore the file and force a write-out. Assert that rollover occurred, the write-out fails, and both GetLastFlushedBlock() and persisted file information remain at the baseline.


Link

[suggestion] · The second block-file cursor has no durability regression test

Current tests can miss a block-file sync loop restricted to the flushing chainstate's cursor, because the non-cursor-file case checks only undo data.

Location: src/test/durability_machine_tests.cpp:49 (head).

Details and suggested fix

FlushChainstateBlockFile() selects one cursor by height, whereas the shared index can record blocks written through either cursor. The left-file test does not cover this distinction: rollover already synced the old block file, and only its undo file becomes dirty afterward. Set m_snapshot_height between two written heights to create distinct normal and assumed cursor files with pending block data. Verify that flushing the higher-height cursor leaves the lower file Unsynced, then that SyncWrittenFiles() makes it Synced. This directly pins the other-chainstate block-file case named in the commit message.


Link

[suggestion] · The snapshot guard has no rationale in the durability commit message

Commit 9d11db0d0b changes snapshot-completion behavior without explaining it in the message, obscuring a guard that is independently meaningful on the base.

Location: src/validation.cpp:6191 at 9d11db0d0b47 (commit) (commit).

Details and suggested fix

Commit 9d11db0d0b474a80b1e99d5d92ca495ce368f26a replaces the unchecked snapshot force-flush with a checked call returning STATS_FAILED, but its message does not mention snapshot validation. This guard matters because hashing CoinsDB() after an unsuccessful write can judge a valid snapshot against an older UTXO set. Put it in a prerequisite commit before that durability commit, or add this rationale to the existing message. FlushStateToDisk() already returns bool on the base, so placing the guard first avoids introducing sticky failure before its snapshot handling.


Link

[suggestion] · The durability fix is coupled to its diagnostic tables in one commit

Separating the synchronization barrier from its Assume-only tables would make the durability fix independently reviewable and backportable without the transition-table machinery.

Location: src/validation.cpp:2882 at 9d11db0d0b47 (commit) (commit).

Details and suggested fix

In 9d11db0d0b474a80b1e99d5d92ca495ce368f26a, the tracking sets, failure latch and SyncWrittenFiles() barrier share a commit with the FLUSH_TABLE step lambda, per-entry DURABILITY_TABLE checks and derived-state accessors. The persistence changes need none of util/machine.h, introduced by a49c60467ce82d7ee565bf89fcba83d7f386852e; the PR also plans to replace the durability table in #45. Split the durability commit into the tracker, barrier, latch and snapshot guard first, followed by the tables, accessors and checks. Use outcome-based tests on return values, GetLastFlushedBlock() and persisted file information in the first commit, then add the DurabilityState assertions in the second. This isolates the persistence fix without changing the final tree or leaving the latch without its snapshot guard.


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

The file → block index → coins ordering was introduced to preserve a persistent reference chain: the index refers to file positions, and the coins database refers to a best-block hash in the index. Dirty tracking delayed index writes until their referenced data had been flushed.

This is the direct historical requirement behind the ordering now named by the flush table. It concerns recoverable references after an unclean shutdown, not merely the sequence of ordinary writes. The base already implements this ordering; the change expands which files must satisfy its first step.

Source 1 · Source 2 · Source 3

Strict dependency ordering deliberately enabled batching rather than flushing every block. The original proposal sought lower block-relay latency by moving nonessential persistence after relay and flushing according to elapsed time or cache pressure.

The historical tradeoff was crash recoverability with fewer synchronous operations, not durability of every newly received block immediately. Syncing additional written files changes the cost and coverage of a persistence boundary whose batching purpose remains relevant.

Source 1 · Source 2

Reindex was explicitly required to survive interruption and resume without corrupt undo data. #6948 distinguished existing block files, which reindex does not rewrite, from undo files, which it does generate; it therefore added file-switch flushing during reindex.

Reindex cannot be treated as uniformly read-only storage work. Historical acceptance of pre-existing block bytes does not remove the durability requirement for newly generated undo bytes. This distinction also limits what a current-run written-file tracker can certify about files inherited from an earlier run.

Source 1 · Source 2

Undo-file finalization was separated from block-file switching because receipt order and connection order differ. #17994 primarily addressed wasted preallocated space: an undo file can continue growing after its corresponding block file is left behind, so finalization must cover both caught-up and lagging-validation cases.

This explains why the base combines cursor flushing, file-switch handling, and a highest-block-height trigger. The inspected history documents a trimming/finalization strategy; it does not establish that every possible later undo write is covered by synchronizing only the current cursor.

Source 1 · Source 2 · Source 3

Earlier error handling intentionally distinguished a failed persistence attempt from inherently unrecoverable corruption. In #27866, Ryan Ofsky distinguished valid-but-stale disk state from invalid disk state and argued for separate flush-error and fatal-error notifications. The subsequent revision deliberately stopped propagating file-switch and undo-finalization errors at those call sites.

The base's non-propagation was an explicit, conservative behavior-preservation decision, not a documented universal proof that flush failures are harmless. Its file-switch comment assumes previously written data introduces no expected additional block-data inconsistency, while acknowledging reindex undo and trimming qualifications. Sticky failure strengthens the persistence contract beyond that local return-code policy.

Source 1 · Source 2 · Source 3

The pinned predecessor #35714 explicitly required a failed block/undo flush to stop that invocation before index and coins writes, leaving the last-flushed marker unchanged. It intentionally retained later retries, including shutdown retries, and documented that connect/disconnect can propagate failure after applying coins changes but before updating the chain tip.

Permanent per-run failure is therefore a substantive extension of the immediately preceding contract. The documented in-memory ordering also explains why preventing persistence is not equivalent to making continued block processing safe after a failed write-out.

Source 1 · Source 2

Ralph's inferences

Pruning reverses the reference dependency: remove persistent index references before unlinking their files. Recovery additionally depends on retaining the block and undo data needed to reconstruct an interrupted coins update; write ordering alone is not an atomic transaction across these stores.

Both base and head place unlinking after the index write and before the coins write. ReplayBlocks uses indexed old/new tips, rolls back the old branch, and rolls forward the new branch using block data. Historically, autoprune also retained a recent-block window rather than promising arbitrary-depth recovery. These are the recovery constraints surrounding the new pruning and durability states, not a correctness assessment of their implementation.

Source 1

Multiple chainstates share the persistence dependency even though their write cursors differ. A chainstate-local cursor flush and a shared block-index write have different scopes.

The base selects the cursor using the flushing chainstate's tip height, whereas the head's index writer drains the shared dirty-index set. The new SyncWrittenFiles barrier and sticky failure act at BlockManager scope, so their consequences extend to write-outs initiated by either chainstate; they are not evidence that either chainstate's consensus state is invalid.

Snapshot verification requires the intended validated UTXO set to be available for hashing, not merely a completed hashing operation. Failure to persist that set is not evidence of a snapshot hash mismatch.

The base force-flushes and then computes statistics from validated_cs.CoinsDB(), rather than the in-memory coins cache. A persistence barrier that remains failed can therefore leave an older comparison set on disk. The supplied snapshot guard separates this inability to obtain the comparison state from a verdict on the snapshot.

Source 1

A run-local refusal to persist limits further commitments after uncertainty; it does not itself repair or revalidate storage inherited at restart.

The head barrier consults an in-memory failure flag and written-file sets. Historical reindex rationale separately accepts existing block files while requiring synchronization of newly generated undo data. Thus restart and reindex remain recovery boundaries, not proof that a later successful sync retroactively made an earlier failed write durable.

Source 1 · Source 2

Unresolved disagreements

The inspected record leaves the safe scope of retry unresolved. #27866 entertained sporadic failures and valid-but-stale disk state, while warning about indexing unsynchronized bytes; #35714 deliberately preserved later retries. No inspected historical source establishes when a successful retry restores the durability assurance lost by a failed fsync.

This is the central distinction between the accepted predecessor behavior and sticky per-run failure. The historical arguments explain why retryability and application-controlled shutdown existed, but do not independently settle the stronger operating-system failure model invoked by the new barrier.

Source 1 · Source 2 · Source 3