Skip to content

node: batch block file pruning in a single pass over block index - #36621

Open
mutatrum wants to merge 3 commits into
bitcoin:masterfrom
mutatrum:pr-batch-pruning
Open

mutatrum wants to merge 3 commits into
bitcoin:masterfrom
mutatrum:pr-batch-pruning

Conversation

@mutatrum

@mutatrum mutatrum commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

When enabling pruning on a full chain (e.g. -prune=550) or pruning a large backlog after downtime, FindFilesToPrune and FindFilesToPruneManual previously called PruneOneBlockFile once per file. Because PruneOneBlockFile scanned all of m_block_index on every call, pruning $M$ files across $N$ blocks took $O(M \times N)$ work (~5.6B iterations for ~5,770 files and ~972k blocks, stalling startup while holding cs_main).

This PR splits the changes into three commits:

  1. Test setup and manual pruning test: Apply BlockManager options in ChainTestingSetup and add blockmanager_find_files_to_prune_manual, covering file selection through FlushStateToDisk on both sides of the prune height cutoff.
  2. Batch block file pruning: Replace PruneOneBlockFile with PruneBlockFiles(const std::set<int>&) to prune all selected files in a single pass over m_block_index using a std::vector<bool> bitmap (sized to MaxBlockfileNum() + 1, independent of how many files are selected). Out-of-range file numbers are rejected up front before any index entry is modified. Adds blockmanager_prune_unlinked_siblings, and updates existing caller tests.
  3. Skip data-less index entries: Skip CBlockIndex entries without BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO in PruneBlockFiles. Because header-only and already-pruned entries also have nFile == 0, this avoids dirtying them when file 0 is selected (after file 0 is pruned, both selectors skip its zero-sized record, so batching is what accounts for the speedup on later backlogs). Adds blockmanager_prune_skips_dataless_entries.

Benchmarked with ~972k blocks and 5,770 files to prune:

  • x86_64 (i7-8665U @ 1.90 GHz): 75.1s -> 14.7ms
  • ARM64 (Raspberry Pi 5): 606.0s -> 26.3ms

@DrahtBot

DrahtBot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

External sites

Reviews

See the guideline and AI policy for information on the review process.

Type Reviewers
Concept ACK jeanpablojp, l0rinc

If your review is incorrectly listed, please copy-paste <!--meta-tag:bot-skip--> into the comment that the bot should ignore.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #37094 (validation: validate assumeutxo snapshots with a single chainstate by fjahr)
  • #36858 (refactor: break the blockstorage/validation circular dependency by pzafonte)
  • #36856 (kernel: add manual pruning by pzafonte)
  • #36854 (kernel: let callers create the block manager by pzafonte)
  • #36739 (refactor: pass BlockManager to ChainstateManager by pzafonte)
  • #36738 (refactor: move block writes and pruning into BlockManager by pzafonte)
  • #36548 (net: serve MSG_BLOCK by stripping witnesses in place by l0rinc)
  • #36149 (validation: Leave some pruned blocks in m_blocks_unlinked, fix another nSequenceId issue by mzumsande)
  • #36000 (validation: prefetch blocks while connecting by l0rinc)
  • #35731 (Indexes: Harden the flush-error notification invariant by arejula27)

If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.

LLM Linter (✨ experimental)

Possible places where comparison-specific test macros should replace generic comparisons:

  • src/test/blockmanager_tests.cpp: BOOST_CHECK_THROW(blockman.PruneBlockFiles({-1}), std::out_of_range) → Prefer BOOST_CHECK_EXCEPTION(..., std::out_of_range, HasReason{"PruneBlockFiles: file number out of range"}).
  • src/test/blockmanager_tests.cpp: BOOST_CHECK_THROW(blockman.PruneBlockFiles({1, 4}), std::out_of_range) → Prefer BOOST_CHECK_EXCEPTION(..., std::out_of_range, HasReason{"PruneBlockFiles: file number out of range"}).

2026-12-03 10:53:12

@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task macOS-cross to x86_64: https://github.com/bitcoin/bitcoin/actions/runs/39947671739/job/120394208316
LLM reason (✨ experimental): CI failed compiling blockmanager_tests.cpp: Clang’s thread-safety checks report accesses to nFile and nStatus without holding cs_main, and -Werror treats them as errors.

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • An intermittent issue.

Leave a comment here, if you need help tracking down a confusing failure.

@DrahtBot

DrahtBot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task ASan + LSan + UBSan + integer: https://github.com/bitcoin/bitcoin/actions/runs/41544539018/job/125616778379
LLM reason (✨ experimental): CI failed because blockmanager_tests triggered UBSan on an implicit signed-to-unsigned conversion in BlockManager::PruneBlockFiles (blockstorage.cpp:280).

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • An intermittent issue.

Leave a comment here, if you need help tracking down a confusing failure.

@jeanpablojp jeanpablojp left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Concept ACK

The speedup holds here too. PruneBlockFiles takes 0.65s on my i9 laptop for a first prune, and 0.09s, one pass over the index, when the entries are already pruned.

nit: the commit message still says out-of-range file numbers are rejected with vector::at(). Maybe the message could name the explicit range check instead.

@l0rinc l0rinc left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Concept ACK

I also had this in my backlog, solved it slightly differently, I did a quick pass over the diff.
I’d split the batching from the change to which entries get marked dirty so each is easier to review. Ideally commits are telling a story, leading the reviewers through the changes. Besides splitting the commits, also check if you can simplify the added tests. As usual, please make sure you understand every line you're submitting so that reviewers not the first humans that will try to understand it fully. Human review is the bottleneck so please make sure it's easy to review.

The description is also quite verbose, a few details to fix in the description, quick AI summary of the suggestions:

The dirty-write savings apply when file 0 is selected. After file 0 has been pruned, both selectors skip its zero-sized record, so batching explains the savings after downtime. The mixed valid and out-of-range case calls PruneBlockFiles directly. The manual test covers file selection through FlushStateToDisk. The single index pass is the main improvement, and the bitmap size depends on the highest file number even when only a few files are selected.

Comment thread src/node/blockstorage.cpp Resolved
Comment thread src/test/blockmanager_tests.cpp Resolved
Comment thread src/test/blockmanager_tests.cpp Resolved
Comment thread src/test/blockmanager_tests.cpp Resolved
Comment thread src/node/blockstorage.cpp Resolved
@mutatrum

mutatrum commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the review! I've added all proposed patches, split the PR into 3 commits and condensed the PR description.

As usual, please make sure you understand every line you're submitting so that reviewers not the first humans that will try to understand it fully. Human review is the bottleneck so please make sure it's easy to review.

I am aware of this, I'm not submitting PRs lightly. I do understand the code changes, but I'm not familiar in the codebase. This was not a random AI find, I was thoroughly confused by the long pause at startup caused by this bug, and wanted to prevent other people from running into it as well. I will take your remarks into account for the future.

@DrahtBot

DrahtBot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task MSan: https://github.com/bitcoin/bitcoin/actions/runs/46905709854/job/143547183789
LLM reason (✨ experimental): intermittent_network: Docker image metadata requests to mirror.gcr.io returned HTTP 429 Too Many Requests, preventing the CI container image from building.

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • Intermittent network issues can occur; re-run CI for now, and report the issue if they keep happening.

  • A functional or integration test failure may be intermittent or unrelated to this pull request.
    If no dedicated issue thread exists, create a new one to track it.

Leave a comment here, if you need help tracking down a confusing failure.

@l0rinc l0rinc left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The split makes the batching and file-zero changes a bit easier to follow, but the implementation is still very verbose, please simplify it more - left some hints.

Comment thread src/test/blockmanager_tests.cpp Resolved
Comment thread src/test/blockmanager_tests.cpp Resolved
Comment thread src/test/blockmanager_tests.cpp Resolved
Comment thread src/test/blockmanager_tests.cpp Resolved
…uning

Apply BlockManager arguments via ApplyArgsManOptions in
ChainTestingSetup so unit tests can run in prune mode.

Add blockmanager_find_files_to_prune_manual to cover manual pruning
through FlushStateToDisk, closing file 2 and placing the prune cutoff
at file 1's last block so both sides of the height cutoff are tested.
When starting the node with pruning enabled (e.g. -prune=550) on a
node with full chain history or pruning many files at once,
FindFilesToPrune and FindFilesToPruneManual previously called
PruneOneBlockFile once per file.

Because PruneOneBlockFile iterated over the entire m_block_index for
each file, this was an O(M * N) operation (M = files to prune,
N = total blocks). When pruning a full chain (~5,770 files and ~972k
blocks), this triggered ~5.6 billion iterations and froze the node
for ~10 minutes on startup while holding cs_main.

Replace PruneOneBlockFile with PruneBlockFiles(const std::set<int>&),
which collects all candidate files and prunes them in a single pass
over m_block_index using a compact bitmap (std::vector<bool> sized to
MaxBlockfileNum() + 1). Validate the sorted set's extremes against
[0, MaxBlockfileNum()] up front and throw std::out_of_range so
out-of-range file numbers fail before any block index entry is
modified.

Add unit test blockmanager_prune_unlinked_siblings covering batch
pruning with a gap, m_blocks_unlinked sibling retention, and
out-of-range rejection, and update existing caller tests in
blockmanager_tests and rescan_tests.
CBlockIndex::nFile is only meaningful when BLOCK_HAVE_DATA or
BLOCK_HAVE_UNDO is set. Header-only and already-pruned entries also
have nFile == 0, so pruning file 0 previously matched them and marked
them dirty in m_dirty_blockindex.

Skip entries without BLOCK_HAVE_MASK in PruneBlockFiles to avoid
unnecessary dirty writes when file 0 is pruned and to avoid bitmap
lookups on already-pruned entries.

Extend blockmanager_prune_unlinked_siblings to verify that pruning
file 0 dirties the genesis entry while leaving the header-only parent
and already-pruned sibling clean, using a private test-access peer to
inspect m_dirty_blockindex.
@DrahtBot DrahtBot removed the CI failed label Dec 3, 2026
knst added a commit to knst/dash that referenced this pull request Dec 3, 2026
In a profiled mainnet IBD with -prune=2048, 7.4% of the validation thread's on-CPU samples between BRR and v19 (47-55% in windows with a prune event) were in PruneOneBlockFile under FindFilesToPrune: every pruned file walked all ~2.6M block index entries to find the few with that nFile, a 4.2-4.4 s stall under cs_main each time a 128 MiB block file became prunable.
BlockManager now keeps the index entries that have block or undo data grouped by file number. The map is built by one walk on the first PruneOneBlockFile call, so nodes that never prune pay nothing, and ReceivedBlockTransactions adds each stored block to it afterwards. Pruning a file takes its list out of the map and visits only those entries, clearing their data flags, positions and m_blocks_unlinked links and marking them dirty as before. Entries without data, which all have nFile 0, are no longer marked dirty when file 0 is pruned. Upstream bitcoin#36621 (open) batches all files of one prune into a single walk, which does not help IBD where each prune removes one file.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants