Skip to content

mempool: asynchronous mempool fee rate diagram updates via validation interface - #34803

Closed
ismaelsadeeq wants to merge 7 commits into
bitcoin:masterfrom
ismaelsadeeq:03-2026-notify-mempool-update
Closed

ismaelsadeeq wants to merge 7 commits into
bitcoin:masterfrom
ismaelsadeeq:03-2026-notify-mempool-update

Conversation

@ismaelsadeeq

@ismaelsadeeq ismaelsadeeq commented Mar 11, 2026 •

Copy link
Copy Markdown
Member

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:

  1. Making CBlockPolicyEstimator package aware
  2. Preventing redundant block template builds in the proposed block template manager BlockTemplateManager Proposal.

During 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 transaction TxGraph::Refs in that chunk. This lets before/after fee-rate
    diagrams 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 — MemPoolRemovalReason identifying the update type.
    • block_height — set only for block-connected removals; defaults to std::nullopt.
  • Added a new CValidationInterface::MempoolUpdated callback receiving a MemPoolChunksUpdate.

  • Added GetHashFromWitnesses (src/util/hasher.{h,cpp}), which sorts a vector of Wtxids deterministically and hashes them to produce a stable chunk
    hash. GetPackageHash in src/policy/packages.cpp now 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 notification
    emission without recomputing a different diagram.

  • Extracted the dependency addition logic in UpdateTransactionsFromBlock into the private helper addDependenciesFromBlock.

MempoolUpdated is emitted for mempool update paths including:

  • Transaction addition and RBF replacement: emitted in CTxMemPool::ChangeSet::Apply with reason REPLACED.
  • Block connection: emitted in removeForBlock with reason BLOCK; block_height carries the connecting block height.
  • Reorg removals: emitted in removeForReorg with reason REORG.
  • Recursive removals: emitted in removeRecursive with the caller-supplied reason, such as CONFLICT, EXPIRY, or REORG.
  • Expiry: emitted in Expire with reason EXPIRY.
  • Size-limit eviction: emitted in TrimToSize with reason SIZELIMIT.
  • Post-reorg dependency update: emitted in UpdateTransactionsFromBlock with reason SIZELIMIT.

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 addDependenciesFromBlock to register newly discovered parent-child relationships, then call Trim().

  • If Trim() returns no transactions, no cluster exceeded the limit. The code snapshots the diagram, commits staging, emits MempoolUpdated(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 from
    txgraph staging, dependencies are added again, the diagram is snapshotted, staging is committed, MempoolUpdated(SIZELIMIT) is emitted, and then
    RemoveStaged fully 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 the MempoolUpdated emission paths and validating chunk contents, fee rates, block height
propagation, and deterministic chunk hashes.

Chunk hashes are computed in ValidationSignals::MempoolUpdated before the event is queued, so subscribers receive chunks with populated hashes while the
mempool mutation path avoids carrying hash computation logic directly.

@DrahtBot

DrahtBot commented Mar 11, 2026 •

Copy link
Copy Markdown
Contributor

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

Code Coverage & Benchmarks

For details see: https://corecheck.dev/bitcoin/bitcoin/pulls/34803.

Reviews

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

Type Reviewers
Concept ACK sedited

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:

  • #36030 (util: move function calls outside standard assertions by l0rinc)
  • #34075 (fees: Introduce Mempool Based Fee Estimation to reduce overestimation by ismaelsadeeq)

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.

@ismaelsadeeq

Copy link
Copy Markdown
Member Author

This PR is targeted for v32.0.

The main changes are not significant; the test in the last commit constitutes the bulk of the diff, 493 lines of code addition.

@sedited

sedited commented Mar 14, 2026

Copy link
Copy Markdown
Contributor

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.

@sedited sedited left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Comment thread src/txmempool.cpp Resolved
Comment thread src/util/hasher.h Resolved
@ismaelsadeeq

ismaelsadeeq commented Apr 26, 2026 •

Copy link
Copy Markdown
Member Author

Do you have an example that already wires this up to a client?

Yeah, I linked an example in the PR description

ismaelsadeeq@fd88b16

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.

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.
To do this, we have to iterate through the cluster chunks vector, then iterate through the chunk vector of refs, get the actual transaction fees and wtxid, compute the chunk hash and cumulative fees.
Then move it to the mempool updated notification, where the notification dispatch passes a reference and not a copy.
So we do build a 2D vector of witness IDs, and a 1D vector of the actual chunks for both the old and new diagram. I am happy to incorporate suggestions to simplify this.

@ismaelsadeeq
ismaelsadeeq force-pushed the 03-2026-notify-mempool-update branch from 899fa5c to 2ee9a33 Compare April 29, 2026 10:43
@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task macOS native: https://github.com/bitcoin/bitcoin/actions/runs/25104403535/job/73561784519
LLM reason (✨ experimental): CI failed due to a failing ctest run: mempool_update_tests failed (1 test failure in Bitcoin Core Test Suite).

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.

@ismaelsadeeq
ismaelsadeeq force-pushed the 03-2026-notify-mempool-update branch from 2ee9a33 to 09ed1b7 Compare April 29, 2026 11:45
@ismaelsadeeq
ismaelsadeeq force-pushed the 03-2026-notify-mempool-update branch from 09ed1b7 to 0412515 Compare May 1, 2026 10:38
Comment thread src/txgraph.h Resolved
@ismaelsadeeq
ismaelsadeeq force-pushed the 03-2026-notify-mempool-update branch from 0412515 to 1b2fe5c Compare May 6, 2026 10:46
@ismaelsadeeq

Copy link
Copy Markdown
Member Author

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.
@ismaelsadeeq

Copy link
Copy Markdown
Member Author

As discussed IRL, I have now also implemented the version that uses TxGraph directly to reason about the fee increase across a series of selected chunks, so the trade-offs between the two approaches can be compared concretely.

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.
Staleness then becomes an O(1) check: tracked fees minus the original template fees must be greater than or equal to the caller's threshold.
This is fully implemented in #35675.

Approach 2: track chunk fee bounds inside TxGraph
https://github.com/ismaelsadeeq/bitcoin/tree/07-2026-optimized-waitnext

TxGraph already maintains a chunk index sorted in mining order. A caller registers a (max_weight, min_feerate) tracker, and TxGraph keeps a running lower and upper fee bound over the chunks that would be selected from the front of that index. It updates these bounds incrementally as the graph is mutated by adding and subtracting chunks. This is essentially @sipa's implicit-template suggestion from the Delving thread: https://delvingbitcoin.org/t/determining-blocktemplate-fee-increase-using-fee-rate-diagram/2052/3.

When the bounds change, TxGraph executes a caller-provided callback. Callers can use this callback to check the bound against a threshold and, for example, wake a waiting thread or trigger a template rebuild. In this implementation, waitNext() uses the callback to wake up when the upper bound indicates that the fee threshold might be reached. It then builds one real template and only returns it if the template actually clears the threshold.

Trade-offs

  • Layer separation*. TxGraph knows nothing about policy, so the bounds do not account for transaction finality or sigops cost. This means the bounds may include chunks that a real template would never have included. This could be tightened by letting callers pass an acceptance callback that TxGraph consults before adding or removing a chunk from the bound, passing chunk refs to the callback.

  • Footprint*. Approach 1 rewrites every mempool removal path, including removeRecursive, Expire, TrimToSize, RBF Apply, and the reorg re-add path, through a ChangeSet so before/after diagrams can be diffed. It also fires the new signal on every mempool update, whether or not any miner is listening, which adds a lot of code for this purpose.

    Approach 2 is confined to TxGraph, touches fewer lines, needs O(1) memory per tracker, and has O(modified chunks) update cost folded into existing TxGraph operations. It costs nothing when no tracker is registered.

  • Latency*. Validation signals are delivered asynchronously, so the tracked state lags the mempool, and the wait loop still polls the staleness check on a one-second tick. In Approach 2, the callback runs synchronously when the graph settles and wakes the waiting thread directly.

  • Multiple templates. Approach 1 naturally tracks many concurrent templates with different options via per-template snapshots. In Approach 2, each waiter registers its own scoped tracker.

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.
I am open to switching to whichever approach receives the strongest reviewer support.

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.

@sedited sedited removed this from the 32.0 milestone Aug 12, 2026
@sedited

sedited commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

Removed this from the milestone again. Given the interest here, I don't think this is perceived as an immediate priority.

@DrahtBot

Copy link
Copy Markdown
Contributor

🐙 This pull request conflicts with the target branch and needs rebase.

@ismaelsadeeq

Copy link
Copy Markdown
Member Author

Closing this due to lack of review interest. I may revisit this later. This can be marked up for grabs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants