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

Open
mutatrum wants to merge 3 commits from pr-batch-pruning into master AGit
mutatrum commented 2026-10-23 11:39:55 +00:00 (Migrated from github.com)

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
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 commented 2026-10-23 11:40:03 +00:00 (Migrated from github.com)

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

<!--e57a25ab6845829454e8d69fc972939a--> The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. <!--006a51241073e994b41acfe9ec718e94--> ### External sites * Code coverage & benchmarks: https://corecheck.dev/bitcoin/bitcoin/pulls/36621 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/36621.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/36621#author-ralph <!--021abf342d371248e50ceaed478a90ca--> ### Reviews See [the guideline](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#code-review) and [AI policy](https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md) for information on the review process. | Type | Reviewers | | ---- | --------- | | Concept ACK | [jeanpablojp](https://github.com/bitcoin/bitcoin/pull/36621#pullrequestreview-6000584721), [l0rinc](https://github.com/bitcoin/bitcoin/pull/36621#pullrequestreview-6131484296) | If your review is incorrectly listed, please copy-paste <code>&lt;!--meta-tag:bot-skip--&gt;</code> into the comment that the bot should ignore. <!--174a7506f384e20aa4161008e828411d--> ### Conflicts Reviewers, this pull request conflicts with the following ones: * [#37094](https://github.com/bitcoin/bitcoin/pull/37094) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/37094.svg"></sub> (validation: validate assumeutxo snapshots with a single chainstate by fjahr) * [#36858](https://github.com/bitcoin/bitcoin/pull/36858) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36858.svg"></sub> (refactor: break the blockstorage/validation circular dependency by pzafonte) * [#36856](https://github.com/bitcoin/bitcoin/pull/36856) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36856.svg"></sub> (kernel: add manual pruning by pzafonte) * [#36854](https://github.com/bitcoin/bitcoin/pull/36854) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36854.svg"></sub> (kernel: let callers create the block manager by pzafonte) * [#36739](https://github.com/bitcoin/bitcoin/pull/36739) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36739.svg"></sub> (refactor: pass BlockManager to ChainstateManager by pzafonte) * [#36738](https://github.com/bitcoin/bitcoin/pull/36738) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36738.svg"></sub> (refactor: move block writes and pruning into BlockManager by pzafonte) * [#36548](https://github.com/bitcoin/bitcoin/pull/36548) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36548.svg"></sub> (net: serve `MSG_BLOCK` by stripping witnesses in place by l0rinc) * [#36149](https://github.com/bitcoin/bitcoin/pull/36149) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36149.svg"></sub> (validation: Leave some pruned blocks in `m_blocks_unlinked`, fix another `nSequenceId` issue by mzumsande) * [#36000](https://github.com/bitcoin/bitcoin/pull/36000) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36000.svg"></sub> (validation: prefetch blocks while connecting by l0rinc) * [#35731](https://github.com/bitcoin/bitcoin/pull/35731) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35731.svg"></sub> (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. <!--5faf32d7da4f0f540f40219e4f7537a3--> ### 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"})`. <sup>2026-12-03 10:53:12</sup>
First-time contributor

🔵 Suggestion · Invalid-batch test misses block-index changes before rejection

The invalid-batch test can miss premature changes to sibling 1's availability, disk position or unlinked membership because the following successful prune clears the same state.

Location: src/test/blockmanager_tests.cpp:144 (head).

🔵 Suggestion · Manual-pruning test conflates the requested and retention cutoffs

The manual-pruning test uses identical requested and retention cutoffs, so it would still pass if GetPruneRange ignored the requested height.

Location: src/test/blockmanager_tests.cpp:199 (head).

🔵 Suggestion · PR description names nonexistent pruning tests

The PR description points to two nonexistent test cases instead of blockmanager_prune_unlinked_siblings, which contains their described checks.

Location: src/test/blockmanager_tests.cpp:120 (head).


Reviewed: e7346a974631 · Review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:e1a29e5e677c47d383756f0fcf8f3760725c91d1104dd3ccb2f333b6217eba26:47880f5569fd2047d249266f337c4f2a509adf7d96c3ccb1c7644c2c2a650bff --> <!-- ralph-base:3a89a6a2a645acd9a691318250ce656a4e469bf5 --> <!-- ralph-head:e7346a974631184fd0d71ee1c99bce1fda564019 --> <!-- ralph-case:0c007f3d76cab0132766cccc9191e27304b878f1f8eb60d5418c287696086b05 --> **🔵 Suggestion · Invalid-batch test misses block-index changes before rejection** The invalid-batch test can miss premature changes to sibling 1's availability, disk position or unlinked membership because the following successful prune clears the same state. Location: [`src/test/blockmanager_tests.cpp:144`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/e7346a974631184fd0d71ee1c99bce1fda564019/src/test/blockmanager_tests.cpp#L144>) (head). **🔵 Suggestion · Manual-pruning test conflates the requested and retention cutoffs** The manual-pruning test uses identical requested and retention cutoffs, so it would still pass if `GetPruneRange` ignored the requested height. Location: [`src/test/blockmanager_tests.cpp:199`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/e7346a974631184fd0d71ee1c99bce1fda564019/src/test/blockmanager_tests.cpp#L199>) (head). **🔵 Suggestion · PR description names nonexistent pruning tests** The PR description points to two nonexistent test cases instead of `blockmanager_prune_unlinked_siblings`, which contains their described checks. Location: [`src/test/blockmanager_tests.cpp:120`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/e7346a974631184fd0d71ee1c99bce1fda564019/src/test/blockmanager_tests.cpp#L120>) (head). <!-- Review tier: sensitive --> --- Reviewed: [`e7346a974631`](<https://git.fish.foo/bitcoin/bitcoin/commit/e7346a974631184fd0d71ee1c99bce1fda564019>) · [Review report](<https://review.fish.foo/report/36621-e7346a974631184fd0d71ee1c99bce1fda564019-3475-15.html>) · [Previous reports](<https://review.fish.foo/traces/36621/>) [permalink](<https://review.fish.foo/report/36621-e7346a974631184fd0d71ee1c99bce1fda564019-3475-15.html>)
DrahtBot commented 2026-10-23 12:41:45 +00:00 (Migrated from github.com)

🚧 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.

<!--85328a0da195eb286784d51f73fa0af9--> 🚧 At least one of the CI tasks failed. <sub>Task `macOS-cross to x86_64`: https://github.com/bitcoin/bitcoin/actions/runs/39947671739/job/120394208316</sub> <sub>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.</sub> <details><summary>Hints</summary> 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. </details>
DrahtBot commented 2026-11-03 00:21:29 +00:00 (Migrated from github.com)

🚧 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.

<!--85328a0da195eb286784d51f73fa0af9--> 🚧 At least one of the CI tasks failed. <sub>Task `ASan + LSan + UBSan + integer`: https://github.com/bitcoin/bitcoin/actions/runs/41544539018/job/125616778379</sub> <sub>LLM reason (✨ experimental): CI failed because `blockmanager_tests` triggered UBSan on an implicit signed-to-unsigned conversion in `BlockManager::PruneBlockFiles` (`blockstorage.cpp:280`).</sub> <details><summary>Hints</summary> 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. </details>
jeanpablojp (Migrated from github.com) reviewed 2026-11-20 23:09:09 +00:00
jeanpablojp (Migrated from github.com) left a comment

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.

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 (Migrated from github.com) requested changes 2026-12-01 14:03:30 +00:00
l0rinc (Migrated from github.com) left a comment

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.

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.
l0rinc (Migrated from github.com) commented 2026-12-01 12:44:39 +00:00

The single index scan and the change to which entries get marked dirty are in the same commit, so it’s harder to review what batching does on its own. I’d put the ChainTestingSetup change and the manual pruning test first, then put batching and the file 0 change in separate commits.

The single index scan and the change to which entries get marked dirty are in the same commit, so it’s harder to review what batching does on its own. I’d put the `ChainTestingSetup` change and the manual pruning test first, then put batching and the file 0 change in separate commits.
l0rinc (Migrated from github.com) commented 2026-12-01 12:45:22 +00:00

PruneBlockFiles walks the selected files once to set the bits and again to clear their metadata. Both updates fit in the same loop.

Patch
diff --git a/src/node/blockstorage.cpp b/src/node/blockstorage.cpp
index f61f23e921..6725d3eef7 100644
--- a/src/node/blockstorage.cpp
+++ b/src/node/blockstorage.cpp
@@ -277,13 +277,16 @@ void BlockManager::PruneBlockFiles(const std::set<int>& setFilesToPrune)
 
     // Validate up front so an invalid file number fails before any block index
     // entry is modified. The extremes of the sorted set bound every entry.
-    if (*setFilesToPrune.begin() < 0 || *setFilesToPrune.rbegin() > this->MaxBlockfileNum()) {
+    const int max_file{this->MaxBlockfileNum()};
+    if (*setFilesToPrune.begin() < 0 || *setFilesToPrune.rbegin() > max_file) {
         throw std::out_of_range("PruneBlockFiles: file number out of range");
     }
 
-    std::vector<bool> prune_file(this->MaxBlockfileNum() + 1, false);
+    std::vector<bool> prune_file(max_file + 1, false);
     for (int fileNumber : setFilesToPrune) {
         prune_file[fileNumber] = true;
+        m_blockfile_info.at(fileNumber) = CBlockFileInfo{};
+        m_dirty_fileinfo.insert(fileNumber);
     }
 
     for (auto& entry : m_block_index) {
@@ -316,11 +319,6 @@ void BlockManager::PruneBlockFiles(const std::set<int>& setFilesToPrune)
             }
         }
     }
-
-    for (int fileNumber : setFilesToPrune) {
-        m_blockfile_info.at(fileNumber) = CBlockFileInfo{};
-        m_dirty_fileinfo.insert(fileNumber);
-    }
 }
 
 void BlockManager::FindFilesToPruneManual(
`PruneBlockFiles` walks the selected files once to set the bits and again to clear their metadata. Both updates fit in the same loop. <details> <summary>Patch</summary> ```diff diff --git a/src/node/blockstorage.cpp b/src/node/blockstorage.cpp index f61f23e921..6725d3eef7 100644 --- a/src/node/blockstorage.cpp +++ b/src/node/blockstorage.cpp @@ -277,13 +277,16 @@ void BlockManager::PruneBlockFiles(const std::set<int>& setFilesToPrune) // Validate up front so an invalid file number fails before any block index // entry is modified. The extremes of the sorted set bound every entry. - if (*setFilesToPrune.begin() < 0 || *setFilesToPrune.rbegin() > this->MaxBlockfileNum()) { + const int max_file{this->MaxBlockfileNum()}; + if (*setFilesToPrune.begin() < 0 || *setFilesToPrune.rbegin() > max_file) { throw std::out_of_range("PruneBlockFiles: file number out of range"); } - std::vector<bool> prune_file(this->MaxBlockfileNum() + 1, false); + std::vector<bool> prune_file(max_file + 1, false); for (int fileNumber : setFilesToPrune) { prune_file[fileNumber] = true; + m_blockfile_info.at(fileNumber) = CBlockFileInfo{}; + m_dirty_fileinfo.insert(fileNumber); } for (auto& entry : m_block_index) { @@ -316,11 +319,6 @@ void BlockManager::PruneBlockFiles(const std::set<int>& setFilesToPrune) } } } - - for (int fileNumber : setFilesToPrune) { - m_blockfile_info.at(fileNumber) = CBlockFileInfo{}; - m_dirty_fileinfo.insert(fileNumber); - } } void BlockManager::FindFilesToPruneManual( ``` </details>
l0rinc (Migrated from github.com) commented 2026-12-01 12:44:51 +00:00

The batch test would still pass if pruning erased every unlinked child under a parent, including one in a file it should keep. A separate test would check that pruning files 1 and 3 leaves the child in file 2 in m_blocks_unlinked.

Patch
diff --git a/src/test/blockmanager_tests.cpp b/src/test/blockmanager_tests.cpp
index 368a2042bf..7dc08b1e3e 100644
--- a/src/test/blockmanager_tests.cpp
+++ b/src/test/blockmanager_tests.cpp
@@ -231,6 +231,31 @@ BOOST_FIXTURE_TEST_CASE(blockmanager_prune_block_files_batch, TestChain100Setup)
     check_unmodified();
 }
 
+BOOST_FIXTURE_TEST_CASE(blockmanager_prune_unlinked_siblings, TestingSetup)
+{
+    auto& chainman{*Assert(m_node.chainman)};
+    auto& blockman{chainman.m_blockman};
+    LOCK(::cs_main);
+    auto* parent{chainman.ActiveChain().Tip()};
+    for (int file : {1, 2, 3}) {
+        CBlock block{chainman.GetParams().GenesisBlock()};
+        block.hashPrevBlock = parent->GetBlockHash();
+        block.nNonce = file;
+        const FlatFilePos pos{file, STORAGE_HEADER_BYTES};
+        blockman.UpdateBlockInfo(block, parent->nHeight + 1, pos);
+        auto* child{blockman.AddToBlockIndex(block, chainman.m_best_header)};
+        chainman.ReceivedBlockTransactions(block, child, pos);
+        blockman.AddUnlinkedBlock(child);
+    }
+
+    BOOST_REQUIRE_EQUAL(blockman.m_blocks_unlinked.count(parent), 3U);
+    blockman.PruneBlockFiles({1, 3});
+    BOOST_REQUIRE_EQUAL(blockman.m_blocks_unlinked.count(parent), 1U);
+    const auto* retained{blockman.m_blocks_unlinked.find(parent)->second};
+    BOOST_CHECK_EQUAL(retained->nFile, 2);
+    BOOST_CHECK(retained->nStatus & BLOCK_HAVE_DATA);
+}
+
 // Prune mode is required for FindFilesToPruneManual, and -prune=1 keeps automatic pruning disabled.
 struct PruneManualSetup : TestChain100Setup {
     PruneManualSetup() : TestChain100Setup{ChainType::REGTEST, TestOpts{.extra_args = {"-prune=1"}}} {}
The batch test would still pass if pruning erased every unlinked child under a parent, including one in a file it should keep. A separate test would check that pruning files 1 and 3 leaves the child in file 2 in `m_blocks_unlinked`. <details> <summary>Patch</summary> ```diff diff --git a/src/test/blockmanager_tests.cpp b/src/test/blockmanager_tests.cpp index 368a2042bf..7dc08b1e3e 100644 --- a/src/test/blockmanager_tests.cpp +++ b/src/test/blockmanager_tests.cpp @@ -231,6 +231,31 @@ BOOST_FIXTURE_TEST_CASE(blockmanager_prune_block_files_batch, TestChain100Setup) check_unmodified(); } +BOOST_FIXTURE_TEST_CASE(blockmanager_prune_unlinked_siblings, TestingSetup) +{ + auto& chainman{*Assert(m_node.chainman)}; + auto& blockman{chainman.m_blockman}; + LOCK(::cs_main); + auto* parent{chainman.ActiveChain().Tip()}; + for (int file : {1, 2, 3}) { + CBlock block{chainman.GetParams().GenesisBlock()}; + block.hashPrevBlock = parent->GetBlockHash(); + block.nNonce = file; + const FlatFilePos pos{file, STORAGE_HEADER_BYTES}; + blockman.UpdateBlockInfo(block, parent->nHeight + 1, pos); + auto* child{blockman.AddToBlockIndex(block, chainman.m_best_header)}; + chainman.ReceivedBlockTransactions(block, child, pos); + blockman.AddUnlinkedBlock(child); + } + + BOOST_REQUIRE_EQUAL(blockman.m_blocks_unlinked.count(parent), 3U); + blockman.PruneBlockFiles({1, 3}); + BOOST_REQUIRE_EQUAL(blockman.m_blocks_unlinked.count(parent), 1U); + const auto* retained{blockman.m_blocks_unlinked.find(parent)->second}; + BOOST_CHECK_EQUAL(retained->nFile, 2); + BOOST_CHECK(retained->nStatus & BLOCK_HAVE_DATA); +} + // Prune mode is required for FindFilesToPruneManual, and -prune=1 keeps automatic pruning disabled. struct PruneManualSetup : TestChain100Setup { PruneManualSetup() : TestChain100Setup{ChainType::REGTEST, TestOpts{.extra_args = {"-prune=1"}}} {} ``` </details>
l0rinc (Migrated from github.com) commented 2026-12-01 12:45:11 +00:00

The test repeats the same checks for file 1 after pruning and after each range error. One helper would keep those assertions in sync across all three calls.
See what else you can simplify since the tests are quite verbose.

Patch
diff --git a/src/test/blockmanager_tests.cpp b/src/test/blockmanager_tests.cpp
index 5f2a72f4e2..c7efe3a208 100644
--- a/src/test/blockmanager_tests.cpp
+++ b/src/test/blockmanager_tests.cpp
@@ -165,4 +165,12 @@ BOOST_FIXTURE_TEST_CASE(blockmanager_prune_block_files_batch, TestChain100Setup)
     const auto tip1_undo_pos{tip1->nUndoPos};
     const auto file1_size{blockman.GetBlockFileInfo(file1)->nSize};
+    const auto check_file1_untouched = [&]() EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
+        BOOST_CHECK(tip1->nStatus & BLOCK_HAVE_DATA);
+        BOOST_CHECK(tip1->nStatus & BLOCK_HAVE_UNDO);
+        BOOST_CHECK_EQUAL(tip1->nFile, file1);
+        BOOST_CHECK_EQUAL(tip1->nDataPos, tip1_data_pos);
+        BOOST_CHECK_EQUAL(tip1->nUndoPos, tip1_undo_pos);
+        BOOST_CHECK_EQUAL(blockman.GetBlockFileInfo(file1)->nSize, file1_size);
+    };
 
     blockman.PruneBlockFiles({file0, file2});
@@ -177,10 +185,5 @@ BOOST_FIXTURE_TEST_CASE(blockmanager_prune_block_files_batch, TestChain100Setup)
 
     // Blocks in the unselected file1 between them should remain completely untouched
-    BOOST_CHECK(tip1->nStatus & BLOCK_HAVE_DATA);
-    BOOST_CHECK(tip1->nStatus & BLOCK_HAVE_UNDO);
-    BOOST_CHECK_EQUAL(tip1->nFile, file1);
-    BOOST_CHECK_EQUAL(tip1->nDataPos, tip1_data_pos);
-    BOOST_CHECK_EQUAL(tip1->nUndoPos, tip1_undo_pos);
-    BOOST_CHECK_EQUAL(blockman.GetBlockFileInfo(file1)->nSize, file1_size);
+    check_file1_untouched();
 
     // Block file info records for both pruned files should be cleared, unselected kept
@@ -214,20 +217,11 @@ BOOST_FIXTURE_TEST_CASE(blockmanager_prune_block_files_batch, TestChain100Setup)
     // 5. An out-of-range file number is rejected before any index entry is modified,
     // including when it follows a valid, still-unpruned file in the set.
-    const auto is_range_error = [](const std::out_of_range& e) {
-        return std::string{e.what()} == "PruneBlockFiles: file number out of range";
-    };
-    const auto check_unmodified = [&]() EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
-        BOOST_CHECK(blockman.GetDirtyBlockIndex().empty());
-        BOOST_CHECK(tip1->nStatus & BLOCK_HAVE_DATA);
-        BOOST_CHECK(tip1->nStatus & BLOCK_HAVE_UNDO);
-        BOOST_CHECK_EQUAL(tip1->nFile, file1);
-        BOOST_CHECK_EQUAL(tip1->nDataPos, tip1_data_pos);
-        BOOST_CHECK_EQUAL(tip1->nUndoPos, tip1_undo_pos);
-        BOOST_CHECK_EQUAL(blockman.GetBlockFileInfo(file1)->nSize, file1_size);
-    };
-    BOOST_CHECK_EXCEPTION(blockman.PruneBlockFiles({-1}), std::out_of_range, is_range_error);
-    check_unmodified();
-    BOOST_CHECK_EXCEPTION(blockman.PruneBlockFiles({file1, file2 + 1}), std::out_of_range, is_range_error);
-    check_unmodified();
+    const HasReason range_error{"PruneBlockFiles: file number out of range"};
+    BOOST_CHECK_EXCEPTION(blockman.PruneBlockFiles({-1}), std::out_of_range, range_error);
+    BOOST_CHECK(blockman.GetDirtyBlockIndex().empty());
+    check_file1_untouched();
+    BOOST_CHECK_EXCEPTION(blockman.PruneBlockFiles({file1, file2 + 1}), std::out_of_range, range_error);
+    BOOST_CHECK(blockman.GetDirtyBlockIndex().empty());
+    check_file1_untouched();
 }
 
The test repeats the same checks for file 1 after pruning and after each range error. One helper would keep those assertions in sync across all three calls. See what else you can simplify since the tests are quite verbose. <details> <summary>Patch</summary> ```diff diff --git a/src/test/blockmanager_tests.cpp b/src/test/blockmanager_tests.cpp index 5f2a72f4e2..c7efe3a208 100644 --- a/src/test/blockmanager_tests.cpp +++ b/src/test/blockmanager_tests.cpp @@ -165,4 +165,12 @@ BOOST_FIXTURE_TEST_CASE(blockmanager_prune_block_files_batch, TestChain100Setup) const auto tip1_undo_pos{tip1->nUndoPos}; const auto file1_size{blockman.GetBlockFileInfo(file1)->nSize}; + const auto check_file1_untouched = [&]() EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { + BOOST_CHECK(tip1->nStatus & BLOCK_HAVE_DATA); + BOOST_CHECK(tip1->nStatus & BLOCK_HAVE_UNDO); + BOOST_CHECK_EQUAL(tip1->nFile, file1); + BOOST_CHECK_EQUAL(tip1->nDataPos, tip1_data_pos); + BOOST_CHECK_EQUAL(tip1->nUndoPos, tip1_undo_pos); + BOOST_CHECK_EQUAL(blockman.GetBlockFileInfo(file1)->nSize, file1_size); + }; blockman.PruneBlockFiles({file0, file2}); @@ -177,10 +185,5 @@ BOOST_FIXTURE_TEST_CASE(blockmanager_prune_block_files_batch, TestChain100Setup) // Blocks in the unselected file1 between them should remain completely untouched - BOOST_CHECK(tip1->nStatus & BLOCK_HAVE_DATA); - BOOST_CHECK(tip1->nStatus & BLOCK_HAVE_UNDO); - BOOST_CHECK_EQUAL(tip1->nFile, file1); - BOOST_CHECK_EQUAL(tip1->nDataPos, tip1_data_pos); - BOOST_CHECK_EQUAL(tip1->nUndoPos, tip1_undo_pos); - BOOST_CHECK_EQUAL(blockman.GetBlockFileInfo(file1)->nSize, file1_size); + check_file1_untouched(); // Block file info records for both pruned files should be cleared, unselected kept @@ -214,20 +217,11 @@ BOOST_FIXTURE_TEST_CASE(blockmanager_prune_block_files_batch, TestChain100Setup) // 5. An out-of-range file number is rejected before any index entry is modified, // including when it follows a valid, still-unpruned file in the set. - const auto is_range_error = [](const std::out_of_range& e) { - return std::string{e.what()} == "PruneBlockFiles: file number out of range"; - }; - const auto check_unmodified = [&]() EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { - BOOST_CHECK(blockman.GetDirtyBlockIndex().empty()); - BOOST_CHECK(tip1->nStatus & BLOCK_HAVE_DATA); - BOOST_CHECK(tip1->nStatus & BLOCK_HAVE_UNDO); - BOOST_CHECK_EQUAL(tip1->nFile, file1); - BOOST_CHECK_EQUAL(tip1->nDataPos, tip1_data_pos); - BOOST_CHECK_EQUAL(tip1->nUndoPos, tip1_undo_pos); - BOOST_CHECK_EQUAL(blockman.GetBlockFileInfo(file1)->nSize, file1_size); - }; - BOOST_CHECK_EXCEPTION(blockman.PruneBlockFiles({-1}), std::out_of_range, is_range_error); - check_unmodified(); - BOOST_CHECK_EXCEPTION(blockman.PruneBlockFiles({file1, file2 + 1}), std::out_of_range, is_range_error); - check_unmodified(); + const HasReason range_error{"PruneBlockFiles: file number out of range"}; + BOOST_CHECK_EXCEPTION(blockman.PruneBlockFiles({-1}), std::out_of_range, range_error); + BOOST_CHECK(blockman.GetDirtyBlockIndex().empty()); + check_file1_untouched(); + BOOST_CHECK_EXCEPTION(blockman.PruneBlockFiles({file1, file2 + 1}), std::out_of_range, range_error); + BOOST_CHECK(blockman.GetDirtyBlockIndex().empty()); + check_file1_untouched(); } ``` </details>
l0rinc (Migrated from github.com) commented 2026-12-01 12:45:01 +00:00

File 2 is still active, so the prune loop skips it without checking its height. I’d close it and set the cutoff at file 1’s last block so the test covers both sides of the cutoff.

Patch
diff --git a/src/test/blockmanager_tests.cpp b/src/test/blockmanager_tests.cpp
index 7dc08b1e3e..5f2a72f4e2 100644
--- a/src/test/blockmanager_tests.cpp
+++ b/src/test/blockmanager_tests.cpp
@@ -278,16 +278,16 @@ BOOST_FIXTURE_TEST_CASE(blockmanager_find_files_to_prune_manual, PruneManualSetu
     WITH_LOCK(chainman.GetMutex(), blockman.GetBlockFileInfo(file1)->nSize = MAX_BLOCKFILE_SIZE);
     CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
 
-    // Everything mined below stays in file2, which lies above the prune height.
     const CBlockIndex* block_file2{WITH_LOCK(chainman.GetMutex(), return chainman.ActiveChain().Tip())};
     const int file2{WITH_LOCK(chainman.GetMutex(), return block_file2->GetBlockPos().nFile)};
-    const int prune_height{block_file2->nHeight};
-    BOOST_CHECK_EQUAL(file2, file1 + 1);
+    const int prune_height{block_file1->nHeight};
+    BOOST_REQUIRE_EQUAL(block_file2->nHeight, prune_height + 1);
 
-    // The manual prune range ends MIN_BLOCKS_TO_KEEP below the tip.
-    while (WITH_LOCK(chainman.GetMutex(), return chainman.ActiveChain().Height()) < prune_height + static_cast<int>(MIN_BLOCKS_TO_KEEP)) {
-        CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
-    }
+    // Close file2 so the prune loop considers it alongside file0 and file1.
+    WITH_LOCK(chainman.GetMutex(), blockman.GetBlockFileInfo(file2)->nSize = MAX_BLOCKFILE_SIZE);
+
+    // File 2 already starts one block above the cutoff.
+    mineBlocks(MIN_BLOCKS_TO_KEEP - 1);
 
     // FlushStateToDisk is the manual-pruning path used by the pruneblockchain RPC.
     BlockValidationState state;
File 2 is still active, so the prune loop skips it without checking its height. I’d close it and set the cutoff at file 1’s last block so the test covers both sides of the cutoff. <details> <summary>Patch</summary> ```diff diff --git a/src/test/blockmanager_tests.cpp b/src/test/blockmanager_tests.cpp index 7dc08b1e3e..5f2a72f4e2 100644 --- a/src/test/blockmanager_tests.cpp +++ b/src/test/blockmanager_tests.cpp @@ -278,16 +278,16 @@ BOOST_FIXTURE_TEST_CASE(blockmanager_find_files_to_prune_manual, PruneManualSetu WITH_LOCK(chainman.GetMutex(), blockman.GetBlockFileInfo(file1)->nSize = MAX_BLOCKFILE_SIZE); CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())); - // Everything mined below stays in file2, which lies above the prune height. const CBlockIndex* block_file2{WITH_LOCK(chainman.GetMutex(), return chainman.ActiveChain().Tip())}; const int file2{WITH_LOCK(chainman.GetMutex(), return block_file2->GetBlockPos().nFile)}; - const int prune_height{block_file2->nHeight}; - BOOST_CHECK_EQUAL(file2, file1 + 1); + const int prune_height{block_file1->nHeight}; + BOOST_REQUIRE_EQUAL(block_file2->nHeight, prune_height + 1); - // The manual prune range ends MIN_BLOCKS_TO_KEEP below the tip. - while (WITH_LOCK(chainman.GetMutex(), return chainman.ActiveChain().Height()) < prune_height + static_cast<int>(MIN_BLOCKS_TO_KEEP)) { - CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())); - } + // Close file2 so the prune loop considers it alongside file0 and file1. + WITH_LOCK(chainman.GetMutex(), blockman.GetBlockFileInfo(file2)->nSize = MAX_BLOCKFILE_SIZE); + + // File 2 already starts one block above the cutoff. + mineBlocks(MIN_BLOCKS_TO_KEEP - 1); // FlushStateToDisk is the manual-pruning path used by the pruneblockchain RPC. BlockValidationState state; ``` </details>
mutatrum (Migrated from github.com) reviewed 2026-12-01 16:17:50 +00:00
mutatrum (Migrated from github.com) commented 2026-12-01 16:17:50 +00:00

Thanks for the review, will process the remarks. I though single commits were preferred, but I can definitely split them as there are indeed 2 separate issues, the O(n²) scan issue (the main performance culprit) and the file 0 dirty marking.

Thanks for the review, will process the remarks. I though single commits were preferred, but I can definitely split them as there are indeed 2 separate issues, the O(n²) scan issue (the main performance culprit) and the file 0 dirty marking.
mutatrum commented 2026-12-02 14:46:56 +00:00 (Migrated from github.com)

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.

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 commented 2026-12-02 15:57:16 +00:00 (Migrated from github.com)

🚧 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.

<!--85328a0da195eb286784d51f73fa0af9--> 🚧 At least one of the CI tasks failed. <sub>Task `MSan`: https://github.com/bitcoin/bitcoin/actions/runs/46905709854/job/143547183789</sub> <sub>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.</sub> <details><summary>Hints</summary> 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. </details>
l0rinc (Migrated from github.com) requested changes 2026-12-03 09:59:55 +00:00
l0rinc (Migrated from github.com) left a comment

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.

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.
l0rinc (Migrated from github.com) commented 2026-12-02 14:55:55 +00:00

0ee24db test: apply BlockManager args in ChainTestingSetup and test manual pruning:

The functional case already checks that one pruneblockchain call unlinks two files. One extra RPC assertion can check that the block index marks a block as pruned too, so the new unit test and its shared fixture change can go.

Example patch
diff --git a/src/test/blockmanager_tests.cpp b/src/test/blockmanager_tests.cpp
index 22d9ad4ad7..f6df5aa9f6 100644
--- a/src/test/blockmanager_tests.cpp
+++ b/src/test/blockmanager_tests.cpp
@@ -101,60 +101,6 @@ BOOST_FIXTURE_TEST_CASE(blockmanager_scan_unlink_already_pruned_files, TestChain
     BOOST_CHECK(!blockman.OpenBlockFile(new_pos, true).IsNull());
 }
 
-// Prune mode is required for FindFilesToPruneManual, and -prune=1 keeps automatic pruning disabled.
-struct PruneManualSetup : TestChain100Setup {
-    PruneManualSetup() : TestChain100Setup{ChainType::REGTEST, TestOpts{.extra_args = {"-prune=1"}}} {}
-};
-
-BOOST_FIXTURE_TEST_CASE(blockmanager_find_files_to_prune_manual, PruneManualSetup)
-{
-    auto& chainman{*Assert(m_node.chainman)};
-    auto& blockman{chainman.m_blockman};
-
-    auto close_current_file = [&]() {
-        LOCK(chainman.GetMutex());
-        const CBlockIndex* tip{chainman.ActiveChain().Tip()};
-        const int file{tip->GetBlockPos().nFile};
-        blockman.GetBlockFileInfo(file)->nSize = MAX_BLOCKFILE_SIZE;
-        return std::pair{tip, file};
-    };
-
-    // Distribute blocks across file0, file1, and file2, closing all three so the
-    // manual prune loop evaluates file2 alongside file0 and file1.
-    const auto [block_file0, file0] = close_current_file();
-    mineBlocks(1);
-    const auto [block_file1, file1] = close_current_file();
-    BOOST_REQUIRE_NE(file0, file1);
-    mineBlocks(1);
-    const auto [block_file2, file2] = close_current_file();
-    BOOST_REQUIRE_EQUAL(file2, file1 + 1);
-
-    const int prune_height{block_file1->nHeight};
-    BOOST_REQUIRE_EQUAL(block_file2->nHeight, prune_height + 1);
-
-    // File 2 already starts one block above the cutoff.
-    mineBlocks(MIN_BLOCKS_TO_KEEP - 1);
-
-    // FlushStateToDisk is the manual-pruning path used by the pruneblockchain RPC.
-    BlockValidationState state;
-    BOOST_CHECK(chainman.ActiveChainstate().FlushStateToDisk(state, FlushStateMode::NONE, prune_height));
-    BOOST_CHECK(state.IsValid());
-
-    LOCK(::cs_main);
-    for (const CBlockIndex* pruned : {block_file0, block_file1}) {
-        BOOST_CHECK(!(pruned->nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO)));
-        BOOST_CHECK_EQUAL(pruned->nFile, 0);
-        BOOST_CHECK_EQUAL(pruned->nDataPos, 0U);
-        BOOST_CHECK_EQUAL(pruned->nUndoPos, 0U);
-    }
-    BOOST_CHECK(block_file2->nStatus & BLOCK_HAVE_DATA);
-    BOOST_CHECK_EQUAL(block_file2->nFile, file2);
-
-    BOOST_CHECK_EQUAL(blockman.GetBlockFileInfo(file0)->nSize, 0);
-    BOOST_CHECK_EQUAL(blockman.GetBlockFileInfo(file1)->nSize, 0);
-    BOOST_CHECK_GT(blockman.GetBlockFileInfo(file2)->nSize, 0);
-}
-
 BOOST_FIXTURE_TEST_CASE(blockmanager_block_data_availability, TestChain100Setup)
 {
     // The goal of the function is to return the first not pruned block in the range [upper_block, lower_block].
diff --git a/src/test/util/setup_common.cpp b/src/test/util/setup_common.cpp
index fa4590b6a6..274a27713e 100644
--- a/src/test/util/setup_common.cpp
+++ b/src/test/util/setup_common.cpp
@@ -27,7 +27,6 @@
 #include <netbase.h>
 #include <netgroup.h>
 #include <node/block_template_manager.h>
-#include <node/blockmanager_args.h>
 #include <node/blockstorage.h>
 #include <node/chainstate.h>
 #include <node/context.h>
@@ -319,7 +318,7 @@ ChainTestingSetup::ChainTestingSetup(const ChainType chainType, TestOpts opts)
             chainman_opts.script_execution_cache_bytes = 0;
             chainman_opts.signature_cache_bytes = 0;
         }
-        BlockManager::Options blockman_opts{
+        const BlockManager::Options blockman_opts{
             .chainparams = chainman_opts.chainparams,
             .blocks_dir = m_args.GetBlocksDirPath(),
             .notifications = chainman_opts.notifications,
@@ -330,7 +329,6 @@ ChainTestingSetup::ChainTestingSetup(const ChainType chainType, TestOpts opts)
                 .wipe_data = m_args.GetBoolArg("-reindex", false),
             },
         };
-        Assert(ApplyArgsManOptions(*m_node.args, blockman_opts));
         m_node.chainman = std::make_unique<ChainstateManager>(*Assert(m_node.shutdown_signal), chainman_opts, blockman_opts);
     };
     m_make_chainman();
diff --git a/test/functional/feature_pruning.py b/test/functional/feature_pruning.py
index db06f24d92..711d7f8b93 100755
--- a/test/functional/feature_pruning.py
+++ b/test/functional/feature_pruning.py
@@ -336,7 +336,9 @@ class PruneTest(BitcoinTestFramework):
 
         # advance the tip so blk00002.dat and blk00003.dat can be pruned (the last 288 blocks should now be in blk00004.dat)
         self.generate(node, MIN_BLOCKS_TO_KEEP, sync_fun=self.no_op)
+        first_unpruned = node.getblockhash(node.getblockchaininfo()['pruneheight'])
         prune(1000)
+        assert_raises_rpc_error(-1, "Block not available (pruned data)", node.getblock, first_unpruned)
         assert not has_block(2), "blk00002.dat is still there, should be pruned by now"
         assert not has_block(3), "blk00003.dat is still there, should be pruned by now"
 
> [0ee24db](https://github.com/bitcoin/bitcoin/pull/36621/changes/0ee24dbfbb009ca5147d581519af9d19e8cef9cd) _test: apply BlockManager args in ChainTestingSetup and test manual pruning_: The functional case already checks that one `pruneblockchain` call unlinks two files. One extra RPC assertion can check that the block index marks a block as pruned too, so the new unit test and its shared fixture change can go. <details> <summary>Example patch</summary> ```diff diff --git a/src/test/blockmanager_tests.cpp b/src/test/blockmanager_tests.cpp index 22d9ad4ad7..f6df5aa9f6 100644 --- a/src/test/blockmanager_tests.cpp +++ b/src/test/blockmanager_tests.cpp @@ -101,60 +101,6 @@ BOOST_FIXTURE_TEST_CASE(blockmanager_scan_unlink_already_pruned_files, TestChain BOOST_CHECK(!blockman.OpenBlockFile(new_pos, true).IsNull()); } -// Prune mode is required for FindFilesToPruneManual, and -prune=1 keeps automatic pruning disabled. -struct PruneManualSetup : TestChain100Setup { - PruneManualSetup() : TestChain100Setup{ChainType::REGTEST, TestOpts{.extra_args = {"-prune=1"}}} {} -}; - -BOOST_FIXTURE_TEST_CASE(blockmanager_find_files_to_prune_manual, PruneManualSetup) -{ - auto& chainman{*Assert(m_node.chainman)}; - auto& blockman{chainman.m_blockman}; - - auto close_current_file = [&]() { - LOCK(chainman.GetMutex()); - const CBlockIndex* tip{chainman.ActiveChain().Tip()}; - const int file{tip->GetBlockPos().nFile}; - blockman.GetBlockFileInfo(file)->nSize = MAX_BLOCKFILE_SIZE; - return std::pair{tip, file}; - }; - - // Distribute blocks across file0, file1, and file2, closing all three so the - // manual prune loop evaluates file2 alongside file0 and file1. - const auto [block_file0, file0] = close_current_file(); - mineBlocks(1); - const auto [block_file1, file1] = close_current_file(); - BOOST_REQUIRE_NE(file0, file1); - mineBlocks(1); - const auto [block_file2, file2] = close_current_file(); - BOOST_REQUIRE_EQUAL(file2, file1 + 1); - - const int prune_height{block_file1->nHeight}; - BOOST_REQUIRE_EQUAL(block_file2->nHeight, prune_height + 1); - - // File 2 already starts one block above the cutoff. - mineBlocks(MIN_BLOCKS_TO_KEEP - 1); - - // FlushStateToDisk is the manual-pruning path used by the pruneblockchain RPC. - BlockValidationState state; - BOOST_CHECK(chainman.ActiveChainstate().FlushStateToDisk(state, FlushStateMode::NONE, prune_height)); - BOOST_CHECK(state.IsValid()); - - LOCK(::cs_main); - for (const CBlockIndex* pruned : {block_file0, block_file1}) { - BOOST_CHECK(!(pruned->nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))); - BOOST_CHECK_EQUAL(pruned->nFile, 0); - BOOST_CHECK_EQUAL(pruned->nDataPos, 0U); - BOOST_CHECK_EQUAL(pruned->nUndoPos, 0U); - } - BOOST_CHECK(block_file2->nStatus & BLOCK_HAVE_DATA); - BOOST_CHECK_EQUAL(block_file2->nFile, file2); - - BOOST_CHECK_EQUAL(blockman.GetBlockFileInfo(file0)->nSize, 0); - BOOST_CHECK_EQUAL(blockman.GetBlockFileInfo(file1)->nSize, 0); - BOOST_CHECK_GT(blockman.GetBlockFileInfo(file2)->nSize, 0); -} - BOOST_FIXTURE_TEST_CASE(blockmanager_block_data_availability, TestChain100Setup) { // The goal of the function is to return the first not pruned block in the range [upper_block, lower_block]. diff --git a/src/test/util/setup_common.cpp b/src/test/util/setup_common.cpp index fa4590b6a6..274a27713e 100644 --- a/src/test/util/setup_common.cpp +++ b/src/test/util/setup_common.cpp @@ -27,7 +27,6 @@ #include <netbase.h> #include <netgroup.h> #include <node/block_template_manager.h> -#include <node/blockmanager_args.h> #include <node/blockstorage.h> #include <node/chainstate.h> #include <node/context.h> @@ -319,7 +318,7 @@ ChainTestingSetup::ChainTestingSetup(const ChainType chainType, TestOpts opts) chainman_opts.script_execution_cache_bytes = 0; chainman_opts.signature_cache_bytes = 0; } - BlockManager::Options blockman_opts{ + const BlockManager::Options blockman_opts{ .chainparams = chainman_opts.chainparams, .blocks_dir = m_args.GetBlocksDirPath(), .notifications = chainman_opts.notifications, @@ -330,7 +329,6 @@ ChainTestingSetup::ChainTestingSetup(const ChainType chainType, TestOpts opts) .wipe_data = m_args.GetBoolArg("-reindex", false), }, }; - Assert(ApplyArgsManOptions(*m_node.args, blockman_opts)); m_node.chainman = std::make_unique<ChainstateManager>(*Assert(m_node.shutdown_signal), chainman_opts, blockman_opts); }; m_make_chainman(); diff --git a/test/functional/feature_pruning.py b/test/functional/feature_pruning.py index db06f24d92..711d7f8b93 100755 --- a/test/functional/feature_pruning.py +++ b/test/functional/feature_pruning.py @@ -336,7 +336,9 @@ class PruneTest(BitcoinTestFramework): # advance the tip so blk00002.dat and blk00003.dat can be pruned (the last 288 blocks should now be in blk00004.dat) self.generate(node, MIN_BLOCKS_TO_KEEP, sync_fun=self.no_op) + first_unpruned = node.getblockhash(node.getblockchaininfo()['pruneheight']) prune(1000) + assert_raises_rpc_error(-1, "Block not available (pruned data)", node.getblock, first_unpruned) assert not has_block(2), "blk00002.dat is still there, should be pruned by now" assert not has_block(3), "blk00003.dat is still there, should be pruned by now" ``` </details>
l0rinc (Migrated from github.com) commented 2026-12-03 09:56:33 +00:00

Ralph pointed out that all the children in this setup have a data-bearing genesis parent, so CheckBlockIndex would reject the unlinked entries the test adds. A header-only parent lets ReceivedBlockTransactions put them there through the ordinary path.

Example patch
diff --git a/src/test/blockmanager_tests.cpp b/src/test/blockmanager_tests.cpp
index 1c72c8500f..16094aeafb 100644
--- a/src/test/blockmanager_tests.cpp
+++ b/src/test/blockmanager_tests.cpp
@@ -18,6 +18,9 @@
 #include <test/util/logging.h>
 #include <test/util/setup_common.h>
 
+#include <map>
+#include <set>
+
 using kernel::CBlockFileInfo;
 using node::STORAGE_HEADER_BYTES;
 using node::BlockManager;
@@ -179,16 +182,18 @@ BOOST_FIXTURE_TEST_CASE(blockmanager_prune_unlinked_siblings, TestingSetup)
     auto& chainman{*Assert(m_node.chainman)};
     auto& blockman{chainman.m_blockman};
     LOCK(::cs_main);
-    auto* parent{chainman.ActiveChain().Tip()};
+    const CBlock& genesis{chainman.GetParams().GenesisBlock()};
+    CBlockHeader parent_header{genesis};
+    parent_header.hashPrevBlock = chainman.ActiveChain().Tip()->GetBlockHash();
+    auto* parent{blockman.AddToBlockIndex(parent_header, chainman.m_best_header)};
     for (int file : {1, 2, 3}) {
-        CBlock block{chainman.GetParams().GenesisBlock()};
+        CBlock block{genesis};
         block.hashPrevBlock = parent->GetBlockHash();
         block.nNonce = file;
         const FlatFilePos pos{file, STORAGE_HEADER_BYTES};
         blockman.UpdateBlockInfo(block, parent->nHeight + 1, pos);
         auto* child{blockman.AddToBlockIndex(block, chainman.m_best_header)};
         chainman.ReceivedBlockTransactions(block, child, pos);
-        blockman.AddUnlinkedBlock(child);
     }
 
     BOOST_REQUIRE_EQUAL(blockman.m_blocks_unlinked.count(parent), 3U);
Ralph pointed out that all the children in this setup have a data-bearing genesis parent, so `CheckBlockIndex` would reject the unlinked entries the test adds. A header-only parent lets `ReceivedBlockTransactions` put them there through the ordinary path. <details> <summary>Example patch</summary> ```diff diff --git a/src/test/blockmanager_tests.cpp b/src/test/blockmanager_tests.cpp index 1c72c8500f..16094aeafb 100644 --- a/src/test/blockmanager_tests.cpp +++ b/src/test/blockmanager_tests.cpp @@ -18,6 +18,9 @@ #include <test/util/logging.h> #include <test/util/setup_common.h> +#include <map> +#include <set> + using kernel::CBlockFileInfo; using node::STORAGE_HEADER_BYTES; using node::BlockManager; @@ -179,16 +182,18 @@ BOOST_FIXTURE_TEST_CASE(blockmanager_prune_unlinked_siblings, TestingSetup) auto& chainman{*Assert(m_node.chainman)}; auto& blockman{chainman.m_blockman}; LOCK(::cs_main); - auto* parent{chainman.ActiveChain().Tip()}; + const CBlock& genesis{chainman.GetParams().GenesisBlock()}; + CBlockHeader parent_header{genesis}; + parent_header.hashPrevBlock = chainman.ActiveChain().Tip()->GetBlockHash(); + auto* parent{blockman.AddToBlockIndex(parent_header, chainman.m_best_header)}; for (int file : {1, 2, 3}) { - CBlock block{chainman.GetParams().GenesisBlock()}; + CBlock block{genesis}; block.hashPrevBlock = parent->GetBlockHash(); block.nNonce = file; const FlatFilePos pos{file, STORAGE_HEADER_BYTES}; blockman.UpdateBlockInfo(block, parent->nHeight + 1, pos); auto* child{blockman.AddToBlockIndex(block, chainman.m_best_header)}; chainman.ReceivedBlockTransactions(block, child, pos); - blockman.AddUnlinkedBlock(child); } BOOST_REQUIRE_EQUAL(blockman.m_blocks_unlinked.count(parent), 3U); ``` </details>
l0rinc (Migrated from github.com) commented 2026-12-03 09:56:57 +00:00

The sibling and RPC cases cover pruning several files and preserving the file we skip. The mixed valid and out-of-range check is the part I'd keep from the larger unit test. It catches a rejected batch clearing a valid file's metadata.

Example patch
diff --git a/src/test/blockmanager_tests.cpp b/src/test/blockmanager_tests.cpp
index 16094aeafb..a21a9a69f3 100644
--- a/src/test/blockmanager_tests.cpp
+++ b/src/test/blockmanager_tests.cpp
@@ -20,6 +20,7 @@
 
 #include <map>
 #include <set>
+#include <stdexcept>
 
 using kernel::CBlockFileInfo;
 using node::STORAGE_HEADER_BYTES;
@@ -104,79 +105,6 @@ BOOST_FIXTURE_TEST_CASE(blockmanager_scan_unlink_already_pruned_files, TestChain
     BOOST_CHECK(!blockman.OpenBlockFile(new_pos, true).IsNull());
 }
 
-BOOST_FIXTURE_TEST_CASE(blockmanager_prune_block_files_batch, TestChain100Setup)
-{
-    auto& chainman{*Assert(m_node.chainman)};
-    auto& blockman{chainman.m_blockman};
-
-    auto close_current_file = [&]() {
-        LOCK(chainman.GetMutex());
-        const CBlockIndex* tip{chainman.ActiveChain().Tip()};
-        const int file{tip->GetBlockPos().nFile};
-        blockman.GetBlockFileInfo(file)->nSize = MAX_BLOCKFILE_SIZE;
-        return std::pair{tip, file};
-    };
-
-    // Distribute blocks across file0, file1, and file2.
-    const auto [tip0, file0] = close_current_file();
-    mineBlocks(1);
-    const auto [tip1, file1] = close_current_file();
-    BOOST_REQUIRE_NE(file0, file1);
-    mineBlocks(1);
-    const CBlockIndex* tip2{WITH_LOCK(chainman.GetMutex(), return chainman.ActiveChain().Tip())};
-    const int file2{WITH_LOCK(chainman.GetMutex(), return tip2->GetBlockPos().nFile)};
-    BOOST_REQUIRE_NE(file1, file2);
-
-    LOCK(::cs_main);
-
-    // 1. Empty set is a safe no-op.
-    blockman.PruneBlockFiles({});
-    for (const CBlockIndex* tip : {tip0, tip1, tip2}) {
-        BOOST_CHECK(tip->nStatus & BLOCK_HAVE_DATA);
-        BOOST_CHECK(tip->nStatus & BLOCK_HAVE_UNDO);
-        BOOST_CHECK_GT(tip->nDataPos, 0U);
-    }
-
-    const auto tip1_data_pos{tip1->nDataPos};
-    const auto tip1_undo_pos{tip1->nUndoPos};
-    const auto file1_size{blockman.GetBlockFileInfo(file1)->nSize};
-    const auto check_file1_untouched = [&]() EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
-        BOOST_CHECK(tip1->nStatus & BLOCK_HAVE_DATA);
-        BOOST_CHECK(tip1->nStatus & BLOCK_HAVE_UNDO);
-        BOOST_CHECK_EQUAL(tip1->nFile, file1);
-        BOOST_CHECK_EQUAL(tip1->nDataPos, tip1_data_pos);
-        BOOST_CHECK_EQUAL(tip1->nUndoPos, tip1_undo_pos);
-        BOOST_CHECK_EQUAL(blockman.GetBlockFileInfo(file1)->nSize, file1_size);
-    };
-
-    // 2. Batch prune file0 and file2, leaving populated file1 unselected between them.
-    blockman.PruneBlockFiles({file0, file2});
-
-    for (const CBlockIndex* tip : {tip0, tip2}) {
-        BOOST_CHECK(!(tip->nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO)));
-        BOOST_CHECK_EQUAL(int{tip->nFile}, 0);
-        BOOST_CHECK_EQUAL(tip->nDataPos, 0U);
-        BOOST_CHECK_EQUAL(tip->nUndoPos, 0U);
-    }
-    check_file1_untouched();
-
-    BOOST_CHECK_EQUAL(blockman.GetBlockFileInfo(file0)->nSize, 0);
-    BOOST_CHECK_EQUAL(blockman.GetBlockFileInfo(file2)->nSize, 0);
-
-    // 3. Out-of-range file numbers fail before any index entry is modified,
-    // including when paired with a valid, still-unpruned file.
-    blockman.WriteBlockIndexDB();
-    BOOST_REQUIRE(blockman.GetDirtyBlockIndex().empty());
-
-    const HasReason range_error{"PruneBlockFiles: file number out of range"};
-    BOOST_CHECK_EXCEPTION(blockman.PruneBlockFiles({-1}), std::out_of_range, range_error);
-    BOOST_CHECK(blockman.GetDirtyBlockIndex().empty());
-    check_file1_untouched();
-    BOOST_CHECK_EXCEPTION(blockman.PruneBlockFiles({file1, file2 + 1}), std::out_of_range, range_error);
-    BOOST_CHECK(blockman.GetDirtyBlockIndex().empty());
-    check_file1_untouched();
-}
-
 BOOST_FIXTURE_TEST_CASE(blockmanager_prune_unlinked_siblings, TestingSetup)
 {
     auto& chainman{*Assert(m_node.chainman)};
@@ -197,6 +125,9 @@ BOOST_FIXTURE_TEST_CASE(blockmanager_prune_unlinked_siblings, TestingSetup)
     }
 
     BOOST_REQUIRE_EQUAL(blockman.m_blocks_unlinked.count(parent), 3U);
+    BOOST_CHECK_THROW(blockman.PruneBlockFiles({1, 4}), std::out_of_range);
+    BOOST_CHECK_GT(blockman.GetBlockFileInfo(1)->nSize, 0U);
+
     blockman.PruneBlockFiles({1, 3});
     BOOST_REQUIRE_EQUAL(blockman.m_blocks_unlinked.count(parent), 1U);
     const auto* retained{blockman.m_blocks_unlinked.find(parent)->second};
The sibling and RPC cases cover pruning several files and preserving the file we skip. The mixed valid and out-of-range check is the part I'd keep from the larger unit test. It catches a rejected batch clearing a valid file's metadata. <details> <summary>Example patch</summary> ```diff diff --git a/src/test/blockmanager_tests.cpp b/src/test/blockmanager_tests.cpp index 16094aeafb..a21a9a69f3 100644 --- a/src/test/blockmanager_tests.cpp +++ b/src/test/blockmanager_tests.cpp @@ -20,6 +20,7 @@ #include <map> #include <set> +#include <stdexcept> using kernel::CBlockFileInfo; using node::STORAGE_HEADER_BYTES; @@ -104,79 +105,6 @@ BOOST_FIXTURE_TEST_CASE(blockmanager_scan_unlink_already_pruned_files, TestChain BOOST_CHECK(!blockman.OpenBlockFile(new_pos, true).IsNull()); } -BOOST_FIXTURE_TEST_CASE(blockmanager_prune_block_files_batch, TestChain100Setup) -{ - auto& chainman{*Assert(m_node.chainman)}; - auto& blockman{chainman.m_blockman}; - - auto close_current_file = [&]() { - LOCK(chainman.GetMutex()); - const CBlockIndex* tip{chainman.ActiveChain().Tip()}; - const int file{tip->GetBlockPos().nFile}; - blockman.GetBlockFileInfo(file)->nSize = MAX_BLOCKFILE_SIZE; - return std::pair{tip, file}; - }; - - // Distribute blocks across file0, file1, and file2. - const auto [tip0, file0] = close_current_file(); - mineBlocks(1); - const auto [tip1, file1] = close_current_file(); - BOOST_REQUIRE_NE(file0, file1); - mineBlocks(1); - const CBlockIndex* tip2{WITH_LOCK(chainman.GetMutex(), return chainman.ActiveChain().Tip())}; - const int file2{WITH_LOCK(chainman.GetMutex(), return tip2->GetBlockPos().nFile)}; - BOOST_REQUIRE_NE(file1, file2); - - LOCK(::cs_main); - - // 1. Empty set is a safe no-op. - blockman.PruneBlockFiles({}); - for (const CBlockIndex* tip : {tip0, tip1, tip2}) { - BOOST_CHECK(tip->nStatus & BLOCK_HAVE_DATA); - BOOST_CHECK(tip->nStatus & BLOCK_HAVE_UNDO); - BOOST_CHECK_GT(tip->nDataPos, 0U); - } - - const auto tip1_data_pos{tip1->nDataPos}; - const auto tip1_undo_pos{tip1->nUndoPos}; - const auto file1_size{blockman.GetBlockFileInfo(file1)->nSize}; - const auto check_file1_untouched = [&]() EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { - BOOST_CHECK(tip1->nStatus & BLOCK_HAVE_DATA); - BOOST_CHECK(tip1->nStatus & BLOCK_HAVE_UNDO); - BOOST_CHECK_EQUAL(tip1->nFile, file1); - BOOST_CHECK_EQUAL(tip1->nDataPos, tip1_data_pos); - BOOST_CHECK_EQUAL(tip1->nUndoPos, tip1_undo_pos); - BOOST_CHECK_EQUAL(blockman.GetBlockFileInfo(file1)->nSize, file1_size); - }; - - // 2. Batch prune file0 and file2, leaving populated file1 unselected between them. - blockman.PruneBlockFiles({file0, file2}); - - for (const CBlockIndex* tip : {tip0, tip2}) { - BOOST_CHECK(!(tip->nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))); - BOOST_CHECK_EQUAL(int{tip->nFile}, 0); - BOOST_CHECK_EQUAL(tip->nDataPos, 0U); - BOOST_CHECK_EQUAL(tip->nUndoPos, 0U); - } - check_file1_untouched(); - - BOOST_CHECK_EQUAL(blockman.GetBlockFileInfo(file0)->nSize, 0); - BOOST_CHECK_EQUAL(blockman.GetBlockFileInfo(file2)->nSize, 0); - - // 3. Out-of-range file numbers fail before any index entry is modified, - // including when paired with a valid, still-unpruned file. - blockman.WriteBlockIndexDB(); - BOOST_REQUIRE(blockman.GetDirtyBlockIndex().empty()); - - const HasReason range_error{"PruneBlockFiles: file number out of range"}; - BOOST_CHECK_EXCEPTION(blockman.PruneBlockFiles({-1}), std::out_of_range, range_error); - BOOST_CHECK(blockman.GetDirtyBlockIndex().empty()); - check_file1_untouched(); - BOOST_CHECK_EXCEPTION(blockman.PruneBlockFiles({file1, file2 + 1}), std::out_of_range, range_error); - BOOST_CHECK(blockman.GetDirtyBlockIndex().empty()); - check_file1_untouched(); -} - BOOST_FIXTURE_TEST_CASE(blockmanager_prune_unlinked_siblings, TestingSetup) { auto& chainman{*Assert(m_node.chainman)}; @@ -197,6 +125,9 @@ BOOST_FIXTURE_TEST_CASE(blockmanager_prune_unlinked_siblings, TestingSetup) } BOOST_REQUIRE_EQUAL(blockman.m_blocks_unlinked.count(parent), 3U); + BOOST_CHECK_THROW(blockman.PruneBlockFiles({1, 4}), std::out_of_range); + BOOST_CHECK_GT(blockman.GetBlockFileInfo(1)->nSize, 0U); + blockman.PruneBlockFiles({1, 3}); BOOST_REQUIRE_EQUAL(blockman.m_blocks_unlinked.count(parent), 1U); const auto* retained{blockman.m_blocks_unlinked.find(parent)->second}; ``` </details>
l0rinc (Migrated from github.com) commented 2026-12-03 09:57:30 +00:00

0ef8cc3 node: skip data-less index entries when pruning block files:

The sibling test already has a header-only parent and produces pruned index entries. Pruning file 0 next lets the same fixture check that both stay clean while the genesis entry gets marked dirty. The test peer keeps dirty-index access private. The example builds on the other test suggestions.

Example patch
diff --git a/src/node/blockstorage.h b/src/node/blockstorage.h
index 05c68c5f0e..dbf8ab810f 100644
--- a/src/node/blockstorage.h
+++ b/src/node/blockstorage.h
@@ -195,4 +195,5 @@ class BlockManager
     friend Chainstate;
     friend ChainstateManager;
+    friend struct BlockManagerTestAccess;
 
 private:
@@ -383,11 +384,4 @@ public:
     CBlockFileInfo* GetBlockFileInfo(size_t n) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
 
-    /** Return all dirty block index entries. */
-    const std::set<CBlockIndex*>& GetDirtyBlockIndex() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
-    {
-        AssertLockHeld(::cs_main);
-        return m_dirty_blockindex;
-    }
-
     bool WriteBlockUndo(const CBlockUndo& blockundo, BlockValidationState& state, CBlockIndex& block)
         EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
diff --git a/src/test/blockmanager_tests.cpp b/src/test/blockmanager_tests.cpp
index 34f5d3b4c3..e51010da3b 100644
--- a/src/test/blockmanager_tests.cpp
+++ b/src/test/blockmanager_tests.cpp
@@ -19,4 +19,5 @@
 #include <test/util/setup_common.h>
 
+#include <array>
 #include <map>
 #include <set>
@@ -29,4 +30,14 @@ using node::KernelNotifications;
 using node::MAX_BLOCKFILE_SIZE;
 
+namespace node {
+struct BlockManagerTestAccess {
+    static const auto& DirtyBlockIndex(const BlockManager& blockman) EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
+    {
+        AssertLockHeld(::cs_main);
+        return blockman.m_dirty_blockindex;
+    }
+};
+} // namespace node
+
 // use BasicTestingSetup here for the data directory configuration, setup, and cleanup
 BOOST_FIXTURE_TEST_SUITE(blockmanager_tests, BasicTestingSetup)
@@ -112,7 +123,9 @@ BOOST_FIXTURE_TEST_CASE(blockmanager_prune_unlinked_siblings, TestingSetup)
     LOCK(::cs_main);
     const CBlock& genesis{chainman.GetParams().GenesisBlock()};
+    auto* genesis_index{chainman.ActiveChain().Tip()};
     CBlockHeader parent_header{genesis};
-    parent_header.hashPrevBlock = chainman.ActiveChain().Tip()->GetBlockHash();
+    parent_header.hashPrevBlock = genesis_index->GetBlockHash();
     auto* parent{blockman.AddToBlockIndex(parent_header, chainman.m_best_header)};
+    std::array<CBlockIndex*, 3> siblings;
     for (int file : {1, 2, 3}) {
         CBlock block{genesis};
@@ -123,4 +136,5 @@ BOOST_FIXTURE_TEST_CASE(blockmanager_prune_unlinked_siblings, TestingSetup)
         auto* child{blockman.AddToBlockIndex(block, chainman.m_best_header)};
         chainman.ReceivedBlockTransactions(block, child, pos);
+        siblings[file - 1] = child;
     }
 
@@ -134,40 +148,17 @@ BOOST_FIXTURE_TEST_CASE(blockmanager_prune_unlinked_siblings, TestingSetup)
     BOOST_CHECK_EQUAL(retained->nFile, 2);
     BOOST_CHECK(retained->nStatus & BLOCK_HAVE_DATA);
-}
-
-BOOST_FIXTURE_TEST_CASE(blockmanager_prune_skips_dataless_entries, TestChain100Setup)
-{
-    auto& chainman{*Assert(m_node.chainman)};
-    auto& blockman{chainman.m_blockman};
 
-    // Submit only a header so the index holds a genuine header-only entry
-    // (nFile == 0, no block or undo data) with a valid parent.
-    const CBlock header_block{CreateBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()))};
-    BlockValidationState header_state;
-    BOOST_REQUIRE(chainman.ProcessNewBlockHeaders({{header_block}}, true, header_state));
-
-    LOCK(::cs_main);
-    const CBlockIndex* tip0{chainman.ActiveChain().Tip()};
-    const int file0{tip0->GetBlockPos().nFile};
-    BOOST_REQUIRE_EQUAL(file0, 0);
-
-    CBlockIndex* header_index{blockman.LookupBlockIndex(header_block.GetHash())};
-    BOOST_REQUIRE(header_index != nullptr);
-    BOOST_REQUIRE_EQUAL(header_index->nFile, 0);
-    BOOST_REQUIRE_EQUAL(static_cast<int>(header_index->nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO)), 0);
-
-    blockman.WriteBlockIndexDB();
-    BOOST_REQUIRE(blockman.GetDirtyBlockIndex().empty());
-
-    // Pruning file 0 dirties blocks that had data in file 0, not header_index.
-    blockman.PruneBlockFiles({file0});
-    BOOST_CHECK(blockman.GetDirtyBlockIndex().contains(const_cast<CBlockIndex*>(tip0)));
-    BOOST_CHECK(!blockman.GetDirtyBlockIndex().contains(header_index));
-
-    // Pruning already-pruned file 0 again must not re-dirty any index entries.
+    // The header-only parent and a pruned sibling both report file 0
+    BOOST_REQUIRE_EQUAL(genesis_index->GetBlockPos().nFile, 0);
+    for (const auto* dataless : {parent, siblings[0]}) {
+        BOOST_REQUIRE_EQUAL(dataless->nFile, 0);
+        BOOST_REQUIRE(!(dataless->nStatus & BLOCK_HAVE_MASK));
+    }
     blockman.WriteBlockIndexDB();
-    BOOST_REQUIRE(blockman.GetDirtyBlockIndex().empty());
-    blockman.PruneBlockFiles({file0});
-    BOOST_CHECK(blockman.GetDirtyBlockIndex().empty());
+    blockman.PruneBlockFiles({0});
+    const auto& dirty_index{node::BlockManagerTestAccess::DirtyBlockIndex(blockman)};
+    BOOST_CHECK(dirty_index.contains(genesis_index));
+    BOOST_CHECK(!dirty_index.contains(parent));
+    BOOST_CHECK(!dirty_index.contains(siblings[0]));
 }
 
> [0ef8cc3](https://github.com/bitcoin/bitcoin/pull/36621/changes/0ef8cc30bf0a38dc69d77d42c67eb1120e4f8533) _node: skip data-less index entries when pruning block files_: The sibling test already has a header-only parent and produces pruned index entries. Pruning file 0 next lets the same fixture check that both stay clean while the genesis entry gets marked dirty. The test peer keeps dirty-index access private. The example builds on the other test suggestions. <details> <summary>Example patch</summary> ```diff diff --git a/src/node/blockstorage.h b/src/node/blockstorage.h index 05c68c5f0e..dbf8ab810f 100644 --- a/src/node/blockstorage.h +++ b/src/node/blockstorage.h @@ -195,4 +195,5 @@ class BlockManager friend Chainstate; friend ChainstateManager; + friend struct BlockManagerTestAccess; private: @@ -383,11 +384,4 @@ public: CBlockFileInfo* GetBlockFileInfo(size_t n) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); - /** Return all dirty block index entries. */ - const std::set<CBlockIndex*>& GetDirtyBlockIndex() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main) - { - AssertLockHeld(::cs_main); - return m_dirty_blockindex; - } - bool WriteBlockUndo(const CBlockUndo& blockundo, BlockValidationState& state, CBlockIndex& block) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); diff --git a/src/test/blockmanager_tests.cpp b/src/test/blockmanager_tests.cpp index 34f5d3b4c3..e51010da3b 100644 --- a/src/test/blockmanager_tests.cpp +++ b/src/test/blockmanager_tests.cpp @@ -19,4 +19,5 @@ #include <test/util/setup_common.h> +#include <array> #include <map> #include <set> @@ -29,4 +30,14 @@ using node::KernelNotifications; using node::MAX_BLOCKFILE_SIZE; +namespace node { +struct BlockManagerTestAccess { + static const auto& DirtyBlockIndex(const BlockManager& blockman) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) + { + AssertLockHeld(::cs_main); + return blockman.m_dirty_blockindex; + } +}; +} // namespace node + // use BasicTestingSetup here for the data directory configuration, setup, and cleanup BOOST_FIXTURE_TEST_SUITE(blockmanager_tests, BasicTestingSetup) @@ -112,7 +123,9 @@ BOOST_FIXTURE_TEST_CASE(blockmanager_prune_unlinked_siblings, TestingSetup) LOCK(::cs_main); const CBlock& genesis{chainman.GetParams().GenesisBlock()}; + auto* genesis_index{chainman.ActiveChain().Tip()}; CBlockHeader parent_header{genesis}; - parent_header.hashPrevBlock = chainman.ActiveChain().Tip()->GetBlockHash(); + parent_header.hashPrevBlock = genesis_index->GetBlockHash(); auto* parent{blockman.AddToBlockIndex(parent_header, chainman.m_best_header)}; + std::array<CBlockIndex*, 3> siblings; for (int file : {1, 2, 3}) { CBlock block{genesis}; @@ -123,4 +136,5 @@ BOOST_FIXTURE_TEST_CASE(blockmanager_prune_unlinked_siblings, TestingSetup) auto* child{blockman.AddToBlockIndex(block, chainman.m_best_header)}; chainman.ReceivedBlockTransactions(block, child, pos); + siblings[file - 1] = child; } @@ -134,40 +148,17 @@ BOOST_FIXTURE_TEST_CASE(blockmanager_prune_unlinked_siblings, TestingSetup) BOOST_CHECK_EQUAL(retained->nFile, 2); BOOST_CHECK(retained->nStatus & BLOCK_HAVE_DATA); -} - -BOOST_FIXTURE_TEST_CASE(blockmanager_prune_skips_dataless_entries, TestChain100Setup) -{ - auto& chainman{*Assert(m_node.chainman)}; - auto& blockman{chainman.m_blockman}; - // Submit only a header so the index holds a genuine header-only entry - // (nFile == 0, no block or undo data) with a valid parent. - const CBlock header_block{CreateBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()))}; - BlockValidationState header_state; - BOOST_REQUIRE(chainman.ProcessNewBlockHeaders({{header_block}}, true, header_state)); - - LOCK(::cs_main); - const CBlockIndex* tip0{chainman.ActiveChain().Tip()}; - const int file0{tip0->GetBlockPos().nFile}; - BOOST_REQUIRE_EQUAL(file0, 0); - - CBlockIndex* header_index{blockman.LookupBlockIndex(header_block.GetHash())}; - BOOST_REQUIRE(header_index != nullptr); - BOOST_REQUIRE_EQUAL(header_index->nFile, 0); - BOOST_REQUIRE_EQUAL(static_cast<int>(header_index->nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO)), 0); - - blockman.WriteBlockIndexDB(); - BOOST_REQUIRE(blockman.GetDirtyBlockIndex().empty()); - - // Pruning file 0 dirties blocks that had data in file 0, not header_index. - blockman.PruneBlockFiles({file0}); - BOOST_CHECK(blockman.GetDirtyBlockIndex().contains(const_cast<CBlockIndex*>(tip0))); - BOOST_CHECK(!blockman.GetDirtyBlockIndex().contains(header_index)); - - // Pruning already-pruned file 0 again must not re-dirty any index entries. + // The header-only parent and a pruned sibling both report file 0 + BOOST_REQUIRE_EQUAL(genesis_index->GetBlockPos().nFile, 0); + for (const auto* dataless : {parent, siblings[0]}) { + BOOST_REQUIRE_EQUAL(dataless->nFile, 0); + BOOST_REQUIRE(!(dataless->nStatus & BLOCK_HAVE_MASK)); + } blockman.WriteBlockIndexDB(); - BOOST_REQUIRE(blockman.GetDirtyBlockIndex().empty()); - blockman.PruneBlockFiles({file0}); - BOOST_CHECK(blockman.GetDirtyBlockIndex().empty()); + blockman.PruneBlockFiles({0}); + const auto& dirty_index{node::BlockManagerTestAccess::DirtyBlockIndex(blockman)}; + BOOST_CHECK(dirty_index.contains(genesis_index)); + BOOST_CHECK(!dirty_index.contains(parent)); + BOOST_CHECK(!dirty_index.contains(siblings[0])); } ``` </details>
mutatrum (Migrated from github.com) reviewed 2026-12-03 10:46:55 +00:00
mutatrum (Migrated from github.com) commented 2026-12-03 10:46:55 +00:00

That's clever, makes it a lot more concise to cover multiple test cases.

That's clever, makes it a lot more concise to cover multiple test cases.
mutatrum (Migrated from github.com) reviewed 2026-12-03 10:47:29 +00:00
mutatrum (Migrated from github.com) commented 2026-12-03 10:47:29 +00:00

Done.

Done.
mutatrum (Migrated from github.com) reviewed 2026-12-03 10:47:46 +00:00
mutatrum (Migrated from github.com) commented 2026-12-03 10:47:46 +00:00

Also done, much cleaner indeed.

Also done, much cleaner indeed.
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
bitcoin/bitcoin!36621
No description provided.