Repository navigation
Conversation
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. ReviewsSee the guideline for information on the review process.
If your review is incorrectly listed, please copy-paste LLM Linter (✨ experimental)Possible typos and grammar issues:
2026-03-16 15:53:38 |
356fb62 to
dd15ced
Compare
| @@ -154,6 +154,10 @@ class Cluster | |||
| return m_quality == QualityLevel::NEEDS_SPLIT || m_quality == QualityLevel::NEEDS_SPLIT_FIX; | |||
| } | |||
|
|
|||
| /** Whether this Cluster type is compatible with chain topology (Singleton and Chain are, | |||
| * Generic is not). Used to determine if a group of clusters can be optimistically merged | |||
This comment was marked as spam.
This comment was marked as spam.
Sorry, something went wrong.
3fed23a to
bf6aa69
Compare
|
Interesting work, thank you for following up on the feedback. How does this compare directly to #34643 under the same replay system? did you benchmark memory usage to compare? Would be interested seeing that. any feeling why also interested in a pessimal benchmark where no one is making chains beyond say, size 2, and yet we're still trying to optimistically detect and merge chains. (in case people decide other shapes are cooler or whatever) |
Add IsChainCompatible() virtual method to Cluster base class. Singleton returns true (chain-compatible), Generic returns false. During GroupClusters(), detect whether all clusters in a merge group are chain-compatible and record this in the new GroupEntry::m_maybe_chain flag. This will be used by subsequent commits to optimistically merge groups of Singleton/Chain clusters into a ChainCluster instead of always falling back to GenericCluster.
Add ChainClusterImpl, a Cluster implementation optimized for chain-shaped
topologies where transaction at position i only depends on transaction i-1
except position 0. Dependencies are implicit (no DepGraph needed), saving
memory and enabling O(N) operations.
Key design:
- m_txdata: vector of {graph_index, feerate} in chain order
- m_linearization: always [0, 1, 2, ..., n-1] (only valid topological order)
- Chunks computed by greedy merging of consecutive transactions
- Always OPTIMAL quality (no relinearization needed)
- Ancestors/descendants computed trivially from chain position
Also adds CreateEmptyChainCluster() factory method and friend declaration.
ChainClusterImpl is not yet created anywhere; subsequent commits will add
the optimistic merge path that creates ChainClusters during merge.
ChainClusterImpl's m_linearization is always [0, 1, 2, ..., n-1] since chain transactions have a fixed topological order matching their array position. Replace all m_linearization usages with direct index iteration over m_txdata, saving one vector allocation per chain cluster.
When all clusters in a merge group are chain-compatible (Singletons or ChainClusters), attempt TryChainMerge() before falling back to the standard Generic merge path. TryChainMerge() succeeds iff every dep connects the tail (last tx) of one cluster to the head (first tx) of another, and the resulting cluster-level graph is itself a linear chain. On success, a ChainCluster is created directly without going through a GenericCluster. Chain detection operates at the cluster level (O(n_clusters + n_deps)) rather than the individual transaction level, since every cluster in to_merge is already chain-compatible by the m_maybe_chain invariant. To support the fallback path: ChainCluster is excluded from being selected as the Merge() target (it cannot absorb arbitrary topologies), and the largest Generic cluster is preferred as the merge target to minimise transaction moves.
10 test cases covering: - Successful chain merges: two singletons, three singletons, ChainCluster extended by a singleton, singleton prepended to a ChainCluster, two ChainClusters connected, and duplicate deps. - Failed merges (fallback to generic): diamond topology (two parents), fork topology (two children), dep from a non-tail tx, dep to a non-head tx.
Verify that removing transactions from the interior of a ChainCluster correctly splits it into disconnected segments: - Remove one middle tx from a 4-tx chain → singleton + 2-chain - Remove two alternating middle txs from a 5-tx chain → 3 singletons - Remove the middle of a 6-tx chain → two separate chains - Remove head only → single chain preserved - Remove tail only → single chain preserved
- TxGraphChainMergeSingletons: ApplyDependencies merging 64 singletons into one chain via TryChainMerge. - TxGraphChainMergeFromChains: ApplyDependencies merging 64 pre-built ChainClusters (10 txs each) into one chain of 640 txs. - TxGraphChainBlockBuilder: repeated GetBlockBuilder calls on a single 64-tx ChainCluster.
No, I'll do these tests in the next days.
have roughly thought about this, no clues yet, will have a deep research on it.
All great points — I'll make these comparisons. |
Hey @instagibbs , I did some research on these topic, and add them in the PR description, from section |
|
light concept NACK, from me for now. It was helpful to me to see what kind of costs we have for now, but modest reduction in already-"trivial" linearization cases isn't very compelling, unless we had quite significant memory savings or similar. It's just enough boilerplate to be too annoying to maintain unless there's a clearer win, to me. Going forward, I think focusing on reducing the adversarially-bad cases is a more fruitful line of further inquiry. |
I see—maintainability is definitely something that needs to be considered. |
|
Is there no way to avoid the |
I see, I'll look into it. |
I removed m_split_segments from the implementation and ran benchmarks. When the memory ratio |
as per offline talking, I wrote some script to tracing the transaction lifecycle, |
|
There's doesn't seem to be much more interest here. So closing for now. |
This one replaces #34643
Summary
This PR adds an optimized
ChainClusterImplfor chain-shaped transaction topologies (A→B→C→D…). It replaces the genericDepGraph-based cluster with a compact linear representation (m_txdata) and a backward-absorbing chunk algorithm, reducing memory and improving performance for common chain patterns.Key changes
m_maybe_chainflag onGroupEntryto hint at chain-shaped mergesChainClusterImplwithm_txdata(chain order) andm_split_segments(contiguous segments after removals)TryChainMergeinApplyDependenciesto detect and merge chains via the fast pathApplyRemovals/Splitcorrectly split chains when middle transactions are removed (no spurious dependencies)m_linearizationfromChainClusterImpl(always[0,1,…,n-1])ComputeChunks()helper to centralize the backward-absorbing chunk logicSetFee/Relinearizefix: downgrade toNEEDS_RELINEARIZEon fee change to avoid dereferencing destroyed Refs;Relinearizepromotes back to OPTIMAL and recomputes chunksTesting
txgraph_chain_merge(TryChainMerge),txgraph_chain_split_on_removal(ApplyRemovals/Split)Trace replay comparison
Trace recording (TracingTxGraph) and replay (
txgraph-replay,analyze_trace.py) code:[email protected]:HowHsu/bitcoin.gitbranchbefore_chaincluster. Usage guide: TxGraph Trace & Replay.The trace file is on github LFS: https://howhsu.github.io/thinking-in-bitcoin/data/txgraph.trace.4.5days.final.xz
Same trace replayed on baseline vs ChainCluster branch. Parameters:
max_cluster_count=64,max_cluster_size=404000,acceptable_cost=75000. Total ops: 71,313,272.Mutations (not timed): ADD_TX 1,764,814, REMOVE_TX 33,050, ADD_DEP 791,630, SET_FEE 0, UNLINK_REF 1,764,814.
Trace analysis
analyze_trace.pyon the same trace file (/tmp/txgraph.trace).Note on oversized clusters: Clusters with size > 64 appear because the trace captures graph state at discrete snapshots (e.g. after each CommitStaging). Split is triggered lazily by DoWork/ApplyDependencies; at snapshot time, some clusters may not yet have been processed and thus exceed
max_cluster_count.Note on peak state: Peak state is the snapshot with the most transactions (27,512), not necessarily the one with the most chain clusters.
Peak state (27,512 transactions, 8,596 clusters):
max_cluster_count=64(oversized)Final state (6,079 transactions, 4,665 clusters):
max_cluster_count=64The trace file is about 0.5 GB, I'll find a place to upload it soon.
Memory Analysis
As per @instagibbs 's comment, I make some memory tests, the results are in below article:
https://howhsu.github.io/thinking-in-bitcoin/articles/chain-cluster-memory.en.html
No-chain mempool
As @instagibbs points out, mempool usage patterns may evolve over time. We should evaluate the impact of this optimization in the no-chain scenario (i.e., when there are no chains of size ≥ 3; chains of size 2 are typically CPFP cases). Below link is the comparison and results.
https://howhsu.github.io/thinking-in-bitcoin/articles/chain-cluster-nochain-baseline.en.html
In short, chaincluster is ~21% faster, which is most likely caused by size=2 chains.
Compare with PR #34643
https://howhsu.github.io/thinking-in-bitcoin/articles/chain-linearize-vs-chaincluster.en.html
Compare with the previous chain linearize idea. In short, chaincluster branch is about 15.5% faster.
Overhead of
IsOversizedandCountDistinctClustersThe increase in overhead for these two components is caused by chunk computation in
Updated. This logic was moved fromDoWorktoIsOversizedandCountDistinctClustersas part of the chain cluster design. For more details, see: https://howhsu.github.io/thinking-in-bitcoin/articles/chain-isoversized-chunk-overhead.en.htmlBench Environment
The above results were obtained on the test machine.
Hardware
Host OS
Docker Container
Fuzz testing
** Fuzz Environment**
txgraphfuzz_corpus/txgraph