1 minor finding · 6 suggestions
Findings
[minor] · The copied-position undo reader arrives after its caller
Source inspection shows that the base calls an undeclared ReadBlockUndo() overload, preventing independent builds of the earlier stack; this PR supplies it only later, and no build was run.
Location: src/node/blockstorage.h:798 (head).
Details and suggested fix
The TakeBackCommit() callback attributed to c66f2288b8d59b18d9213a030af3a096105e4ceb, the window-connection commit in #45, calls ReadBlockUndo(undo, pos, prev_hash). The pinned base declares only the index overload. The position overload is added by 7e9df4791ac3a25651ddfe21cc63248cbee91b9b, the reorg-read-ahead commit here. Although the head supplies the missing method, the earlier stack cannot compile this call, obstructing per-PR validation and bisection.
Move the overload declaration and the reader split from 7e9df4791ac3a25651ddfe21cc63248cbee91b9b into c66f2288b8d59b18d9213a030af3a096105e4ceb, then describe the reorg commit as reusing it. The extraction needs only the existing undo-reader machinery and leaves the combined tree unchanged.
Optional improvements
[suggestion] · Reorg tests never change the target during read-ahead
The fixed-target tests cannot distinguish correct re-selection from regressions in replacement-branch planning or reuse of reads when the target is extended.
Location: src/test/validation_chainstate_tests.cpp:436 (head).
Details and suggested fix
CheckReorgReadAhead() stores both branches before calling ActivateBestChain(), so the target recomputed after ReadForReorg() remains unchanged. Different ancestry must discard the old plan and prepare new reads, whereas an extension must retain the existing reads to avoid restarting prefetch on each arrival. Add a deterministic pause in ReadForReorg() outside cs_main, before the first disconnect. Store a higher-work replacement branch and check its final tip and coins. In a second case, extend the original target and check that activation reaches the extension without repeating the prefetch batch. Both cases can preserve the existing uninterrupted reorg hold.
[suggestion] · Disconnect read-ahead can go unused without failing the tests
Both reorg tests would still pass if disconnect-side prefetch were ignored, because their logs observe produced reads and connect-side reuse, while synchronous fallback preserves the final coins.
Location: src/test/validation_chainstate_tests.cpp:435 (head).
Details and suggested fix
The disconnect count logged by ReadForReorg() measures read.block != nullptr, not consumption by DisconnectTip(). Dropping TakeDisconnect() from PlanConnectStep(), or discarding the prefetched undo data, would move those reads back under cs_main. Their BLOCK_FILE_WORK_UNDER_CS_MAIN scopes deliberately permit this, so neither the lock check nor the final tip and coin assertions would detect the lost optimization. Make consumption of both the pre-read block and undo data observable, then assert two such consumptions in the shallow case and sixteen in the deep case, with the remaining disconnects using the fallback.
[suggestion] · Default page-cache release lacks evidence for its intended benefit
Linux windowed IBD now advises dropping older block-file cache pages when no historical chainstate exists, but the reported local run shows unchanged throughput and leaves the intended huge-page benefit unverified.
Location: src/validation.cpp:4407 (head).
Details and suggested fix
ReleaseBlockFilesBelow() opens each newly passed file and issues whole-file POSIX_FADV_DONTNEED advice. This affects the file's shared cache, not just this sync's reads, so subsequent readers may need disk I/O again. The sixteen-file lag and historical-chainstate guard limit that tradeoff, but there is no independent opt-out. The commit reports unchanged local throughput and leaves the expected huge-page gain for a mainnet-scale sync to demonstrate. Keep this optimization behind a debug-only option until measurements show fewer huge-page fallbacks or improved throughput, rather than enabling the cache-policy change by default.
[suggestion] · Partial disconnect read-ahead has no regression test
The deep reorg exercises an empty DisconnectRead, but no test covers a successfully prefetched block whose undo read fails and must be retried under cs_main.
Location: src/validation.cpp:5491 (head).
Details and suggested fix
ReadForDisconnect() keeps the block when its undo read fails. DisconnectTip() must then use that block and obtain the missing undo data through the scoped index-based DisconnectBlock() fallback. The standalone wrong-parent checksum test never passes a partial result through this path. Inject a one-shot failure affecting only the speculative undo read, allow the locked retry to succeed, and disconnect a block containing a spend. Check the restored input coin and final tip, including in a DEBUG_LOCKORDER build.
[suggestion] · Page-cache advice delays submission of the block's validation
In Linux IBD resumed at a high file number, an initial windowed read can scan older files before queueing validation, delaying ordered publication; the elapsed cost is unmeasured.
Location: src/validation.cpp:4407 (head).
Details and suggested fix
m_block_files_released starts at zero, so the winning I/O task scans [0, pos.nFile - 16) before Submit(), performing open, posix_fadvise and close for files it successfully opens. If this task holds the lowest block in flight, the connector cannot publish it until that scan finishes. Capture read->data && staged.release_files before submission, then perform the advisory release after Submit() and its inline fallback. Use the copied position and flag so the trailing work does not inspect moved read data or a potentially freed staged object.
[suggestion] · Page-cache release boundaries and guards are untested
No test detects an off-by-one release boundary, repeated advice, or eviction advice during historical sync or after a failed read.
Location: src/node/blockstorage.cpp:1474 (head).
Details and suggested fix
The atomic watermark selects [from, file), and the caller subtracts BLOCK_FILE_RELEASE_LAG before advancing it. Route the advice through an injectable sink and assert that a successful read from file 17 advises only file 0, followed by a read from file 19 advising files 1 and 2. Repeated or lower positions should advise nothing. Also exercise the caller with a historical chainstate and with a failed read, checking that neither produces advice. These assertions test the selection policy without depending on whether the kernel actually evicts pages.
Background
Ralph's summary of historical context for the behaviour affected by this change. The historical record reviewed here is incomplete.
Documented decisions
CBlockIndex identity and immutable ancestry deliberately outlive individual block files. In the historical discussion of passing index pointers to notification consumers, Pieter Wuille explained that pruning can remove disk-position information without removing index entries; parent links, skip links, chainwork, block hash, height, and other header-derived facts remain immutable.
This distinguishes safe references from mutable storage metadata. Reorg prefetch can retain index pointers and use immutable hashes and ancestry after releasing cs_main, while block and undo positions must be copied under the lock. PruneOneBlockFile at the pinned base clears availability flags and offsets rather than deleting the index objects.
Copying a file position is not a promise that pruning cannot remove its file. The historical proposal explicitly advocated locking only to read position metadata and releasing the lock before disk I/O; the existing ordering contract permits this only when the position remains readable or the reader handles failure.
The new copied-position undo overload inherits a best-effort read contract, not a read-side pruning pin. Reorg prefetch leaves failed reads absent, and its retained blocks are associated with their index entries. This is materially different from assuming that a valid index pointer guarantees available bytes.
Earlier concurrency work separated undo I/O from ordered publication: undo writes and their subsequent BlockConnected notifications run through the effects executor, and pruning waits for queued work when it will actually take files. This preserves availability and notification ordering without making every block wait synchronously for disk work.
At the pinned base, claiming undo space does not publish nUndoPos or BLOCK_HAVE_UNDO. Successful completion publishes them under cs_main, and SettleUndoWrites waits for I/O and applies completions. Reorg prefetch must therefore settle a queued write and recopy its position rather than treating an initially null undo position as permanent absence. The base also requires settlement before disconnection so connection notifications cannot be overtaken by disconnection notifications.
Reorg locking protects an externally coherent chain-and-mempool transition, not merely individual container accesses. The 2017 forward-progress change explicitly prohibited releasing cs_main after merely attempting a reorg, because internal structures could remain inconsistent. The preceding window proposal likewise requires reorg connection signals to wait until disconnected transactions have been returned to the mempool, and published tip snapshots must not expose intermediate reorg tips.
The pinned base retains cs_main and the mempool lock from disconnection through step completion: the tip is temporarily behind, candidates describe a partially switched chain, and the mempool is inconsistent with that tip. If a candidate proves invalid, the uninterrupted hold also covers recovery while the tip remains worse than its starting point. Prefetch belongs before this transition; deeper or missing reads remain synchronous exceptions rather than reasons to expose intermediate state.
Source 1 · Source 2 · Source 3
Ralph's inferences
The file-lifetime rules protect outstanding writes more strongly than speculative readers. In-flight block writes pin their files; pruning settles queued effects before selecting files; pruned file numbers are not reclaimed for later writes; and the pruning ceiling also preserves blocks needed to replay from the lagging coins database.
Together these rules prevent an outstanding write from targeting an unlinked file, a late undo completion from restoring availability for an already-pruned block, or deferred unlinking from deleting a newly reused file number. They do not make a copied read position infallible. Reorg prefetch relies on these existing write-order guarantees plus read-failure handling, rather than acquiring a new file-lifetime guarantee.
The read-ahead cap exchanges bounded retained memory and queued work for incomplete removal of reorg I/O from the critical section. The prefetched objects coexist: at most 16 disconnect blocks with their undo data and 16 connect blocks. Deeper reorganisations read the remainder under the uninterrupted hold.
The cap prevents speculative retention from growing with arbitrary fork depth while retaining the existing atomic transition. It is a count bound, not the byte-budget mechanism used for the normal connection window, and it is not a maximum supported reorg depth. The inspected evidence explains having a bound, but not the numerical optimality of 16.
Page-cache release trades possible rereads against memory available to the coin store, particularly huge-page allocation. The lag accommodates the mismatch between arrival-order file placement and height-order validation: files sufficiently far behind are unlikely to be useful soon, but releasing one early remains a performance cost rather than a correctness event.
The head advises release only after a successful window read, for files strictly below the current file minus 16—17 or more files behind—and documents that each file is advised once. Release is disabled when a historical chainstate exists, consistent with avoiding eviction ahead of a second reader far behind the active chainstate. These are resource-policy choices, distinct from pruning or undo durability; the inspected record does not establish the exact lag's tuning or a realised huge-page benefit.