mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 10:50:37 +00:00
WIP: index: batch db writes during initial sync #34489
No reviewers
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!34489
Loading…
Reference in a new issue
No description provided.
Delete branch "2026_index_batch_processing"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Pending on #34897 review. Please go there first.
Decouples part of #26966.
Right now, index initial sync writes to disk for every block, which is not the best for HDD. This change batches those, so disk writes are less frequent during initial sync. This also cuts down
cs_maincontention by reducing the number ofNextBlockSynccalls (instead of calling it for every block, we will call it once per block window), making the node more responsive (IBD and validation) while indexes sync up. On top of that, it lays the groundwork for the bigger speedups, since part of the parallelization pre-work is already in place.Just as a small summary:
cs_mainlock contention, which improves the overall node responsiveness (and primarily IBD) while the indexes threads are syncing.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.
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:
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 typos and grammar issues:
// attached while m_synced is still false, and it would not be -> // attached while m_synced is still false, and it would not be indexed. [fragmentary comment missing its conclusion; adding "indexed." completes the sentence and makes the intent clear]
// No need to handle errors in Commit. If it fails, the error will be already be -> // No need to handle errors in Commit. If it fails, the error will already be -> duplicate word "be" makes the sentence ungrammatical; remove the extra "be" to restore correct syntax.
Possible places where named args for integral literals may be used (e.g.
func(x, /*named_arg=*/0)in C++, andfunc(x, named_arg=0)in Python):2026-03-08 18:11:08
🚧 At least one of the CI tasks failed.
Task
iwyu: https://github.com/bitcoin/bitcoin/actions/runs/21616547248/job/62296358632LLM reason (✨ experimental): IWYU (include-what-you-use) reported a failure in the test script, causing the CI to fail.
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.
This relates to what you wrote here right? It would be helpful that you check if it solves the LevelDB file issue in coinstatsindex and I am also curious about your benchmark results because @l0rinc did not find that this was leading to a speed up.
Why keep
ProcessBlockaround? It should be simpler if we just have one function and it can be handed one or many blocks.Has this been optimized with benchmarks or are you planning to do that? This might be something differs between the indexes so it might make sense to let each index define their own value.
Or, if you just want to keep it for encapsulation, consider making it private at least?
Concept ACK, I prefer this over https://github.com/bitcoin/bitcoin/pull/33306 - and will investigate if this solves that problem once my benchmarking servers free up.
I experimented with something similar in https://github.com/l0rinc/bitcoin/pull/37/changes, will compare it against this change. I wrote:
Most likely since writing isn't the bottleneck but MuHash calculations were.
@fjahr the comment was merely an excuse to decouple the DB writes batching code out of #26966 rather than me having a formed opinion in favor or against #33306. That's why I didn't mention it in the PR description. Maybe the changes complement each other.
To be crystal clear, just updated the PR description with further details on why this change worth alone, independently on #33306.
To summarize it here, the goal of the changes are:
cs_mainlock contention, which orthogonally improves the overall node responsiveness (and primarily IBD) while the indexes threads are syncing.Let's handle it in a focused follow-up so we don't lose momentum here tuning a parameter.
I'd rather land the structural improvements first, since they unblock other improvements and allow us to continue working on the parallelization goal (which introduces the major sync speedup).
Because
ProcessBlockswill be specialized in a follow-up commit (please see #26966) to enable additional speedups, such as processing blocks out-of-order for indexes that support it.Also, I wouldn't merge them because these two methods solve different problems.
ProcessBlockshandles ordering,ProcessBlockhandles a single unit of work. I think keeping them separate keeps the code clean and easy to follow while allowing us to introduce improvements in the future.Yeah, could do that.just realized that
ProcessBlocksis private already.Updated per feedback from @hebasto (thanks!).
Changed
<cinttypes>include for<cstdint>to make IWYU happy.I guess, this is a bug in IWYU caused bygithub.com/include-what-you-use/include-what-you-use@44480a2de0.UPDATE: Fixed in https://github.com/bitcoin/bitcoin/pull/34498.
Can you run all unit and functional tests on all commits? Or do they time out?
Bad squash, my bad. Thanks for the heads up. Fixed.
Also rebased the branch to pick up the CI changes.
Builds clean on ARM64 (Pi 5, Debian Bookworm). All index-related functional tests and blockfilter_index unit tests pass.
:)
This function doesn't exist anymore.
Done, thanks.
The start and end are set here, according to the desired size. However,
block_batch.start_indexcan change below. Wouldn't it be better/cleaner to set it just before theProcessBlockscall? (I mean to keep the logic up to the deletedpindex = pindex_next;line, and put the bactch setup there.)I am confused as to how this batching relates to the batching logic of the orginal code.
Looking at the pre-changeBaseIndex::Sync(), it seems that Commit/WriteBatch occured only every 30 seconds (or at the chain tip), not after each block. This change does aWriteBatchafter every 500 blocks, which in fact may be even more frequent. The original commit-after-every-30-secs is still there, so I don't see how this change makes less writes. Maybe I misunderstand the change.It seems the code I had for this case got dropped in the previous bad squash. Good catch.
See the missing line
github.com/furszy/bitcoin-core@54874bf43b (diff-5251d9361). Will re-add it. Thanks.That would not only require taking
cs_mainan extra time, but would also introduce race conditions.The extra locking comes from the chain lookup needed to determine the window’s end index. And, more importantly, if the tip changes between setting the start index and computing the end, we could end up on a fork at a lower height, resulting in an invalid window (start_index > end_index).
What I had in mind is setting both the start and end a bit later, after the
pindexis finalized.I will try it out and provide a concrete code snippet a bit later.
Commit()only persists the locator (i.e. "how far the index has synced") so we can resume from that point after a restart. It does not flush or batch the per-block digested data.The block data is written inside
CustomAppend()which is called fromProcessBlock()per block, and it writes to the db immediately.We're not replacing locator update time nor merging it with something else here, we're only batching something that previously wasn't batched at all.
Also, using a block window instead of reusing the existing time-based window is intentional. Time-based flushing makes memory usage hard to predict, and difficult to test (see #32878), because the amount of buffered data depends on runtime speed, which does not necessarily correlate with available memory (batched data stays in memory until it's flushed..). A fixed block window provides predictable memory usage and deterministic behavior, which is overall better and also integrates nicely with multiple workers sync (#26966). I would argue in favor of ditching the time window in the future, but.. that's not something related to this PR.
I see the same two problems there, with an extra requirement of a reorg check and another rewind call. Which makes it even worse.
Updated per feedback, plus added test coverage for the introduced changes. Thanks @optout21.
Thanks for the explanations, and apologies for asking trivial/irrelevant questions.
I was puzzled by the fact that there is a loop in
Sync(), and another loop is introduced inProcessBlocks(). But the two complement each other.Another approach would be to keep the outer loop in
Sync()block-by-block, store aCDBBatchvariable, process one block, count the blocks in the batch, and flush the batch if batch size is reached (outside ofProcessBlock). This would be slightly less change (no secondary loop), but -- if I'm correct -- thecs_mainlock would be still accessed at every block.I acknowledge that it's important to take the cs_main lock only once in the typical scenario.
Also, the missing update of end was identified and fixed! Thx
Yes. That would still lock
cs_mainon every block, which harms the overall node responsiveness, and it is also not very helpful for the parallelization goal, which requires certain isolation between batches so worker threads can process them concurrently.Code review shows that by this point
start_indexandend_indexare not null, but there is several if's to ensure that, it's not trivial. I propose to document/ensure this invariant with anAssumebefore this line, especially having in mind thatProcessBlockscrashes if start or end isnullptr.nit: the "// error logged internally" comment could be passed on here as well.
A minor comment on the commit description: I feel an ambiguity or typo around "during".
crACK 3687ead892d207ddbdfec3f2ef5c086130414d9a
LGTM after clarifications and changes! Code review, no assessment on performance.
Prev:
crACK d0f793ac61a0659f4f1e89f7943813244499bf7d
Done as suggested.
Fixed.
Probably better to just pass them by ref instead. Will do if have to re-touch. Otherwise it can be tackled in a quick follow-up too.
nits addressed, thanks @optout21.
Also, just for completeness, added test coverage for the "reorg during initial sync" scenario that was not covered before.
I just finished measuring the size and file count for this PR (it was running previously for a week with the wrong
tail -Fgrep I reused from https://github.com/bitcoin/bitcoin/pull/26966#pullrequestreview-2965376357)CoinStatsIndex DB: Before vs After Batch Writes (
47c9297→ dd76491)and
I haven't measured the speeds yet but will do that next.
Interesting, cool thanks. Another good point in favor of this change then. Will add it to the PR description.
I have finished benchmarking them:
indexes | i9-ssd | x86_64 | Intel(R) Core(TM) i9-9900K CPU @ 3.60GHz | 16 cores | 62Gi RAM | xfs | SSD
Speed is basically the same and the number of files in
coinstatsindexwere fixed.The
txindexfile count change seems like noise.I will review the code soon, thanks for extracting it from the big PR.
You have a really nice machine there. The real batching gains should show up on HDDs rather than SSDs.
Still, great to know this works properly on high end hardware. Thanks for the benchmark.
yes, I would expect that to be the case - that will also be part of my review before I can ack it.
Bitcoin blocks do not have a consistent size, so batching by block size will result in irregular batch sizes. I suggest considering other approaches, such as a fixed transaction count (e.g., adding blocks until the number of transactions within them falls within a target range). This could be particularly interesting for txindex, as most batches would have a similar byte size. This would make batches more uniform and lead to more predictable computation and performance.
However, this approach would make parallelisation more difficult, since generating the batch would require a precomputation step. This is a considerable trade-off, especially given that parallelisation of the batch computation (#26966) would likely be a more impactful enhancement.
you know, even if it runs at the same speed on an HDD (which I doubt), the other improvements this PR brings still make it worth it.
Concept ACK [3687ead892d207ddbdfec3f2ef5c086130414d9a]
I really like the idea and I think it will be a massive upgrade with your parallelisation proposal #26966
I wouldn’t say this test truly mimics a restart (i.e., shutting down the node and immediately restarting it, without the blockchain growing). It is closer to a continuation after a clean shutdown of the whole node for a long period of time. This test is still interesting, but it does not cover a new bug window introduced by the batch approach (shutting down the node during a batch).
The test currently does the following:
In a real-world scenario, all blocks would already exist on disk, and a restart would likely happen during a batch (for example at height 196, where the previous batch ended at 180).
I would like to see a test (either a modification of this one or a new one) that verifies the index is not corrupted and can correctly resume if the node is restarted during a sync, before reaching the tip.
A possible approach for such a test could be:
batch_size = 30Sorry, I don't see the point here. What you described is essentially a restart. The index gets recreated, initial sync resumes from the last stored index. That's all what we need.
Feel free to experiment on a follow-up, or I could also add it here if you have some code too.
Sorry if I didn’t explain this clearly before, let me try again.
With this PR, some blocks are being indexed (on disk), but the index pointer is not updated because the
Commit()function has not been called. The commit is executed every 30 seconds (which won’t happen during the test) or when the tip is processed (batch tip).What I’m suggesting is to test the scenario where a batch is processed but the tip is not processed. In that case, the index should sync starting from the last committed block.
After debugging your test case, the second round started from the last element of the last batch, as it was the end of the chain at round 0. I would suggest checking the following cases (with a batch of 30 blocks and at least 101 blocks):
Update
I noticed that in the code, interruptions are handled by committing:
Because of this, the scenarios described above may not be useful, since the last processed block might always be committed before shutdown.
I’m not sure whether this interruption only applies to graceful shutdowns or if it also covers crash scenarios.
Just to be accurate: batch writes and the index locator update are, on purpose, not related procedures.
Commit()happens every 30 secs, during interruption or when the tip is reached prior to finishing initial sync.Sure, we could return an error inside the test child index
CustomAppend()that finishes the process early.It shouldn't be hard to code. Feel encouraged to experiment with it. I can cherry-pick your changes if you have a test commit for it.
Yes, ofc :D
Having played around with the code, I found that the case i mentioned didnt worked correctly
Round 0:
Round 1:
Round 2:
This happens because CustomAppend() returns false and the process is stpped before the following branch is reached
Below is the code to reproduce the issue:
GDB output before
Sync()in round 2:Haven't gone through this in detail, but the locator won't update in your second round unless you advance the mock time. Also, keep in mind that if any block within the batch fails, the entire process aborts. The process doesn't save intermediate batch states.
yes i didnt want to simulate 30 sec, i wanted the error before the timmer commit (to fail into the error handling
m_interrupt)I saw that when
CustomAppendreturns false, it executesFatalErrorf, which simply stops the node (not gracefully) instead of raisingm_interrupt, my badWhat do you think about modifying the error handling in the sync process to prevent losing stored data by raising the
m_interruptflag? In the worst case, we lose 29.59 seconds of execution, it might not be worth it and let everything as it currently isI will try to modify the
CustomAppendto raise them_interruptand create a test to show how it is correctly processed, i think it is more interesting this approachReturning
falsehere causes the interrupt to be handled incorrectly as it will be handled in the Sync function like this:This early return prevents execution from reaching line 226, where the correct interrupt-handling logic resides. As a result, the expected recovery path is skipped.
Specifically, this makes the following block effectively unreachable in this scenario:
I didn't find in the file a place where m_interrupt is handled in this way, might be interesting to try to make the code fall on the graceful path. A possible solution might be changing the return by continue, so it will go to the start of the loop and fall into the error handling logic
I debbuged and with this code, the restart point is ok:
Nice catch. Pushed an update that fixes it and adds test coverage.
I'm considering alternative options for the structure, like removing the interruption update, but will let the ideas settle over the weekend. At least we have some nice test coverage for it now.
Some context on "removing the interruption update":
Since we save progress every 30 seconds, saving it during interruptions makes little sense, as the work lost is minimal. The code is probably there merely because it was introduced on the early index days, where things were way more chaotic, and no one really paid much attention to it afterwards.
As you said, since we already save progress every 30 seconds, saving it during interruptions makes very little sense. The amount of work lost is minimal. Yet, this has been the case since the indexes were introduced, and I suspect it hasn't received much attention, which is probably why no one removed it before..
It’s something we could consider.
🚧 At least one of the CI tasks failed.
Task
test max 6 ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/22020957853/job/63629927583LLM reason (✨ experimental): Block filter index test initial_sync_reorg failed, causing the test suite to abort and CI failure.
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.
Nice, if you agree, you can mark this thread as resolved then
Nice. I finally managed to explain the scenario I’ve been trying to describe from the beginning, sorry for not expressing it clearly before (I’m still new as a core reviewer), at least I found a potential bug.
I don’t want to take up more of your time on it, so feel free to resolve this thread. I think the test implemented for the scenario is enough.
That’s a fair point. However, I’m not sure I see the benefit of removing it. I agree that this could be an argument for not introducing the code in the first place, since the potential work lost is minimal. But given that it’s already there, I’m not sure whether removing it (even if the performance impact is small) is an improvement. Do you have something specific in mind? Perhaps something related to the parallelisation of the indexing process?
re Concept ACK [c2953e446d53a8ac86ae3e4801208df5c9c6d2cc]
Done as suggested.
Made a few improvements to the commits descriptions with additional rationale for the changes, and rebased on master to pick up the latest CI updates.
Nit (clang-format): could drop the empty line after this too.
In commit 965d4299a76badcf2257f390f5c02e6007ec6244
Nit: Why introduce the
BlockBatchat all when we don't pass it on here? I don't think we gain much by de-referencing here.Why not re-apply the same logic from before here? Is there a reason why we should only ever process one block here? If that is possible could we make
NextSyncBlockabsorb this logic and return aBlockBatchdirectly?Just a question: Why do we need to define all of these?
Done as suggested.
Mainly for the block range computation, it's less error-prone to use a range structure instead of two independent variables. In the concurrent future (#26966), many block ranges will be computed at once and submitted to the pool (which will avoid further
cs_mainlocking). This requires storing them in a container, and I wasn't really a fan of using a less readablestd::pair. But complain taken, have reworked it soNextBlockToSyncreturns the range, which gives this struct a more powerful use case.Regarding
ProcessBlocksusage, I thought about it a few times. In #26966, the structure takes on a more meaningful role, it becomes the work unit state (we call itTaskthere), and we expand it to store intermediate results there as well. Because of that, I didn't think that makingProcessBlocksto use it was the best, the function should only receive what it will use, not an struct that contains other stuff.On a side comment, I'm going to rebase #26966 on top of this PR now it is mature enough, so we use the same terms on both PRs and what I described above is super clear there as well.
Not needed here, will remove them.
But, just to describe why these methods exist in the parent PR (and refresh my memory while doing it):
In #26966, this struct is extended to hold the block range processed data, it essentially becomes the work unit that flows through the entire pipeline:
The whole rationale behind this design is that work units are processed in parallel, no ordering required. And once a worker finishes a task, it opportunistically checks whether the next in-order unit is ready for post-processing. If it is, that worker performs the post-processing step and continues draining any subsequent ready units in order. This basically ensures we can process blocks in parallel while still preserving the ordered persistence requirement that some of the indexes require.
Done as suggested. Thanks!
Updated per feedback, thanks @sedited!
Also had to rebase the PR due to silent conflicts with the new
TxoSpenderindex.CI failure is unrelated.
This PR only touches indexes code and nothing else. CI was failing in
interface_ipc.pythis morning, and now after the restart fails onp2p_orphan_handling.py. None of these tests have any index enabled.Yeah, I guess this is a good point. It is just odd that the
p2p_orphan_handling.pyhappened twice here, but nowhere else so far. The IPC one is tracked in https://github.com/bitcoin/bitcoin/issues/34711Edit: Let's see if the CI fails in https://github.com/bitcoin/bitcoin/pull/34726 ...
Could add some debug logging to see where it's getting stuck. At first glance, it looks like it stalls during block creation.
Also, just to be clear to other reviewers. Since the issue happens there as well, we know for sure it is not related to this PR.
looks like CI passed now
yes, review can continue.
Im not sure if removing
finalfromBlockFilterIndexonly to allowIndexBlockSimto subclass it for testing is the better decision, i undertsand that it was used final for a reason, and i do not think modifying the code fo fit a test is the best option.Restoring final makes the compilation to fail with error:
Maybe we should base
BlockFilterIndexfromBaseIndexlikeIndexReorgCrashSince
WriteTxswas moved out ofTxIndex::DB, it no longer has static or anonymous namespace scoping, which gives it external linkage. To avoid potential linker conflicts with other translation units, it might be worth wrapping it in an anonymous namespace as this function is not expected to be used outside this fileI compiled and passed all tests with this change
Two small comments, I feel the one about removing
finalis relevant, the other one not really but I saw the same pattern on other files of the project so if it is not an inconvenient you can add it, if not just resolve it.Waiting for the HDD benchmark of @l0rinc. I can do it if he is busy
why not using
staticinstead?Having more benchmarks does not hurt :). Feel more than welcome adding your results as well!
Yeah, I went back and forth on this decision for a while before pushing it. The idea was to actually cover
BlockFilterIndexmethods during reorgs, not just theBaseIndexbehavior, even if they aren't strictly required for this PR changes.Ideally, we should have both testing scenarios: reorgs during initial sync against
BaseIndex, and reorgs againstBlockFilterIndex. But.. doing that would require extractingBuildChainTestingSetupinto a separate file, and I didn't want to expand the scope of this PR any further. This test, and even the existingindex_reorg_crash(the one that usesIndexReorgCrash) do not belong toblockfilter_index_tests.cpp. They only test against the base class. But well, that is something that already exists in our codebase, and not something we are including here, so it is better to leave it for a different PR.Also, the
finaldeclaration here (and in all other indexes) seems really unnecessary. I cannot think of anything we gain from it. It only restricts our unit testing capabilities. I would remove it from all indexes.That being said, most of this is just me ranting about improvements we could make. So will take your suggestion and use the
BaseIndexclass here for now. Let's go step by step. Thanks for the feedback.Updated per feedback. Thanks @arejula27.
Also rebased on master to pull the CI fixes.
idm, i read that anonymous namespaces are more standarized in C++ and
staticis more C-compatible. I'm fine keeping it as staticWhy? Isn't that redundant?
Sounds reasonable to discuss in another PR. I like the idea of removing
finalif it is not needed, but as you said, it should be consistent across all indexes.We can test at different levels.
The
BaseIndextest can verify that we always follow the best chain during initial sync, that the appropriate child methods are called in order (append - remove), and check the db chain locator updates. Then,BlockFilterIndextest, and others, should only focus on manually connecting and disconnecting blocks, verifying that its data is consistent in memory and disk.Due to this new
ifthis is not a straight refactor, maybe this is worth mentioning in the commit description. This if is a minor optimization or readability improvement, as in this special case theFindFork/Nextcombo below would returnnullptr. Discussed at length in #32875Did another index benchmark for the latest push on an HDD:
indexes | i7-hdd | x86_64 | Intel(R) Core(TM) i7-7700 CPU @ 3.60GHz | 8 cores | 62Gi RAM | ext4 | HDD
Benchmark 1: before (
4c40a923f0)Time (abs ≡): 23757.916 s [User: 13234.906 s, System: 1697.284 s]
Benchmark 1: after (5be65dbcdceaafb6f5a0e34c69efc2b3dfcfe27a)
Time (abs ≡): 21134.433 s [User: 12627.245 s, System: 1483.096 s]
Benchmark 1: before (
4c40a923f0)Time (abs ≡): 14205.566 s [User: 8328.684 s, System: 418.981 s]
Benchmark 1: after (5be65dbcdceaafb6f5a0e34c69efc2b3dfcfe27a)
Time (abs ≡): 14046.610 s [User: 8286.885 s, System: 415.464 s]
Benchmark 1: before (
4c40a923f0)Time (abs ≡): 40075.612 s [User: 34320.885 s, System: 403.669 s]
Benchmark 1: after (5be65dbcdceaafb6f5a0e34c69efc2b3dfcfe27a)
Time (abs ≡): 39869.235 s [User: 34307.695 s, System: 398.322 s]
Benchmark 1: after (5be65db)
Time (abs ≡): 26375.223 s [User: 21783.716 s, System: 1690.540 s]
Edit: added
txospenderindexIt looks like the improvement is not very noticeable for two of the indexes. It might be interesting to try increasing the batch size. Do you have any suggestions on what could be causing this?
I'm not sure this is really surprising given the difference in the amount of data written to the latter two. I would expect a jump more similar to the txindex for the txospenderindex.
What is the expectation on the increase of memory usage here? I tried profiling it with massif, but usage when running with this patch seemed a bit erratic, which I guess is still an indication that it is likely to be higher. Can we really batch operations in this way without putting more memory pressure on the OS?
The batch size is intentionally small. I was very conservative with the chosen value to avoid having to worry about it here. The goal of this PR is to land the structural improvements, with a net positive: less
cs_mainlocking, merging prerequisites for the parallelization goal, and the last discovery of reducing the number of created LBD files.It's expected that any batching implementation adds some memory overhead, but that shouldn't be a problem, it pays off in many other areas, not only with a faster sync promise. And, if we ever wanted to, we could add a config flag to disable batching by setting the batch size to 1. But realistically speaking, I don't think anyone running indexes would want them to take hours to sync while locking
cs_mainand slowing down the whole node. People who run indexes want them to sync-up quickly so they can start using them.Also, an important point. All these changes only matter during the index initial sync period. Once the index is synced, they are no longer relevant.
We can benchmark this on small devices like the Pi 4 to see the benefits more clearly, but I honestly wouldn't spend too much time on it. If we agree this PR lands structural, scalable improvements with many benefits and no noticeable downside, and also lets us move forward with the major parallelization speedup path, it seems reasonable to just move forward. This also has a good number of tests we currently lack from.
Sure, done. Added mention to the
Tip()fast-path in the commit description.Concept ACK on the goal: batching is the right direction for reducing write amplification,
cs_maincontention, and LDB file proliferation.However, I think it's important to stress my concern that this change is more complex than it's being treated as.
It alters the invariants every index subclass relies on: in-memory state can now advance ahead of what's persisted, and the interrupt/shutdown paths haven't been fully thought through for each subclass.
The most serious issue seems to me that
Commit()during interrupt writes advancedm_muhashalongside a stale locator, which causesCoinStatsIndex::CustomInitto reject the index as corrupted on restart.blockfilterindexhas a milder variant (orphaned flat file data). I wonder if fuzzing could catch these.More generally, several "no behavior change" refactoring commits don't explain why the restructuring is safe, and memory concerns are brushed away with "shouldn't be a problem".
I also left a ton of comments about the
ProcessBlocksloop needing tighter bounds and the shutdown test only exercising a no-opBaseIndexsubclass. It doesn't catch the actual subclass corruption paths.Some of the earlier commits (e.g. the iterator ordering fix) could land as standalone PRs to reduce the review surface here.
See inline comments for details on these and other issues (interrupt handler scoping,
NextSyncBlockinvariants, loop safety, stale comments, etc.).I would focus in the commit message (and PR description) on batching reducing write amplification - i.e. fewer
LevelDBcompactions because the payload is more predictableCan we squash this with
0336c61aac? We just introduced it and now we're modifying the same code area.nit:
const CBlockIndex*is confusing in a mutable struct whose fields are reassigned every iteration. I understand that it's notCBlockIndex* const last, but a "pointer-to-const block index". Would seem simpler to me to just have:We don't usually const primitive arguments
The diff would be a lot simpler if we kept the early return guard here instead:
which would reduce the indentation of the following code and the awkward naming of "first" for "next"
I find it a bit confusing that the return value of
Nextis calledfirst, which is clearly the next of the prev.Can you please avoid modifying the same line in different commits? The change is already quite difficult to review.
I still find it confusing, as mentioned, this is just an optimization, not sure how it fits into and a clearer special case for "already at tip". It's a reasonable change, but another one without any test coverage - please see the mentioned https://github.com/bitcoin/bitcoin/pull/32875#discussion_r2758807954 and https://github.com/bitcoin/bitcoin/pull/32875#discussion_r2758871724 for how this could be tested.
The
Assume(first)at the end is non-obvious. After thepindex_prev == chain.Tip()fast path returnsnullptr, the remaining path reacheschain.Next(chain.FindFork(pindex_prev)).A reader needs to convince themselves this can't be
nullptr, i.e., thatFindForkcan never return the tip here. Could you add a comment explaining why? Or add it to the commit message to help with review.Is it safe because the fork point can't be the tip, because that would mean
pindex_previs in the active chain, which contradictschain.Next(pindex_prev)having returnednullptrabove?nit: for consistency we could use the same comment style as below:
When can
blockbenullptrhere? Wouldn't it be a fatal error if we walk past genesis? And what if the caller mixes up begin and end? Or ifstartandendhave valid heights but are on different forks.Given how intertwined the code is here, a serious mess-up could cause an infinite loop and would be really hard to trace back to the source.
I would probably sleep better if we asserted that
end->nHeight >= start->nHeightand used a boundedforloop here instead.The method comment states:
But if the interruption happens before we call the first
ProcessBlock, we should be safe since no state was changed - i.e. nothing to recover from.We're changing behavior in a commit that claims it's not a behavior change, without adding context for why this change was needed or how to validate that it is correct. Given that it wasn't obvious to the original authors, an explanation is needed. Also, No test was added to exercise this behavior, to explain exactly why it was necessary, and make sure it doesn't happen again.
It also seems independent enough to be pushed in a separate PR, with a test documenting the current behavior in the first commit and, in the next commit, a fix and a test update that reflects the new behavior.
This comment seem stale now and mismatches the new API.
The commit claims there's no behavior change, but it doesn't explain why the move is safe. Given all the internal
returns andbreaks it's not self-evident.It seems to me that previously a synced, and later interrupted, path could hit
, but after the change it hits
and returns.
I'm not sure there is any other change, but I would appreciate a commit message explanation, and maybe a test exercising this path, preferably a fuzz test to cover all these weird combinations.
How can we tell this failed "due to an interruption"?
m_interruptcould have been set independentlyIs
ProcessBlocksguaranteed to make only temporary changes that we can just revert if this gets interrupted?Before this PR,
CustomAppendwrote directly to the DB per block, som_muhashand the DB were always in sync. With batching, in-memory state advances ahead of what's persisted, and the interrupt handler'sCommit()can write the advancedm_muhashalongside the old locator. After reload it could probably crash, or worse, maybe just continue with incorrect state (not sure, please confirm).If this is accurate, it directly contradicts the code comment:
@dergoegge, is this something we can test currently? I'm surprised this wasn't caught by our fuzzers. Maybe I'm missing some constraint in the review, since I haven't tried reproducing this race explicitly.
unrelated nit:
I don't think that matters. Whichever is simpler.
I agree with @fjahr that tuning this based on measurements should be part of the PR. This seems like a random number, not based on actual behavior. What are the memory implications of this batch? What would be the speedup with bigger ones, and what's the effect on LevelDB compaction and the number of files, etc.?
I personally find this hand-wavy approach concerning.
I also personally find this troubling. We should be concerned with correctness here, and not even mention parallelization before we're sure batching is actually correct.
And since I have concerns about the current implementation (reorgs, save + load, state + tip writing inconsistencies) and the lack of testing, I don't think we should treat this as just a quick hack that helps us get to parallelization.
nit:
inline constexpris more idiomatic for headers:Are we exposing this for testing only? An incorrect call to this could possibly cause an infinite loop, or at least continue until genesis. Not sure, but I would prefer if we made the public interface safer.
We seem to be writing to disk to eagerly here, this also is misaligned with the batching.
Adding tests at the very end doesn't help document the progression of the changes introduced in this PR, commit by commit.
We could add this test as a first commit:
and later, in the batch size commit, just add
filter_index.SetProcessingBatchSize(BATCH_SIZE);to the test to prove that it still passes. That way, we are asserting that the previous behavior is retained, not just that the new behavior is covered.This test almost completely passes on
master- we should add as much coverage before the refactor.But we need to make it more realistic, likely by overriding
CustomAppendas well.This should have probably caught the partial write regression.
Can we extend
IndexCommitStateSimto implementCustomCommitas well?This passes before the change with:
(and no
SetProcessingBatchSize, of course)FWIW, I didn't say that tweaking the value has to be part of this PR. I was just curious how this value was picked and didn't judge it. It isn't even related to this comment direct but the time of my initial pass there were no benchmarks as far as I can remember and I had a bit of fear that this might get merged quickly and could end up in v31 without benchmarks and without the multithreading for which this is part of the setup. In that case I would have been a bit concerned that this might still introduce a performance penalty in a release. But the benchmarks have been run now and quite extensively and I haven't seen any penalty from this change. I think the follow-up that tweaks the value (if it turns out it can be optimized) as well as the multithreading should be tagged accordingly so they can make it into the same release as this change, if that is the case then I don't think my comment should be considered a blocker.
Clarifying one of the comments.
I'm puzzled here. You are claiming this is a behavior change without explaining how, and based on that, you write a strong affirmation for other reviewers rather than engaging with me about what you think this change introduces. That is not something I can act on, and it risks misleading other reviewers.
This is not a behavior change, it is a correctness change. The loop iterator that tracks the last successfully processed block was modified to be updated after processing the block, not before. The reordering of
pindex = pindex_nextto after theProcessBlockcall has zero effects on any execution path, because we immediately return if block processing fails, and at that pointpindexis never read again. If you believe otherwise, please point to the specific code path you think is affected. This change was made to prepare the ground for the batch end block set, which is the actual focus of this PR. Splitting it out into a separate PR would add unnecessary overhead for a one-line reordering with no behavioral effect.On the commit message: if the description was not clear enough, just say so. I would have updated it. Engaging directly about what is unclear is far more constructive than making assertions aimed at other reviewers.
On tone: "it wasn't obvious to the original authors" is truly unhelpful. It does not engage with the code, it does not help improve anything, and it makes it genuinely harder to engage with your other comments in good faith, even the ones that may be perfectly valid. The purpose of review is to work with the author to improve the code, not to editorialize for other readers.
Not sure what you mean, I commented on your PR, meant it for you to read it.
I'm not sure about the past tense, I reviewed it because I'm expecting further changes, especially because of the bugs introduced here.
How so? I don't know or care who wrote the original code, they had an intention here, if we're changing it, it needs explanation and preferably tests.
Please stick to the topic in question. I have not yet read your other comments on this PR. This is the first one, and it makes a strong claim without a proper explanation to back it up.
Can you please point to the specific code path where this commit introduces a behavior change? Thanks.
That explains the confusion.
Please read the rest of my comments, that's why I posted them...
It seems obvious to me that
95fc91fc99cannot change behavior; it's only swapping the change of local variable with a return statement, at which point the local variable disappears anyway. So I agree with @furszy that I don't understand what the comment in https://github.com/bitcoin/bitcoin/pull/34489/changes/95fc91fc99a14c6635c13ba7b6a8e7c2a1efe7be#r2905123979 is about, independently from all other comments left on this PR.This commit does not explain why the swap is needed. That only becomes clear later, when a non-adjacent commit relies on
pindexmeaning "last successfully processed block" for the new interrupt path, see #34489 (comment).So the issue is not this line movement in isolation, but that it is a preparatory change whose purpose is only revealed several commits later, in a commit that changes behavior while claiming to be a refactor. I think those commits should be squashed and the behavior change either fixed or documented.
Ok, but I did, we can't just add a random value here, we have to back it by some measurements.
I have measured a batch size of 1000 and it doesn't seem to reduce the size further. The implementation still contains some bugs, so we probably have to remeasure after they're fixed. I'm also curious about the peak memory usage here.
INDEX_BATCH_SIZE = 1000
I will measure
INDEX_BATCH_SIZE = 100next,Finished
INDEX_BATCH_SIZE = 100:Details
Finished
INDEX_BATCH_SIZE = 300:Details
I'd be interested in the extra memory consumption of these to help with choosing a good batch value.
I was thinking to buy and external disk (HDD) and try to benchmark the memory impact, would it be interesting or having the blockchain and the index on different disks make the test not useful?
for memory profiling it shouldn't matter - just know that these measurements are notoriously slow
Finished batch=700:
Details
Summarizing the measurements so far looks like this:
@furszy Do you think #34897 has any implications on this PR and #26966? If indexes can only commit up to the chainstate's last flushed block, the batching and parallelisation speedups might be limited by the flush interval (~50-70 min) rather than by index processing itself. Would it make sense to keep the current per-block behaviour during IBD (where the index is catching up and flush lag matters most) and use batching only for fully synced nodes processing new blocks using new methods?? Another option could be each index sets its own batch size. For example,
blockfilterindex(required during IBD) could use a batch size of 1 to keep commit granularity tight, while optional indexes likecoinstatsindexortxindexcould use larger batches since their commit timing is less critical.PS: I got my chain synced, will try to do the memory benchmark this week
🐙 This pull request conflicts with the target branch and needs rebase.
concept ACK
Just did a swift code review for the Spanish PR review club :)
I'm 0 familiar with this part of the codebase, but left some comments that ¿might? be useful.
I found the first two commits a bit difficult to understand because, although it is obvious that it is not a behavior change, there's no explanation in the commit message on why those changes are needed. I think a small sentence saying why that helps is useful :)
in
64578a7888index: make NextSyncBlock return block rangesProbably worth not using auto here so it's visible that it can not have a value and that means it is the tip.
Also I think you meant if block_range is not set? not range.first
in
64578a7888index: make NextSyncBlock return block rangesI guess
ProcessBlockscan just take the newBlockRangestruct.in
1628b1005aindex: add block range computationwhy 500? is it an arbitrary number?
I think that was decided as an arbitrary small number just for the first approach, then each index will have different batch sizes based on the benchmarks
https://github.com/bitcoin/bitcoin/pull/34489#discussion_r2944626098
I working on rebasing this PR onto current master. I think i am quite advanced. Hoping to have it ready in two weeks(not a promise cuz i will go on vacation next week).
This PR nows not only have conflicts but also requires hard changes due to some merged PR. Things I'm keeping in mind/focusing:
baseindex_testsand now run against every index type. #35847txindexblock sequence counter now lives in memory. Reading it from disk per block collides once writes are batched. #35531@arejula27 let's talk via DM to organize the remaining work here better. Rebasing this one shouldn't take me more than an hour, there is just one missing check regarding the race condition that we should consider properly. I just didn't do it waiting for #35847, and other feature freeze priorities. Should have more availability these coming weeks, happy to tackle the remaining work together.
I have the PR already rebased but i wanted to review it more before sending it to u, i can share it but if it only requires one hour of your time maybe it is faster if you do it directly instead of reviewing mine.
Happy to discuss this on DM and organise the remaining work to collaborate 😁, idk which chat do you prefer
@furszy, could we fix this as well (in a separate PR or here) before we continue?
Not sure how to fix it before this PR, but maybe we could fix it here. Let me know how I can help.
3 additional verified findings in the Review report.
🔴 Major ·
coinstatsindexsaves a mismatched checkpoint on mid-range interruptionInterrupting
coinstatsindexcatch-up inside a range can save a MuHash that does not match the recovery locator, making the next startup fail even after a clean shutdown.Location:
src/index/base.cpp:276(head).🔴 Major ·
NextSyncRange()crashes when the active tip is an ancestor of the indexed tipThe trusted
invalidateblockRPC can leave an index above the active tip, after which restarting with that index enabled crashes inNextSyncRange()if no replacement branch exists.Location:
src/index/base.cpp:181(head).🟠 Minor ·
Sync()can overwrite callback progress during shutdownA narrow shutdown race after
m_syncedbecomes true letsSync()overwrite callback progress and persist a mismatchedcoinstatsindexcheckpoint.Location:
src/index/base.cpp:303(head).🔵 Suggestion ·
initial_sync_reorgdoes not check multi-block rollbackinitial_sync_reorguses single-block ranges and a stateless simulator, so its final-tip assertions do not verify the rollback behavior introduced by multi-block processing.Location:
src/test/blockfilter_index_tests.cpp:486(head).🔵 Suggestion · 500-block batches lack a byte budget
All production indexes accumulate up to 500 blocks of writes outside
-dbcache, althoughtxindexandtxospenderindexbatch sizes vary with transaction and input counts.Location:
src/index/base.h:32(head).🔵 Suggestion ·
shutdown_during_initial_syncnever observes batched entriesBecause the simulator writes no entries,
shutdown_during_initial_syncwould still pass if writes happened per block or entries from an interrupted range reached the database.Location:
src/test/blockfilter_index_tests.cpp:468(head).Reviewed:
1497086cdb0e· Review report · Previous reportspermalink
⌛ There hasn't been much activity lately and the patch still needs rebase. What is the status here?
⌛ There hasn't been much activity lately and the patch still needs rebase. What is the status here?
@arejula27 @furszy What is the status here, after your last message?