Repository navigation
Conversation
… Linearize
Add MakeChainGraph() to build deterministic random chain dependency graphs
(tx0->tx1->...->tx_{n-1}) with randomized feerates, and two sets of
chain-specific benchmarks:
- PostLinearizeChain{16,32,48,64,75,99}Tx: measure PostLinearize throughput
on chain-shaped clusters across a range of sizes.
- LinearizeOptimallyChainTotal_{9,16,32,48,63}tx: measure the total time for
Linearize to reach an optimal result on chain-shaped clusters.
Chain clusters are a common real-world mempool pattern (each transaction
spending an output of the previous one). Dedicated benchmarks make it easy
to observe the effect of topology-specific linearization optimizations.
…d clusters Add MakeRandomTreeGraph() which generates random tree-shaped dependency graphs in two orientations: - Upright tree: each transaction i picks a random parent from [0, i), giving a DAG where every node has at most one direct parent. - Reverse tree: each transaction i picks a random child from [0, i), giving a DAG where every node has at most one direct child. Add postlinearize_tree_optimal_tests which verifies, for random trees of various sizes (5..30 transactions), that PostLinearize matches the quality of the exhaustive Linearize() result, as guaranteed by PostLinearize's interface. Also verifies idempotency: a second PostLinearize pass produces no change.
…ters
Add MakeRandomChainGraph() which generates random linear chain dependency
graphs (tx0->tx1->...->tx_{n-1}) with randomized feerates.
Add postlinearize_chain_optimal_tests which verifies, for chains of various
sizes (5..50 transactions), that PostLinearize matches the quality of the
exhaustive Linearize() result. A chain satisfies both tree-shape conditions
simultaneously (each transaction has at most one parent and at most one
child), so PostLinearize is guaranteed to produce an optimal linearization.
Also verifies idempotency: a second PostLinearize pass produces no change.
Add TryLinearizeChain() which detects chain-shaped clusters and
produces an optimal linearization in O(N) time, bypassing the O(N^2)
SPF algorithm in Linearize().
Detection relies on the property that a cluster with N transactions is
a chain iff its ancestor-set sizes form exactly {1,...,N}. This is
checked in O(N) using a presence array, since Ancestors().Count() is
O(1) for the fixed-size BitSets used here.
The topological order is recovered in O(N) by mapping each node's
ancestor count to its position. For a chain, this topological order is
unique and already optimal — no further chunking or merge pass is
needed. PostLinearize can also be skipped: every adjacent pair has a
dependency, so ChunkLinearizationInfo's unconditional merge and
PostLinearize's merge/swap behave identically (the swap branch never
triggers).
…stribution Add MakeMonotoneChainGraph() which builds a chain of N transactions with strictly increasing individual feerates (fee_i = i+1, size_i = 1). This is a pessimal feerate distribution for the SPF algorithm: every transaction looks attractive in isolation, but including tx_i requires all i ancestors, so SPF must discover through many improvement steps that the entire chain is the single optimal chunk. Without TryLinearizeChain this exhibits O(N²) behaviour; with TryLinearizeChain the result is produced in O(N). Add LinearizeOptimallyMonotoneChainTotal benchmarks (sizes 9..63 tx) to measure this worst-case scenario and confirm the O(N) speedup.
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. ReviewsSee the guideline for information on the review process. 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. |
|
Why would this be worth the code complexity and review cost? |
|
🚧 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. |
|
I think a useful question to answer is-- is this faster primarily on cases that are already quite fast? It won't improve the worst case performance (because the worst cases aren't these chains) -- but it could perhaps be justified on the basis of improving average case performance (as time saved could be spent elsewhere, including optimizing harder clusters). But the savings may not be significant if the cases this is speeding up are already fast. A similar issue came up vs CSS in that CSS is generally faster than SFL for small clusters or for some range of dependency densities. And small clusters are even quite common... but these are cases that are quite fast for SFL in any case and so keeping CSS around for those cases hardly makes a difference in total runtime. I think it would be reasonable to benchmark this with real data and exclude clusters of size 1 (most of them...), and 2/3 (which probably should get their own specialized solvers because one can essentially hardcode the possibilities for those and solve them very quickly e.g. just by checking the area under the curve for the n! orderings). If it doesn't make a real speed up in that kind of benchmark I think it's hard to justify. One could try to make a case that clusters of larger than 64 could be accepted for such special shapes, but the issue there is that one additional transaction (potentially by a third party) can easily knock it out of the special shape and then the resulting cluster is no longer acceptable and that seems brittle and hard to reason about compared to a consistent cluster size limit. |
Hi gmaxwell,
|
#34643 (comment) |
|
https://howhsu.github.io/thinking-in-bitcoin/articles/chain-fast-path-replay-bench.en.html |
|
@HowHsu If you want, I have dumps with mempool cluster data for all of 2023 (built by @sdaftuar by replaying historical p2p data) and recent data since october 2025: https://bitcoin.sipa.be/mempool_dumps/. The file format is:
The recent data has a dump every 60 seconds, so it's quite large when decompressed, due to duplication. Regarding this PR:
|
|
Hi @sipa ,
Thanks for providing this.
I'll look into this.
I see, I thought about a separate
Sorry, I'll fix it if later this PR is proved to be meaningful. |
Hi @sipa, Does the 2023 dataset also include a dump every 60 seconds (i.e., replaying P2P data to reconstruct the mempool state and dumping it every 60 seconds)? I'm inferring this from the timestamps. |
https://github.com/HowHsu/thinking-in-bitcoin/blob/main/articles/mempool-cluster-distribution-2025.en.md |
I didn't remember what frequency of dumps was used there, but yes, that's certainly possible. |
|
🐙 This pull request conflicts with the target branch and needs rebase. |
|
re: chain usage patterns, I think most of this is explained by runestones, see these longs chains like https://mempool.space/tx/d4dbdcfe1b96a441a618c4c11e9a8a249ff94aa2999956c44716a1f61c143813 iirc these didnt exist in 2023 |
|
Close this one, I've created a new PR for Chain Cluster: #34821 |
This PR relies on PR #34625
Summary
This PR adds
TryLinearizeChain(), an O(N) specialised linearizer for chain-shapedclusters, and a benchmark targeting the feerate distribution that triggers the worst-case
behaviour of the general SFL algorithm on chains.
Commits:
ad15466be1e4cluster_linearize: add O(N) fast path for chain-shaped clusters72bf0faf820ccluster_linearize: benchmark Linearize on worst-case chain feerate distributionMotivation
Instrumentation added to a running node revealed that virtually most cluster seen in the
mempool is chain-shaped — each transaction spends an output of the previous one. This is
consistent with widespread use of CPFP (Child-Pays-For-Parent) fee bumping, where a
low-feerate parent transaction is paired with a high-feerate child that spends one of its
outputs, forming a two-transaction chain; longer chains arise from repeated CPFP stacking or
batch-payment patterns.
Because chain clusters dominate in practice, a topology-specific O(N) fast path has
disproportionately large impact compared with optimising for rarer topologies.
The general
Linearize()function uses the Spanning Forest Linearization (SFL) algorithm, whoseMakeTopological()phase merges chunks iteratively. For a chain cluster with N transactionsand strictly increasing individual feerates (fee_i = i+1),
MakeTopologicaltriggers acascade that merges the entire chain into one chunk step-by-step. At merge step k, two
operations each scan the growing top-part chunk of size k:
UpdateChunkiterates over all k transactions to write theirchunk_rep(unconditionally,regardless of any inner-loop conditions).
MergeChunksiterates over all k transactions to locate the dependency connecting top andbottom chunks.
This accumulates O(1+2+...+(N-1)) = O(N²) loop iterations across the full cascade.
An O(N) specialised path avoids the SFL overhead entirely for chain-shaped clusters.
Algorithm
Detection (
TryLinearizeChain)A cluster with N transactions is a chain if and only if its ancestor-set sizes form exactly
{1, 2, ..., N}. This is checked in O(N) using a boolean presence array;
Ancestors(i).Count()is O(1) for the fixed-sizeBitSet<64>used here.Topological order
The node with k ancestors occupies position k−1 in the unique topological order. Recovered
in O(N) by a single mapping pass.
Why PostLinearize is not needed
The topological order of a chain cluster is unique, and every adjacent pair has a dependency,
so
ChunkLinearizationInfo's unconditional merge andPostLinearize's merge/swap behaveidentically (the swap branch never triggers). The topological order itself is the optimal
linearization, and
PostLinearizecan be safely skipped.The result is returned early from
Linearize()before the SFL machinery is initialised:The fourth return value (
is_chain) allows the caller (Relinearize()) to skip thePostLinearize()pass, which is redundant for chains:TryLinearizeChainalreadyproduces an optimal, connected linearization.
Benchmark results
LinearizeOptimallyMonotoneChainTotal— increasing feerates (SFL worst case)MakeMonotoneChainGraphbuilds a chain with fee_i = i+1, size_i = 1. For the SFLalgorithm, every prefix of the chain has feerate (k+1)/2 (strictly increasing with length),
so
MakeTopologicalmust merge the entire chain into a single chunk through N−1 steps.Each step scans the growing top-part chunk (via
UpdateChunk's unconditionalchunk_repwrite loop and
MergeChunks's dep-search loop), accumulating O(N²) iterations in total.TryLinearizeChaineliminates this entirely.Instructions per call after optimisation:
The "after" timings confirm that
TryLinearizeChainruns in O(N) regardless of feeratedistribution (~65–106 instructions per transaction at N=9..63, constant converging as N
grows). The speedup grows with N because the baseline trends towards O(N²) while the
optimised path remains O(N).