Repository navigation
mempool: asynchronous mempool fee rate diagram updates via validation interface - #34803
ismaelsadeeq wants to merge 7 commits into
Conversation
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. Code Coverage & BenchmarksFor details see: https://corecheck.dev/bitcoin/bitcoin/pulls/34803. ReviewsSee the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste ConflictsReviewers, 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. |
|
This PR is targeted for The main changes are not significant; the test in the last commit constitutes the bulk of the diff, 493 lines of code addition. |
|
Concept ACK Put this on the milestone. I am a bit surprised at the amount of changes this requires, but I guess this is what it takes to wire up the new cluster mempool data structures. |
9eac888 to
db0a2b1
Compare
31abe4c to
899fa5c
Compare
sedited
left a comment
There was a problem hiding this comment.
Just a few questions so far. Do you have an example that already wires this up to a client? From a first glance, it seems a bit unfortunate that we're rebuilding the various vectors for different clients of the diagram. I wonder if some more work could be saved there by adapting some of the current users a bit.
Yeah, I linked an example in the PR description
txgraph is agnostic of the chunk information, so we cannot just wire that up; we have to add that information: the chunk cumulative fee and the chunk identifier. Which I think it is a good design and should be kept as is. |
899fa5c to
2ee9a33
Compare
|
🚧 At least one of the CI tasks failed. HintsTry to run the tests locally, according to the documentation. However, a CI failure may still
Leave a comment here, if you need help tracking down a confusing failure. |
2ee9a33 to
09ed1b7
Compare
09ed1b7 to
0412515
Compare
0412515 to
1b2fe5c
Compare
|
Forced pushed from 0412515d4f05ac6208cc237ef021df521229e219 to 1b2fe5c860e0c9f848a82f8e1dc63c0e1a55ea50 0412515d4f...1b2fe5c860
|
GetMainStagingDiagrams currently returns a pair of vector<FeeFrac> containing only chunk feerates. Some callers need to know which transactions belong to each chunk in order to compute a chunk hash. Introduce TxGraph::Chunk, which pairs a chunk feerate with the refs of all transactions in that chunk. Update GetMainStagingDiagrams to return a pair of vector<TxGraph::Chunk>, and rename AppendChunkFeerates to AppendChunks to reflect the richer return type. Add SanityCheck coverage for the new behaviour.
CalculateChunksForRBF extracts only the FeeFrac from each TxGraph::Chunk and discards the rest. Cache the fee rate diagram chunks in ChangeSet for use in subsequent commits.
Extract SnapshotDiagrams from CalculateChunksForRBF so the diagram snapshot can be taken on removal paths that do not go through the RBF codepath. The const fix to RemoveStaged is required because GetRemovals() returns a const reference.
Add MemPoolChunk and MemPoolChunksUpdate structs to kernel/mempool_entry.h and MakeMemPoolChunks helper to txmempool.cpp for converting TxGraph::Chunk vectors into MemPoolChunk vectors. Each removal path now captures the before/after fee rate diagram chunks and fires MempoolUpdated so subscribers can observe every mempool change. This signal allows subscribers to observe mempool fee rate diagram changes in an asynchronous way without holding the mempool lock. This changes the order of operations in removeForBlock: all block transactions in the mempool are now removed before conflict removals. In blockencodings_tests, SyncWithValidationInterfaceQueue() drains the async MempoolUpdated signal queue before LOCK2(cs_main, pool.cs). The LOCK2 moves after the sync to avoid deadlock.
1b2fe5c to
f98889d
Compare
|
As discussed IRL, I have now also implemented the version that uses For context, for those who are not aware, there are two candidate approaches for detecting that a block template has become stale due to fee inflow without rebuilding a template every second. Approach 1: propagate mempool mutations via validation signals (#34803) Every mempool mutation is propagated through the validation interface as a before/after fee-rate diagram diff. The block template manager listens to these updates and maintains a snapshot of template metadata. Chunks that leave the mempool are subtracted, and new chunks that qualify for the template, based on minimum feerate, finality, sigops, and weight, are added. Lower-feerate tracked chunks are evicted when necessary to make room. Approach 2: track chunk fee bounds inside
When the bounds change, Trade-offs
I have implemented both approaches, and we discussed the design IRL as well as in the Delving thread: https://delvingbitcoin.org/t/determining-blocktemplate-fee-increase-using-fee-rate-diagram/2052/3. I initially preferred the first approach because it seemed simpler, but after implementing the second one, I no longer think the first approach's extra machinery is justified. One thing to note is that even if we go with approach 2, we may still need something like #35675 for a chunk-based block policy fee rate estimator see thread https://delvingbitcoin.org/t/package-aware-fee-estimator-post-cluster-mempool/312/9. |
|
Removed this from the milestone again. Given the interest here, I don't think this is perceived as an immediate priority. |
|
🐙 This pull request conflicts with the target branch and needs rebase. |
|
Closing this due to lack of review interest. I may revisit this later. This can be marked up for grabs. |
Motivation
Now that we have the full linearization of mempool clusters, whenever a cluster in the mempool gets updated either due to replacement, eviction for various reasons, or block connection, we now have the previous linearization of the affected cluster and the new linearization of the new clusters available.
This brings two advantages the ability for outside observers to make decisions based on fee rate diagram updates without direct access to the mempool, and reduced lock contention.
It can used primarily for:
CBlockPolicyEstimatorpackage awareDuring the development of cluster mempool those usage was discussed.
Note: This is not the motivation behind cluster mempool just a part of it.
See discussion in Package aware fee estimator and Determining BlockTemplate Fee Increase Using Fee Rate Diagram.
Currently the fee estimator is asynchronous but not package-aware.
After this PR it is possible to make it package-aware, a follow-up branch on top of this does exactly that see commit.
For the mining interface, the node every 1 seconds rebuilds a block template regardless of whether any significant mempool change occurred to the top block.
Even after cluster mempool, building a block template is not free since we have to pause the node (holding
cs_main).With this notification, a proposed block template manager that observes the mempool update will only rebuild after an inflow in the mempool top block template warrants it. Redundant builds where no significant fee rate change occurred are eliminated.
And doing this becomes even more useful because of proposed improvements like mempool-based fee rate estimation, which also builds a block template. Right now, it uses a constant 7-second interval and rebuilds regardless of whether an inflow affects the top block template or not. This will fix that.
A proposed sendtemplate in the p2p layer also builds a block template. I propose that it also use the proposed block template manager, which should be built on top of this, so that redundant block template builds are eliminated.
There is a different approach to determining updates in the top block template, but that still requires some direct interaction with the mempool. Since the fee estimator needs this notification anyway and we already have it, the block template manager can use it too and not interact with the mempool at all, it becomes a purely passive observer.
Changes
Added
TxGraph::Chunk, a new struct carrying a chunk fee rate plus the transactionTxGraph::Refs in that chunk. This lets before/after fee-ratediagrams carry enough information to build mempool chunk notifications.
Added
MemPoolChunk(kernel/mempool_entry.h), representing a mempool chunk with:m_fee_rate— chunk fee rate.m_transactions— transactions in the chunk.m_sigops_cost— total sigops cost for the chunk.m_chunk_hash— deterministic hash identifying the chunk transaction set, computed before dispatching the validation callback.Added
MemPoolChunksUpdate(kernel/mempool_entry.h), carrying:old_chunks— chunks before the update.new_chunks— chunks after the update.reason—MemPoolRemovalReasonidentifying the update type.block_height— set only for block-connected removals; defaults tostd::nullopt.Added a new
CValidationInterface::MempoolUpdatedcallback receiving aMemPoolChunksUpdate.Added
GetHashFromWitnesses(src/util/hasher.{h,cpp}), which sorts a vector ofWtxids deterministically and hashes them to produce a stable chunkhash.
GetPackageHashinsrc/policy/packages.cppnow uses this helper.Changed
TxGraph::GetMainStagingDiagrams()to return chunk objects instead of fee-rate-only diagrams.Cached the fee-rate diagram chunks inside
CTxMemPool::ChangeSet, so the same snapshot can be reused for RBF feerate checks and later notificationemission without recomputing a different diagram.
Extracted the dependency addition logic in
UpdateTransactionsFromBlockinto the private helperaddDependenciesFromBlock.MempoolUpdatedis emitted for mempool update paths including:CTxMemPool::ChangeSet::Applywith reasonREPLACED.removeForBlockwith reasonBLOCK;block_heightcarries the connecting block height.removeForReorgwith reasonREORG.removeRecursivewith the caller-supplied reason, such asCONFLICT,EXPIRY, orREORG.Expirewith reasonEXPIRY.TrimToSizewith reasonSIZELIMIT.UpdateTransactionsFromBlockwith reasonSIZELIMIT.The before/after chunks are snapshotted from the txgraph staging state before committing the staging graph. The mempool entries are removed afterward
through
RemoveStaged.Note on
UpdateTransactionsFromBlock:A naive single-pass approach that adds dependencies and trims directly can leave the staging graph oversized, and oversized clusters cannot produce a valid
fee-rate diagram. The implementation therefore uses a two-stage approach:
Phase 1: create txgraph staging, call
addDependenciesFromBlockto register newly discovered parent-child relationships, then callTrim().If
Trim()returns no transactions, no cluster exceeded the limit. The code snapshots the diagram, commits staging, emitsMempoolUpdated(SIZELIMIT),and finishes.
If
Trim()returns transactions to evict, the oversized staging graph is discarded. A fresh staging graph is opened, the evicted txs are removed fromtxgraph staging, dependencies are added again, the diagram is snapshotted, staging is committed,
MempoolUpdated(SIZELIMIT)is emitted, and thenRemoveStagedfully removes the evicted entries from the mempool.Reorgs are rare, and reorgs that exceed the cluster size limit are rarer still, so the common optimistic path only applies dependencies once.
Added
mempool_update_tests, a unit test suite covering theMempoolUpdatedemission paths and validating chunk contents, fee rates, block heightpropagation, and deterministic chunk hashes.
Chunk hashes are computed in
ValidationSignals::MempoolUpdatedbefore the event is queued, so subscribers receive chunks with populated hashes while themempool mutation path avoids carrying hash computation logic directly.