coins,dbwrapper: make point-read and txindex lookup failures fatal

bitcoin/bitcoin: PR #34132

2 minor findings · 6 suggestions

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

Findings

Link

[minor] · Non-validation database read errors now abort the whole node

Optional-index and rollback dumptxoutset read failures now abort validation and relay rather than failing one request; peer triggering requires existing corruption and filter-service options, and no production occurrence was identified.

Location: src/dbwrapper.cpp:369 (head).

Details and suggested fix

With -blockfilterindex and -peerblockfilters, a valid getcfheaders request for an uncached predecessor header reaches LookupFilterHeader, then LookUpOne and Read. Previously, a decode failure returned false, while the message-processing boundary caught LevelDB exceptions. Both now reach the unconditional abort in FatalReadError. The request does not create the corruption, but the damaged entry remains available to trigger the same failure after a restart.

During an on-disk rollback snapshot, a read failure in temp_utxo_<height> likewise now aborts instead of unwinding the RPC and running TemporaryUTXODatabase cleanup. Use a per-database failure policy: retain aborts for validation databases, let optional indexes report and propagate errors so orderly shutdown remains possible, and let scratch errors unwind the RPC. Restoring scratch recovery also requires an exception-capable coin-view path; a DBParams policy flag alone cannot bypass the newly noexcept lookups.


Link

[minor] · txindex failures skip the orderly shutdown they request

With -txindex, an unreadable block file or corrupt index now causes an immediate abort after requesting shutdown, bypassing normal persistence even though exceptions distinguish errors from absence; no production occurrence was identified.

Location: src/index/txindex.cpp:214 (head).

Details and suggested fix

FindTx and FindLegacyTx now follow their checked failure paths with FatalError(...); std::abort(). Normal node notification handling sets the fatal warning and requests shutdown, but the immediate abort bypasses the orderly path that persists the mempool and flushes chainstate. These branches previously threw std::runtime_error, so propagating an exception cannot be mistaken for not-found. Direct block reads still report errors, while with -rest, an unauthenticated /rest/tx request can reach this abort path; remote ability to induce the underlying file-open failure is unestablished. Keep fatal reporting, then throw a distinct error so the requested shutdown can attempt normal persistence, as other BaseIndex failures allow. Further storage faults could still prevent those writes from succeeding.


Optional improvements

Link

[suggestion] · Startup point-read aborts remove the existing recovery hints

Constructor and metadata point-read failures now bypass the GUI rebuild question and noninteractive recovery hint without replacement guidance; coin-view failures through the old error catcher already aborted.

Location: src/dbwrapper.cpp:360 (head).

Details and suggested fix

For example, reading OBFUSCATION_KEY in the CDBWrapper constructor now reaches FatalReadError and aborts. Previously, a LevelDB failure threw dbwrapper_error, which initialization converted to ChainstateLoadStatus::FAILURE. That returned status enabled the GUI rebuild question or the noninteractive -reindex/-reindex-chainstate hint. The replacement fatal notification only directs the user to the log. If aborting these startup reads is intentional, add recovery guidance appropriate to the affected database, distinguishing chainstate, block-index and optional-index rebuilding without implying that rebuilding repairs an underlying storage fault.


Link

[suggestion] · Public fatal_error documentation omits worker delivery and creation-time aborts

The public docs omit worker-thread/reentrancy constraints for fatal_error and creation-time aborts for btck_chainstate_manager_create; no current reentrant embedder handler was identified.

Location: src/kernel/bitcoinkernel.h:542 (head).

Details and suggested fix

The new database path invokes fatal_error synchronously on the reading thread. Prevout workers call PeekCoin while ConnectTip holds cs_main and can wait for their results. The C adapter forwards the notification directly, without serializing concurrent callbacks. A handler that re-enters btck_chainstate_manager_get_block_tree_entry_by_hash, or waits for the in-flight validation call, can block the worker while validation waits, preventing the subsequent abort. Document that delivery may occur concurrently on internal workers and that handlers must not wait for the operation or acquire its locks.

Also qualify the creation function's null-on-error documentation: point-read failures during construction or loading now abort instead of reaching its exception catches. These are documentation and handler-contract changes for an unstable API, not a stable-API compatibility objection.


Link

[suggestion] · Release note overstates fatal handling for iterator-based lookups

The release note describes database lookup errors generally, but unchanged iterator-based FindTx scans can still return not-found when corruption hides all matching hashed entries and no legacy fallback applies.

Location: doc/release-notes-34132.md:4 (head).

Details and suggested fix

FindTx locates hashed entries through CDBIterator, not CDBWrapper::Read. On a data-block checksum failure, LevelDB saves the iterator error and skips the invalid block; CDBIterator::Valid() never checks status(). If this hides every matching hashed entry and no legacy fallback applies, FindTx returns nullopt, and getrawtransaction can still report the confirmed transaction as missing. Limit the release-note claim to direct key point reads and state that iterator behavior remains unchanged.


Link

[suggestion] · feature_init does not distinguish the new startup abort from normal failure

The chainstate/*.ldb startup round accepts any nonzero exit status plus a partial message match, so it cannot distinguish the intended abort from normal initialization failure after fatal reporting.

Location: test/functional/feature_init.py:169 (head).

Details and suggested fix

start_expecting_error uses assert_start_raises_init_error with ErrorMatch.PARTIAL_REGEX. AbortNode prints the expected database-read message before FatalReadError calls std::abort(). A regression that notified and then threw into initialization handling would therefore still pass. Start this round with node.start(...), then use node.wait_until_aborted(fatal_error="Error reading from database, shutting down.") to check the abort exit codes. Keep the chainstate/CURRENT database-open failure on the existing initialization-error helper.


Link

[suggestion] · New fatal txindex consistency branches lack targeted coverage

The tests cover unreadable tables and block-file opens, but not the newly fatal missing-BlockSeqKey, active-chain-without-data, or legacy txid-mismatch branches.

Location: src/index/txindex.cpp:186 (head).

Details and suggested fix

feature_io_errors.py renames a block file and requires the open-failure diagnostic. feature_coinsdb_read_error.py requires a LevelDB read-failure diagnostic. Neither establishes that the consistency branches abort rather than return an RPC error or nullopt, and the existing collision, legacy and reorg tests retain valid mappings and readable block data. Add targeted cases requiring the branch-specific diagnostic and wait_until_aborted(). For example, retain a hashed transaction entry but erase its referenced BlockSeqKey before looking it up.


Link

[suggestion] · ccoins_cache_have_inputs does not attribute the fetch to HaveInputs

In ccoins_cache_have_inputs, a premature-success regression in HaveInputs would still pass because a later GetCoin supplies the sole expected backing read.

Location: src/test/coins_tests.cpp:1105 (head).

Details and suggested fix

The test checks getcoin_calls only after GetCoin, AccessCoin, HaveCoin and SpendCoin. In the cold-cache case, HaveInputs could incorrectly return true without fetching anything, and the following GetCoin would still produce the single expected spy call. Immediately after the first HaveInputs, assert getcoin_calls == (prefilled ? 0 : 1) and HaveCoinInCache(outpoint). Keep the final count assertion to verify that subsequent cached operations make no additional backing reads.


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 wrapper's placement was an architectural boundary: keep UI and main-program dependencies out of shared database code. The original proposal also distinguished block-index reads because they occurred only during startup.

These sources explain why coin-read termination originally lived outside CDBWrapper rather than expressing one universal database error policy. Routing owner-supplied notifications into CDBWrapper changes that boundary while retaining an application-facing reporting interface.

Source 1 · Source 2 · Source 3

Unresolved disagreements

Historical kernel discussion questioned whether callback-before-return and calling-thread behavior should be explicit, enforced guarantees. One position requested documentation and enforcement; another distinguished normal blocking function calls from promises that would constrain future asynchronous delivery.

This bears directly on synchronous database notifications under locks. The inspected, truncated discussion does not justify asserting a universal enforced calling-thread guarantee for all kernel notifications.

Source 1 · Source 2 · Source 3