Coverage Report

Created: 2026-11-13 17:38

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/txgraph.cpp
Line
Count
Source
1
// Copyright (c) The Bitcoin Core developers
2
// Distributed under the MIT software license, see the accompanying
3
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5
#include <txgraph.h>
6
7
#include <cluster_linearize.h>
8
#include <random.h>
9
#include <util/bitset.h>
10
#include <util/check.h>
11
#include <util/feefrac.h>
12
#include <util/vector.h>
13
14
#include <compare>
15
#include <functional>
16
#include <memory>
17
#include <ranges>
18
#include <set>
19
#include <span>
20
#include <unordered_set>
21
#include <utility>
22
#include <vector>
23
24
namespace {
25
26
using namespace cluster_linearize;
27
28
/** The maximum number of levels a TxGraph can have (0 = main, 1 = staging). */
29
static constexpr int MAX_LEVELS{2};
30
31
// Forward declare the TxGraph implementation class.
32
class TxGraphImpl;
33
34
/** Position of a DepGraphIndex within a Cluster::m_linearization. */
35
using LinearizationIndex = uint32_t;
36
/** Position of a Cluster within TxGraphImpl::ClusterSet::m_clusters. */
37
using ClusterSetIndex = uint32_t;
38
39
/** Quality levels for cached cluster linearizations. */
40
enum class QualityLevel
41
{
42
    /** This is a singleton cluster consisting of a transaction that individually exceeds the
43
     *  cluster size limit. It cannot be merged with anything. */
44
    OVERSIZED_SINGLETON,
45
    /** This cluster may have multiple disconnected components, which are all NEEDS_FIX. */
46
    NEEDS_SPLIT_FIX,
47
    /** This cluster may have multiple disconnected components, which are all NEEDS_RELINEARIZE. */
48
    NEEDS_SPLIT,
49
    /** This cluster may be non-topological. */
50
    NEEDS_FIX,
51
    /** This cluster has undergone changes that warrant re-linearization. */
52
    NEEDS_RELINEARIZE,
53
    /** The minimal level of linearization has been performed, but it is not known to be optimal. */
54
    ACCEPTABLE,
55
    /** The linearization is known to be optimal. */
56
    OPTIMAL,
57
    /** This cluster is not registered in any ClusterSet::m_clusters.
58
     *  This must be the last entry in QualityLevel as ClusterSet::m_clusters is sized using it. */
59
    NONE,
60
};
61
62
/** Information about a transaction inside TxGraphImpl::Trim. */
63
struct TrimTxData
64
{
65
    // Fields populated by Cluster::AppendTrimData(). These are immutable after TrimTxData
66
    // construction.
67
    /** Chunk feerate for this transaction. */
68
    FeePerWeight m_chunk_feerate;
69
    /** GraphIndex of the transaction. */
70
    TxGraph::GraphIndex m_index;
71
    /** Size of the transaction. */
72
    uint32_t m_tx_size;
73
74
    // Fields only used internally by TxGraphImpl::Trim():
75
    /** Number of unmet dependencies this transaction has. -1 if the transaction is included. */
76
    uint32_t m_deps_left;
77
    /** Number of dependencies that apply to this transaction as child. */
78
    uint32_t m_parent_count;
79
    /** Where in deps_by_child those dependencies begin. */
80
    uint32_t m_parent_offset;
81
    /** Number of dependencies that apply to this transaction as parent. */
82
    uint32_t m_children_count;
83
    /** Where in deps_by_parent those dependencies begin. */
84
    uint32_t m_children_offset;
85
86
    // Fields only used internally by TxGraphImpl::Trim()'s union-find implementation, and only for
87
    // transactions that are definitely included or definitely rejected.
88
    //
89
    // As transactions get processed, they get organized into trees which form partitions
90
    // representing the would-be clusters up to that point. The root of each tree is a
91
    // representative for that partition. See
92
    // https://en.wikipedia.org/wiki/Disjoint-set_data_structure.
93
    //
94
    /** Pointer to another TrimTxData, towards the root of the tree. If this is a root, m_uf_parent
95
     *  is equal to this itself. */
96
    TrimTxData* m_uf_parent;
97
    /** If this is a root, the total number of transactions in the partition. */
98
    uint32_t m_uf_count;
99
    /** If this is a root, the total size of transactions in the partition. */
100
    uint64_t m_uf_size;
101
};
102
103
/** A grouping of connected transactions inside a TxGraphImpl::ClusterSet. */
104
class Cluster
105
{
106
    friend class TxGraphImpl;
107
    friend class BlockBuilderImpl;
108
109
protected:
110
    using GraphIndex = TxGraph::GraphIndex;
111
    using SetType = BitSet<MAX_CLUSTER_COUNT_LIMIT>;
112
    /** The quality level of m_linearization. */
113
    QualityLevel m_quality{QualityLevel::NONE};
114
    /** Which position this Cluster has in TxGraphImpl::ClusterSet::m_clusters[m_quality]. */
115
    ClusterSetIndex m_setindex{ClusterSetIndex(-1)};
116
    /** Sequence number for this Cluster (for tie-breaking comparison between equal-chunk-feerate
117
        transactions in distinct clusters). */
118
    uint64_t m_sequence;
119
120
136k
    explicit Cluster(uint64_t sequence) noexcept : m_sequence(sequence) {}
121
122
public:
123
    // Provide virtual destructor, for safe polymorphic usage inside std::unique_ptr.
124
136k
    virtual ~Cluster() = default;
125
126
    // Cannot move or copy (would invalidate Cluster* in Locator and ClusterSet). */
127
    Cluster(const Cluster&) = delete;
128
    Cluster& operator=(const Cluster&) = delete;
129
    Cluster(Cluster&&) = delete;
130
    Cluster& operator=(Cluster&&) = delete;
131
132
    // Generic helper functions.
133
134
    /** Whether the linearization of this Cluster can be exposed. */
135
    bool IsAcceptable() const noexcept
136
180M
    {
137
180M
        return m_quality == QualityLevel::ACCEPTABLE || m_quality == QualityLevel::OPTIMAL;
138
180M
    }
139
    /** Whether the linearization of this Cluster is topological. */
140
    bool IsTopological() const noexcept
141
412k
    {
142
412k
        return m_quality != QualityLevel::NEEDS_FIX && m_quality != QualityLevel::NEEDS_SPLIT_FIX;
143
412k
    }
144
    /** Whether the linearization of this Cluster is optimal. */
145
    bool IsOptimal() const noexcept
146
6.94M
    {
147
6.94M
        return m_quality == QualityLevel::OPTIMAL;
148
6.94M
    }
149
    /** Whether this cluster is oversized. Note that no changes that can cause oversizedness are
150
     *  ever applied, so the only way a materialized Cluster object can be oversized is by being
151
     *  an individually oversized transaction singleton. */
152
14.0M
    bool IsOversized() const noexcept { return m_quality == QualityLevel::OVERSIZED_SINGLETON; }
153
    /** Whether this cluster requires splitting. */
154
    bool NeedsSplitting() const noexcept
155
179M
    {
156
179M
        return m_quality == QualityLevel::NEEDS_SPLIT || m_quality == QualityLevel::NEEDS_SPLIT_FIX;
157
179M
    }
158
159
    /** Get the smallest number of transactions this Cluster is intended for. */
160
    virtual DepGraphIndex GetMinIntendedTxCount() const noexcept = 0;
161
    /** Get the maximum number of transactions this Cluster supports. */
162
    virtual DepGraphIndex GetMaxTxCount() const noexcept = 0;
163
    /** Total memory usage currently for this Cluster, including all its dynamic memory, plus Cluster
164
     *  structure itself, and ClusterSet::m_clusters entry. */
165
    virtual size_t TotalMemoryUsage() const noexcept = 0;
166
    /** Determine the range of DepGraphIndexes used by this Cluster. */
167
    virtual DepGraphIndex GetDepGraphIndexRange() const noexcept = 0;
168
    /** Get the number of transactions in this Cluster. */
169
    virtual LinearizationIndex GetTxCount() const noexcept = 0;
170
    /** Get the total size of the transactions in this Cluster. */
171
    virtual uint64_t GetTotalTxSize() const noexcept = 0;
172
    /** Given a DepGraphIndex into this Cluster, find the corresponding GraphIndex. */
173
    virtual GraphIndex GetClusterEntry(DepGraphIndex index) const noexcept = 0;
174
    /** Append a transaction with given GraphIndex at the end of this Cluster and its
175
     *  linearization. Return the DepGraphIndex it was placed at. */
176
    virtual DepGraphIndex AppendTransaction(GraphIndex graph_idx, FeePerWeight feerate) noexcept = 0;
177
    /** Add dependencies to a given child in this cluster. */
178
    virtual void AddDependencies(SetType parents, DepGraphIndex child) noexcept = 0;
179
    /** Invoke visit1_fn for each transaction in the cluster, in linearization order, then
180
     *  visit2_fn in the same order, then wipe this Cluster. */
181
    virtual void ExtractTransactions(const std::function<void (DepGraphIndex, GraphIndex, FeePerWeight)>& visit1_fn, const std::function<void (DepGraphIndex, GraphIndex, SetType)>& visit2_fn) noexcept = 0;
182
    /** Figure out what level this Cluster exists at in the graph. In most cases this is known by
183
     *  the caller already (see all "int level" arguments below), but not always. */
184
    virtual int GetLevel(const TxGraphImpl& graph) const noexcept = 0;
185
    /** Only called by TxGraphImpl::SwapIndexes. */
186
    virtual void UpdateMapping(DepGraphIndex cluster_idx, GraphIndex graph_idx) noexcept = 0;
187
    /** Push changes to Cluster and its linearization to the TxGraphImpl Entry objects. Main chunk
188
     *  information is computed if the cluster is acceptable, or when rename is set. Rename is used
189
     *  when called from Compact, to recompute after GraphIndexes may have changed; in this case,
190
     *  no chunk index objects are removed or created either. */
191
    virtual void Updated(TxGraphImpl& graph, int level, bool rename) noexcept = 0;
192
    /** Remove all chunk index entries for this cluster (level=0 only). */
193
    virtual void RemoveChunkData(TxGraphImpl& graph) noexcept = 0;
194
    /** Create a copy of this Cluster in staging, returning a pointer to it (used by PullIn). */
195
    virtual Cluster* CopyToStaging(TxGraphImpl& graph) const noexcept = 0;
196
    /** Get the list of Clusters in main that conflict with this one (which is assumed to be in staging). */
197
    virtual void GetConflicts(const TxGraphImpl& graph, std::vector<Cluster*>& out) const noexcept = 0;
198
    /** Mark all the Entry objects belonging to this staging Cluster as missing. The Cluster must be
199
     *  deleted immediately after. */
200
    virtual void MakeStagingTransactionsMissing(TxGraphImpl& graph) noexcept = 0;
201
    /** Remove all transactions from a (non-empty) Cluster. */
202
    virtual void Clear(TxGraphImpl& graph, int level) noexcept = 0;
203
    /** Change a Cluster's level from 1 (staging) to 0 (main). */
204
    virtual void MoveToMain(TxGraphImpl& graph) noexcept = 0;
205
    /** Minimize this Cluster's memory usage. */
206
    virtual void Compact() noexcept = 0;
207
208
    // Functions that implement the Cluster-specific side of internal TxGraphImpl mutations.
209
210
    /** Apply all removals from the front of to_remove that apply to this Cluster, popping them
211
     *  off. There must be at least one such entry. */
212
    virtual void ApplyRemovals(TxGraphImpl& graph, int level, std::span<GraphIndex>& to_remove) noexcept = 0;
213
    /** Split this cluster (must have a NEEDS_SPLIT* quality). Returns whether to delete this
214
     *  Cluster afterwards. */
215
    [[nodiscard]] virtual bool Split(TxGraphImpl& graph, int level) noexcept = 0;
216
    /** Move all transactions from cluster to *this (as separate components). */
217
    virtual void Merge(TxGraphImpl& graph, int level, Cluster& cluster) noexcept = 0;
218
    /** Given a span of (parent, child) pairs that all belong to this Cluster, apply them. */
219
    virtual void ApplyDependencies(TxGraphImpl& graph, int level, std::span<std::pair<GraphIndex, GraphIndex>> to_apply) noexcept = 0;
220
    /** Improve the linearization of this Cluster. Returns how much work was performed and whether
221
     *  the Cluster's QualityLevel improved as a result. */
222
    virtual std::pair<uint64_t, bool> Relinearize(TxGraphImpl& graph, int level, uint64_t max_cost) noexcept = 0;
223
    /** For every chunk in the cluster, append its FeeFrac to ret. */
224
    virtual void AppendChunkFeerates(std::vector<FeeFrac>& ret) const noexcept = 0;
225
    /** Add a TrimTxData entry (filling m_chunk_feerate, m_index, m_tx_size) for every
226
     *  transaction in the Cluster to ret. Implicit dependencies between consecutive transactions
227
     *  in the linearization are added to deps. Return the Cluster's total transaction size. */
228
    virtual uint64_t AppendTrimData(std::vector<TrimTxData>& ret, std::vector<std::pair<GraphIndex, GraphIndex>>& deps) const noexcept = 0;
229
230
    // Functions that implement the Cluster-specific side of public TxGraph functions.
231
232
    /** Process elements from the front of args that apply to this cluster, and append Refs for the
233
     *  union of their ancestors to output. */
234
    virtual void GetAncestorRefs(const TxGraphImpl& graph, std::span<std::pair<Cluster*, DepGraphIndex>>& args, std::vector<TxGraph::Ref*>& output) noexcept = 0;
235
    /** Process elements from the front of args that apply to this cluster, and append Refs for the
236
     *  union of their descendants to output. */
237
    virtual void GetDescendantRefs(const TxGraphImpl& graph, std::span<std::pair<Cluster*, DepGraphIndex>>& args, std::vector<TxGraph::Ref*>& output) noexcept = 0;
238
    /** Populate range with refs for the transactions in this Cluster's linearization, from
239
     *  position start_pos until start_pos+range.size()-1, inclusive. Returns whether that
240
     *  range includes the last transaction in the linearization. */
241
    virtual bool GetClusterRefs(TxGraphImpl& graph, std::span<TxGraph::Ref*> range, LinearizationIndex start_pos) noexcept = 0;
242
    /** Get the individual transaction feerate of a Cluster element. */
243
    virtual FeePerWeight GetIndividualFeerate(DepGraphIndex idx) noexcept = 0;
244
    /** Modify the fee of a Cluster element. */
245
    virtual void SetFee(TxGraphImpl& graph, int level, DepGraphIndex idx, int64_t fee) noexcept = 0;
246
247
    // Debugging functions.
248
249
    virtual void SanityCheck(const TxGraphImpl& graph, int level) const = 0;
250
};
251
252
/** An implementation of Cluster that uses a DepGraph and vectors, to support arbitrary numbers of
253
 *  transactions up to MAX_CLUSTER_COUNT_LIMIT. */
254
class GenericClusterImpl final : public Cluster
255
{
256
    friend class TxGraphImpl;
257
    /** The DepGraph for this cluster, holding all feerates, and ancestors/descendants. */
258
    DepGraph<SetType> m_depgraph;
259
    /** m_mapping[i] gives the GraphIndex for the position i transaction in m_depgraph. Values for
260
     *  positions i that do not exist in m_depgraph shouldn't ever be accessed and thus don't
261
     *  matter. m_mapping.size() equals m_depgraph.PositionRange(). */
262
    std::vector<GraphIndex> m_mapping;
263
    /** The current linearization of the cluster. m_linearization.size() equals
264
     *  m_depgraph.TxCount(). This is always kept topological. */
265
    std::vector<DepGraphIndex> m_linearization;
266
267
public:
268
    /** The smallest number of transactions this Cluster implementation is intended for. */
269
    static constexpr DepGraphIndex MIN_INTENDED_TX_COUNT{2};
270
    /** The largest number of transactions this Cluster implementation supports. */
271
    static constexpr DepGraphIndex MAX_TX_COUNT{SetType::Size()};
272
273
    GenericClusterImpl() noexcept = delete;
274
    /** Construct an empty GenericClusterImpl. */
275
    explicit GenericClusterImpl(uint64_t sequence) noexcept;
276
277
    size_t TotalMemoryUsage() const noexcept final;
278
69.0k
    constexpr DepGraphIndex GetMinIntendedTxCount() const noexcept final { return MIN_INTENDED_TX_COUNT; }
279
73.5k
    constexpr DepGraphIndex GetMaxTxCount() const noexcept final { return MAX_TX_COUNT; }
280
11
    DepGraphIndex GetDepGraphIndexRange() const noexcept final { return m_depgraph.PositionRange(); }
281
375k
    LinearizationIndex GetTxCount() const noexcept final { return m_linearization.size(); }
282
    uint64_t GetTotalTxSize() const noexcept final;
283
404k
    GraphIndex GetClusterEntry(DepGraphIndex index) const noexcept final { return m_mapping[index]; }
284
    DepGraphIndex AppendTransaction(GraphIndex graph_idx, FeePerWeight feerate) noexcept final;
285
    void AddDependencies(SetType parents, DepGraphIndex child) noexcept final;
286
    void ExtractTransactions(const std::function<void (DepGraphIndex, GraphIndex, FeePerWeight)>& visit1_fn, const std::function<void (DepGraphIndex, GraphIndex, SetType)>& visit2_fn) noexcept final;
287
    int GetLevel(const TxGraphImpl& graph) const noexcept final;
288
822
    void UpdateMapping(DepGraphIndex cluster_idx, GraphIndex graph_idx) noexcept final { m_mapping[cluster_idx] = graph_idx; }
289
    void Updated(TxGraphImpl& graph, int level, bool rename) noexcept final;
290
    void RemoveChunkData(TxGraphImpl& graph) noexcept final;
291
    Cluster* CopyToStaging(TxGraphImpl& graph) const noexcept final;
292
    void GetConflicts(const TxGraphImpl& graph, std::vector<Cluster*>& out) const noexcept final;
293
    void MakeStagingTransactionsMissing(TxGraphImpl& graph) noexcept final;
294
    void Clear(TxGraphImpl& graph, int level) noexcept final;
295
    void MoveToMain(TxGraphImpl& graph) noexcept final;
296
    void Compact() noexcept final;
297
    void ApplyRemovals(TxGraphImpl& graph, int level, std::span<GraphIndex>& to_remove) noexcept final;
298
    [[nodiscard]] bool Split(TxGraphImpl& graph, int level) noexcept final;
299
    void Merge(TxGraphImpl& graph, int level, Cluster& cluster) noexcept final;
300
    void ApplyDependencies(TxGraphImpl& graph, int level, std::span<std::pair<GraphIndex, GraphIndex>> to_apply) noexcept final;
301
    std::pair<uint64_t, bool> Relinearize(TxGraphImpl& graph, int level, uint64_t max_cost) noexcept final;
302
    void AppendChunkFeerates(std::vector<FeeFrac>& ret) const noexcept final;
303
    uint64_t AppendTrimData(std::vector<TrimTxData>& ret, std::vector<std::pair<GraphIndex, GraphIndex>>& deps) const noexcept final;
304
    void GetAncestorRefs(const TxGraphImpl& graph, std::span<std::pair<Cluster*, DepGraphIndex>>& args, std::vector<TxGraph::Ref*>& output) noexcept final;
305
    void GetDescendantRefs(const TxGraphImpl& graph, std::span<std::pair<Cluster*, DepGraphIndex>>& args, std::vector<TxGraph::Ref*>& output) noexcept final;
306
    bool GetClusterRefs(TxGraphImpl& graph, std::span<TxGraph::Ref*> range, LinearizationIndex start_pos) noexcept final;
307
    FeePerWeight GetIndividualFeerate(DepGraphIndex idx) noexcept final;
308
    void SetFee(TxGraphImpl& graph, int level, DepGraphIndex idx, int64_t fee) noexcept final;
309
    void SanityCheck(const TxGraphImpl& graph, int level) const final;
310
};
311
312
/** An implementation of Cluster that only supports 1 transaction. */
313
class SingletonClusterImpl final : public Cluster
314
{
315
    friend class TxGraphImpl;
316
317
    /** The feerate of the (singular) transaction in this Cluster. */
318
    FeePerWeight m_feerate;
319
    /** Constant to indicate that this Cluster is empty. */
320
    static constexpr auto NO_GRAPH_INDEX = GraphIndex(-1);
321
    /** The GraphIndex of the transaction. NO_GRAPH_INDEX if this Cluster is empty. */
322
    GraphIndex m_graph_index = NO_GRAPH_INDEX;
323
324
public:
325
    /** The smallest number of transactions this Cluster implementation is intended for. */
326
    static constexpr DepGraphIndex MIN_INTENDED_TX_COUNT{1};
327
    /** The largest number of transactions this Cluster implementation supports. */
328
    static constexpr DepGraphIndex MAX_TX_COUNT{1};
329
330
    SingletonClusterImpl() noexcept = delete;
331
    /** Construct an empty SingletonClusterImpl. */
332
134k
    explicit SingletonClusterImpl(uint64_t sequence) noexcept : Cluster(sequence) {}
333
334
    size_t TotalMemoryUsage() const noexcept final;
335
6.93M
    constexpr DepGraphIndex GetMinIntendedTxCount() const noexcept final { return MIN_INTENDED_TX_COUNT; }
336
6.93M
    constexpr DepGraphIndex GetMaxTxCount() const noexcept final { return MAX_TX_COUNT; }
337
63.6M
    LinearizationIndex GetTxCount() const noexcept final { return m_graph_index != NO_GRAPH_INDEX; }
338
7.96k
    DepGraphIndex GetDepGraphIndexRange() const noexcept final { return GetTxCount(); }
339
7.07M
    uint64_t GetTotalTxSize() const noexcept final { return GetTxCount() ? m_feerate.size : 0; }
340
6.93M
    GraphIndex GetClusterEntry(DepGraphIndex index) const noexcept final { Assume(index == 0); Assume(GetTxCount()); return m_graph_index; }
341
    DepGraphIndex AppendTransaction(GraphIndex graph_idx, FeePerWeight feerate) noexcept final;
342
    void AddDependencies(SetType parents, DepGraphIndex child) noexcept final;
343
    void ExtractTransactions(const std::function<void (DepGraphIndex, GraphIndex, FeePerWeight)>& visit1_fn, const std::function<void (DepGraphIndex, GraphIndex, SetType)>& visit2_fn) noexcept final;
344
    int GetLevel(const TxGraphImpl& graph) const noexcept final;
345
12.5k
    void UpdateMapping(DepGraphIndex cluster_idx, GraphIndex graph_idx) noexcept final { Assume(cluster_idx == 0); m_graph_index = graph_idx; }
346
    void Updated(TxGraphImpl& graph, int level, bool rename) noexcept final;
347
    void RemoveChunkData(TxGraphImpl& graph) noexcept final;
348
    Cluster* CopyToStaging(TxGraphImpl& graph) const noexcept final;
349
    void GetConflicts(const TxGraphImpl& graph, std::vector<Cluster*>& out) const noexcept final;
350
    void MakeStagingTransactionsMissing(TxGraphImpl& graph) noexcept final;
351
    void Clear(TxGraphImpl& graph, int level) noexcept final;
352
    void MoveToMain(TxGraphImpl& graph) noexcept final;
353
    void Compact() noexcept final;
354
    void ApplyRemovals(TxGraphImpl& graph, int level, std::span<GraphIndex>& to_remove) noexcept final;
355
    [[nodiscard]] bool Split(TxGraphImpl& graph, int level) noexcept final;
356
    void Merge(TxGraphImpl& graph, int level, Cluster& cluster) noexcept final;
357
    void ApplyDependencies(TxGraphImpl& graph, int level, std::span<std::pair<GraphIndex, GraphIndex>> to_apply) noexcept final;
358
    std::pair<uint64_t, bool> Relinearize(TxGraphImpl& graph, int level, uint64_t max_cost) noexcept final;
359
    void AppendChunkFeerates(std::vector<FeeFrac>& ret) const noexcept final;
360
    uint64_t AppendTrimData(std::vector<TrimTxData>& ret, std::vector<std::pair<GraphIndex, GraphIndex>>& deps) const noexcept final;
361
    void GetAncestorRefs(const TxGraphImpl& graph, std::span<std::pair<Cluster*, DepGraphIndex>>& args, std::vector<TxGraph::Ref*>& output) noexcept final;
362
    void GetDescendantRefs(const TxGraphImpl& graph, std::span<std::pair<Cluster*, DepGraphIndex>>& args, std::vector<TxGraph::Ref*>& output) noexcept final;
363
    bool GetClusterRefs(TxGraphImpl& graph, std::span<TxGraph::Ref*> range, LinearizationIndex start_pos) noexcept final;
364
    FeePerWeight GetIndividualFeerate(DepGraphIndex idx) noexcept final;
365
    void SetFee(TxGraphImpl& graph, int level, DepGraphIndex idx, int64_t fee) noexcept final;
366
    void SanityCheck(const TxGraphImpl& graph, int level) const final;
367
};
368
369
/** The transaction graph, including staged changes.
370
 *
371
 * The overall design of the data structure consists of 3 interlinked representations:
372
 * - The transactions (held as a vector of TxGraphImpl::Entry inside TxGraphImpl).
373
 * - The clusters (Cluster objects in per-quality vectors inside TxGraphImpl::ClusterSet).
374
 * - The Refs (TxGraph::Ref objects, held externally by users of the TxGraph class)
375
 *
376
 * The Clusters are kept in one or two ClusterSet objects, one for the "main" graph, and one for
377
 * the proposed changes ("staging"). If a transaction occurs in both, they share the same Entry,
378
 * but there will be a separate Cluster per graph.
379
 *
380
 * Clusters and Refs contain the index of the Entry objects they refer to, and the Entry objects
381
 * refer back to the Clusters and Refs the corresponding transaction is contained in.
382
 *
383
 * While redundant, this permits moving all of them independently, without invalidating things
384
 * or costly iteration to fix up everything:
385
 * - Entry objects can be moved to fill holes left by removed transactions in the Entry vector
386
 *   (see TxGraphImpl::Compact).
387
 * - Clusters can be rewritten continuously (removals can cause them to split, new dependencies
388
 *   can cause them to be merged).
389
 * - Ref objects can be held outside the class, while permitting them to be moved around, and
390
 *   inherited from.
391
 */
392
class TxGraphImpl final : public TxGraph
393
{
394
    friend class Cluster;
395
    friend class SingletonClusterImpl;
396
    friend class GenericClusterImpl;
397
    friend class BlockBuilderImpl;
398
private:
399
    /** Internal RNG. */
400
    FastRandomContext m_rng;
401
    /** This TxGraphImpl's maximum cluster count limit. */
402
    const DepGraphIndex m_max_cluster_count;
403
    /** This TxGraphImpl's maximum cluster size limit. */
404
    const uint64_t m_max_cluster_size;
405
    /** The amount of linearization work needed per cluster to be considered acceptable. */
406
    const uint64_t m_acceptable_cost;
407
    /** Fallback ordering for transactions. */
408
    const std::function<std::strong_ordering(const TxGraph::Ref&, const TxGraph::Ref&)> m_fallback_order;
409
410
    /** Information about one group of Clusters to be merged. */
411
    struct GroupEntry
412
    {
413
        /** Where the clusters to be merged start in m_group_clusters. */
414
        uint32_t m_cluster_offset;
415
        /** How many clusters to merge. */
416
        uint32_t m_cluster_count;
417
        /** Where the dependencies for this cluster group in m_deps_to_add start. */
418
        uint32_t m_deps_offset;
419
        /** How many dependencies to add. */
420
        uint32_t m_deps_count;
421
    };
422
423
    /** Information about all groups of Clusters to be merged. */
424
    struct GroupData
425
    {
426
        /** The groups of Clusters to be merged. */
427
        std::vector<GroupEntry> m_groups;
428
        /** Which clusters are to be merged. GroupEntry::m_cluster_offset indexes into this. */
429
        std::vector<Cluster*> m_group_clusters;
430
    };
431
432
    /** The collection of all Clusters in main or staged. */
433
    struct ClusterSet
434
    {
435
        /** The vectors of clusters, one vector per quality level. ClusterSetIndex indexes into each. */
436
        std::array<std::vector<std::unique_ptr<Cluster>>, int(QualityLevel::NONE)> m_clusters;
437
        /** Which removals have yet to be applied. */
438
        std::vector<GraphIndex> m_to_remove;
439
        /** Which dependencies are to be added ((parent,child) pairs). GroupData::m_deps_offset indexes
440
         *  into this. */
441
        std::vector<std::pair<GraphIndex, GraphIndex>> m_deps_to_add;
442
        /** Information about the merges to be performed, if known. */
443
        std::optional<GroupData> m_group_data = GroupData{};
444
        /** Which entries were removed in this ClusterSet (so they can be wiped on abort). This
445
         *  includes all entries which have an (R) removed locator at this level (staging only),
446
         *  plus optionally any transaction in m_unlinked. */
447
        std::vector<GraphIndex> m_removed;
448
        /** Total number of transactions in this graph (sum of all transaction counts in all
449
         *  Clusters, and for staging also those inherited from the main ClusterSet). */
450
        GraphIndex m_txcount{0};
451
        /** Total number of individually oversized transactions in the graph. */
452
        GraphIndex m_txcount_oversized{0};
453
        /** Whether this graph is oversized (if known). */
454
        std::optional<bool> m_oversized{false};
455
        /** The combined TotalMemoryUsage of all clusters in this level (only Clusters that
456
         *  are materialized; in staging, implicit Clusters from main are not counted), */
457
        size_t m_cluster_usage{0};
458
459
69.1k
        ClusterSet() noexcept = default;
460
    };
461
462
    /** The main ClusterSet. */
463
    ClusterSet m_main_clusterset;
464
    /** The staging ClusterSet, if any. */
465
    std::optional<ClusterSet> m_staging_clusterset;
466
    /** Next sequence number to assign to created Clusters. */
467
    uint64_t m_next_sequence_counter{0};
468
469
    /** Information about a chunk in the main graph. */
470
    struct ChunkData
471
    {
472
        /** The Entry which is the last transaction of the chunk. */
473
        mutable GraphIndex m_graph_index;
474
        /** How many transactions the chunk contains (-1 = singleton tail of cluster). */
475
        LinearizationIndex m_chunk_count;
476
477
        ChunkData(GraphIndex graph_index, LinearizationIndex chunk_count) noexcept :
478
171k
            m_graph_index{graph_index}, m_chunk_count{chunk_count} {}
479
    };
480
481
    /** Compare two Cluster* by their m_sequence value (while supporting nullptr). */
482
    static std::strong_ordering CompareClusters(Cluster* a, Cluster* b) noexcept
483
171k
    {
484
        // The nullptr pointer compares before everything else.
485
171k
        if (a == nullptr || b == nullptr) {
486
0
            return (a != nullptr) <=> (b != nullptr);
487
0
        }
488
        // If neither pointer is nullptr, compare the Clusters' sequence numbers.
489
171k
        Assume(a == b || a->m_sequence != b->m_sequence);
490
171k
        return a->m_sequence <=> b->m_sequence;
491
171k
    }
492
493
    /** Compare two entries (which must both exist within the main graph). */
494
    std::strong_ordering CompareMainTransactions(GraphIndex a, GraphIndex b) const noexcept
495
88.3M
    {
496
88.3M
        if (a == b) return std::strong_ordering::equal;
497
88.3M
        Assume(a < m_entries.size() && b < m_entries.size());
498
88.3M
        const auto& entry_a = m_entries[a];
499
88.3M
        const auto& entry_b = m_entries[b];
500
        // Compare chunk feerates, and return result if it differs.
501
88.3M
        auto feerate_cmp = ByRatio{entry_b.m_main_chunk_feerate} <=> ByRatio{entry_a.m_main_chunk_feerate};
502
88.3M
        if (feerate_cmp != 0) return feerate_cmp;
503
        // Compare equal-feerate chunk prefix size for comparing equal chunk feerates. This does two
504
        // things: it distinguishes equal-feerate chunks within the same cluster (because later
505
        // ones will always have a higher prefix size), and it may distinguish equal-feerate chunks
506
        // from distinct clusters.
507
50.5M
        if (entry_a.m_main_equal_feerate_chunk_prefix_size != entry_b.m_main_equal_feerate_chunk_prefix_size) {
508
1.65M
            return entry_a.m_main_equal_feerate_chunk_prefix_size <=> entry_b.m_main_equal_feerate_chunk_prefix_size;
509
1.65M
        }
510
        // Compare by maximum m_fallback_order element to order equal-feerate chunks in distinct
511
        // clusters, when the equal-feerate-prefix size is also the same.
512
48.8M
        const auto& locator_a = entry_a.m_locator[0];
513
48.8M
        const auto& locator_b = entry_b.m_locator[0];
514
48.8M
        Assume(locator_a.IsPresent() && locator_b.IsPresent());
515
48.8M
        if (locator_a.cluster != locator_b.cluster) {
516
47.7M
            auto fallback_cmp = m_fallback_order(*m_entries[entry_a.m_main_max_chunk_fallback].m_ref,
517
47.7M
                                                 *m_entries[entry_b.m_main_max_chunk_fallback].m_ref);
518
47.7M
            if (fallback_cmp != 0) return fallback_cmp;
519
            // This shouldn't be reachable as m_fallback_order defines a strong ordering.
520
0
            Assume(false);
521
0
            return CompareClusters(locator_a.cluster, locator_b.cluster);
522
47.7M
        }
523
        // Within a single chunk, sort by position within cluster linearization.
524
1.13M
        return entry_a.m_main_lin_index <=> entry_b.m_main_lin_index;
525
48.8M
    }
526
527
    /** Comparator for ChunkData objects in mining order. */
528
    class ChunkOrder
529
    {
530
        const TxGraphImpl* const m_graph;
531
    public:
532
1.39k
        explicit ChunkOrder(const TxGraphImpl* graph) : m_graph(graph) {}
533
534
        bool operator()(const ChunkData& a, const ChunkData& b) const noexcept
535
2.10M
        {
536
2.10M
            return m_graph->CompareMainTransactions(a.m_graph_index, b.m_graph_index) < 0;
537
2.10M
        }
538
    };
539
540
    /** Definition for the mining index type. */
541
    using ChunkIndex = std::set<ChunkData, ChunkOrder>;
542
543
    /** Index of ChunkData objects, indexing the last transaction in each chunk in the main
544
     *  graph. */
545
    ChunkIndex m_main_chunkindex;
546
    /** Number of index-observing objects in existence (BlockBuilderImpls). */
547
    size_t m_main_chunkindex_observers{0};
548
    /** Cache of discarded ChunkIndex node handles to reuse, avoiding additional allocation. */
549
    std::vector<ChunkIndex::node_type> m_main_chunkindex_discarded;
550
551
    /** A Locator that describes whether, where, and in which Cluster an Entry appears.
552
     *  Every Entry has MAX_LEVELS locators, as it may appear in one Cluster per level.
553
     *
554
     *  Each level of a Locator is in one of three states:
555
     *
556
     *  - (P)resent: actually occurs in a Cluster at that level.
557
     *
558
     *  - (M)issing:
559
     *    - In the main graph:    the transaction does not exist in main.
560
     *    - In the staging graph: the transaction's existence is the same as in main. If it doesn't
561
     *                            exist in main, (M) in staging means it does not exist there
562
     *                            either. If it does exist in main, (M) in staging means the
563
     *                            cluster it is in has not been modified in staging, and thus the
564
     *                            transaction implicitly exists in staging too (without explicit
565
     *                            Cluster object; see PullIn() to create it in staging too).
566
     *
567
     *  - (R)emoved: only possible in staging; it means the transaction exists in main, but is
568
     *               removed in staging.
569
     *
570
     * The following combinations are possible:
571
     * - (M,M): the transaction doesn't exist in either graph.
572
     * - (P,M): the transaction exists in both, but only exists explicitly in a Cluster object in
573
     *          main. Its existence in staging is inherited from main.
574
     * - (P,P): the transaction exists in both, and is materialized in both. Thus, the clusters
575
     *          and/or their linearizations may be different in main and staging.
576
     * - (M,P): the transaction is added in staging, and does not exist in main.
577
     * - (P,R): the transaction exists in main, but is removed in staging.
578
     *
579
     * When staging does not exist, only (M,M) and (P,M) are possible.
580
     */
581
    struct Locator
582
    {
583
        /** Which Cluster the Entry appears in (nullptr = missing). */
584
        Cluster* cluster{nullptr};
585
        /** Where in the Cluster it appears (if cluster == nullptr: 0 = missing, -1 = removed). */
586
        DepGraphIndex index{0};
587
588
        /** Mark this Locator as missing (= same as lower level, or non-existing if level 0). */
589
98.9k
        void SetMissing() noexcept { cluster = nullptr; index = 0; }
590
        /** Mark this Locator as removed (not allowed in level 0). */
591
2.18k
        void SetRemoved() noexcept { cluster = nullptr; index = DepGraphIndex(-1); }
592
        /** Mark this Locator as present, in the specified Cluster. */
593
376k
        void SetPresent(Cluster* c, DepGraphIndex i) noexcept { cluster = c; index = i; }
594
        /** Check if this Locator is missing. */
595
16.0M
        bool IsMissing() const noexcept { return cluster == nullptr && index == 0; }
596
        /** Check if this Locator is removed. */
597
23.4M
        bool IsRemoved() const noexcept { return cluster == nullptr && index == DepGraphIndex(-1); }
598
        /** Check if this Locator is present (in some Cluster). */
599
307M
        bool IsPresent() const noexcept { return cluster != nullptr; }
600
    };
601
602
    /** Internal information about each transaction in a TxGraphImpl. */
603
    struct Entry
604
    {
605
        /** Pointer to the corresponding Ref object if any, or nullptr if unlinked. */
606
        Ref* m_ref{nullptr};
607
        /** Iterator to the corresponding ChunkData, if any, and m_main_chunkindex.end() otherwise.
608
         *  This is initialized on construction of the Entry, in AddTransaction. */
609
        ChunkIndex::iterator m_main_chunkindex_iterator;
610
        /** Which Cluster and position therein this Entry appears in. ([0] = main, [1] = staged). */
611
        Locator m_locator[MAX_LEVELS];
612
        /** The chunk feerate of this transaction in main (if present in m_locator[0]). */
613
        FeePerWeight m_main_chunk_feerate;
614
        /** The equal-feerate chunk prefix size of this transaction in main. If the transaction is
615
         *  part of chunk C in main, then this gives the sum of the sizes of all chunks in C's
616
         *  cluster, whose feerate is equal to that of C, which do not appear after C itself in
617
         *  the cluster's linearization.
618
         *  This provides a way to sort equal-feerate chunks across clusters, in a way that agrees
619
         *  with the within-cluster chunk ordering. */
620
        int32_t m_main_equal_feerate_chunk_prefix_size;
621
        /** The position this transaction has in the main linearization (if present). */
622
        LinearizationIndex m_main_lin_index;
623
        /** Of all transactions within this transaction's chunk in main (if present there), the
624
         *  maximal one according to m_fallback_order. */
625
        GraphIndex m_main_max_chunk_fallback = GraphIndex(-1);
626
    };
627
628
    /** The set of all transactions (in all levels combined). GraphIndex values index into this. */
629
    std::vector<Entry> m_entries;
630
631
    /** Set of Entries which have no linked Ref anymore. */
632
    std::vector<GraphIndex> m_unlinked;
633
634
public:
635
    /** Construct a new TxGraphImpl with the specified limits and fallback order. */
636
    explicit TxGraphImpl(
637
        DepGraphIndex max_cluster_count,
638
        uint64_t max_cluster_size,
639
        uint64_t acceptable_cost,
640
        const std::function<std::strong_ordering(const TxGraph::Ref&, const TxGraph::Ref&)>& fallback_order
641
    ) noexcept :
642
1.39k
        m_max_cluster_count(max_cluster_count),
643
1.39k
        m_max_cluster_size(max_cluster_size),
644
1.39k
        m_acceptable_cost(acceptable_cost),
645
1.39k
        m_fallback_order(fallback_order),
646
1.39k
        m_main_chunkindex(ChunkOrder(this))
647
1.39k
    {
648
1.39k
        Assume(max_cluster_count >= 1);
649
1.39k
        Assume(max_cluster_count <= MAX_CLUSTER_COUNT_LIMIT);
650
1.39k
    }
651
652
    /** Destructor. */
653
    ~TxGraphImpl() noexcept;
654
655
    // Cannot move or copy (would invalidate TxGraphImpl* in Ref, MiningOrder, EvictionOrder).
656
    TxGraphImpl(const TxGraphImpl&) = delete;
657
    TxGraphImpl& operator=(const TxGraphImpl&) = delete;
658
    TxGraphImpl(TxGraphImpl&&) = delete;
659
    TxGraphImpl& operator=(TxGraphImpl&&) = delete;
660
661
    // Simple helper functions.
662
663
    /** Swap the Entry referred to by a and the one referred to by b. Gather main clusters to
664
     *  update afterwards. */
665
    void SwapIndexes(GraphIndex a, GraphIndex b, std::vector<Cluster*>& affected_main) noexcept;
666
    /** If idx exists in the specified level ClusterSet (explicitly, or in the level below and not
667
    *   removed), return the Cluster it is in. Otherwise, return nullptr. */
668
1.00M
    Cluster* FindCluster(GraphIndex idx, int level) const noexcept { return FindClusterAndLevel(idx, level).first; }
669
    /** Like FindCluster, but also return what level the match was found in (-1 if not found). */
670
    std::pair<Cluster*, int> FindClusterAndLevel(GraphIndex idx, int level) const noexcept;
671
    /** Extract a Cluster from its ClusterSet, and set its quality to QualityLevel::NONE. */
672
    std::unique_ptr<Cluster> ExtractCluster(int level, QualityLevel quality, ClusterSetIndex setindex) noexcept;
673
    /** Delete a Cluster. */
674
    void DeleteCluster(Cluster& cluster, int level) noexcept;
675
    /** Insert a Cluster into its ClusterSet. */
676
    ClusterSetIndex InsertCluster(int level, std::unique_ptr<Cluster>&& cluster, QualityLevel quality) noexcept;
677
    /** Change the QualityLevel of a Cluster (identified by old_quality and old_index). */
678
    void SetClusterQuality(int level, QualityLevel old_quality, ClusterSetIndex old_index, QualityLevel new_quality) noexcept;
679
    /** Get the index of the top level ClusterSet (staging if it exists, main otherwise). */
680
3.92M
    int GetTopLevel() const noexcept { return m_staging_clusterset.has_value(); }
681
    /** Get the specified level (staging if it exists and level is TOP, main otherwise). */
682
548k
    int GetSpecifiedLevel(Level level) const noexcept { return level == Level::TOP && m_staging_clusterset.has_value(); }
683
    /** Get a reference to the ClusterSet at the specified level (which must exist). */
684
    ClusterSet& GetClusterSet(int level) noexcept;
685
    const ClusterSet& GetClusterSet(int level) const noexcept;
686
    /** Make a transaction not exist at a specified level. It must currently exist there.
687
     *  oversized_tx indicates whether the transaction is an individually-oversized one
688
     *  (OVERSIZED_SINGLETON). */
689
    void ClearLocator(int level, GraphIndex index, bool oversized_tx) noexcept;
690
    /** Find which Clusters in main conflict with ones in staging. */
691
    std::vector<Cluster*> GetConflicts() const noexcept;
692
    /** Clear an Entry's ChunkData. */
693
    void ClearChunkData(Entry& entry) noexcept;
694
    /** Give an Entry a ChunkData object. */
695
    void CreateChunkData(GraphIndex idx, LinearizationIndex chunk_count) noexcept;
696
    /** Create an empty GenericClusterImpl object. */
697
    std::unique_ptr<GenericClusterImpl> CreateEmptyGenericCluster() noexcept
698
1.75k
    {
699
1.75k
        return std::make_unique<GenericClusterImpl>(m_next_sequence_counter++);
700
1.75k
    }
701
    /** Create an empty SingletonClusterImpl object. */
702
    std::unique_ptr<SingletonClusterImpl> CreateEmptySingletonCluster() noexcept
703
134k
    {
704
134k
        return std::make_unique<SingletonClusterImpl>(m_next_sequence_counter++);
705
134k
    }
706
    /** Create an empty Cluster of the appropriate implementation for the specified (maximum) tx
707
     *  count. */
708
    std::unique_ptr<Cluster> CreateEmptyCluster(DepGraphIndex tx_count) noexcept
709
134k
    {
710
134k
        if (tx_count >= SingletonClusterImpl::MIN_INTENDED_TX_COUNT && tx_count <= SingletonClusterImpl::MAX_TX_COUNT) {
711
133k
            return CreateEmptySingletonCluster();
712
133k
        }
713
1.42k
        if (tx_count >= GenericClusterImpl::MIN_INTENDED_TX_COUNT && tx_count <= GenericClusterImpl::MAX_TX_COUNT) {
714
1.42k
            return CreateEmptyGenericCluster();
715
1.42k
        }
716
1.42k
        assert(false);
717
0
        return {};
718
0
    }
719
720
    // Functions for handling Refs.
721
722
    /** Only called by Ref's move constructor/assignment to update Ref locations. */
723
    void UpdateRef(GraphIndex idx, Ref& new_location) noexcept final
724
65.5k
    {
725
65.5k
        auto& entry = m_entries[idx];
726
65.5k
        Assume(entry.m_ref != nullptr);
727
65.5k
        entry.m_ref = &new_location;
728
65.5k
    }
729
730
    /** Only called by Ref::~Ref to unlink Refs, and Ref's move assignment. */
731
    void UnlinkRef(GraphIndex idx) noexcept final
732
68.7k
    {
733
68.7k
        auto& entry = m_entries[idx];
734
68.7k
        Assume(entry.m_ref != nullptr);
735
68.7k
        Assume(m_main_chunkindex_observers == 0 || !entry.m_locator[0].IsPresent());
736
        // Remove all chunk index entries for the affected cluster, to avoid any chunk indexes
737
        // referencing unlinked/destroyed Refs.
738
68.7k
        if (entry.m_locator[0].IsPresent()) {
739
44.1k
            entry.m_locator[0].cluster->RemoveChunkData(*this);
740
44.1k
        }
741
68.7k
        entry.m_ref = nullptr;
742
        // Mark the transaction as to be removed in all levels where it explicitly or implicitly
743
        // exists.
744
68.7k
        bool exists_anywhere{false};
745
68.7k
        bool exists{false};
746
137k
        for (int level = 0; level <= GetTopLevel(); ++level) {
747
68.7k
            if (entry.m_locator[level].IsPresent()) {
748
44.1k
                exists_anywhere = true;
749
44.1k
                exists = true;
750
44.1k
            } else if (entry.m_locator[level].IsRemoved()) {
751
0
                exists = false;
752
0
            }
753
68.7k
            if (exists) {
754
44.1k
                auto& clusterset = GetClusterSet(level);
755
44.1k
                clusterset.m_to_remove.push_back(idx);
756
                // Force recomputation of grouping data.
757
44.1k
                clusterset.m_group_data = std::nullopt;
758
                // Do not wipe the oversized state of main if staging exists. The reason for this
759
                // is that the alternative would mean that cluster merges may need to be applied to
760
                // a formerly-oversized main graph while staging exists (to satisfy chunk feerate
761
                // queries into main, for example), and such merges could conflict with pulls of
762
                // some of their constituents into staging.
763
44.1k
                if (level == GetTopLevel() && clusterset.m_oversized == true) {
764
0
                    clusterset.m_oversized = std::nullopt;
765
0
                }
766
44.1k
            }
767
68.7k
        }
768
68.7k
        m_unlinked.push_back(idx);
769
68.7k
        if (!exists_anywhere) Compact();
770
68.7k
    }
771
772
    // Functions related to various normalization/application steps.
773
    /** Get rid of unlinked Entry objects in m_entries, if possible (this changes the GraphIndex
774
     *  values for remaining Entry objects, so this only does something when no to-be-applied
775
     *  operations or staged removals referring to GraphIndexes remain). */
776
    void Compact() noexcept;
777
    /** If cluster is not in staging, copy it there, and return a pointer to it.
778
    *   Staging must exist, and this modifies the locators of its
779
    *   transactions from inherited (P,M) to explicit (P,P). */
780
    Cluster* PullIn(Cluster* cluster, int level) noexcept;
781
    /** Apply all removals queued up in m_to_remove to the relevant Clusters (which get a
782
     *  NEEDS_SPLIT* QualityLevel) up to the specified level. */
783
    void ApplyRemovals(int up_to_level) noexcept;
784
    /** Split an individual cluster. */
785
    void Split(Cluster& cluster, int level) noexcept;
786
    /** Split all clusters that need splitting up to the specified level. */
787
    void SplitAll(int up_to_level) noexcept;
788
    /** Populate m_group_data based on m_deps_to_add in the specified level. */
789
    void GroupClusters(int level) noexcept;
790
    /** Merge the specified clusters. */
791
    void Merge(std::span<Cluster*> to_merge, int level) noexcept;
792
    /** Apply all m_deps_to_add to the relevant Clusters in the specified level. */
793
    void ApplyDependencies(int level) noexcept;
794
    /** Make a specified Cluster have quality ACCEPTABLE or OPTIMAL. */
795
    void MakeAcceptable(Cluster& cluster, int level) noexcept;
796
    /** Make all Clusters at the specified level have quality ACCEPTABLE or OPTIMAL. */
797
    void MakeAllAcceptable(int level) noexcept;
798
799
    // Implementations for the public TxGraph interface.
800
801
    void AddTransaction(Ref& arg, const FeePerWeight& feerate) noexcept final;
802
    void RemoveTransaction(const Ref& arg) noexcept final;
803
    void AddDependency(const Ref& parent, const Ref& child) noexcept final;
804
    void SetTransactionFee(const Ref&, int64_t fee) noexcept final;
805
806
    bool DoWork(uint64_t max_cost) noexcept final;
807
808
    void StartStaging() noexcept final;
809
    void CommitStaging() noexcept final;
810
    void AbortStaging() noexcept final;
811
67.7k
    bool HaveStaging() const noexcept final { return m_staging_clusterset.has_value(); }
812
813
    bool Exists(const Ref& arg, Level level) noexcept final;
814
    FeePerWeight GetMainChunkFeerate(const Ref& arg) noexcept final;
815
    FeePerWeight GetIndividualFeerate(const Ref& arg) noexcept final;
816
    std::vector<Ref*> GetCluster(const Ref& arg, Level level) noexcept final;
817
    std::vector<Ref*> GetAncestors(const Ref& arg, Level level) noexcept final;
818
    std::vector<Ref*> GetDescendants(const Ref& arg, Level level) noexcept final;
819
    std::vector<Ref*> GetAncestorsUnion(std::span<const Ref* const> args, Level level) noexcept final;
820
    std::vector<Ref*> GetDescendantsUnion(std::span<const Ref* const> args, Level level) noexcept final;
821
    GraphIndex GetTransactionCount(Level level) noexcept final;
822
    bool IsOversized(Level level) noexcept final;
823
    std::strong_ordering CompareMainOrder(const Ref& a, const Ref& b) noexcept final;
824
    GraphIndex CountDistinctClusters(std::span<const Ref* const> refs, Level level) noexcept final;
825
    std::pair<std::vector<FeeFrac>, std::vector<FeeFrac>> GetMainStagingDiagrams() noexcept final;
826
    std::vector<Ref*> Trim() noexcept final;
827
828
    std::unique_ptr<BlockBuilder> GetBlockBuilder() noexcept final;
829
    std::pair<std::vector<Ref*>, FeePerWeight> GetWorstMainChunk() noexcept final;
830
831
    size_t GetMainMemoryUsage() noexcept final;
832
833
    void SanityCheck() const final;
834
};
835
836
TxGraphImpl::ClusterSet& TxGraphImpl::GetClusterSet(int level) noexcept
837
179M
{
838
179M
    if (level == 0) return m_main_clusterset;
839
427k
    Assume(level == 1);
840
427k
    Assume(m_staging_clusterset.has_value());
841
427k
    return *m_staging_clusterset;
842
179M
}
843
844
const TxGraphImpl::ClusterSet& TxGraphImpl::GetClusterSet(int level) const noexcept
845
192k
{
846
192k
    if (level == 0) return m_main_clusterset;
847
46.7k
    Assume(level == 1);
848
46.7k
    Assume(m_staging_clusterset.has_value());
849
46.7k
    return *m_staging_clusterset;
850
192k
}
851
852
/** Implementation of the TxGraph::BlockBuilder interface. */
853
class BlockBuilderImpl final : public TxGraph::BlockBuilder
854
{
855
    /** Which TxGraphImpl this object is doing block building for. It will have its
856
     *  m_main_chunkindex_observers incremented as long as this BlockBuilderImpl exists. */
857
    TxGraphImpl* const m_graph;
858
    /** Cluster sequence numbers which we're not including further transactions from. */
859
    std::unordered_set<uint64_t> m_excluded_clusters;
860
    /** Iterator to the current chunk in the chunk index. end() if nothing further remains. */
861
    TxGraphImpl::ChunkIndex::const_iterator m_cur_iter;
862
    /** Which cluster the current chunk belongs to, so we can exclude further transactions from it
863
     *  when that chunk is skipped. */
864
    Cluster* m_cur_cluster;
865
    /** Whether we know that m_cur_iter points to the last chunk of m_cur_cluster. */
866
    bool m_known_end_of_cluster;
867
868
    // Move m_cur_iter / m_cur_cluster to the next acceptable chunk.
869
    void Next() noexcept;
870
871
public:
872
    /** Construct a new BlockBuilderImpl to build blocks for the provided graph. */
873
    BlockBuilderImpl(TxGraphImpl& graph) noexcept;
874
875
    // Implement the public interface.
876
    ~BlockBuilderImpl() final;
877
    std::optional<std::pair<std::vector<TxGraph::Ref*>, FeePerWeight>> GetCurrentChunk() noexcept final;
878
    void Include() noexcept final;
879
    void Skip() noexcept final;
880
};
881
882
void TxGraphImpl::ClearChunkData(Entry& entry) noexcept
883
524k
{
884
524k
    if (entry.m_main_chunkindex_iterator != m_main_chunkindex.end()) {
885
109k
        Assume(m_main_chunkindex_observers == 0);
886
        // If the Entry has a non-empty m_main_chunkindex_iterator, extract it, and move the handle
887
        // to the cache of discarded chunkindex entries.
888
109k
        m_main_chunkindex_discarded.emplace_back(m_main_chunkindex.extract(entry.m_main_chunkindex_iterator));
889
109k
        entry.m_main_chunkindex_iterator = m_main_chunkindex.end();
890
109k
    }
891
524k
}
892
893
void TxGraphImpl::CreateChunkData(GraphIndex idx, LinearizationIndex chunk_count) noexcept
894
172k
{
895
172k
    auto& entry = m_entries[idx];
896
    // Make sure to not create chunk data for unlinked entries, which would make invoking
897
    // m_fallback_order on them impossible.
898
172k
    Assume(entry.m_ref != nullptr);
899
172k
    if (!m_main_chunkindex_discarded.empty()) {
900
        // Reuse an discarded node handle.
901
1.40k
        auto& node = m_main_chunkindex_discarded.back().value();
902
1.40k
        node.m_graph_index = idx;
903
1.40k
        node.m_chunk_count = chunk_count;
904
1.40k
        auto insert_result = m_main_chunkindex.insert(std::move(m_main_chunkindex_discarded.back()));
905
1.40k
        Assume(insert_result.inserted);
906
1.40k
        entry.m_main_chunkindex_iterator = insert_result.position;
907
1.40k
        m_main_chunkindex_discarded.pop_back();
908
171k
    } else {
909
        // Construct a new entry.
910
171k
        auto emplace_result = m_main_chunkindex.emplace(idx, chunk_count);
911
171k
        Assume(emplace_result.second);
912
171k
        entry.m_main_chunkindex_iterator = emplace_result.first;
913
171k
    }
914
172k
}
915
916
size_t GenericClusterImpl::TotalMemoryUsage() const noexcept
917
83.9k
{
918
83.9k
    return // Dynamic memory allocated in this Cluster.
919
83.9k
           memusage::DynamicUsage(m_mapping) + memusage::DynamicUsage(m_linearization) +
920
           // Dynamic memory usage inside m_depgraph.
921
83.9k
           m_depgraph.DynamicMemoryUsage() +
922
           // Memory usage of the allocated Cluster itself.
923
83.9k
           memusage::MallocUsage(sizeof(GenericClusterImpl)) +
924
           // Memory usage of the ClusterSet::m_clusters entry.
925
83.9k
           sizeof(std::unique_ptr<Cluster>);
926
83.9k
}
927
928
size_t SingletonClusterImpl::TotalMemoryUsage() const noexcept
929
7.19M
{
930
7.19M
    return // Memory usage of the allocated SingletonClusterImpl itself.
931
7.19M
           memusage::MallocUsage(sizeof(SingletonClusterImpl)) +
932
           // Memory usage of the ClusterSet::m_clusters entry.
933
7.19M
           sizeof(std::unique_ptr<Cluster>);
934
7.19M
}
935
936
uint64_t GenericClusterImpl::GetTotalTxSize() const noexcept
937
74.6k
{
938
74.6k
    uint64_t ret{0};
939
491k
    for (auto i : m_linearization) {
940
491k
        ret += m_depgraph.FeeRate(i).size;
941
491k
    }
942
74.6k
    return ret;
943
74.6k
}
944
945
DepGraphIndex GenericClusterImpl::AppendTransaction(GraphIndex graph_idx, FeePerWeight feerate) noexcept
946
15
{
947
15
    Assume(graph_idx != GraphIndex(-1));
948
15
    auto ret = m_depgraph.AddTransaction(feerate);
949
15
    m_mapping.push_back(graph_idx);
950
15
    m_linearization.push_back(ret);
951
15
    return ret;
952
15
}
953
954
DepGraphIndex SingletonClusterImpl::AppendTransaction(GraphIndex graph_idx, FeePerWeight feerate) noexcept
955
133k
{
956
133k
    Assume(!GetTxCount());
957
133k
    m_graph_index = graph_idx;
958
133k
    m_feerate = feerate;
959
133k
    return 0;
960
133k
}
961
962
void GenericClusterImpl::AddDependencies(SetType parents, DepGraphIndex child) noexcept
963
15
{
964
15
    m_depgraph.AddDependencies(parents, child);
965
15
}
966
967
void SingletonClusterImpl::AddDependencies(SetType parents, DepGraphIndex child) noexcept
968
381
{
969
    // Singletons cannot have any dependencies.
970
381
    Assume(child == 0);
971
381
    Assume(parents == SetType{} || parents == SetType::Fill(0));
972
381
}
973
974
void GenericClusterImpl::ExtractTransactions(const std::function<void (DepGraphIndex, GraphIndex, FeePerWeight)>& visit1_fn, const std::function<void (DepGraphIndex, GraphIndex, SetType)>& visit2_fn) noexcept
975
11
{
976
42
    for (auto pos : m_linearization) {
977
42
        visit1_fn(pos, m_mapping[pos], FeePerWeight::FromFeeFrac(m_depgraph.FeeRate(pos)));
978
42
    }
979
42
    for (auto pos : m_linearization) {
980
42
        visit2_fn(pos, m_mapping[pos], m_depgraph.GetReducedParents(pos));
981
42
    }
982
    // Purge this Cluster, now that everything has been moved.
983
11
    m_depgraph = DepGraph<SetType>{};
984
11
    m_linearization.clear();
985
11
    m_mapping.clear();
986
11
}
987
988
void SingletonClusterImpl::ExtractTransactions(const std::function<void (DepGraphIndex, GraphIndex, FeePerWeight)>& visit1_fn, const std::function<void (DepGraphIndex, GraphIndex, SetType)>& visit2_fn) noexcept
989
7.96k
{
990
7.96k
    if (GetTxCount()) {
991
7.96k
        visit1_fn(0, m_graph_index, m_feerate);
992
7.96k
        visit2_fn(0, m_graph_index, SetType{});
993
7.96k
        m_graph_index = NO_GRAPH_INDEX;
994
7.96k
    }
995
7.96k
}
996
997
int GenericClusterImpl::GetLevel(const TxGraphImpl& graph) const noexcept
998
69.0k
{
999
    // GetLevel() does not work for empty Clusters.
1000
69.0k
    if (!Assume(!m_linearization.empty())) return -1;
1001
1002
    // Pick an arbitrary Entry that occurs in this Cluster.
1003
69.0k
    const auto& entry = graph.m_entries[m_mapping[m_linearization.front()]];
1004
    // See if there is a level whose Locator matches this Cluster, if so return that level.
1005
69.0k
    for (int level = 0; level < MAX_LEVELS; ++level) {
1006
69.0k
        if (entry.m_locator[level].cluster == this) return level;
1007
69.0k
    }
1008
    // Given that we started with an Entry that occurs in this Cluster, one of its Locators must
1009
    // point back to it.
1010
69.0k
    assert(false);
1011
0
    return -1;
1012
0
}
1013
1014
int SingletonClusterImpl::GetLevel(const TxGraphImpl& graph) const noexcept
1015
7.00M
{
1016
    // GetLevel() does not work for empty Clusters.
1017
7.00M
    if (!Assume(GetTxCount())) return -1;
1018
1019
    // Get the Entry in this Cluster.
1020
7.00M
    const auto& entry = graph.m_entries[m_graph_index];
1021
    // See if there is a level whose Locator matches this Cluster, if so return that level.
1022
7.00M
    for (int level = 0; level < MAX_LEVELS; ++level) {
1023
7.00M
        if (entry.m_locator[level].cluster == this) return level;
1024
7.00M
    }
1025
    // Given that we started with an Entry that occurs in this Cluster, one of its Locators must
1026
    // point back to it.
1027
7.00M
    assert(false);
1028
0
    return -1;
1029
0
}
1030
1031
void TxGraphImpl::ClearLocator(int level, GraphIndex idx, bool oversized_tx) noexcept
1032
28.2k
{
1033
28.2k
    auto& entry = m_entries[idx];
1034
28.2k
    auto& clusterset = GetClusterSet(level);
1035
28.2k
    Assume(entry.m_locator[level].IsPresent());
1036
    // Change the locator from Present to Missing or Removed.
1037
28.2k
    if (level == 0 || !entry.m_locator[level - 1].IsPresent()) {
1038
26.0k
        entry.m_locator[level].SetMissing();
1039
26.0k
    } else {
1040
2.18k
        entry.m_locator[level].SetRemoved();
1041
2.18k
        clusterset.m_removed.push_back(idx);
1042
2.18k
    }
1043
    // Update the transaction count.
1044
28.2k
    --clusterset.m_txcount;
1045
28.2k
    clusterset.m_txcount_oversized -= oversized_tx;
1046
    // If clearing main, adjust the status of Locators of this transaction in staging, if it exists.
1047
28.2k
    if (level == 0 && GetTopLevel() == 1) {
1048
2.14k
        if (entry.m_locator[1].IsRemoved()) {
1049
1.59k
            entry.m_locator[1].SetMissing();
1050
1.59k
        } else if (!entry.m_locator[1].IsPresent()) {
1051
0
            --m_staging_clusterset->m_txcount;
1052
0
            m_staging_clusterset->m_txcount_oversized -= oversized_tx;
1053
0
        }
1054
2.14k
    }
1055
28.2k
    if (level == 0) ClearChunkData(entry);
1056
28.2k
}
1057
1058
void GenericClusterImpl::RemoveChunkData(TxGraphImpl& graph) noexcept
1059
7.02k
{
1060
171k
    for (DepGraphIndex idx : m_linearization) {
1061
171k
        auto& entry = graph.m_entries[m_mapping[idx]];
1062
171k
        graph.ClearChunkData(entry);
1063
171k
    }
1064
7.02k
}
1065
1066
void SingletonClusterImpl::RemoveChunkData(TxGraphImpl& graph) noexcept
1067
37.1k
{
1068
37.1k
    if (GetTxCount() == 0) return;
1069
37.1k
    auto& entry = graph.m_entries[m_graph_index];
1070
37.1k
    graph.ClearChunkData(entry);
1071
37.1k
}
1072
1073
void GenericClusterImpl::Updated(TxGraphImpl& graph, int level, bool rename) noexcept
1074
14.3k
{
1075
    // Update all the Locators for this Cluster's Entry objects.
1076
181k
    for (DepGraphIndex idx : m_linearization) {
1077
181k
        auto& entry = graph.m_entries[m_mapping[idx]];
1078
        // Discard any potential ChunkData prior to modifying the Cluster (as that could
1079
        // invalidate its ordering).
1080
181k
        if (level == 0 && !rename) graph.ClearChunkData(entry);
1081
181k
        entry.m_locator[level].SetPresent(this, idx);
1082
181k
    }
1083
    // If this is for the main graph (level = 0), and the Cluster's quality is ACCEPTABLE or
1084
    // OPTIMAL, compute its chunking and store its information in the Entry's m_main_lin_index
1085
    // and m_main_chunk_feerate. These fields are only accessed after making the entire graph
1086
    // ACCEPTABLE, so it is pointless to compute these if we haven't reached that quality level
1087
    // yet.
1088
    // When rename=true, this is always performed for level 0, to make sure the values inside the
1089
    // entries remain consistent with the chunk index (otherwise unrelated chunk index operations
1090
    // could cause the index to become corrupted, by inserting elements in the wrong place).
1091
14.3k
    if (level == 0 && (rename || IsAcceptable())) {
1092
6.64k
        auto chunking = ChunkLinearizationInfo(m_depgraph, m_linearization);
1093
6.64k
        LinearizationIndex lin_idx{0};
1094
        /** The sum of all chunk feerate FeeFracs with the same feerate as the current chunk,
1095
         *  up to and including the current chunk. */
1096
6.64k
        FeeFrac equal_feerate_chunk_feerate;
1097
        // Iterate over the chunks.
1098
73.3k
        for (unsigned chunk_idx = 0; chunk_idx < chunking.size(); ++chunk_idx) {
1099
66.7k
            auto& chunk = chunking[chunk_idx];
1100
66.7k
            auto chunk_count = chunk.transactions.Count();
1101
66.7k
            Assume(chunk_count > 0);
1102
            // Update equal_feerate_chunk_feerate to include this chunk, starting over when the
1103
            // feerate changed.
1104
66.7k
            if (ByRatio{chunk.feerate} < ByRatio{equal_feerate_chunk_feerate}) {
1105
3.29k
                equal_feerate_chunk_feerate = chunk.feerate;
1106
63.4k
            } else {
1107
                // Note that this is adding fees to fees, and sizes to sizes, so the overall
1108
                // ratio remains the same; it's just accounting for the size of the added chunk.
1109
63.4k
                equal_feerate_chunk_feerate += chunk.feerate;
1110
63.4k
            }
1111
            // Determine the m_fallback_order maximum transaction in the chunk.
1112
66.7k
            auto it = chunk.transactions.begin();
1113
66.7k
            GraphIndex max_element = m_mapping[*it];
1114
66.7k
            ++it;
1115
91.2k
            while (it != chunk.transactions.end()) {
1116
24.5k
                GraphIndex this_element = m_mapping[*it];
1117
24.5k
                if (graph.m_fallback_order(*graph.m_entries[this_element].m_ref, *graph.m_entries[max_element].m_ref) > 0) {
1118
2.99k
                    max_element = this_element;
1119
2.99k
                }
1120
24.5k
                ++it;
1121
24.5k
            }
1122
            // Iterate over the transactions in the linearization, which must match those in chunk.
1123
91.2k
            while (true) {
1124
91.2k
                DepGraphIndex idx = m_linearization[lin_idx];
1125
91.2k
                GraphIndex graph_idx = m_mapping[idx];
1126
91.2k
                auto& entry = graph.m_entries[graph_idx];
1127
91.2k
                entry.m_main_lin_index = lin_idx++;
1128
91.2k
                entry.m_main_chunk_feerate = FeePerWeight::FromFeeFrac(chunk.feerate);
1129
91.2k
                entry.m_main_equal_feerate_chunk_prefix_size = equal_feerate_chunk_feerate.size;
1130
91.2k
                entry.m_main_max_chunk_fallback = max_element;
1131
91.2k
                Assume(chunk.transactions[idx]);
1132
91.2k
                chunk.transactions.Reset(idx);
1133
91.2k
                if (chunk.transactions.None()) {
1134
                    // Last transaction in the chunk.
1135
66.7k
                    if (chunk_count == 1 && chunk_idx + 1 == chunking.size()) {
1136
                        // If this is the final chunk of the cluster, and it contains just a single
1137
                        // transaction (which will always be true for the very common singleton
1138
                        // clusters), store the special value -1 as chunk count.
1139
4.67k
                        chunk_count = LinearizationIndex(-1);
1140
4.67k
                    }
1141
66.7k
                    if (!rename) graph.CreateChunkData(graph_idx, chunk_count);
1142
66.7k
                    break;
1143
66.7k
                }
1144
91.2k
            }
1145
66.7k
        }
1146
6.64k
    }
1147
14.3k
}
1148
1149
void SingletonClusterImpl::Updated(TxGraphImpl& graph, int level, bool rename) noexcept
1150
187k
{
1151
    // Don't do anything if this is empty.
1152
187k
    if (GetTxCount() == 0) return;
1153
1154
187k
    auto& entry = graph.m_entries[m_graph_index];
1155
    // Discard any potential ChunkData prior to modifying the Cluster (as that could
1156
    // invalidate its ordering).
1157
187k
    if (level == 0 && !rename) graph.ClearChunkData(entry);
1158
187k
    entry.m_locator[level].SetPresent(this, 0);
1159
    // If this is for the main graph (level = 0), compute its chunking and store its information in
1160
    // the Entry's m_main_lin_index and m_main_chunk_feerate.
1161
187k
    if (level == 0 && (rename || IsAcceptable())) {
1162
117k
        entry.m_main_lin_index = 0;
1163
117k
        entry.m_main_chunk_feerate = m_feerate;
1164
117k
        entry.m_main_equal_feerate_chunk_prefix_size = m_feerate.size;
1165
117k
        entry.m_main_max_chunk_fallback = m_graph_index;
1166
        // Always use the special LinearizationIndex(-1), indicating singleton chunk at end of
1167
        // Cluster, here.
1168
117k
        if (!rename) graph.CreateChunkData(m_graph_index, LinearizationIndex(-1));
1169
117k
    }
1170
187k
}
1171
1172
void GenericClusterImpl::GetConflicts(const TxGraphImpl& graph, std::vector<Cluster*>& out) const noexcept
1173
135
{
1174
1.24k
    for (auto i : m_linearization) {
1175
1.24k
        auto& entry = graph.m_entries[m_mapping[i]];
1176
        // For every transaction Entry in this Cluster, if it also exists in a lower-level Cluster,
1177
        // then that Cluster conflicts.
1178
1.24k
        if (entry.m_locator[0].IsPresent()) {
1179
1.08k
            out.push_back(entry.m_locator[0].cluster);
1180
1.08k
        }
1181
1.24k
    }
1182
135
}
1183
1184
void SingletonClusterImpl::GetConflicts(const TxGraphImpl& graph, std::vector<Cluster*>& out) const noexcept
1185
46.7k
{
1186
    // Empty clusters have no conflicts.
1187
46.7k
    if (GetTxCount() == 0) return;
1188
1189
46.7k
    auto& entry = graph.m_entries[m_graph_index];
1190
    // If the transaction in this Cluster also exists in a lower-level Cluster, then that Cluster
1191
    // conflicts.
1192
46.7k
    if (entry.m_locator[0].IsPresent()) {
1193
130
        out.push_back(entry.m_locator[0].cluster);
1194
130
    }
1195
46.7k
}
1196
1197
std::vector<Cluster*> TxGraphImpl::GetConflicts() const noexcept
1198
46.7k
{
1199
46.7k
    Assume(GetTopLevel() == 1);
1200
46.7k
    auto& clusterset = GetClusterSet(1);
1201
46.7k
    std::vector<Cluster*> ret;
1202
    // All main Clusters containing transactions in m_removed (so (P,R) ones) are conflicts.
1203
46.7k
    for (auto i : clusterset.m_removed) {
1204
3.77k
        auto& entry = m_entries[i];
1205
3.77k
        if (entry.m_locator[0].IsPresent()) {
1206
3.77k
            ret.push_back(entry.m_locator[0].cluster);
1207
3.77k
        }
1208
3.77k
    }
1209
    // Then go over all Clusters at this level, and find their conflicts (the (P,P) ones).
1210
373k
    for (int quality = 0; quality < int(QualityLevel::NONE); ++quality) {
1211
327k
        auto& clusters = clusterset.m_clusters[quality];
1212
327k
        for (const auto& cluster : clusters) {
1213
46.9k
            cluster->GetConflicts(*this, ret);
1214
46.9k
        }
1215
327k
    }
1216
    // Deduplicate the result (the same Cluster may appear multiple times).
1217
46.7k
    std::ranges::sort(ret, [](Cluster* a, Cluster* b) noexcept { return CompareClusters(a, b) < 0; });
1218
46.7k
    ret.erase(std::ranges::unique(ret).begin(), ret.end());
1219
46.7k
    return ret;
1220
46.7k
}
1221
1222
Cluster* GenericClusterImpl::CopyToStaging(TxGraphImpl& graph) const noexcept
1223
332
{
1224
    // Construct an empty Cluster.
1225
332
    auto ret = graph.CreateEmptyGenericCluster();
1226
332
    auto ptr = ret.get();
1227
    // Copy depgraph, mapping, and linearization.
1228
332
    ptr->m_depgraph = m_depgraph;
1229
332
    ptr->m_mapping = m_mapping;
1230
332
    ptr->m_linearization = m_linearization;
1231
    // Insert the new Cluster into the graph.
1232
332
    graph.InsertCluster(/*level=*/1, std::move(ret), m_quality);
1233
    // Update its Locators.
1234
332
    ptr->Updated(graph, /*level=*/1, /*rename=*/false);
1235
    // Update memory usage.
1236
332
    graph.GetClusterSet(/*level=*/1).m_cluster_usage += ptr->TotalMemoryUsage();
1237
332
    return ptr;
1238
332
}
1239
1240
Cluster* SingletonClusterImpl::CopyToStaging(TxGraphImpl& graph) const noexcept
1241
1.42k
{
1242
    // Construct an empty Cluster.
1243
1.42k
    auto ret = graph.CreateEmptySingletonCluster();
1244
1.42k
    auto ptr = ret.get();
1245
    // Copy data.
1246
1.42k
    ptr->m_graph_index = m_graph_index;
1247
1.42k
    ptr->m_feerate = m_feerate;
1248
    // Insert the new Cluster into the graph.
1249
1.42k
    graph.InsertCluster(/*level=*/1, std::move(ret), m_quality);
1250
    // Update its Locators.
1251
1.42k
    ptr->Updated(graph, /*level=*/1, /*rename=*/false);
1252
    // Update memory usage.
1253
1.42k
    graph.GetClusterSet(/*level=*/1).m_cluster_usage += ptr->TotalMemoryUsage();
1254
1.42k
    return ptr;
1255
1.42k
}
1256
1257
void GenericClusterImpl::ApplyRemovals(TxGraphImpl& graph, int level, std::span<GraphIndex>& to_remove) noexcept
1258
1.25k
{
1259
    // Iterate over the prefix of to_remove that applies to this cluster.
1260
1.25k
    Assume(!to_remove.empty());
1261
1.25k
    SetType todo;
1262
1.25k
    graph.GetClusterSet(level).m_cluster_usage -= TotalMemoryUsage();
1263
6.15k
    do {
1264
6.15k
        GraphIndex idx = to_remove.front();
1265
6.15k
        Assume(idx < graph.m_entries.size());
1266
6.15k
        auto& entry = graph.m_entries[idx];
1267
6.15k
        auto& locator = entry.m_locator[level];
1268
        // Stop once we hit an entry that applies to another Cluster.
1269
6.15k
        if (locator.cluster != this) break;
1270
        // - Remember it in a set of to-remove DepGraphIndexes.
1271
5.38k
        todo.Set(locator.index);
1272
        // - Remove from m_mapping. This isn't strictly necessary as unused positions in m_mapping
1273
        //   are just never accessed, but set it to -1 here to increase the ability to detect a bug
1274
        //   that causes it to be accessed regardless.
1275
5.38k
        m_mapping[locator.index] = GraphIndex(-1);
1276
        // - Remove its linearization index from the Entry (if in main).
1277
5.38k
        if (level == 0) {
1278
4.62k
            entry.m_main_lin_index = LinearizationIndex(-1);
1279
4.62k
        }
1280
        // - Mark it as missing/removed in the Entry's locator.
1281
5.38k
        graph.ClearLocator(level, idx, m_quality == QualityLevel::OVERSIZED_SINGLETON);
1282
5.38k
        to_remove = to_remove.subspan(1);
1283
5.38k
    } while(!to_remove.empty());
1284
1285
1.25k
    Assume(todo.Any());
1286
    // Wipe from the Cluster's DepGraph (this is O(n) regardless of the number of entries
1287
    // removed, so we benefit from batching all the removals).
1288
1.25k
    m_depgraph.RemoveTransactions(todo);
1289
1.25k
    m_mapping.resize(m_depgraph.PositionRange());
1290
1291
    // Filter removed transactions out of m_linearization.
1292
6.19k
    std::erase_if(m_linearization, [&](auto pos) { return todo[pos]; });
1293
1294
1.25k
    Compact();
1295
1.25k
    graph.GetClusterSet(level).m_cluster_usage += TotalMemoryUsage();
1296
1.25k
    auto new_quality = IsTopological() ? QualityLevel::NEEDS_SPLIT : QualityLevel::NEEDS_SPLIT_FIX;
1297
1.25k
    graph.SetClusterQuality(level, m_quality, m_setindex, new_quality);
1298
1.25k
    Updated(graph, /*level=*/level, /*rename=*/false);
1299
1.25k
}
1300
1301
void SingletonClusterImpl::ApplyRemovals(TxGraphImpl& graph, int level, std::span<GraphIndex>& to_remove) noexcept
1302
20.7k
{
1303
    // We can only remove the one transaction this Cluster has.
1304
20.7k
    Assume(!to_remove.empty());
1305
20.7k
    Assume(GetTxCount());
1306
20.7k
    Assume(to_remove.front() == m_graph_index);
1307
    // Pop all copies of m_graph_index from the front of to_remove (at least one, but there may be
1308
    // multiple).
1309
20.7k
    do {
1310
20.7k
        to_remove = to_remove.subspan(1);
1311
20.7k
    } while (!to_remove.empty() && to_remove.front() == m_graph_index);
1312
    // Clear this cluster.
1313
20.7k
    graph.ClearLocator(level, m_graph_index, m_quality == QualityLevel::OVERSIZED_SINGLETON);
1314
20.7k
    m_graph_index = NO_GRAPH_INDEX;
1315
20.7k
    graph.SetClusterQuality(level, m_quality, m_setindex, QualityLevel::NEEDS_SPLIT);
1316
    // No need to account for m_cluster_usage changes here, as SingletonClusterImpl has constant
1317
    // memory usage.
1318
20.7k
}
1319
1320
void GenericClusterImpl::Clear(TxGraphImpl& graph, int level) noexcept
1321
230
{
1322
230
    Assume(GetTxCount());
1323
230
    graph.GetClusterSet(level).m_cluster_usage -= TotalMemoryUsage();
1324
1.09k
    for (auto i : m_linearization) {
1325
1.09k
        graph.ClearLocator(level, m_mapping[i], m_quality == QualityLevel::OVERSIZED_SINGLETON);
1326
1.09k
    }
1327
230
    m_depgraph = {};
1328
230
    m_linearization.clear();
1329
230
    m_mapping.clear();
1330
230
}
1331
1332
void SingletonClusterImpl::Clear(TxGraphImpl& graph, int level) noexcept
1333
1.04k
{
1334
1.04k
    Assume(GetTxCount());
1335
1.04k
    graph.GetClusterSet(level).m_cluster_usage -= TotalMemoryUsage();
1336
1.04k
    graph.ClearLocator(level, m_graph_index, m_quality == QualityLevel::OVERSIZED_SINGLETON);
1337
1.04k
    m_graph_index = NO_GRAPH_INDEX;
1338
1.04k
}
1339
1340
void GenericClusterImpl::MoveToMain(TxGraphImpl& graph) noexcept
1341
56
{
1342
558
    for (auto i : m_linearization) {
1343
558
        GraphIndex idx = m_mapping[i];
1344
558
        auto& entry = graph.m_entries[idx];
1345
558
        entry.m_locator[1].SetMissing();
1346
558
    }
1347
56
    auto quality = m_quality;
1348
    // Subtract memory usage from staging and add it to main.
1349
56
    graph.GetClusterSet(/*level=*/1).m_cluster_usage -= TotalMemoryUsage();
1350
56
    graph.GetClusterSet(/*level=*/0).m_cluster_usage += TotalMemoryUsage();
1351
    // Remove cluster itself from staging and add it to main.
1352
56
    auto cluster = graph.ExtractCluster(1, quality, m_setindex);
1353
56
    graph.InsertCluster(/*level=*/0, std::move(cluster), quality);
1354
56
    Updated(graph, /*level=*/0, /*rename=*/false);
1355
56
}
1356
1357
void SingletonClusterImpl::MoveToMain(TxGraphImpl& graph) noexcept
1358
45.4k
{
1359
45.4k
    if (GetTxCount()) {
1360
45.4k
        auto& entry = graph.m_entries[m_graph_index];
1361
45.4k
        entry.m_locator[1].SetMissing();
1362
45.4k
    }
1363
45.4k
    auto quality = m_quality;
1364
45.4k
    graph.GetClusterSet(/*level=*/1).m_cluster_usage -= TotalMemoryUsage();
1365
45.4k
    auto cluster = graph.ExtractCluster(/*level=*/1, quality, m_setindex);
1366
45.4k
    graph.InsertCluster(/*level=*/0, std::move(cluster), quality);
1367
45.4k
    graph.GetClusterSet(/*level=*/0).m_cluster_usage += TotalMemoryUsage();
1368
45.4k
    Updated(graph, /*level=*/0, /*rename=*/false);
1369
45.4k
}
1370
1371
void GenericClusterImpl::Compact() noexcept
1372
7.22k
{
1373
7.22k
    m_linearization.shrink_to_fit();
1374
7.22k
    m_mapping.shrink_to_fit();
1375
7.22k
    m_depgraph.Compact();
1376
7.22k
}
1377
1378
void SingletonClusterImpl::Compact() noexcept
1379
381
{
1380
    // Nothing to compact; SingletonClusterImpl is constant size.
1381
381
}
1382
1383
void GenericClusterImpl::AppendChunkFeerates(std::vector<FeeFrac>& ret) const noexcept
1384
410
{
1385
410
    auto chunk_feerates = ChunkLinearization(m_depgraph, m_linearization);
1386
410
    ret.reserve(ret.size() + chunk_feerates.size());
1387
410
    ret.insert(ret.end(), chunk_feerates.begin(), chunk_feerates.end());
1388
410
}
1389
1390
void SingletonClusterImpl::AppendChunkFeerates(std::vector<FeeFrac>& ret) const noexcept
1391
2.76k
{
1392
2.76k
    if (GetTxCount()) {
1393
2.76k
        ret.push_back(m_feerate);
1394
2.76k
    }
1395
2.76k
}
1396
1397
uint64_t GenericClusterImpl::AppendTrimData(std::vector<TrimTxData>& ret, std::vector<std::pair<GraphIndex, GraphIndex>>& deps) const noexcept
1398
0
{
1399
0
    Assume(IsAcceptable());
1400
0
    auto linchunking = ChunkLinearizationInfo(m_depgraph, m_linearization);
1401
0
    LinearizationIndex pos{0};
1402
0
    uint64_t size{0};
1403
0
    auto prev_index = GraphIndex(-1);
1404
    // Iterate over the chunks of this cluster's linearization.
1405
0
    for (const auto& [chunk, chunk_feerate] : linchunking) {
1406
        // Iterate over the transactions of that chunk, in linearization order.
1407
0
        auto chunk_tx_count = chunk.Count();
1408
0
        for (unsigned j = 0; j < chunk_tx_count; ++j) {
1409
0
            auto cluster_idx = m_linearization[pos];
1410
            // The transaction must appear in the chunk.
1411
0
            Assume(chunk[cluster_idx]);
1412
            // Construct a new element in ret.
1413
0
            auto& entry = ret.emplace_back();
1414
0
            entry.m_chunk_feerate = FeePerWeight::FromFeeFrac(chunk_feerate);
1415
0
            entry.m_index = m_mapping[cluster_idx];
1416
            // If this is not the first transaction of the cluster linearization, it has an
1417
            // implicit dependency on its predecessor.
1418
0
            if (pos != 0) deps.emplace_back(prev_index, entry.m_index);
1419
0
            prev_index = entry.m_index;
1420
0
            entry.m_tx_size = m_depgraph.FeeRate(cluster_idx).size;
1421
0
            size += entry.m_tx_size;
1422
0
            ++pos;
1423
0
        }
1424
0
    }
1425
0
    return size;
1426
0
}
1427
1428
uint64_t SingletonClusterImpl::AppendTrimData(std::vector<TrimTxData>& ret, std::vector<std::pair<GraphIndex, GraphIndex>>& deps) const noexcept
1429
64.2k
{
1430
64.2k
    if (!GetTxCount()) return 0;
1431
64.2k
    auto& entry = ret.emplace_back();
1432
64.2k
    entry.m_chunk_feerate = m_feerate;
1433
64.2k
    entry.m_index = m_graph_index;
1434
64.2k
    entry.m_tx_size = m_feerate.size;
1435
64.2k
    return m_feerate.size;
1436
64.2k
}
1437
1438
bool GenericClusterImpl::Split(TxGraphImpl& graph, int level) noexcept
1439
1.24k
{
1440
    // This function can only be called when the Cluster needs splitting.
1441
1.24k
    Assume(NeedsSplitting());
1442
    // Determine the new quality the split-off Clusters will have.
1443
1.24k
    QualityLevel new_quality = IsTopological() ? QualityLevel::NEEDS_RELINEARIZE : QualityLevel::NEEDS_FIX;
1444
    /** Which positions are still left in this Cluster. */
1445
1.24k
    auto todo = m_depgraph.Positions();
1446
    /** Mapping from transaction positions in this Cluster to the Cluster where it ends up, and
1447
     *  its position therein. */
1448
1.24k
    std::vector<std::pair<Cluster*, DepGraphIndex>> remap(m_depgraph.PositionRange());
1449
1.24k
    std::vector<Cluster*> new_clusters;
1450
1.24k
    bool first{true};
1451
    // Iterate over the connected components of this Cluster's m_depgraph.
1452
1.63k
    while (todo.Any()) {
1453
409
        auto component = m_depgraph.FindConnectedComponent(todo);
1454
409
        auto component_size = component.Count();
1455
409
        auto split_quality = component_size <= 1 ? QualityLevel::OPTIMAL : new_quality;
1456
409
        if (first && component == todo && SetType::Fill(component_size) == component && component_size >= MIN_INTENDED_TX_COUNT) {
1457
            // The existing Cluster is an entire component, without holes. Leave it be, but update
1458
            // its quality. If there are holes, we continue, so that the Cluster is reconstructed
1459
            // without holes, reducing memory usage. If the component's size is below the intended
1460
            // transaction count for this Cluster implementation, continue so that it can get
1461
            // converted.
1462
22
            Assume(todo == m_depgraph.Positions());
1463
22
            graph.SetClusterQuality(level, m_quality, m_setindex, split_quality);
1464
            // If this made the quality ACCEPTABLE or OPTIMAL, we need to compute and cache its
1465
            // chunking.
1466
22
            Updated(graph, /*level=*/level, /*rename=*/false);
1467
22
            return false;
1468
22
        }
1469
387
        first = false;
1470
        // Construct a new Cluster to hold the found component.
1471
387
        auto new_cluster = graph.CreateEmptyCluster(component_size);
1472
387
        new_clusters.push_back(new_cluster.get());
1473
        // Remember that all the component's transactions go to this new Cluster. The positions
1474
        // will be determined below, so use -1 for now.
1475
396
        for (auto i : component) {
1476
396
            remap[i] = {new_cluster.get(), DepGraphIndex(-1)};
1477
396
        }
1478
387
        graph.InsertCluster(level, std::move(new_cluster), split_quality);
1479
387
        todo -= component;
1480
387
    }
1481
    // We have to split the Cluster up. Remove accounting for the existing one first.
1482
1.22k
    graph.GetClusterSet(level).m_cluster_usage -= TotalMemoryUsage();
1483
    // Redistribute the transactions.
1484
1.22k
    for (auto i : m_linearization) {
1485
        /** The cluster which transaction originally in position i is moved to. */
1486
396
        Cluster* new_cluster = remap[i].first;
1487
        // Copy the transaction to the new cluster's depgraph, and remember the position.
1488
396
        remap[i].second = new_cluster->AppendTransaction(m_mapping[i], FeePerWeight::FromFeeFrac(m_depgraph.FeeRate(i)));
1489
396
    }
1490
    // Redistribute the dependencies.
1491
1.22k
    for (auto i : m_linearization) {
1492
        /** The cluster transaction in position i is moved to. */
1493
396
        Cluster* new_cluster = remap[i].first;
1494
        // Copy its parents, translating positions.
1495
396
        SetType new_parents;
1496
396
        for (auto par : m_depgraph.GetReducedParents(i)) new_parents.Set(remap[par].second);
1497
396
        new_cluster->AddDependencies(new_parents, remap[i].second);
1498
396
    }
1499
    // Update all the Locators of moved transactions, and memory usage.
1500
1.22k
    for (Cluster* new_cluster : new_clusters) {
1501
387
        new_cluster->Updated(graph, /*level=*/level, /*rename=*/false);
1502
387
        new_cluster->Compact();
1503
387
        graph.GetClusterSet(level).m_cluster_usage += new_cluster->TotalMemoryUsage();
1504
387
    }
1505
    // Wipe this Cluster, and return that it needs to be deleted.
1506
1.22k
    m_depgraph = DepGraph<SetType>{};
1507
1.22k
    m_mapping.clear();
1508
1.22k
    m_linearization.clear();
1509
1.22k
    return true;
1510
1.24k
}
1511
1512
bool SingletonClusterImpl::Split(TxGraphImpl& graph, int level) noexcept
1513
20.1k
{
1514
20.1k
    Assume(NeedsSplitting());
1515
20.1k
    Assume(!GetTxCount());
1516
20.1k
    graph.GetClusterSet(level).m_cluster_usage -= TotalMemoryUsage();
1517
20.1k
    return true;
1518
20.1k
}
1519
1520
void GenericClusterImpl::Merge(TxGraphImpl& graph, int level, Cluster& other) noexcept
1521
7.97k
{
1522
    /** Vector to store the positions in this Cluster for each position in other. */
1523
7.97k
    std::vector<DepGraphIndex> remap(other.GetDepGraphIndexRange());
1524
    // Iterate over all transactions in the other Cluster (the one being absorbed).
1525
8.00k
    other.ExtractTransactions([&](DepGraphIndex pos, GraphIndex idx, FeePerWeight feerate) noexcept {
1526
        // Copy the transaction into this Cluster, and remember its position.
1527
8.00k
        auto new_pos = m_depgraph.AddTransaction(feerate);
1528
        // Since this cluster must have been made hole-free before being merged into, all added
1529
        // transactions should appear at the end.
1530
8.00k
        Assume(new_pos == m_mapping.size());
1531
8.00k
        remap[pos] = new_pos;
1532
8.00k
        m_mapping.push_back(idx);
1533
8.00k
        m_linearization.push_back(new_pos);
1534
8.00k
    }, [&](DepGraphIndex pos, GraphIndex idx, SetType other_parents) noexcept {
1535
        // Copy the transaction's dependencies, translating them using remap.
1536
8.00k
        SetType parents;
1537
8.00k
        for (auto par : other_parents) {
1538
31
            parents.Set(remap[par]);
1539
31
        }
1540
8.00k
        m_depgraph.AddDependencies(parents, remap[pos]);
1541
        // Update the transaction's Locator. There is no need to call Updated() to update chunk
1542
        // feerates, as Updated() will be invoked by Cluster::ApplyDependencies on the resulting
1543
        // merged Cluster later anyway.
1544
8.00k
        auto& entry = graph.m_entries[idx];
1545
        // Discard any potential ChunkData prior to modifying the Cluster (as that could
1546
        // invalidate its ordering).
1547
8.00k
        if (level == 0) graph.ClearChunkData(entry);
1548
8.00k
        entry.m_locator[level].SetPresent(this, remap[pos]);
1549
8.00k
    });
1550
7.97k
}
1551
1552
void SingletonClusterImpl::Merge(TxGraphImpl&, int, Cluster&) noexcept
1553
0
{
1554
    // Nothing can be merged into a singleton; it should have been converted to GenericClusterImpl first.
1555
0
    Assume(false);
1556
0
}
1557
1558
void GenericClusterImpl::ApplyDependencies(TxGraphImpl& graph, int level, std::span<std::pair<GraphIndex, GraphIndex>> to_apply) noexcept
1559
5.99k
{
1560
    // Sort the list of dependencies to apply by child, so those can be applied in batch.
1561
29.6k
    std::ranges::sort(to_apply, [](auto& a, auto& b) { return a.second < b.second; });
1562
    // Iterate over groups of to-be-added dependencies with the same child.
1563
5.99k
    auto it = to_apply.begin();
1564
12.3k
    while (it != to_apply.end()) {
1565
6.37k
        auto& first_child = graph.m_entries[it->second].m_locator[level];
1566
6.37k
        const auto child_idx = first_child.index;
1567
        // Iterate over all to-be-added dependencies within that same child, gather the relevant
1568
        // parents.
1569
6.37k
        SetType parents;
1570
17.1k
        while (it != to_apply.end()) {
1571
11.1k
            auto& child = graph.m_entries[it->second].m_locator[level];
1572
11.1k
            auto& parent = graph.m_entries[it->first].m_locator[level];
1573
11.1k
            Assume(child.cluster == this && parent.cluster == this);
1574
11.1k
            if (child.index != child_idx) break;
1575
10.7k
            parents.Set(parent.index);
1576
10.7k
            ++it;
1577
10.7k
        }
1578
        // Push all dependencies to the underlying DepGraph. Note that this is O(N) in the size of
1579
        // the cluster, regardless of the number of parents being added, so batching them together
1580
        // has a performance benefit.
1581
6.37k
        m_depgraph.AddDependencies(parents, child_idx);
1582
6.37k
    }
1583
1584
    // Finally set the cluster to NEEDS_FIX, so its linearization is fixed the next time it is
1585
    // attempted to be made ACCEPTABLE.
1586
5.99k
    Assume(!NeedsSplitting());
1587
5.99k
    Assume(!IsOversized());
1588
5.99k
    graph.SetClusterQuality(level, m_quality, m_setindex, QualityLevel::NEEDS_FIX);
1589
1590
    // Finally push the changes to graph.m_entries.
1591
5.99k
    Updated(graph, /*level=*/level, /*rename=*/false);
1592
5.99k
}
1593
1594
void SingletonClusterImpl::ApplyDependencies(TxGraphImpl&, int, std::span<std::pair<GraphIndex, GraphIndex>>) noexcept
1595
0
{
1596
    // Nothing can actually be applied.
1597
0
    Assume(false);
1598
0
}
1599
1600
TxGraphImpl::~TxGraphImpl() noexcept
1601
1.39k
{
1602
    // If Refs outlive the TxGraphImpl they refer to, unlink them, so that their destructor does not
1603
    // try to reach into a non-existing TxGraphImpl anymore.
1604
84.8k
    for (auto& entry : m_entries) {
1605
84.8k
        if (entry.m_ref != nullptr) {
1606
64.0k
            GetRefGraph(*entry.m_ref) = nullptr;
1607
64.0k
        }
1608
84.8k
    }
1609
1.39k
}
1610
1611
std::unique_ptr<Cluster> TxGraphImpl::ExtractCluster(int level, QualityLevel quality, ClusterSetIndex setindex) noexcept
1612
110k
{
1613
110k
    Assume(quality != QualityLevel::NONE);
1614
1615
110k
    auto& clusterset = GetClusterSet(level);
1616
110k
    auto& quality_clusters = clusterset.m_clusters[int(quality)];
1617
110k
    Assume(setindex < quality_clusters.size());
1618
1619
    // Extract the Cluster-owning unique_ptr.
1620
110k
    std::unique_ptr<Cluster> ret = std::move(quality_clusters[setindex]);
1621
110k
    ret->m_quality = QualityLevel::NONE;
1622
110k
    ret->m_setindex = ClusterSetIndex(-1);
1623
1624
    // Clean up space in quality_cluster.
1625
110k
    auto max_setindex = quality_clusters.size() - 1;
1626
110k
    if (setindex != max_setindex) {
1627
        // If the cluster was not the last element of quality_clusters, move that to take its place.
1628
20.0k
        quality_clusters.back()->m_setindex = setindex;
1629
20.0k
        quality_clusters[setindex] = std::move(quality_clusters.back());
1630
20.0k
    }
1631
    // The last element of quality_clusters is now unused; drop it.
1632
110k
    quality_clusters.pop_back();
1633
1634
110k
    return ret;
1635
110k
}
1636
1637
ClusterSetIndex TxGraphImpl::InsertCluster(int level, std::unique_ptr<Cluster>&& cluster, QualityLevel quality) noexcept
1638
215k
{
1639
    // Cannot insert with quality level NONE (as that would mean not inserted).
1640
215k
    Assume(quality != QualityLevel::NONE);
1641
    // The passed-in Cluster must not currently be in the TxGraphImpl.
1642
215k
    Assume(cluster->m_quality == QualityLevel::NONE);
1643
1644
    // Append it at the end of the relevant TxGraphImpl::m_cluster.
1645
215k
    auto& clusterset = GetClusterSet(level);
1646
215k
    auto& quality_clusters = clusterset.m_clusters[int(quality)];
1647
215k
    ClusterSetIndex ret = quality_clusters.size();
1648
215k
    cluster->m_quality = quality;
1649
215k
    cluster->m_setindex = ret;
1650
215k
    quality_clusters.push_back(std::move(cluster));
1651
215k
    return ret;
1652
215k
}
1653
1654
void TxGraphImpl::SetClusterQuality(int level, QualityLevel old_quality, ClusterSetIndex old_index, QualityLevel new_quality) noexcept
1655
34.0k
{
1656
34.0k
    Assume(new_quality != QualityLevel::NONE);
1657
1658
    // Don't do anything if the quality did not change.
1659
34.0k
    if (old_quality == new_quality) return;
1660
    // Extract the cluster from where it currently resides.
1661
34.0k
    auto cluster_ptr = ExtractCluster(level, old_quality, old_index);
1662
    // And re-insert it where it belongs.
1663
34.0k
    InsertCluster(level, std::move(cluster_ptr), new_quality);
1664
34.0k
}
1665
1666
void TxGraphImpl::DeleteCluster(Cluster& cluster, int level) noexcept
1667
30.6k
{
1668
    // Extract the cluster from where it currently resides.
1669
30.6k
    auto cluster_ptr = ExtractCluster(level, cluster.m_quality, cluster.m_setindex);
1670
    // And throw it away.
1671
30.6k
    cluster_ptr.reset();
1672
30.6k
}
1673
1674
std::pair<Cluster*, int> TxGraphImpl::FindClusterAndLevel(GraphIndex idx, int level) const noexcept
1675
1.37M
{
1676
1.37M
    Assume(level >= 0 && level <= GetTopLevel());
1677
1.37M
    auto& entry = m_entries[idx];
1678
    // Search the entry's locators from top to bottom.
1679
1.41M
    for (int l = level; l >= 0; --l) {
1680
        // If the locator is missing, dig deeper; it may exist at a lower level and therefore be
1681
        // implicitly existing at this level too.
1682
1.41M
        if (entry.m_locator[l].IsMissing()) continue;
1683
        // If the locator has the entry marked as explicitly removed, stop.
1684
1.37M
        if (entry.m_locator[l].IsRemoved()) break;
1685
        // Otherwise, we have found the topmost ClusterSet that contains this entry.
1686
1.37M
        return {entry.m_locator[l].cluster, l};
1687
1.37M
    }
1688
    // If no non-empty locator was found, or an explicitly removed was hit, return nothing.
1689
1.33k
    return {nullptr, -1};
1690
1.37M
}
1691
1692
Cluster* TxGraphImpl::PullIn(Cluster* cluster, int level) noexcept
1693
2.49k
{
1694
2.49k
    int to_level = GetTopLevel();
1695
2.49k
    Assume(to_level == 1);
1696
2.49k
    Assume(level <= to_level);
1697
    // Copy the Cluster from main to staging, if it's not already there.
1698
2.49k
    if (level == 0) {
1699
        // Make the Cluster Acceptable before copying. This isn't strictly necessary, but doing it
1700
        // now avoids doing double work later.
1701
1.75k
        MakeAcceptable(*cluster, level);
1702
1.75k
        cluster = cluster->CopyToStaging(*this);
1703
1.75k
    }
1704
2.49k
    return cluster;
1705
2.49k
}
1706
1707
void TxGraphImpl::ApplyRemovals(int up_to_level) noexcept
1708
625k
{
1709
625k
    Assume(up_to_level >= 0 && up_to_level <= GetTopLevel());
1710
1.31M
    for (int level = 0; level <= up_to_level; ++level) {
1711
688k
        auto& clusterset = GetClusterSet(level);
1712
688k
        auto& to_remove = clusterset.m_to_remove;
1713
        // Skip if there is nothing to remove in this level.
1714
688k
        if (to_remove.empty()) continue;
1715
        // Pull in all Clusters that are not in staging.
1716
3.63k
        if (level == 1) {
1717
2.18k
            for (GraphIndex index : to_remove) {
1718
2.18k
                auto [cluster, cluster_level] = FindClusterAndLevel(index, level);
1719
2.18k
                if (cluster != nullptr) PullIn(cluster, cluster_level);
1720
2.18k
            }
1721
1.36k
        }
1722
        // Group the set of to-be-removed entries by Cluster::m_sequence.
1723
146k
        std::ranges::sort(to_remove, [&](GraphIndex a, GraphIndex b) noexcept {
1724
146k
            Cluster* cluster_a = m_entries[a].m_locator[level].cluster;
1725
146k
            Cluster* cluster_b = m_entries[b].m_locator[level].cluster;
1726
146k
            return CompareClusters(cluster_a, cluster_b) < 0;
1727
146k
        });
1728
        // Process per Cluster.
1729
3.63k
        std::span to_remove_span{to_remove};
1730
25.6k
        while (!to_remove_span.empty()) {
1731
21.9k
            Cluster* cluster = m_entries[to_remove_span.front()].m_locator[level].cluster;
1732
21.9k
            if (cluster != nullptr) {
1733
                // If the first to_remove_span entry's Cluster exists, hand to_remove_span to it, so it
1734
                // can pop off whatever applies to it.
1735
21.9k
                cluster->ApplyRemovals(*this, level, to_remove_span);
1736
21.9k
            } else {
1737
                // Otherwise, skip this already-removed entry. This may happen when
1738
                // RemoveTransaction was called twice on the same Ref, for example.
1739
0
                to_remove_span = to_remove_span.subspan(1);
1740
0
            }
1741
21.9k
        }
1742
3.63k
        to_remove.clear();
1743
3.63k
    }
1744
625k
    Compact();
1745
625k
}
1746
1747
void TxGraphImpl::SwapIndexes(GraphIndex a, GraphIndex b, std::vector<Cluster*>& affected_main) noexcept
1748
14.1k
{
1749
14.1k
    Assume(a < m_entries.size());
1750
14.1k
    Assume(b < m_entries.size());
1751
    // Swap the Entry objects.
1752
14.1k
    std::swap(m_entries[a], m_entries[b]);
1753
    // Iterate over both objects.
1754
42.4k
    for (int i = 0; i < 2; ++i) {
1755
28.3k
        GraphIndex idx = i ? b : a;
1756
28.3k
        Entry& entry = m_entries[idx];
1757
        // Update linked Ref, if any exists.
1758
28.3k
        if (entry.m_ref) GetRefIndex(*entry.m_ref) = idx;
1759
        // Update linked chunk index entries, if any exist.
1760
28.3k
        if (entry.m_main_chunkindex_iterator != m_main_chunkindex.end()) {
1761
13.0k
            entry.m_main_chunkindex_iterator->m_graph_index = idx;
1762
13.0k
        }
1763
        // Update the locators for both levels.
1764
84.9k
        for (int level = 0; level < MAX_LEVELS; ++level) {
1765
56.6k
            Locator& locator = entry.m_locator[level];
1766
56.6k
            if (locator.IsPresent()) {
1767
13.3k
                locator.cluster->UpdateMapping(locator.index, idx);
1768
13.3k
                if (level == 0) affected_main.push_back(locator.cluster);
1769
13.3k
            }
1770
56.6k
        }
1771
28.3k
    }
1772
14.1k
}
1773
1774
void TxGraphImpl::Compact() noexcept
1775
734k
{
1776
    // We cannot compact while any to-be-applied operations or staged removals remain as we'd need
1777
    // to rewrite them. It is easier to delay the compaction until they have been applied.
1778
734k
    if (!m_main_clusterset.m_deps_to_add.empty()) return;
1779
728k
    if (!m_main_clusterset.m_to_remove.empty()) return;
1780
728k
    Assume(m_main_clusterset.m_removed.empty()); // non-staging m_removed is always empty
1781
728k
    if (m_staging_clusterset.has_value()) {
1782
72.3k
        if (!m_staging_clusterset->m_deps_to_add.empty()) return;
1783
43.6k
        if (!m_staging_clusterset->m_to_remove.empty()) return;
1784
43.6k
        if (!m_staging_clusterset->m_removed.empty()) return;
1785
43.6k
    }
1786
1787
    // Release memory used by discarded ChunkData index entries.
1788
695k
    ClearShrink(m_main_chunkindex_discarded);
1789
1790
    // Sort the GraphIndexes that need to be cleaned up. They are sorted in reverse, so the last
1791
    // ones get processed first. This means earlier-processed GraphIndexes will not cause moving of
1792
    // later-processed ones during the "swap with end of m_entries" step below (which might
1793
    // invalidate them).
1794
695k
    std::ranges::sort(m_unlinked, std::greater{});
1795
1796
695k
    std::vector<Cluster*> affected_main;
1797
695k
    auto last = GraphIndex(-1);
1798
695k
    for (GraphIndex idx : m_unlinked) {
1799
        // m_unlinked should never contain the same GraphIndex twice (the code below would fail
1800
        // if so, because GraphIndexes get invalidated by removing them).
1801
47.8k
        Assume(idx != last);
1802
47.8k
        last = idx;
1803
1804
        // Make sure the entry is unlinked.
1805
47.8k
        Entry& entry = m_entries[idx];
1806
47.8k
        Assume(entry.m_ref == nullptr);
1807
        // Make sure the entry does not occur in the graph.
1808
143k
        for (int level = 0; level < MAX_LEVELS; ++level) {
1809
95.7k
            Assume(!entry.m_locator[level].IsPresent());
1810
95.7k
        }
1811
1812
        // Move the entry to the end.
1813
47.8k
        if (idx != m_entries.size() - 1) SwapIndexes(idx, m_entries.size() - 1, affected_main);
1814
        // Drop the entry for idx, now that it is at the end.
1815
47.8k
        m_entries.pop_back();
1816
47.8k
    }
1817
1818
    // Update the affected clusters, to fixup Entry::m_main_max_chunk_fallback values which may
1819
    // have become outdated due to the compaction above.
1820
695k
    std::ranges::sort(affected_main);
1821
695k
    affected_main.erase(std::unique(affected_main.begin(), affected_main.end()), affected_main.end());
1822
695k
    for (Cluster* cluster : affected_main) {
1823
7.72k
        cluster->Updated(*this, /*level=*/0, /*rename=*/true);
1824
7.72k
    }
1825
695k
    m_unlinked.clear();
1826
695k
}
1827
1828
void TxGraphImpl::Split(Cluster& cluster, int level) noexcept
1829
21.3k
{
1830
    // To split a Cluster, first make sure all removals are applied (as we might need to split
1831
    // again afterwards otherwise).
1832
21.3k
    ApplyRemovals(level);
1833
21.3k
    bool del = cluster.Split(*this, level);
1834
21.3k
    if (del) {
1835
        // Cluster::Split reports whether the Cluster is to be deleted.
1836
21.3k
        DeleteCluster(cluster, level);
1837
21.3k
    }
1838
21.3k
}
1839
1840
void TxGraphImpl::SplitAll(int up_to_level) noexcept
1841
550k
{
1842
550k
    Assume(up_to_level >= 0 && up_to_level <= GetTopLevel());
1843
    // Before splitting all Cluster, first make sure all removals are applied.
1844
550k
    ApplyRemovals(up_to_level);
1845
1.11M
    for (int level = 0; level <= up_to_level; ++level) {
1846
1.11M
        for (auto quality : {QualityLevel::NEEDS_SPLIT_FIX, QualityLevel::NEEDS_SPLIT}) {
1847
1.11M
            auto& queue = GetClusterSet(level).m_clusters[int(quality)];
1848
1.14M
            while (!queue.empty()) {
1849
21.3k
                Split(*queue.back().get(), level);
1850
21.3k
            }
1851
1.11M
        }
1852
559k
    }
1853
550k
}
1854
1855
void TxGraphImpl::GroupClusters(int level) noexcept
1856
87.8M
{
1857
87.8M
    auto& clusterset = GetClusterSet(level);
1858
    // If the groupings have been computed already, nothing is left to be done.
1859
87.8M
    if (clusterset.m_group_data.has_value()) return;
1860
1861
    // Before computing which Clusters need to be merged together, first apply all removals and
1862
    // split the Clusters into connected components. If we would group first, we might end up
1863
    // with inefficient and/or oversized Clusters which just end up being split again anyway.
1864
11.1k
    SplitAll(level);
1865
1866
    /** Annotated clusters: an entry for each Cluster, together with the sequence number for the
1867
     *  representative for the partition it is in (initially its own, later that of the
1868
     *  to-be-merged group). */
1869
11.1k
    std::vector<std::pair<Cluster*, uint64_t>> an_clusters;
1870
    /** Annotated dependencies: an entry for each m_deps_to_add entry (excluding ones that apply
1871
     *  to removed transactions), together with the sequence number of the representative root of
1872
     *  Clusters it applies to (initially that of the child Cluster, later that of the
1873
     *  to-be-merged group). */
1874
11.1k
    std::vector<std::pair<std::pair<GraphIndex, GraphIndex>, uint64_t>> an_deps;
1875
1876
    // Construct an an_clusters entry for every oversized cluster, including ones from levels below,
1877
    // as they may be inherited in this one.
1878
31.0k
    for (int level_iter = 0; level_iter <= level; ++level_iter) {
1879
19.8k
        for (auto& cluster : GetClusterSet(level_iter).m_clusters[int(QualityLevel::OVERSIZED_SINGLETON)]) {
1880
6
            auto graph_idx = cluster->GetClusterEntry(0);
1881
6
            auto cur_cluster = FindCluster(graph_idx, level);
1882
6
            if (cur_cluster == nullptr) continue;
1883
6
            an_clusters.emplace_back(cur_cluster, cur_cluster->m_sequence);
1884
6
        }
1885
19.8k
    }
1886
1887
    // Construct a an_clusters entry for every parent and child in the to-be-applied dependencies,
1888
    // and an an_deps entry for each dependency to be applied.
1889
11.1k
    an_deps.reserve(clusterset.m_deps_to_add.size());
1890
140k
    for (const auto& [par, chl] : clusterset.m_deps_to_add) {
1891
140k
        auto par_cluster = FindCluster(par, level);
1892
140k
        auto chl_cluster = FindCluster(chl, level);
1893
        // Skip dependencies for which the parent or child transaction is removed.
1894
140k
        if (par_cluster == nullptr || chl_cluster == nullptr) continue;
1895
140k
        an_clusters.emplace_back(par_cluster, par_cluster->m_sequence);
1896
        // Do not include a duplicate when parent and child are identical, as it'll be removed
1897
        // below anyway.
1898
140k
        if (chl_cluster != par_cluster) an_clusters.emplace_back(chl_cluster, chl_cluster->m_sequence);
1899
        // Add entry to an_deps, using the child sequence number.
1900
140k
        an_deps.emplace_back(std::pair{par, chl}, chl_cluster->m_sequence);
1901
140k
    }
1902
    // Sort and deduplicate an_clusters, so we end up with a sorted list of all involved Clusters
1903
    // to which dependencies apply, or which are oversized.
1904
5.19M
    std::ranges::sort(an_clusters, [](auto& a, auto& b) noexcept { return a.second < b.second; });
1905
11.1k
    an_clusters.erase(std::ranges::unique(an_clusters).begin(), an_clusters.end());
1906
    // Sort an_deps by applying the same order to the involved child cluster.
1907
2.35M
    std::ranges::sort(an_deps, [&](auto& a, auto& b) noexcept { return a.second < b.second; });
1908
1909
    // Run the union-find algorithm to find partitions of the input Clusters which need to be
1910
    // grouped together. See https://en.wikipedia.org/wiki/Disjoint-set_data_structure.
1911
11.1k
    {
1912
        /** Each PartitionData entry contains information about a single input Cluster. */
1913
11.1k
        struct PartitionData
1914
11.1k
        {
1915
            /** The sequence number of the cluster this holds information for. */
1916
11.1k
            uint64_t sequence;
1917
            /** All PartitionData entries belonging to the same partition are organized in a tree.
1918
             *  Each element points to its parent, or to itself if it is the root. The root is then
1919
             *  a representative for the entire tree, and can be found by walking upwards from any
1920
             *  element. */
1921
11.1k
            PartitionData* parent;
1922
            /** (only if this is a root, so when parent == this) An upper bound on the height of
1923
             *  tree for this partition. */
1924
11.1k
            unsigned rank;
1925
11.1k
        };
1926
        /** Information about each input Cluster. Sorted by Cluster::m_sequence. */
1927
11.1k
        std::vector<PartitionData> partition_data;
1928
1929
        /** Given a Cluster, find its corresponding PartitionData. */
1930
273k
        auto locate_fn = [&](uint64_t sequence) noexcept -> PartitionData* {
1931
273k
            auto it = std::lower_bound(partition_data.begin(), partition_data.end(), sequence,
1932
4.09M
                                       [](auto& a, uint64_t seq) noexcept { return a.sequence < seq; });
1933
273k
            Assume(it != partition_data.end());
1934
273k
            Assume(it->sequence == sequence);
1935
273k
            return &*it;
1936
273k
        };
1937
1938
        /** Given a PartitionData, find the root of the tree it is in (its representative). */
1939
423k
        static constexpr auto find_root_fn = [](PartitionData* data) noexcept -> PartitionData* {
1940
747k
            while (data->parent != data) {
1941
                // Replace pointers to parents with pointers to grandparents.
1942
                // See https://en.wikipedia.org/wiki/Disjoint-set_data_structure#Finding_set_representatives.
1943
323k
                auto par = data->parent;
1944
323k
                data->parent = par->parent;
1945
323k
                data = par;
1946
323k
            }
1947
423k
            return data;
1948
423k
        };
1949
1950
        /** Given two PartitionDatas, union the partitions they are in, and return their
1951
         *  representative. */
1952
139k
        static constexpr auto union_fn = [](PartitionData* arg1, PartitionData* arg2) noexcept {
1953
            // Find the roots of the trees, and bail out if they are already equal (which would
1954
            // mean they are in the same partition already).
1955
139k
            auto rep1 = find_root_fn(arg1);
1956
139k
            auto rep2 = find_root_fn(arg2);
1957
139k
            if (rep1 == rep2) return rep1;
1958
            // Pick the lower-rank root to become a child of the higher-rank one.
1959
            // See https://en.wikipedia.org/wiki/Disjoint-set_data_structure#Union_by_rank.
1960
136k
            if (rep1->rank < rep2->rank) std::swap(rep1, rep2);
1961
136k
            rep2->parent = rep1;
1962
136k
            rep1->rank += (rep1->rank == rep2->rank);
1963
136k
            return rep1;
1964
139k
        };
1965
1966
        // Start by initializing every Cluster as its own singleton partition.
1967
11.1k
        partition_data.resize(an_clusters.size());
1968
156k
        for (size_t i = 0; i < an_clusters.size(); ++i) {
1969
145k
            partition_data[i].sequence = an_clusters[i].first->m_sequence;
1970
145k
            partition_data[i].parent = &partition_data[i];
1971
145k
            partition_data[i].rank = 0;
1972
145k
        }
1973
1974
        // Run through all parent/child pairs in an_deps, and union the partitions their Clusters
1975
        // are in.
1976
11.1k
        Cluster* last_chl_cluster{nullptr};
1977
11.1k
        PartitionData* last_partition{nullptr};
1978
140k
        for (const auto& [dep, _] : an_deps) {
1979
140k
            auto [par, chl] = dep;
1980
140k
            auto par_cluster = FindCluster(par, level);
1981
140k
            auto chl_cluster = FindCluster(chl, level);
1982
140k
            Assume(chl_cluster != nullptr && par_cluster != nullptr);
1983
            // Nothing to do if parent and child are in the same Cluster.
1984
140k
            if (par_cluster == chl_cluster) continue;
1985
139k
            Assume(par != chl);
1986
139k
            if (chl_cluster == last_chl_cluster) {
1987
                // If the child Clusters is the same as the previous iteration, union with the
1988
                // tree they were in, avoiding the need for another lookup. Note that an_deps
1989
                // is sorted by child Cluster, so batches with the same child are expected.
1990
5.24k
                last_partition = union_fn(locate_fn(par_cluster->m_sequence), last_partition);
1991
133k
            } else {
1992
133k
                last_chl_cluster = chl_cluster;
1993
133k
                last_partition = union_fn(locate_fn(par_cluster->m_sequence), locate_fn(chl_cluster->m_sequence));
1994
133k
            }
1995
139k
        }
1996
1997
        // Update the sequence numbers in an_clusters and an_deps to be those of the partition
1998
        // representative.
1999
11.1k
        auto deps_it = an_deps.begin();
2000
156k
        for (size_t i = 0; i < partition_data.size(); ++i) {
2001
145k
            auto& data = partition_data[i];
2002
            // Find the sequence of the representative of the partition Cluster i is in, and store
2003
            // it with the Cluster.
2004
145k
            auto rep_seq = find_root_fn(&data)->sequence;
2005
145k
            an_clusters[i].second = rep_seq;
2006
            // Find all dependencies whose child Cluster is Cluster i, and annotate them with rep.
2007
285k
            while (deps_it != an_deps.end()) {
2008
277k
                auto [par, chl] = deps_it->first;
2009
277k
                auto chl_cluster = FindCluster(chl, level);
2010
277k
                Assume(chl_cluster != nullptr);
2011
277k
                if (chl_cluster->m_sequence > data.sequence) break;
2012
140k
                deps_it->second = rep_seq;
2013
140k
                ++deps_it;
2014
140k
            }
2015
145k
        }
2016
11.1k
    }
2017
2018
    // Sort both an_clusters and an_deps by sequence number of the representative of the
2019
    // partition they are in, grouping all those applying to the same partition together.
2020
1.81M
    std::ranges::sort(an_deps, [](auto& a, auto& b) noexcept { return a.second < b.second; });
2021
1.80M
    std::ranges::sort(an_clusters, [](auto& a, auto& b) noexcept { return a.second < b.second; });
2022
2023
    // Translate the resulting cluster groups to the m_group_data structure, and the dependencies
2024
    // back to m_deps_to_add.
2025
11.1k
    clusterset.m_group_data = GroupData{};
2026
11.1k
    clusterset.m_group_data->m_group_clusters.reserve(an_clusters.size());
2027
11.1k
    clusterset.m_deps_to_add.clear();
2028
11.1k
    clusterset.m_deps_to_add.reserve(an_deps.size());
2029
11.1k
    clusterset.m_oversized = false;
2030
11.1k
    auto an_deps_it = an_deps.begin();
2031
11.1k
    auto an_clusters_it = an_clusters.begin();
2032
19.8k
    while (an_clusters_it != an_clusters.end()) {
2033
        // Process all clusters/dependencies belonging to the partition with representative rep.
2034
8.77k
        auto rep = an_clusters_it->second;
2035
        // Create and initialize a new GroupData entry for the partition.
2036
8.77k
        auto& new_entry = clusterset.m_group_data->m_groups.emplace_back();
2037
8.77k
        new_entry.m_cluster_offset = clusterset.m_group_data->m_group_clusters.size();
2038
8.77k
        new_entry.m_cluster_count = 0;
2039
8.77k
        new_entry.m_deps_offset = clusterset.m_deps_to_add.size();
2040
8.77k
        new_entry.m_deps_count = 0;
2041
8.77k
        uint32_t total_count{0};
2042
8.77k
        uint64_t total_size{0};
2043
        // Add all its clusters to it (copying those from an_clusters to m_group_clusters).
2044
153k
        while (an_clusters_it != an_clusters.end() && an_clusters_it->second == rep) {
2045
145k
            clusterset.m_group_data->m_group_clusters.push_back(an_clusters_it->first);
2046
145k
            total_count += an_clusters_it->first->GetTxCount();
2047
145k
            total_size += an_clusters_it->first->GetTotalTxSize();
2048
145k
            ++an_clusters_it;
2049
145k
            ++new_entry.m_cluster_count;
2050
145k
        }
2051
        // Add all its dependencies to it (copying those back from an_deps to m_deps_to_add).
2052
149k
        while (an_deps_it != an_deps.end() && an_deps_it->second == rep) {
2053
140k
            clusterset.m_deps_to_add.push_back(an_deps_it->first);
2054
140k
            ++an_deps_it;
2055
140k
            ++new_entry.m_deps_count;
2056
140k
        }
2057
        // Detect oversizedness.
2058
8.77k
        if (total_count > m_max_cluster_count || total_size > m_max_cluster_size) {
2059
149
            clusterset.m_oversized = true;
2060
149
        }
2061
8.77k
    }
2062
11.1k
    Assume(an_deps_it == an_deps.end());
2063
11.1k
    Assume(an_clusters_it == an_clusters.end());
2064
11.1k
    Compact();
2065
11.1k
}
2066
2067
void TxGraphImpl::Merge(std::span<Cluster*> to_merge, int level) noexcept
2068
5.99k
{
2069
5.99k
    Assume(!to_merge.empty());
2070
    // Nothing to do if a group consists of just a single Cluster.
2071
5.99k
    if (to_merge.size() == 1) return;
2072
2073
    // Move the largest Cluster to the front of to_merge. As all transactions in other to-be-merged
2074
    // Clusters will be moved to that one, putting the largest one first minimizes the number of
2075
    // moves.
2076
5.97k
    size_t max_size_pos{0};
2077
5.97k
    DepGraphIndex max_size = to_merge[max_size_pos]->GetTxCount();
2078
5.97k
    GetClusterSet(level).m_cluster_usage -= to_merge[max_size_pos]->TotalMemoryUsage();
2079
5.97k
    DepGraphIndex total_size = max_size;
2080
12.5k
    for (size_t i = 1; i < to_merge.size(); ++i) {
2081
6.55k
        GetClusterSet(level).m_cluster_usage -= to_merge[i]->TotalMemoryUsage();
2082
6.55k
        DepGraphIndex size = to_merge[i]->GetTxCount();
2083
6.55k
        total_size += size;
2084
6.55k
        if (size > max_size) {
2085
59
            max_size_pos = i;
2086
59
            max_size = size;
2087
59
        }
2088
6.55k
    }
2089
5.97k
    if (max_size_pos != 0) std::swap(to_merge[0], to_merge[max_size_pos]);
2090
2091
5.97k
    size_t start_idx = 1;
2092
5.97k
    Cluster* into_cluster = to_merge[0];
2093
5.97k
    if (total_size > into_cluster->GetMaxTxCount()) {
2094
        // The into_merge cluster is too small to fit all transactions being merged. Construct a
2095
        // a new Cluster using an implementation that matches the total size, and merge everything
2096
        // in there.
2097
1.41k
        auto new_cluster = CreateEmptyCluster(total_size);
2098
1.41k
        into_cluster = new_cluster.get();
2099
1.41k
        InsertCluster(level, std::move(new_cluster), QualityLevel::OPTIMAL);
2100
1.41k
        start_idx = 0;
2101
1.41k
    }
2102
2103
    // Merge all further Clusters in the group into the result (first one, or new one), and delete
2104
    // them.
2105
13.9k
    for (size_t i = start_idx; i < to_merge.size(); ++i) {
2106
7.97k
        into_cluster->Merge(*this, level, *to_merge[i]);
2107
7.97k
        DeleteCluster(*to_merge[i], level);
2108
7.97k
    }
2109
5.97k
    into_cluster->Compact();
2110
5.97k
    GetClusterSet(level).m_cluster_usage += into_cluster->TotalMemoryUsage();
2111
5.97k
}
2112
2113
void TxGraphImpl::ApplyDependencies(int level) noexcept
2114
87.8M
{
2115
87.8M
    auto& clusterset = GetClusterSet(level);
2116
    // Do not bother computing groups if we already know the result will be oversized.
2117
87.8M
    if (clusterset.m_oversized == true) return;
2118
    // Compute the groups of to-be-merged Clusters (which also applies all removals, and splits).
2119
87.8M
    GroupClusters(level);
2120
87.8M
    Assume(clusterset.m_group_data.has_value());
2121
    // Nothing to do if there are no dependencies to be added.
2122
87.8M
    if (clusterset.m_deps_to_add.empty()) return;
2123
    // Dependencies cannot be applied if it would result in oversized clusters.
2124
5.78k
    if (clusterset.m_oversized == true) return;
2125
2126
    // For each group of to-be-merged Clusters.
2127
5.99k
    for (const auto& group_entry : clusterset.m_group_data->m_groups) {
2128
5.99k
        auto cluster_span = std::span{clusterset.m_group_data->m_group_clusters}
2129
5.99k
                                .subspan(group_entry.m_cluster_offset, group_entry.m_cluster_count);
2130
        // Pull in all the Clusters that contain dependencies.
2131
5.99k
        if (level == 1) {
2132
305
            for (Cluster*& cluster : cluster_span) {
2133
305
                cluster = PullIn(cluster, cluster->GetLevel(*this));
2134
305
            }
2135
79
        }
2136
        // Invoke Merge() to merge them into a single Cluster.
2137
5.99k
        Merge(cluster_span, level);
2138
        // Actually apply all to-be-added dependencies (all parents and children from this grouping
2139
        // belong to the same Cluster at this point because of the merging above).
2140
5.99k
        auto deps_span = std::span{clusterset.m_deps_to_add}
2141
5.99k
                             .subspan(group_entry.m_deps_offset, group_entry.m_deps_count);
2142
5.99k
        Assume(!deps_span.empty());
2143
5.99k
        const auto& loc = m_entries[deps_span[0].second].m_locator[level];
2144
5.99k
        Assume(loc.IsPresent());
2145
5.99k
        loc.cluster->ApplyDependencies(*this, level, deps_span);
2146
5.99k
    }
2147
2148
    // Wipe the list of to-be-added dependencies now that they are applied.
2149
5.78k
    clusterset.m_deps_to_add.clear();
2150
5.78k
    Compact();
2151
    // Also no further Cluster mergings are needed (note that we clear, but don't set to
2152
    // std::nullopt, as that would imply the groupings are unknown).
2153
5.78k
    clusterset.m_group_data = GroupData{};
2154
5.78k
}
2155
2156
std::pair<uint64_t, bool> GenericClusterImpl::Relinearize(TxGraphImpl& graph, int level, uint64_t max_cost) noexcept
2157
6.00k
{
2158
    // We can only relinearize Clusters that do not need splitting.
2159
6.00k
    Assume(!NeedsSplitting());
2160
    // No work is required for Clusters which are already optimally linearized.
2161
6.00k
    if (IsOptimal()) return {0, false};
2162
    // Invoke the actual linearization algorithm (passing in the existing one).
2163
6.00k
    uint64_t rng_seed = graph.m_rng.rand64();
2164
89.2k
    const auto fallback_order = [&](DepGraphIndex a, DepGraphIndex b) noexcept {
2165
89.2k
        const auto ref_a = graph.m_entries[m_mapping[a]].m_ref;
2166
89.2k
        const auto ref_b = graph.m_entries[m_mapping[b]].m_ref;
2167
89.2k
        return graph.m_fallback_order(*ref_a, *ref_b);
2168
89.2k
    };
2169
6.00k
    auto [linearization, optimal, cost] = Linearize(
2170
6.00k
        /*depgraph=*/m_depgraph,
2171
6.00k
        /*max_cost=*/max_cost,
2172
6.00k
        /*rng_seed=*/rng_seed,
2173
6.00k
        /*fallback_order=*/fallback_order,
2174
6.00k
        /*old_linearization=*/m_linearization,
2175
6.00k
        /*is_topological=*/IsTopological());
2176
    // Postlinearize to improve the linearization (if optimal, only the sub-chunk order).
2177
    // This also guarantees that all chunks are connected (even when non-optimal).
2178
6.00k
    PostLinearize(m_depgraph, linearization);
2179
    // Update the linearization.
2180
6.00k
    m_linearization = std::move(linearization);
2181
    // Update the Cluster's quality.
2182
6.00k
    bool improved = false;
2183
6.00k
    if (optimal) {
2184
6.00k
        graph.SetClusterQuality(level, m_quality, m_setindex, QualityLevel::OPTIMAL);
2185
6.00k
        improved = true;
2186
6.00k
    } else if (max_cost >= graph.m_acceptable_cost && !IsAcceptable()) {
2187
2
        graph.SetClusterQuality(level, m_quality, m_setindex, QualityLevel::ACCEPTABLE);
2188
2
        improved = true;
2189
2
    } else if (!IsTopological()) {
2190
1
        graph.SetClusterQuality(level, m_quality, m_setindex, QualityLevel::NEEDS_RELINEARIZE);
2191
1
        improved = true;
2192
1
    }
2193
    // Update the Entry objects.
2194
6.00k
    Updated(graph, /*level=*/level, /*rename=*/false);
2195
6.00k
    return {cost, improved};
2196
6.00k
}
2197
2198
std::pair<uint64_t, bool> SingletonClusterImpl::Relinearize(TxGraphImpl& graph, int level, uint64_t max_cost) noexcept
2199
0
{
2200
    // All singletons are optimal, oversized, or need splitting. Each of these precludes
2201
    // Relinearize from being called.
2202
0
    assert(false);
2203
0
    return {0, false};
2204
0
}
2205
2206
void TxGraphImpl::MakeAcceptable(Cluster& cluster, int level) noexcept
2207
172M
{
2208
    // Relinearize the Cluster if needed.
2209
172M
    if (!cluster.NeedsSplitting() && !cluster.IsAcceptable() && !cluster.IsOversized()) {
2210
92
        cluster.Relinearize(*this, level, m_acceptable_cost);
2211
92
    }
2212
172M
}
2213
2214
void TxGraphImpl::MakeAllAcceptable(int level) noexcept
2215
183k
{
2216
183k
    ApplyDependencies(level);
2217
183k
    auto& clusterset = GetClusterSet(level);
2218
183k
    if (clusterset.m_oversized == true) return;
2219
367k
    for (auto quality : {QualityLevel::NEEDS_FIX, QualityLevel::NEEDS_RELINEARIZE}) {
2220
367k
        auto& queue = clusterset.m_clusters[int(quality)];
2221
367k
        while (!queue.empty()) {
2222
83
            MakeAcceptable(*queue.back().get(), level);
2223
83
        }
2224
367k
    }
2225
183k
}
2226
2227
1.75k
GenericClusterImpl::GenericClusterImpl(uint64_t sequence) noexcept : Cluster{sequence} {}
2228
2229
void TxGraphImpl::AddTransaction(Ref& arg, const FeePerWeight& feerate) noexcept
2230
132k
{
2231
132k
    Assume(m_main_chunkindex_observers == 0 || GetTopLevel() != 0);
2232
132k
    Assume(feerate.size > 0);
2233
132k
    Assume(GetRefGraph(arg) == nullptr);
2234
    // Construct a new Entry, and link it with the Ref.
2235
132k
    auto idx = m_entries.size();
2236
132k
    m_entries.emplace_back();
2237
132k
    auto& entry = m_entries.back();
2238
132k
    entry.m_main_chunkindex_iterator = m_main_chunkindex.end();
2239
132k
    entry.m_ref = &arg;
2240
132k
    GetRefGraph(arg) = this;
2241
132k
    GetRefIndex(arg) = idx;
2242
    // Construct a new singleton Cluster (which is necessarily optimally linearized).
2243
132k
    bool oversized = uint64_t(feerate.size) > m_max_cluster_size;
2244
132k
    auto cluster = CreateEmptyCluster(1);
2245
132k
    cluster->AppendTransaction(idx, feerate);
2246
132k
    auto cluster_ptr = cluster.get();
2247
132k
    int level = GetTopLevel();
2248
132k
    auto& clusterset = GetClusterSet(level);
2249
132k
    InsertCluster(level, std::move(cluster), oversized ? QualityLevel::OVERSIZED_SINGLETON : QualityLevel::OPTIMAL);
2250
132k
    cluster_ptr->Updated(*this, /*level=*/level, /*rename=*/false);
2251
132k
    clusterset.m_cluster_usage += cluster_ptr->TotalMemoryUsage();
2252
132k
    ++clusterset.m_txcount;
2253
    // Deal with individually oversized transactions.
2254
132k
    if (oversized) {
2255
9
        ++clusterset.m_txcount_oversized;
2256
9
        clusterset.m_oversized = true;
2257
9
        clusterset.m_group_data = std::nullopt;
2258
9
    }
2259
132k
}
2260
2261
void TxGraphImpl::RemoveTransaction(const Ref& arg) noexcept
2262
2.20k
{
2263
    // Don't do anything if the Ref is empty (which may be indicative of the transaction already
2264
    // having been removed).
2265
2.20k
    if (GetRefGraph(arg) == nullptr) return;
2266
2.20k
    Assume(GetRefGraph(arg) == this);
2267
2.20k
    Assume(m_main_chunkindex_observers == 0 || GetTopLevel() != 0);
2268
    // Find the Cluster the transaction is in, and stop if it isn't in any.
2269
2.20k
    int level = GetTopLevel();
2270
2.20k
    auto cluster = FindCluster(GetRefIndex(arg), level);
2271
2.20k
    if (cluster == nullptr) return;
2272
    // Remember that the transaction is to be removed.
2273
2.20k
    auto& clusterset = GetClusterSet(level);
2274
2.20k
    clusterset.m_to_remove.push_back(GetRefIndex(arg));
2275
    // Wipe m_group_data (as it will need to be recomputed).
2276
2.20k
    clusterset.m_group_data.reset();
2277
2.20k
    if (clusterset.m_oversized == true) clusterset.m_oversized = std::nullopt;
2278
2.20k
}
2279
2280
void TxGraphImpl::AddDependency(const Ref& parent, const Ref& child) noexcept
2281
77.7k
{
2282
    // Don't do anything if either Ref is empty (which may be indicative of it having already been
2283
    // removed).
2284
77.7k
    if (GetRefGraph(parent) == nullptr || GetRefGraph(child) == nullptr) return;
2285
77.7k
    Assume(GetRefGraph(parent) == this && GetRefGraph(child) == this);
2286
77.7k
    Assume(m_main_chunkindex_observers == 0 || GetTopLevel() != 0);
2287
    // Don't do anything if this is a dependency on self.
2288
77.7k
    if (GetRefIndex(parent) == GetRefIndex(child)) return;
2289
    // Find the Cluster the parent and child transaction are in, and stop if either appears to be
2290
    // already removed.
2291
77.7k
    int level = GetTopLevel();
2292
77.7k
    auto par_cluster = FindCluster(GetRefIndex(parent), level);
2293
77.7k
    if (par_cluster == nullptr) return;
2294
77.7k
    auto chl_cluster = FindCluster(GetRefIndex(child), level);
2295
77.7k
    if (chl_cluster == nullptr) return;
2296
    // Remember that this dependency is to be applied.
2297
77.7k
    auto& clusterset = GetClusterSet(level);
2298
77.7k
    clusterset.m_deps_to_add.emplace_back(GetRefIndex(parent), GetRefIndex(child));
2299
    // Wipe m_group_data (as it will need to be recomputed).
2300
77.7k
    clusterset.m_group_data.reset();
2301
77.7k
    if (clusterset.m_oversized == false) clusterset.m_oversized = std::nullopt;
2302
77.7k
}
2303
2304
bool TxGraphImpl::Exists(const Ref& arg, Level level_select) noexcept
2305
302
{
2306
302
    if (GetRefGraph(arg) == nullptr) return false;
2307
302
    Assume(GetRefGraph(arg) == this);
2308
302
    size_t level = GetSpecifiedLevel(level_select);
2309
    // Make sure the transaction isn't scheduled for removal.
2310
302
    ApplyRemovals(level);
2311
302
    auto cluster = FindCluster(GetRefIndex(arg), level);
2312
302
    return cluster != nullptr;
2313
302
}
2314
2315
void GenericClusterImpl::GetAncestorRefs(const TxGraphImpl& graph, std::span<std::pair<Cluster*, DepGraphIndex>>& args, std::vector<TxGraph::Ref*>& output) noexcept
2316
45.9k
{
2317
    /** The union of all ancestors to be returned. */
2318
45.9k
    SetType ancestors_union;
2319
    // Process elements from the front of args, as long as they apply.
2320
91.9k
    while (!args.empty()) {
2321
45.9k
        if (args.front().first != this) break;
2322
45.9k
        ancestors_union |= m_depgraph.Ancestors(args.front().second);
2323
45.9k
        args = args.subspan(1);
2324
45.9k
    }
2325
45.9k
    Assume(ancestors_union.Any());
2326
    // Translate all ancestors (in arbitrary order) to Refs (if they have any), and return them.
2327
265k
    for (auto idx : ancestors_union) {
2328
265k
        const auto& entry = graph.m_entries[m_mapping[idx]];
2329
265k
        Assume(entry.m_ref != nullptr);
2330
265k
        output.push_back(entry.m_ref);
2331
265k
    }
2332
45.9k
}
2333
2334
void SingletonClusterImpl::GetAncestorRefs(const TxGraphImpl& graph, std::span<std::pair<Cluster*, DepGraphIndex>>& args, std::vector<TxGraph::Ref*>& output) noexcept
2335
122k
{
2336
122k
    Assume(GetTxCount());
2337
244k
    while (!args.empty()) {
2338
122k
        if (args.front().first != this) break;
2339
122k
        args = args.subspan(1);
2340
122k
    }
2341
122k
    const auto& entry = graph.m_entries[m_graph_index];
2342
122k
    Assume(entry.m_ref != nullptr);
2343
122k
    output.push_back(entry.m_ref);
2344
122k
}
2345
2346
void GenericClusterImpl::GetDescendantRefs(const TxGraphImpl& graph, std::span<std::pair<Cluster*, DepGraphIndex>>& args, std::vector<TxGraph::Ref*>& output) noexcept
2347
46.7k
{
2348
    /** The union of all descendants to be returned. */
2349
46.7k
    SetType descendants_union;
2350
    // Process elements from the front of args, as long as they apply.
2351
93.5k
    while (!args.empty()) {
2352
46.7k
        if (args.front().first != this) break;
2353
46.7k
        descendants_union |= m_depgraph.Descendants(args.front().second);
2354
46.7k
        args = args.subspan(1);
2355
46.7k
    }
2356
46.7k
    Assume(descendants_union.Any());
2357
    // Translate all descendants (in arbitrary order) to Refs (if they have any), and return them.
2358
404k
    for (auto idx : descendants_union) {
2359
404k
        const auto& entry = graph.m_entries[m_mapping[idx]];
2360
404k
        Assume(entry.m_ref != nullptr);
2361
404k
        output.push_back(entry.m_ref);
2362
404k
    }
2363
46.7k
}
2364
2365
void SingletonClusterImpl::GetDescendantRefs(const TxGraphImpl& graph, std::span<std::pair<Cluster*, DepGraphIndex>>& args, std::vector<TxGraph::Ref*>& output) noexcept
2366
43.1k
{
2367
    // In a singleton cluster, the ancestors or descendants are always just the entire cluster.
2368
43.1k
    GetAncestorRefs(graph, args, output);
2369
43.1k
}
2370
2371
bool GenericClusterImpl::GetClusterRefs(TxGraphImpl& graph, std::span<TxGraph::Ref*> range, LinearizationIndex start_pos) noexcept
2372
224k
{
2373
    // Translate the transactions in the Cluster (in linearization order, starting at start_pos in
2374
    // the linearization) to Refs, and fill them in range.
2375
440k
    for (auto& ref : range) {
2376
440k
        Assume(start_pos < m_linearization.size());
2377
440k
        const auto& entry = graph.m_entries[m_mapping[m_linearization[start_pos++]]];
2378
440k
        Assume(entry.m_ref != nullptr);
2379
440k
        ref = entry.m_ref;
2380
440k
    }
2381
    // Return whether start_pos has advanced to the end of the Cluster.
2382
224k
    return start_pos == m_linearization.size();
2383
224k
}
2384
2385
bool SingletonClusterImpl::GetClusterRefs(TxGraphImpl& graph, std::span<TxGraph::Ref*> range, LinearizationIndex start_pos) noexcept
2386
76.3k
{
2387
76.3k
    Assume(!range.empty());
2388
76.3k
    Assume(GetTxCount());
2389
76.3k
    Assume(start_pos == 0);
2390
76.3k
    const auto& entry = graph.m_entries[m_graph_index];
2391
76.3k
    Assume(entry.m_ref != nullptr);
2392
76.3k
    range[0] = entry.m_ref;
2393
76.3k
    return true;
2394
76.3k
}
2395
2396
FeePerWeight GenericClusterImpl::GetIndividualFeerate(DepGraphIndex idx) noexcept
2397
9
{
2398
9
    return FeePerWeight::FromFeeFrac(m_depgraph.FeeRate(idx));
2399
9
}
2400
2401
FeePerWeight SingletonClusterImpl::GetIndividualFeerate(DepGraphIndex idx) noexcept
2402
2
{
2403
2
    Assume(GetTxCount());
2404
2
    Assume(idx == 0);
2405
2
    return m_feerate;
2406
2
}
2407
2408
void GenericClusterImpl::MakeStagingTransactionsMissing(TxGraphImpl& graph) noexcept
2409
24
{
2410
    // Mark all transactions of a Cluster missing, needed when aborting staging, so that the
2411
    // corresponding Locators don't retain references into aborted Clusters.
2412
133
    for (auto ci : m_linearization) {
2413
133
        GraphIndex idx = m_mapping[ci];
2414
133
        auto& entry = graph.m_entries[idx];
2415
133
        entry.m_locator[1].SetMissing();
2416
133
    }
2417
24
}
2418
2419
void SingletonClusterImpl::MakeStagingTransactionsMissing(TxGraphImpl& graph) noexcept
2420
22.9k
{
2421
22.9k
    if (GetTxCount()) {
2422
22.9k
        auto& entry = graph.m_entries[m_graph_index];
2423
22.9k
        entry.m_locator[1].SetMissing();
2424
22.9k
    }
2425
22.9k
}
2426
2427
std::vector<TxGraph::Ref*> TxGraphImpl::GetAncestors(const Ref& arg, Level level_select) noexcept
2428
126k
{
2429
    // Return the empty vector if the Ref is empty.
2430
126k
    if (GetRefGraph(arg) == nullptr) return {};
2431
126k
    Assume(GetRefGraph(arg) == this);
2432
    // Apply all removals and dependencies, as the result might be incorrect otherwise.
2433
126k
    size_t level = GetSpecifiedLevel(level_select);
2434
126k
    ApplyDependencies(level);
2435
    // Ancestry cannot be known if unapplied dependencies remain.
2436
126k
    Assume(GetClusterSet(level).m_deps_to_add.empty());
2437
    // Find the Cluster the argument is in, and return the empty vector if it isn't in any.
2438
126k
    auto [cluster, cluster_level] = FindClusterAndLevel(GetRefIndex(arg), level);
2439
126k
    if (cluster == nullptr) return {};
2440
    // Dispatch to the Cluster.
2441
124k
    std::pair<Cluster*, DepGraphIndex> match = {cluster, m_entries[GetRefIndex(arg)].m_locator[cluster_level].index};
2442
124k
    auto matches = std::span(&match, 1);
2443
124k
    std::vector<TxGraph::Ref*> ret;
2444
124k
    cluster->GetAncestorRefs(*this, matches, ret);
2445
124k
    return ret;
2446
126k
}
2447
2448
std::vector<TxGraph::Ref*> TxGraphImpl::GetDescendants(const Ref& arg, Level level_select) noexcept
2449
89.8k
{
2450
    // Return the empty vector if the Ref is empty.
2451
89.8k
    if (GetRefGraph(arg) == nullptr) return {};
2452
89.8k
    Assume(GetRefGraph(arg) == this);
2453
    // Apply all removals and dependencies, as the result might be incorrect otherwise.
2454
89.8k
    size_t level = GetSpecifiedLevel(level_select);
2455
89.8k
    ApplyDependencies(level);
2456
    // Ancestry cannot be known if unapplied dependencies remain.
2457
89.8k
    Assume(GetClusterSet(level).m_deps_to_add.empty());
2458
    // Find the Cluster the argument is in, and return the empty vector if it isn't in any.
2459
89.8k
    auto [cluster, cluster_level] = FindClusterAndLevel(GetRefIndex(arg), level);
2460
89.8k
    if (cluster == nullptr) return {};
2461
    // Dispatch to the Cluster.
2462
89.8k
    std::pair<Cluster*, DepGraphIndex> match = {cluster, m_entries[GetRefIndex(arg)].m_locator[cluster_level].index};
2463
89.8k
    auto matches = std::span(&match, 1);
2464
89.8k
    std::vector<TxGraph::Ref*> ret;
2465
89.8k
    cluster->GetDescendantRefs(*this, matches, ret);
2466
89.8k
    return ret;
2467
89.8k
}
2468
2469
std::vector<TxGraph::Ref*> TxGraphImpl::GetAncestorsUnion(std::span<const Ref* const> args, Level level_select) noexcept
2470
0
{
2471
    // Apply all dependencies, as the result might be incorrect otherwise.
2472
0
    size_t level = GetSpecifiedLevel(level_select);
2473
0
    ApplyDependencies(level);
2474
    // Ancestry cannot be known if unapplied dependencies remain.
2475
0
    Assume(GetClusterSet(level).m_deps_to_add.empty());
2476
2477
    // Translate args to matches.
2478
0
    std::vector<std::pair<Cluster*, DepGraphIndex>> matches;
2479
0
    matches.reserve(args.size());
2480
0
    for (auto arg : args) {
2481
0
        Assume(arg);
2482
        // Skip empty Refs.
2483
0
        if (GetRefGraph(*arg) == nullptr) continue;
2484
0
        Assume(GetRefGraph(*arg) == this);
2485
        // Find the Cluster the argument is in, and skip if none is found.
2486
0
        auto [cluster, cluster_level] = FindClusterAndLevel(GetRefIndex(*arg), level);
2487
0
        if (cluster == nullptr) continue;
2488
        // Append to matches.
2489
0
        matches.emplace_back(cluster, m_entries[GetRefIndex(*arg)].m_locator[cluster_level].index);
2490
0
    }
2491
    // Group by Cluster.
2492
0
    std::ranges::sort(matches, [](auto& a, auto& b) noexcept { return CompareClusters(a.first, b.first) < 0; });
2493
    // Dispatch to the Clusters.
2494
0
    std::span match_span(matches);
2495
0
    std::vector<TxGraph::Ref*> ret;
2496
0
    while (!match_span.empty()) {
2497
0
        match_span.front().first->GetAncestorRefs(*this, match_span, ret);
2498
0
    }
2499
0
    return ret;
2500
0
}
2501
2502
std::vector<TxGraph::Ref*> TxGraphImpl::GetDescendantsUnion(std::span<const Ref* const> args, Level level_select) noexcept
2503
16.3k
{
2504
    // Apply all dependencies, as the result might be incorrect otherwise.
2505
16.3k
    size_t level = GetSpecifiedLevel(level_select);
2506
16.3k
    ApplyDependencies(level);
2507
    // Ancestry cannot be known if unapplied dependencies remain.
2508
16.3k
    Assume(GetClusterSet(level).m_deps_to_add.empty());
2509
2510
    // Translate args to matches.
2511
16.3k
    std::vector<std::pair<Cluster*, DepGraphIndex>> matches;
2512
16.3k
    matches.reserve(args.size());
2513
16.3k
    for (auto arg : args) {
2514
84
        Assume(arg);
2515
        // Skip empty Refs.
2516
84
        if (GetRefGraph(*arg) == nullptr) continue;
2517
84
        Assume(GetRefGraph(*arg) == this);
2518
        // Find the Cluster the argument is in, and skip if none is found.
2519
84
        auto [cluster, cluster_level] = FindClusterAndLevel(GetRefIndex(*arg), level);
2520
84
        if (cluster == nullptr) continue;
2521
        // Append to matches.
2522
84
        matches.emplace_back(cluster, m_entries[GetRefIndex(*arg)].m_locator[cluster_level].index);
2523
84
    }
2524
    // Group by Cluster.
2525
16.3k
    std::ranges::sort(matches, [](auto& a, auto& b) noexcept { return CompareClusters(a.first, b.first) < 0; });
2526
    // Dispatch to the Clusters.
2527
16.3k
    std::span match_span(matches);
2528
16.3k
    std::vector<TxGraph::Ref*> ret;
2529
16.4k
    while (!match_span.empty()) {
2530
84
        match_span.front().first->GetDescendantRefs(*this, match_span, ret);
2531
84
    }
2532
16.3k
    return ret;
2533
16.3k
}
2534
2535
std::vector<TxGraph::Ref*> TxGraphImpl::GetCluster(const Ref& arg, Level level_select) noexcept
2536
96.5k
{
2537
    // Return the empty vector if the Ref is empty (which may be indicative of the transaction
2538
    // having been removed already.
2539
96.5k
    if (GetRefGraph(arg) == nullptr) return {};
2540
96.5k
    Assume(GetRefGraph(arg) == this);
2541
    // Apply all removals and dependencies, as the result might be incorrect otherwise.
2542
96.5k
    size_t level = GetSpecifiedLevel(level_select);
2543
96.5k
    ApplyDependencies(level);
2544
    // Cluster linearization cannot be known if unapplied dependencies remain.
2545
96.5k
    Assume(GetClusterSet(level).m_deps_to_add.empty());
2546
    // Find the Cluster the argument is in, and return the empty vector if it isn't in any.
2547
96.5k
    auto [cluster, cluster_level] = FindClusterAndLevel(GetRefIndex(arg), level);
2548
96.5k
    if (cluster == nullptr) return {};
2549
    // Make sure the Cluster has an acceptable quality level, and then dispatch to it.
2550
96.5k
    MakeAcceptable(*cluster, cluster_level);
2551
96.5k
    std::vector<TxGraph::Ref*> ret(cluster->GetTxCount());
2552
96.5k
    cluster->GetClusterRefs(*this, ret, 0);
2553
96.5k
    return ret;
2554
96.5k
}
2555
2556
TxGraph::GraphIndex TxGraphImpl::GetTransactionCount(Level level_select) noexcept
2557
23
{
2558
23
    size_t level = GetSpecifiedLevel(level_select);
2559
23
    ApplyRemovals(level);
2560
23
    return GetClusterSet(level).m_txcount;
2561
23
}
2562
2563
FeePerWeight TxGraphImpl::GetIndividualFeerate(const Ref& arg) noexcept
2564
11
{
2565
    // Return the empty FeePerWeight if the passed Ref is empty.
2566
11
    if (GetRefGraph(arg) == nullptr) return {};
2567
11
    Assume(GetRefGraph(arg) == this);
2568
    // Find the cluster the argument is in (the level does not matter as individual feerates will
2569
    // be identical if it occurs in both), and return the empty FeePerWeight if it isn't in any.
2570
11
    Cluster* cluster{nullptr};
2571
11
    int level;
2572
11
    for (level = 0; level <= GetTopLevel(); ++level) {
2573
        // Apply removals, so that we can correctly report FeePerWeight{} for non-existing
2574
        // transactions.
2575
11
        ApplyRemovals(level);
2576
11
        if (m_entries[GetRefIndex(arg)].m_locator[level].IsPresent()) {
2577
11
            cluster = m_entries[GetRefIndex(arg)].m_locator[level].cluster;
2578
11
            break;
2579
11
        }
2580
11
    }
2581
11
    if (cluster == nullptr) return {};
2582
    // Dispatch to the Cluster.
2583
11
    return cluster->GetIndividualFeerate(m_entries[GetRefIndex(arg)].m_locator[level].index);
2584
11
}
2585
2586
FeePerWeight TxGraphImpl::GetMainChunkFeerate(const Ref& arg) noexcept
2587
60.2k
{
2588
    // Return the empty FeePerWeight if the passed Ref is empty.
2589
60.2k
    if (GetRefGraph(arg) == nullptr) return {};
2590
60.2k
    Assume(GetRefGraph(arg) == this);
2591
    // Apply all removals and dependencies, as the result might be inaccurate otherwise.
2592
60.2k
    ApplyDependencies(/*level=*/0);
2593
    // Chunk feerates cannot be accurately known if unapplied dependencies remain.
2594
60.2k
    Assume(m_main_clusterset.m_deps_to_add.empty());
2595
    // Find the cluster the argument is in, and return the empty FeePerWeight if it isn't in any.
2596
60.2k
    auto [cluster, cluster_level] = FindClusterAndLevel(GetRefIndex(arg), /*level=*/0);
2597
60.2k
    if (cluster == nullptr) return {};
2598
    // Make sure the Cluster has an acceptable quality level, and then return the transaction's
2599
    // chunk feerate.
2600
60.2k
    MakeAcceptable(*cluster, cluster_level);
2601
60.2k
    const auto& entry = m_entries[GetRefIndex(arg)];
2602
60.2k
    return entry.m_main_chunk_feerate;
2603
60.2k
}
2604
2605
bool TxGraphImpl::IsOversized(Level level_select) noexcept
2606
217k
{
2607
217k
    size_t level = GetSpecifiedLevel(level_select);
2608
217k
    auto& clusterset = GetClusterSet(level);
2609
217k
    if (clusterset.m_oversized.has_value()) {
2610
        // Return cached value if known.
2611
209k
        return *clusterset.m_oversized;
2612
209k
    }
2613
7.53k
    ApplyRemovals(level);
2614
7.53k
    if (clusterset.m_txcount_oversized > 0) {
2615
0
        clusterset.m_oversized = true;
2616
7.53k
    } else {
2617
        // Find which Clusters will need to be merged together, as that is where the oversize
2618
        // property is assessed.
2619
7.53k
        GroupClusters(level);
2620
7.53k
    }
2621
7.53k
    Assume(clusterset.m_oversized.has_value());
2622
7.53k
    return *clusterset.m_oversized;
2623
217k
}
2624
2625
void TxGraphImpl::StartStaging() noexcept
2626
67.7k
{
2627
    // Staging cannot already exist.
2628
67.7k
    Assume(!m_staging_clusterset.has_value());
2629
    // Apply all remaining dependencies in main before creating a staging graph. Once staging
2630
    // exists, we cannot merge Clusters anymore (because of interference with Clusters being
2631
    // pulled into staging), so to make sure all inspectors are available (if not oversized), do
2632
    // all merging work now. Call SplitAll() first, so that even if ApplyDependencies does not do
2633
    // any thing due to knowing the result is oversized, splitting is still performed.
2634
67.7k
    SplitAll(0);
2635
67.7k
    ApplyDependencies(0);
2636
    // Construct the staging ClusterSet.
2637
67.7k
    m_staging_clusterset.emplace();
2638
    // Copy statistics, precomputed data, and to-be-applied dependencies (only if oversized) to
2639
    // the new graph. To-be-applied removals will always be empty at this point.
2640
67.7k
    m_staging_clusterset->m_txcount = m_main_clusterset.m_txcount;
2641
67.7k
    m_staging_clusterset->m_txcount_oversized = m_main_clusterset.m_txcount_oversized;
2642
67.7k
    m_staging_clusterset->m_deps_to_add = m_main_clusterset.m_deps_to_add;
2643
67.7k
    m_staging_clusterset->m_group_data = m_main_clusterset.m_group_data;
2644
67.7k
    m_staging_clusterset->m_oversized = m_main_clusterset.m_oversized;
2645
67.7k
    Assume(m_staging_clusterset->m_oversized.has_value());
2646
67.7k
    m_staging_clusterset->m_cluster_usage = 0;
2647
67.7k
}
2648
2649
void TxGraphImpl::AbortStaging() noexcept
2650
22.4k
{
2651
    // Staging must exist.
2652
22.4k
    Assume(m_staging_clusterset.has_value());
2653
    // Mark all removed transactions as Missing (so the staging locator for these transactions
2654
    // can be reused if another staging is created).
2655
22.4k
    for (auto idx : m_staging_clusterset->m_removed) {
2656
589
        m_entries[idx].m_locator[1].SetMissing();
2657
589
    }
2658
    // Do the same with the non-removed transactions in staging Clusters.
2659
179k
    for (int quality = 0; quality < int(QualityLevel::NONE); ++quality) {
2660
156k
        for (auto& cluster : m_staging_clusterset->m_clusters[quality]) {
2661
22.9k
            cluster->MakeStagingTransactionsMissing(*this);
2662
22.9k
        }
2663
156k
    }
2664
    // Destroy the staging ClusterSet.
2665
22.4k
    m_staging_clusterset.reset();
2666
22.4k
    Compact();
2667
22.4k
    if (!m_main_clusterset.m_group_data.has_value()) {
2668
        // In case m_oversized in main was kept after a Ref destruction while staging exists, we
2669
        // need to re-evaluate m_oversized now.
2670
0
        if (m_main_clusterset.m_to_remove.empty() && m_main_clusterset.m_txcount_oversized > 0) {
2671
            // It is possible that a Ref destruction caused a removal in main while staging existed.
2672
            // In this case, m_txcount_oversized may be inaccurate.
2673
0
            m_main_clusterset.m_oversized = true;
2674
0
        } else {
2675
0
            m_main_clusterset.m_oversized = std::nullopt;
2676
0
        }
2677
0
    }
2678
22.4k
}
2679
2680
void TxGraphImpl::CommitStaging() noexcept
2681
45.3k
{
2682
    // Staging must exist.
2683
45.3k
    Assume(m_staging_clusterset.has_value());
2684
45.3k
    Assume(m_main_chunkindex_observers == 0);
2685
    // Get rid of removed transactions in staging before moving to main, so they do not need to be
2686
    // added to the chunk index there. Doing so is impossible if they were unlinked, and thus have
2687
    // no Ref anymore to pass to the fallback comparator.
2688
45.3k
    ApplyRemovals(/*up_to_level=*/1);
2689
    // Delete all conflicting Clusters in main, to make place for moving the staging ones
2690
    // there. All of these have been copied to staging in PullIn().
2691
45.3k
    auto conflicts = GetConflicts();
2692
45.3k
    for (Cluster* conflict : conflicts) {
2693
1.27k
        conflict->Clear(*this, /*level=*/0);
2694
1.27k
        DeleteCluster(*conflict, /*level=*/0);
2695
1.27k
    }
2696
    // Mark the removed transactions as Missing (so the staging locator for these transactions
2697
    // can be reused if another staging is created).
2698
45.3k
    for (auto idx : m_staging_clusterset->m_removed) {
2699
1.59k
        m_entries[idx].m_locator[1].SetMissing();
2700
1.59k
    }
2701
    // Then move all Clusters in staging to main.
2702
362k
    for (int quality = 0; quality < int(QualityLevel::NONE); ++quality) {
2703
317k
        auto& stage_sets = m_staging_clusterset->m_clusters[quality];
2704
363k
        while (!stage_sets.empty()) {
2705
45.4k
            stage_sets.back()->MoveToMain(*this);
2706
45.4k
        }
2707
317k
    }
2708
    // Move all statistics, precomputed data, and to-be-applied removals and dependencies.
2709
45.3k
    m_main_clusterset.m_deps_to_add = std::move(m_staging_clusterset->m_deps_to_add);
2710
45.3k
    m_main_clusterset.m_to_remove = std::move(m_staging_clusterset->m_to_remove);
2711
45.3k
    m_main_clusterset.m_group_data = std::move(m_staging_clusterset->m_group_data);
2712
45.3k
    m_main_clusterset.m_oversized = m_staging_clusterset->m_oversized;
2713
45.3k
    m_main_clusterset.m_txcount = m_staging_clusterset->m_txcount;
2714
45.3k
    m_main_clusterset.m_txcount_oversized = m_staging_clusterset->m_txcount_oversized;
2715
    // Delete the old staging graph, after all its information was moved to main.
2716
45.3k
    m_staging_clusterset.reset();
2717
45.3k
    Compact();
2718
45.3k
}
2719
2720
void GenericClusterImpl::SetFee(TxGraphImpl& graph, int level, DepGraphIndex idx, int64_t fee) noexcept
2721
16
{
2722
    // Make sure the specified DepGraphIndex exists in this Cluster.
2723
16
    Assume(m_depgraph.Positions()[idx]);
2724
    // Bail out if the fee isn't actually being changed.
2725
16
    if (m_depgraph.FeeRate(idx).fee == fee) return;
2726
    // Update the fee, remember that relinearization will be necessary, and update the Entries
2727
    // in the same Cluster.
2728
16
    m_depgraph.FeeRate(idx).fee = fee;
2729
16
    if (m_quality == QualityLevel::OVERSIZED_SINGLETON) {
2730
        // Nothing to do.
2731
16
    } else if (IsAcceptable()) {
2732
12
        graph.SetClusterQuality(level, m_quality, m_setindex, QualityLevel::NEEDS_RELINEARIZE);
2733
12
    }
2734
16
    Updated(graph, /*level=*/level, /*rename=*/false);
2735
16
}
2736
2737
void SingletonClusterImpl::SetFee(TxGraphImpl& graph, int level, DepGraphIndex idx, int64_t fee) noexcept
2738
287
{
2739
287
    Assume(GetTxCount());
2740
287
    Assume(idx == 0);
2741
287
    m_feerate.fee = fee;
2742
287
    Updated(graph, /*level=*/level, /*rename=*/false);
2743
287
}
2744
2745
void TxGraphImpl::SetTransactionFee(const Ref& ref, int64_t fee) noexcept
2746
303
{
2747
    // Don't do anything if the passed Ref is empty.
2748
303
    if (GetRefGraph(ref) == nullptr) return;
2749
303
    Assume(GetRefGraph(ref) == this);
2750
303
    Assume(m_main_chunkindex_observers == 0);
2751
    // Find the entry, its locator, and inform its Cluster about the new feerate, if any.
2752
303
    auto& entry = m_entries[GetRefIndex(ref)];
2753
909
    for (int level = 0; level < MAX_LEVELS; ++level) {
2754
606
        auto& locator = entry.m_locator[level];
2755
606
        if (locator.IsPresent()) {
2756
303
            locator.cluster->SetFee(*this, level, locator.index, fee);
2757
303
        }
2758
606
    }
2759
303
}
2760
2761
std::strong_ordering TxGraphImpl::CompareMainOrder(const Ref& a, const Ref& b) noexcept
2762
86.2M
{
2763
    // The references must not be empty.
2764
86.2M
    Assume(GetRefGraph(a) == this);
2765
86.2M
    Assume(GetRefGraph(b) == this);
2766
    // Apply dependencies in main.
2767
86.2M
    ApplyDependencies(0);
2768
86.2M
    Assume(m_main_clusterset.m_deps_to_add.empty());
2769
    // Make both involved Clusters acceptable, so chunk feerates are relevant.
2770
86.2M
    const auto& entry_a = m_entries[GetRefIndex(a)];
2771
86.2M
    const auto& entry_b = m_entries[GetRefIndex(b)];
2772
86.2M
    const auto& locator_a = entry_a.m_locator[0];
2773
86.2M
    const auto& locator_b = entry_b.m_locator[0];
2774
86.2M
    Assume(locator_a.IsPresent());
2775
86.2M
    Assume(locator_b.IsPresent());
2776
86.2M
    MakeAcceptable(*locator_a.cluster, /*level=*/0);
2777
86.2M
    MakeAcceptable(*locator_b.cluster, /*level=*/0);
2778
    // Invoke comparison logic.
2779
86.2M
    return CompareMainTransactions(GetRefIndex(a), GetRefIndex(b));
2780
86.2M
}
2781
2782
TxGraph::GraphIndex TxGraphImpl::CountDistinctClusters(std::span<const Ref* const> refs, Level level_select) noexcept
2783
1.40k
{
2784
1.40k
    size_t level = GetSpecifiedLevel(level_select);
2785
1.40k
    ApplyDependencies(level);
2786
1.40k
    auto& clusterset = GetClusterSet(level);
2787
1.40k
    Assume(clusterset.m_deps_to_add.empty());
2788
    // Build a vector of Clusters that the specified Refs occur in.
2789
1.40k
    std::vector<Cluster*> clusters;
2790
1.40k
    clusters.reserve(refs.size());
2791
2.76k
    for (const Ref* ref : refs) {
2792
2.76k
        Assume(ref);
2793
2.76k
        if (GetRefGraph(*ref) == nullptr) continue;
2794
2.76k
        Assume(GetRefGraph(*ref) == this);
2795
2.76k
        auto cluster = FindCluster(GetRefIndex(*ref), level);
2796
2.76k
        if (cluster != nullptr) clusters.push_back(cluster);
2797
2.76k
    }
2798
    // Count the number of distinct elements in clusters.
2799
10.2k
    std::ranges::sort(clusters, [](Cluster* a, Cluster* b) noexcept { return CompareClusters(a, b) < 0; });
2800
1.40k
    Cluster* last{nullptr};
2801
1.40k
    GraphIndex ret{0};
2802
2.76k
    for (Cluster* cluster : clusters) {
2803
2.76k
        ret += (cluster != last);
2804
2.76k
        last = cluster;
2805
2.76k
    }
2806
1.40k
    return ret;
2807
1.40k
}
2808
2809
std::pair<std::vector<FeeFrac>, std::vector<FeeFrac>> TxGraphImpl::GetMainStagingDiagrams() noexcept
2810
1.35k
{
2811
1.35k
    Assume(m_staging_clusterset.has_value());
2812
1.35k
    MakeAllAcceptable(0);
2813
1.35k
    Assume(m_main_clusterset.m_deps_to_add.empty()); // can only fail if main is oversized
2814
1.35k
    MakeAllAcceptable(1);
2815
1.35k
    Assume(m_staging_clusterset->m_deps_to_add.empty()); // can only fail if staging is oversized
2816
    // For all Clusters in main which conflict with Clusters in staging (i.e., all that are removed
2817
    // by, or replaced in, staging), gather their chunk feerates.
2818
1.35k
    auto main_clusters = GetConflicts();
2819
1.35k
    std::vector<FeeFrac> main_feerates, staging_feerates;
2820
1.74k
    for (Cluster* cluster : main_clusters) {
2821
1.74k
        cluster->AppendChunkFeerates(main_feerates);
2822
1.74k
    }
2823
    // Do the same for the Clusters in staging themselves.
2824
10.8k
    for (int quality = 0; quality < int(QualityLevel::NONE); ++quality) {
2825
9.45k
        for (const auto& cluster : m_staging_clusterset->m_clusters[quality]) {
2826
1.42k
            cluster->AppendChunkFeerates(staging_feerates);
2827
1.42k
        }
2828
9.45k
    }
2829
    // Sort both by decreasing feerate to obtain diagrams, and return them.
2830
1.35k
    std::ranges::sort(main_feerates, std::greater<ByRatioNegSize<FeeFrac>>{});
2831
1.35k
    std::ranges::sort(staging_feerates, std::greater<ByRatioNegSize<FeeFrac>>{});
2832
1.35k
    return std::make_pair(std::move(main_feerates), std::move(staging_feerates));
2833
1.35k
}
2834
2835
void GenericClusterImpl::SanityCheck(const TxGraphImpl& graph, int level) const
2836
69.0k
{
2837
    // There must be an m_mapping for each m_depgraph position (including holes).
2838
69.0k
    assert(m_depgraph.PositionRange() == m_mapping.size());
2839
    // The linearization for this Cluster must contain every transaction once.
2840
69.0k
    assert(m_depgraph.TxCount() == m_linearization.size());
2841
    // Unless a split is to be applied, the cluster cannot have any holes.
2842
69.0k
    if (!NeedsSplitting()) {
2843
69.0k
        assert(m_depgraph.Positions() == SetType::Fill(m_depgraph.TxCount()));
2844
69.0k
    }
2845
2846
    // Compute the chunking of m_linearization.
2847
69.0k
    auto linchunking = ChunkLinearizationInfo(m_depgraph, m_linearization);
2848
69.0k
    unsigned chunk_num{0};
2849
2850
    // Verify m_linearization.
2851
69.0k
    SetType m_done;
2852
69.0k
    LinearizationIndex linindex{0};
2853
69.0k
    DepGraphIndex chunk_pos{0}; //!< position within the current chunk
2854
69.0k
    assert(m_depgraph.IsAcyclic());
2855
69.0k
    if (m_linearization.empty()) return;
2856
69.0k
    FeeFrac equal_feerate_prefix = linchunking[chunk_num].feerate;
2857
404k
    for (auto lin_pos : m_linearization) {
2858
404k
        assert(lin_pos < m_mapping.size());
2859
404k
        const auto& entry = graph.m_entries[m_mapping[lin_pos]];
2860
        // Check that the linearization is topological.
2861
404k
        m_done.Set(lin_pos);
2862
404k
        if (IsTopological()) {
2863
404k
            assert(m_done.IsSupersetOf(m_depgraph.Ancestors(lin_pos)));
2864
404k
        }
2865
        // Check that the Entry has a locator pointing back to this Cluster & position within it.
2866
404k
        assert(entry.m_locator[level].cluster == this);
2867
404k
        assert(entry.m_locator[level].index == lin_pos);
2868
        // For main-level entries, check linearization position and chunk feerate.
2869
404k
        if (level == 0 && IsAcceptable()) {
2870
404k
            assert(entry.m_main_lin_index == linindex);
2871
404k
            ++linindex;
2872
404k
            if (!linchunking[chunk_num].transactions[lin_pos]) {
2873
                // First transaction of a new chunk.
2874
189k
                ++chunk_num;
2875
189k
                assert(chunk_num < linchunking.size());
2876
189k
                chunk_pos = 0;
2877
189k
                if (ByRatio{linchunking[chunk_num].feerate} < ByRatio{equal_feerate_prefix}) {
2878
9.46k
                    equal_feerate_prefix = linchunking[chunk_num].feerate;
2879
180k
                } else {
2880
180k
                    assert(ByRatio{linchunking[chunk_num].feerate} == ByRatio{equal_feerate_prefix});
2881
180k
                    equal_feerate_prefix += linchunking[chunk_num].feerate;
2882
180k
                }
2883
189k
            }
2884
404k
            assert(entry.m_main_chunk_feerate == linchunking[chunk_num].feerate);
2885
404k
            assert(entry.m_main_equal_feerate_chunk_prefix_size == equal_feerate_prefix.size);
2886
            // Verify that an entry in the chunk index exists for every chunk-ending transaction.
2887
404k
            ++chunk_pos;
2888
404k
            if (graph.m_main_clusterset.m_to_remove.empty()) {
2889
404k
                bool is_chunk_end = (chunk_pos == linchunking[chunk_num].transactions.Count());
2890
404k
                assert((entry.m_main_chunkindex_iterator != graph.m_main_chunkindex.end()) == is_chunk_end);
2891
404k
                if (is_chunk_end) {
2892
258k
                    auto& chunk_data = *entry.m_main_chunkindex_iterator;
2893
258k
                    if (m_done == m_depgraph.Positions() && chunk_pos == 1) {
2894
58.8k
                        assert(chunk_data.m_chunk_count == LinearizationIndex(-1));
2895
199k
                    } else {
2896
199k
                        assert(chunk_data.m_chunk_count == chunk_pos);
2897
199k
                    }
2898
258k
                }
2899
404k
            }
2900
            // If this Cluster has an acceptable quality level, its chunks must be connected.
2901
404k
            assert(m_depgraph.IsConnected(linchunking[chunk_num].transactions));
2902
404k
        }
2903
404k
    }
2904
    // Verify that each element of m_depgraph occurred in m_linearization.
2905
69.0k
    assert(m_done == m_depgraph.Positions());
2906
69.0k
}
2907
2908
void SingletonClusterImpl::SanityCheck(const TxGraphImpl& graph, int level) const
2909
6.93M
{
2910
    // All singletons are optimal, oversized, or need splitting.
2911
6.93M
    Assume(IsOptimal() || IsOversized() || NeedsSplitting());
2912
6.93M
    if (GetTxCount()) {
2913
6.93M
        const auto& entry = graph.m_entries[m_graph_index];
2914
        // Check that the Entry has a locator pointing back to this Cluster & position within it.
2915
6.93M
        assert(entry.m_locator[level].cluster == this);
2916
6.93M
        assert(entry.m_locator[level].index == 0);
2917
        // For main-level entries, check linearization position and chunk feerate.
2918
6.93M
        if (level == 0 && IsAcceptable()) {
2919
6.93M
            assert(entry.m_main_lin_index == 0);
2920
6.93M
            assert(entry.m_main_chunk_feerate == m_feerate);
2921
6.93M
            assert(entry.m_main_equal_feerate_chunk_prefix_size == m_feerate.size);
2922
6.93M
            if (graph.m_main_clusterset.m_to_remove.empty()) {
2923
6.93M
                assert(entry.m_main_chunkindex_iterator != graph.m_main_chunkindex.end());
2924
6.93M
                auto& chunk_data = *entry.m_main_chunkindex_iterator;
2925
6.93M
                assert(chunk_data.m_chunk_count == LinearizationIndex(-1));
2926
6.93M
            }
2927
6.93M
        }
2928
6.93M
    }
2929
6.93M
}
2930
2931
void TxGraphImpl::SanityCheck() const
2932
145k
{
2933
    /** Which GraphIndexes ought to occur in m_unlinked, based on m_entries. */
2934
145k
    std::set<GraphIndex> expected_unlinked;
2935
    /** Which Clusters ought to occur in ClusterSet::m_clusters, based on m_entries. */
2936
145k
    std::set<const Cluster*> expected_clusters[MAX_LEVELS];
2937
    /** Which GraphIndexes ought to occur in ClusterSet::m_removed, based on m_entries. */
2938
145k
    std::set<GraphIndex> expected_removed[MAX_LEVELS];
2939
    /** Which Cluster::m_sequence values have been encountered. */
2940
145k
    std::set<uint64_t> sequences;
2941
    /** Which Clusters are live in ClusterSet::m_clusters up to the level being checked. */
2942
145k
    std::set<const Cluster*> live_clusters;
2943
    /** Which GraphIndexes ought to occur in m_main_chunkindex, based on m_entries. */
2944
145k
    std::set<GraphIndex> expected_chunkindex;
2945
    /** Whether compaction is possible in the current state. */
2946
145k
    bool compact_possible{true};
2947
2948
    // Go over all Entry objects in m_entries.
2949
7.48M
    for (GraphIndex idx = 0; idx < m_entries.size(); ++idx) {
2950
7.34M
        const auto& entry = m_entries[idx];
2951
7.34M
        if (entry.m_ref == nullptr) {
2952
            // Unlinked Entry must have indexes appear in m_unlinked.
2953
0
            expected_unlinked.insert(idx);
2954
7.34M
        } else {
2955
            // Every non-unlinked Entry must have a Ref that points back to it.
2956
7.34M
            assert(GetRefGraph(*entry.m_ref) == this);
2957
7.34M
            assert(GetRefIndex(*entry.m_ref) == idx);
2958
7.34M
        }
2959
7.34M
        if (entry.m_main_chunkindex_iterator != m_main_chunkindex.end()) {
2960
            // Remember which entries we see a chunkindex entry for.
2961
7.19M
            assert(entry.m_locator[0].IsPresent());
2962
7.19M
            expected_chunkindex.insert(idx);
2963
7.19M
        }
2964
        // Verify the Entry m_locators.
2965
7.34M
        bool was_present{false}, was_removed{false};
2966
22.0M
        for (int level = 0; level < MAX_LEVELS; ++level) {
2967
14.6M
            const auto& locator = entry.m_locator[level];
2968
            // Every Locator must be in exactly one of these 3 states.
2969
14.6M
            assert(locator.IsMissing() + locator.IsRemoved() + locator.IsPresent() == 1);
2970
14.6M
            if (locator.IsPresent()) {
2971
                // Once removed, a transaction cannot be revived.
2972
7.34M
                assert(!was_removed);
2973
                // Verify that the Cluster agrees with where the Locator claims the transaction is.
2974
7.34M
                assert(locator.cluster->GetClusterEntry(locator.index) == idx);
2975
                // Remember that we expect said Cluster to appear in the ClusterSet::m_clusters.
2976
7.34M
                expected_clusters[level].insert(locator.cluster);
2977
7.34M
                was_present = true;
2978
7.34M
            } else if (locator.IsRemoved()) {
2979
                // Level 0 (main) cannot have IsRemoved locators (IsMissing there means non-existing).
2980
0
                assert(level > 0);
2981
                // A Locator can only be IsRemoved if it was IsPresent before, and only once.
2982
0
                assert(was_present && !was_removed);
2983
                // Remember that we expect this GraphIndex to occur in the ClusterSet::m_removed.
2984
0
                expected_removed[level].insert(idx);
2985
0
                was_removed = true;
2986
0
            }
2987
14.6M
        }
2988
7.34M
    }
2989
2990
    // For all levels (0 = main, 1 = staged)...
2991
291k
    for (int level = 0; level <= GetTopLevel(); ++level) {
2992
145k
        assert(level < MAX_LEVELS);
2993
145k
        auto& clusterset = GetClusterSet(level);
2994
145k
        std::set<const Cluster*> actual_clusters;
2995
145k
        size_t recomputed_cluster_usage{0};
2996
2997
        // For all quality levels...
2998
1.16M
        for (int qual = 0; qual < int(QualityLevel::NONE); ++qual) {
2999
1.02M
            QualityLevel quality{qual};
3000
1.02M
            const auto& quality_clusters = clusterset.m_clusters[qual];
3001
            // ... for all clusters in them ...
3002
8.02M
            for (ClusterSetIndex setindex = 0; setindex < quality_clusters.size(); ++setindex) {
3003
7.00M
                const auto& cluster = *quality_clusters[setindex];
3004
7.00M
                live_clusters.insert(&cluster);
3005
                // The number of transactions in a Cluster cannot exceed m_max_cluster_count.
3006
7.00M
                assert(cluster.GetTxCount() <= m_max_cluster_count);
3007
                // The level must match the Cluster's own idea of what level it is in (but GetLevel
3008
                // can only be called for non-empty Clusters).
3009
7.00M
                assert(cluster.GetTxCount() == 0 || level == cluster.GetLevel(*this));
3010
                // The sum of their sizes cannot exceed m_max_cluster_size, unless it is an
3011
                // individually oversized transaction singleton. Note that groups of to-be-merged
3012
                // clusters which would exceed this limit are marked oversized, which means they
3013
                // are never applied.
3014
7.00M
                assert(cluster.IsOversized() || cluster.GetTotalTxSize() <= m_max_cluster_size);
3015
                // OVERSIZED clusters are singletons.
3016
7.00M
                assert(!cluster.IsOversized() || cluster.GetTxCount() == 1);
3017
                // Transaction counts cannot exceed the Cluster implementation's maximum
3018
                // supported transactions count.
3019
7.00M
                assert(cluster.GetTxCount() <= cluster.GetMaxTxCount());
3020
                // Unless a Split is yet to be applied, the number of transactions must not be
3021
                // below the Cluster implementation's intended transaction count.
3022
7.00M
                if (!cluster.NeedsSplitting()) {
3023
7.00M
                    assert(cluster.GetTxCount() >= cluster.GetMinIntendedTxCount());
3024
7.00M
                }
3025
3026
                // Check the sequence number.
3027
7.00M
                assert(cluster.m_sequence < m_next_sequence_counter);
3028
7.00M
                assert(!sequences.contains(cluster.m_sequence));
3029
7.00M
                sequences.insert(cluster.m_sequence);
3030
                // Remember we saw this Cluster (only if it is non-empty; empty Clusters aren't
3031
                // expected to be referenced by the Entry vector).
3032
7.00M
                if (cluster.GetTxCount() != 0) {
3033
7.00M
                    actual_clusters.insert(&cluster);
3034
7.00M
                }
3035
                // Sanity check the cluster, according to the Cluster's internal rules.
3036
7.00M
                cluster.SanityCheck(*this, level);
3037
                // Check that the cluster's quality and setindex matches its position in the quality list.
3038
7.00M
                assert(cluster.m_quality == quality);
3039
7.00M
                assert(cluster.m_setindex == setindex);
3040
                // Count memory usage.
3041
7.00M
                recomputed_cluster_usage += cluster.TotalMemoryUsage();
3042
7.00M
            }
3043
1.02M
        }
3044
3045
        // Verify memory usage.
3046
145k
        assert(clusterset.m_cluster_usage == recomputed_cluster_usage);
3047
3048
        // Verify that all to-be-removed transactions have valid identifiers.
3049
145k
        for (GraphIndex idx : clusterset.m_to_remove) {
3050
8
            assert(idx < m_entries.size());
3051
            // We cannot assert that all m_to_remove transactions are still present: ~Ref on a
3052
            // (P,M) transaction (present in main, inherited in staging) will cause an m_to_remove
3053
            // addition in both main and staging, but a subsequence ApplyRemovals in main will
3054
            // cause it to disappear from staging too, leaving the m_to_remove in place.
3055
8
        }
3056
3057
        // Verify that all to-be-added dependencies have valid identifiers.
3058
191k
        for (auto [par_idx, chl_idx] : clusterset.m_deps_to_add) {
3059
191k
            assert(par_idx != chl_idx);
3060
191k
            assert(par_idx < m_entries.size());
3061
191k
            assert(chl_idx < m_entries.size());
3062
191k
        }
3063
3064
        // Verify that the actually encountered clusters match the ones occurring in Entry vector.
3065
145k
        assert(actual_clusters == expected_clusters[level]);
3066
3067
        // Validate m_group_data cluster pointers refer to live clusters at this
3068
        // level or below (staging group data may reference not-yet-pulled-in
3069
        // main clusters).
3070
145k
        if (clusterset.m_group_data.has_value()) {
3071
145k
            for (const Cluster* cl : clusterset.m_group_data->m_group_clusters) {
3072
0
                assert(live_clusters.contains(cl));
3073
0
                assert(cl->GetTxCount() > 0);
3074
0
                assert(FindCluster(cl->GetClusterEntry(0), level) == cl);
3075
0
            }
3076
145k
        }
3077
        // Verify that the contents of m_removed matches what was expected based on the Entry vector.
3078
145k
        std::set<GraphIndex> actual_removed(clusterset.m_removed.begin(), clusterset.m_removed.end());
3079
145k
        for (auto i : expected_unlinked) {
3080
            // If a transaction exists in both main and staging, and is removed from staging (adding
3081
            // it to m_removed there), and consequently destroyed (wiping the locator completely),
3082
            // it can remain in m_removed despite not having an IsRemoved() locator. Exclude those
3083
            // transactions from the comparison here.
3084
0
            actual_removed.erase(i);
3085
0
            expected_removed[level].erase(i);
3086
0
        }
3087
3088
145k
        assert(actual_removed == expected_removed[level]);
3089
3090
        // If any GraphIndex entries remain in this ClusterSet, compact is not possible.
3091
145k
        if (!clusterset.m_deps_to_add.empty()) compact_possible = false;
3092
145k
        if (!clusterset.m_to_remove.empty()) compact_possible = false;
3093
145k
        if (!clusterset.m_removed.empty()) compact_possible = false;
3094
3095
        // For non-top levels, m_oversized must be known (as it cannot change until the level
3096
        // on top is gone).
3097
145k
        if (level < GetTopLevel()) assert(clusterset.m_oversized.has_value());
3098
145k
    }
3099
3100
    // Verify that the contents of m_unlinked matches what was expected based on the Entry vector.
3101
145k
    std::set<GraphIndex> actual_unlinked(m_unlinked.begin(), m_unlinked.end());
3102
145k
    assert(actual_unlinked == expected_unlinked);
3103
3104
    // If compaction was possible, it should have been performed already, and m_unlinked must be
3105
    // empty (to prevent memory leaks due to an ever-growing m_entries vector).
3106
145k
    if (compact_possible) {
3107
145k
        assert(actual_unlinked.empty());
3108
145k
    }
3109
3110
    // Finally, check the chunk index.
3111
145k
    std::set<GraphIndex> actual_chunkindex;
3112
145k
    FeeFrac last_chunk_feerate;
3113
7.19M
    for (const auto& chunk : m_main_chunkindex) {
3114
7.19M
        GraphIndex idx = chunk.m_graph_index;
3115
7.19M
        actual_chunkindex.insert(idx);
3116
7.19M
        auto chunk_feerate = m_entries[idx].m_main_chunk_feerate;
3117
7.19M
        if (!last_chunk_feerate.IsEmpty()) {
3118
7.16M
            assert(ByRatio{last_chunk_feerate} >= ByRatio{FeeFrac{chunk_feerate}});
3119
7.16M
        }
3120
7.19M
        last_chunk_feerate = chunk_feerate;
3121
7.19M
    }
3122
145k
    assert(actual_chunkindex == expected_chunkindex);
3123
145k
}
3124
3125
bool TxGraphImpl::DoWork(uint64_t max_cost) noexcept
3126
153k
{
3127
153k
    uint64_t cost_done{0};
3128
    // First linearize everything in NEEDS_RELINEARIZE to an acceptable level. If more budget
3129
    // remains after that, try to make everything optimal.
3130
460k
    for (QualityLevel quality : {QualityLevel::NEEDS_FIX, QualityLevel::NEEDS_RELINEARIZE, QualityLevel::ACCEPTABLE}) {
3131
        // First linearize staging, if it exists, then main.
3132
921k
        for (int level = GetTopLevel(); level >= 0; --level) {
3133
            // Do not modify main if it has any observers.
3134
460k
            if (level == 0 && m_main_chunkindex_observers != 0) continue;
3135
460k
            ApplyDependencies(level);
3136
460k
            auto& clusterset = GetClusterSet(level);
3137
            // Do not modify oversized levels.
3138
460k
            if (clusterset.m_oversized == true) continue;
3139
460k
            auto& queue = clusterset.m_clusters[int(quality)];
3140
466k
            while (!queue.empty()) {
3141
5.91k
                if (cost_done >= max_cost) return false;
3142
                // Randomize the order in which we process, so that if the first cluster somehow
3143
                // needs more work than what max_cost allows, we don't keep spending it on the same
3144
                // one.
3145
5.91k
                auto pos = m_rng.randrange<size_t>(queue.size());
3146
5.91k
                auto cost_now = max_cost - cost_done;
3147
5.91k
                if (quality == QualityLevel::NEEDS_FIX || quality == QualityLevel::NEEDS_RELINEARIZE) {
3148
                    // If we're working with clusters that need relinearization still, only perform
3149
                    // up to m_acceptable_cost work. If they become ACCEPTABLE, and we still
3150
                    // have budget after all other clusters are ACCEPTABLE too, we'll spend the
3151
                    // remaining budget on trying to make them OPTIMAL.
3152
5.91k
                    cost_now = std::min(cost_now, m_acceptable_cost);
3153
5.91k
                }
3154
5.91k
                auto [cost, improved] = queue[pos].get()->Relinearize(*this, level, cost_now);
3155
5.91k
                cost_done += cost;
3156
                // If no improvement was made to the Cluster, it means we've essentially run out of
3157
                // budget. Even though it may be the case that cost_done < max_cost still, the
3158
                // linearizer decided there wasn't enough budget left to attempt anything with.
3159
                // To avoid an infinite loop that keeps trying clusters with minuscule budgets,
3160
                // stop here too.
3161
5.91k
                if (!improved) return false;
3162
5.91k
            }
3163
460k
        }
3164
460k
    }
3165
    // All possible work has been performed, so we can return true. Note that this does *not* mean
3166
    // that all clusters are optimally linearized now. It may be that there is nothing to do left
3167
    // because all non-optimal clusters are in oversized and/or observer-bearing levels.
3168
153k
    return true;
3169
153k
}
3170
3171
void BlockBuilderImpl::Next() noexcept
3172
7.08M
{
3173
    // Don't do anything if we're already done.
3174
7.08M
    if (m_cur_iter == m_graph->m_main_chunkindex.end()) return;
3175
7.08M
    while (true) {
3176
        // Advance the pointer, and stop if we reach the end.
3177
7.08M
        ++m_cur_iter;
3178
7.08M
        m_cur_cluster = nullptr;
3179
7.08M
        if (m_cur_iter == m_graph->m_main_chunkindex.end()) break;
3180
        // Find the cluster pointed to by m_cur_iter.
3181
7.05M
        const auto& chunk_data = *m_cur_iter;
3182
7.05M
        const auto& chunk_end_entry = m_graph->m_entries[chunk_data.m_graph_index];
3183
7.05M
        m_cur_cluster = chunk_end_entry.m_locator[0].cluster;
3184
7.05M
        m_known_end_of_cluster = false;
3185
        // If we previously skipped a chunk from this cluster we cannot include more from it.
3186
7.05M
        if (!m_excluded_clusters.contains(m_cur_cluster->m_sequence)) break;
3187
7.05M
    }
3188
7.08M
}
3189
3190
std::optional<std::pair<std::vector<TxGraph::Ref*>, FeePerWeight>> BlockBuilderImpl::GetCurrentChunk() noexcept
3191
7.26M
{
3192
7.26M
    std::optional<std::pair<std::vector<TxGraph::Ref*>, FeePerWeight>> ret;
3193
    // Populate the return value if we are not done.
3194
7.26M
    if (m_cur_iter != m_graph->m_main_chunkindex.end()) {
3195
7.08M
        ret.emplace();
3196
7.08M
        const auto& chunk_data = *m_cur_iter;
3197
7.08M
        const auto& chunk_end_entry = m_graph->m_entries[chunk_data.m_graph_index];
3198
7.08M
        if (chunk_data.m_chunk_count == LinearizationIndex(-1)) {
3199
            // Special case in case just a single transaction remains, avoiding the need to
3200
            // dispatch to and dereference Cluster.
3201
6.88M
            ret->first.resize(1);
3202
6.88M
            Assume(chunk_end_entry.m_ref != nullptr);
3203
6.88M
            ret->first[0] = chunk_end_entry.m_ref;
3204
6.88M
            m_known_end_of_cluster = true;
3205
6.88M
        } else {
3206
204k
            Assume(m_cur_cluster);
3207
204k
            ret->first.resize(chunk_data.m_chunk_count);
3208
204k
            auto start_pos = chunk_end_entry.m_main_lin_index + 1 - chunk_data.m_chunk_count;
3209
204k
            m_known_end_of_cluster = m_cur_cluster->GetClusterRefs(*m_graph, ret->first, start_pos);
3210
            // If the chunk size was 1 and at end of cluster, then the special case above should
3211
            // have been used.
3212
204k
            Assume(!m_known_end_of_cluster || chunk_data.m_chunk_count > 1);
3213
204k
        }
3214
7.08M
        ret->second = chunk_end_entry.m_main_chunk_feerate;
3215
7.08M
    }
3216
7.26M
    return ret;
3217
7.26M
}
3218
3219
180k
BlockBuilderImpl::BlockBuilderImpl(TxGraphImpl& graph) noexcept : m_graph(&graph)
3220
180k
{
3221
    // Make sure all clusters in main are up to date, and acceptable.
3222
180k
    m_graph->MakeAllAcceptable(0);
3223
    // There cannot remain any inapplicable dependencies (only possible if main is oversized).
3224
180k
    Assume(m_graph->m_main_clusterset.m_deps_to_add.empty());
3225
    // Remember that this object is observing the graph's index, so that we can detect concurrent
3226
    // modifications.
3227
180k
    ++m_graph->m_main_chunkindex_observers;
3228
    // Find the first chunk.
3229
180k
    m_cur_iter = m_graph->m_main_chunkindex.begin();
3230
180k
    m_cur_cluster = nullptr;
3231
180k
    if (m_cur_iter != m_graph->m_main_chunkindex.end()) {
3232
        // Find the cluster pointed to by m_cur_iter.
3233
35.3k
        const auto& chunk_data = *m_cur_iter;
3234
35.3k
        const auto& chunk_end_entry = m_graph->m_entries[chunk_data.m_graph_index];
3235
35.3k
        m_cur_cluster = chunk_end_entry.m_locator[0].cluster;
3236
35.3k
    }
3237
180k
}
3238
3239
BlockBuilderImpl::~BlockBuilderImpl()
3240
180k
{
3241
180k
    Assume(m_graph->m_main_chunkindex_observers > 0);
3242
    // Permit modifications to the main graph again after destroying the BlockBuilderImpl.
3243
180k
    --m_graph->m_main_chunkindex_observers;
3244
180k
}
3245
3246
void BlockBuilderImpl::Include() noexcept
3247
7.05M
{
3248
    // The actual inclusion of the chunk is done by the calling code. All we have to do is switch
3249
    // to the next chunk.
3250
7.05M
    Next();
3251
7.05M
}
3252
3253
void BlockBuilderImpl::Skip() noexcept
3254
30.3k
{
3255
    // When skipping a chunk we need to not include anything more of the cluster, as that could make
3256
    // the result topologically invalid. However, don't do this if the chunk is known to be the last
3257
    // chunk of the cluster. This may significantly reduce the size of m_excluded_clusters,
3258
    // especially when many singleton clusters are ignored.
3259
30.3k
    if (m_cur_cluster != nullptr && !m_known_end_of_cluster) {
3260
1
        m_excluded_clusters.insert(m_cur_cluster->m_sequence);
3261
1
    }
3262
30.3k
    Next();
3263
30.3k
}
3264
3265
std::unique_ptr<TxGraph::BlockBuilder> TxGraphImpl::GetBlockBuilder() noexcept
3266
180k
{
3267
180k
    return std::make_unique<BlockBuilderImpl>(*this);
3268
180k
}
3269
3270
std::pair<std::vector<TxGraph::Ref*>, FeePerWeight> TxGraphImpl::GetWorstMainChunk() noexcept
3271
53
{
3272
53
    std::pair<std::vector<Ref*>, FeePerWeight> ret;
3273
    // Make sure all clusters in main are up to date, and acceptable.
3274
53
    MakeAllAcceptable(0);
3275
53
    Assume(m_main_clusterset.m_deps_to_add.empty());
3276
    // If the graph is not empty, populate ret.
3277
53
    if (!m_main_chunkindex.empty()) {
3278
53
        const auto& chunk_data = *m_main_chunkindex.rbegin();
3279
53
        const auto& chunk_end_entry = m_entries[chunk_data.m_graph_index];
3280
53
        Cluster* cluster = chunk_end_entry.m_locator[0].cluster;
3281
53
        if (chunk_data.m_chunk_count == LinearizationIndex(-1) || chunk_data.m_chunk_count == 1)  {
3282
            // Special case for singletons.
3283
47
            ret.first.resize(1);
3284
47
            Assume(chunk_end_entry.m_ref != nullptr);
3285
47
            ret.first[0] = chunk_end_entry.m_ref;
3286
47
        } else {
3287
6
            ret.first.resize(chunk_data.m_chunk_count);
3288
6
            auto start_pos = chunk_end_entry.m_main_lin_index + 1 - chunk_data.m_chunk_count;
3289
6
            cluster->GetClusterRefs(*this, ret.first, start_pos);
3290
6
            std::reverse(ret.first.begin(), ret.first.end());
3291
6
        }
3292
53
        ret.second = chunk_end_entry.m_main_chunk_feerate;
3293
53
    }
3294
53
    return ret;
3295
53
}
3296
3297
std::vector<TxGraph::Ref*> TxGraphImpl::Trim() noexcept
3298
2.04k
{
3299
2.04k
    int level = GetTopLevel();
3300
2.04k
    Assume(m_main_chunkindex_observers == 0 || level != 0);
3301
2.04k
    std::vector<TxGraph::Ref*> ret;
3302
3303
    // Compute the groups of to-be-merged Clusters (which also applies all removals, and splits).
3304
2.04k
    auto& clusterset = GetClusterSet(level);
3305
2.04k
    if (clusterset.m_oversized == false) return ret;
3306
32
    GroupClusters(level);
3307
32
    Assume(clusterset.m_group_data.has_value());
3308
    // Nothing to do if not oversized.
3309
32
    Assume(clusterset.m_oversized.has_value());
3310
32
    if (clusterset.m_oversized == false) return ret;
3311
3312
    // In this function, would-be clusters (as precomputed in m_group_data by GroupClusters) are
3313
    // trimmed by removing transactions in them such that the resulting clusters satisfy the size
3314
    // and count limits.
3315
    //
3316
    // It works by defining for each would-be cluster a rudimentary linearization: at every point
3317
    // the highest-chunk-feerate remaining transaction is picked among those with no unmet
3318
    // dependencies. "Dependency" here means either a to-be-added dependency (m_deps_to_add), or
3319
    // an implicit dependency added between any two consecutive transaction in their current
3320
    // cluster linearization. So it can be seen as a "merge sort" of the chunks of the clusters,
3321
    // but respecting the dependencies being added.
3322
    //
3323
    // This rudimentary linearization is computed lazily, by putting all eligible (no unmet
3324
    // dependencies) transactions in a heap, and popping the highest-feerate one from it. Along the
3325
    // way, the counts and sizes of the would-be clusters up to that point are tracked (by
3326
    // partitioning the involved transactions using a union-find structure). Any transaction whose
3327
    // addition would cause a violation is removed, along with all their descendants.
3328
    //
3329
    // A next invocation of GroupClusters (after applying the removals) will compute the new
3330
    // resulting clusters, and none of them will violate the limits.
3331
3332
    /** All dependencies (both to be added ones, and implicit ones between consecutive transactions
3333
     *  in existing cluster linearizations), sorted by parent. */
3334
4
    std::vector<std::pair<GraphIndex, GraphIndex>> deps_by_parent;
3335
    /** Same, but sorted by child. */
3336
4
    std::vector<std::pair<GraphIndex, GraphIndex>> deps_by_child;
3337
    /** Information about all transactions involved in a Cluster group to be trimmed, sorted by
3338
     *  GraphIndex. It contains entries both for transactions that have already been included,
3339
     *  and ones that have not yet been. */
3340
4
    std::vector<TrimTxData> trim_data;
3341
    /** Iterators into trim_data, treated as a max heap according to cmp_fn below. Each entry is
3342
     *  a transaction that has not yet been included yet, but all its ancestors have. */
3343
4
    std::vector<std::vector<TrimTxData>::iterator> trim_heap;
3344
    /** The list of representatives of the partitions a given transaction depends on. */
3345
4
    std::vector<TrimTxData*> current_deps;
3346
3347
    /** Function to define the ordering of trim_heap. */
3348
1.07M
    static constexpr auto cmp_fn = [](auto a, auto b) noexcept {
3349
        // Sort by increasing chunk feerate, and then by decreasing size.
3350
        // We do not need to sort by cluster or within clusters, because due to the implicit
3351
        // dependency between consecutive linearization elements, no two transactions from the
3352
        // same Cluster will ever simultaneously be in the heap.
3353
1.07M
        return ByRatioNegSize{a->m_chunk_feerate} < ByRatioNegSize{b->m_chunk_feerate};
3354
1.07M
    };
3355
3356
    /** Given a TrimTxData entry, find the representative of the partition it is in. */
3357
188k
    static constexpr auto find_fn = [](TrimTxData* arg) noexcept {
3358
250k
        while (arg != arg->m_uf_parent) {
3359
            // Replace pointer to parent with pointer to grandparent (path splitting).
3360
            // See https://en.wikipedia.org/wiki/Disjoint-set_data_structure#Finding_set_representatives.
3361
61.4k
            auto par = arg->m_uf_parent;
3362
61.4k
            arg->m_uf_parent = par->m_uf_parent;
3363
61.4k
            arg = par;
3364
61.4k
        }
3365
188k
        return arg;
3366
188k
    };
3367
3368
    /** Given two TrimTxData entries, union the partitions they are in, and return the
3369
     *  representative. */
3370
62.5k
    static constexpr auto union_fn = [](TrimTxData* arg1, TrimTxData* arg2) noexcept {
3371
        // Replace arg1 and arg2 by their representatives.
3372
62.5k
        auto rep1 = find_fn(arg1);
3373
62.5k
        auto rep2 = find_fn(arg2);
3374
        // Bail out if both representatives are the same, because that means arg1 and arg2 are in
3375
        // the same partition already.
3376
62.5k
        if (rep1 == rep2) return rep1;
3377
        // Pick the lower-count root to become a child of the higher-count one.
3378
        // See https://en.wikipedia.org/wiki/Disjoint-set_data_structure#Union_by_size.
3379
62.5k
        if (rep1->m_uf_count < rep2->m_uf_count) std::swap(rep1, rep2);
3380
62.5k
        rep2->m_uf_parent = rep1;
3381
        // Add the statistics of arg2 (which is no longer a representative) to those of arg1 (which
3382
        // is now the representative for both).
3383
62.5k
        rep1->m_uf_size += rep2->m_uf_size;
3384
62.5k
        rep1->m_uf_count += rep2->m_uf_count;
3385
62.5k
        return rep1;
3386
62.5k
    };
3387
3388
    /** Get iterator to TrimTxData entry for a given index. */
3389
127k
    auto locate_fn = [&](GraphIndex index) noexcept {
3390
2.02M
        auto it = std::lower_bound(trim_data.begin(), trim_data.end(), index, [](TrimTxData& elem, GraphIndex idx) noexcept {
3391
2.02M
            return elem.m_index < idx;
3392
2.02M
        });
3393
127k
        Assume(it != trim_data.end() && it->m_index == index);
3394
127k
        return it;
3395
127k
    };
3396
3397
    // For each group of to-be-merged Clusters.
3398
9
    for (const auto& group_data : clusterset.m_group_data->m_groups) {
3399
9
        trim_data.clear();
3400
9
        trim_heap.clear();
3401
9
        deps_by_child.clear();
3402
9
        deps_by_parent.clear();
3403
3404
        // Gather trim data and implicit dependency data from all involved Clusters.
3405
9
        auto cluster_span = std::span{clusterset.m_group_data->m_group_clusters}
3406
9
                                .subspan(group_data.m_cluster_offset, group_data.m_cluster_count);
3407
9
        uint64_t size{0};
3408
64.2k
        for (Cluster* cluster : cluster_span) {
3409
64.2k
            MakeAcceptable(*cluster, cluster->GetLevel(*this));
3410
64.2k
            size += cluster->AppendTrimData(trim_data, deps_by_child);
3411
64.2k
        }
3412
        // If this group of Clusters does not violate any limits, continue to the next group.
3413
9
        if (trim_data.size() <= m_max_cluster_count && size <= m_max_cluster_size) continue;
3414
        // Sort the trim data by GraphIndex. In what follows, we will treat this sorted vector as
3415
        // a map from GraphIndex to TrimTxData via locate_fn, and its ordering will not change
3416
        // anymore.
3417
1.32M
        std::ranges::sort(trim_data, [](auto& a, auto& b) noexcept { return a.m_index < b.m_index; });
3418
3419
        // Add the explicitly added dependencies to deps_by_child.
3420
9
        deps_by_child.insert(deps_by_child.end(),
3421
9
                             clusterset.m_deps_to_add.begin() + group_data.m_deps_offset,
3422
9
                             clusterset.m_deps_to_add.begin() + group_data.m_deps_offset + group_data.m_deps_count);
3423
3424
        // Sort deps_by_child by child transaction GraphIndex. The order will not be changed
3425
        // anymore after this.
3426
1.46M
        std::ranges::sort(deps_by_child, [](auto& a, auto& b) noexcept { return a.second < b.second; });
3427
        // Fill m_parents_count and m_parents_offset in trim_data, as well as m_deps_left, and
3428
        // initially populate trim_heap. Because of the sort above, all dependencies involving the
3429
        // same child are grouped together, so a single linear scan suffices.
3430
9
        auto deps_it = deps_by_child.begin();
3431
64.2k
        for (auto trim_it = trim_data.begin(); trim_it != trim_data.end(); ++trim_it) {
3432
64.2k
            trim_it->m_parent_offset = deps_it - deps_by_child.begin();
3433
64.2k
            trim_it->m_deps_left = 0;
3434
128k
            while (deps_it != deps_by_child.end() && deps_it->second == trim_it->m_index) {
3435
64.2k
                ++trim_it->m_deps_left;
3436
64.2k
                ++deps_it;
3437
64.2k
            }
3438
64.2k
            trim_it->m_parent_count = trim_it->m_deps_left;
3439
            // If this transaction has no unmet dependencies, and is not oversized, add it to the
3440
            // heap (just append for now, the heapification happens below).
3441
64.2k
            if (trim_it->m_deps_left == 0 && trim_it->m_tx_size <= m_max_cluster_size) {
3442
1.15k
                trim_heap.push_back(trim_it);
3443
1.15k
            }
3444
64.2k
        }
3445
9
        Assume(deps_it == deps_by_child.end());
3446
3447
        // Construct deps_by_parent, sorted by parent transaction GraphIndex. The order will not be
3448
        // changed anymore after this.
3449
9
        deps_by_parent = deps_by_child;
3450
1.75M
        std::ranges::sort(deps_by_parent, [](auto& a, auto& b) noexcept { return a.first < b.first; });
3451
        // Fill m_children_offset and m_children_count in trim_data. Because of the sort above, all
3452
        // dependencies involving the same parent are grouped together, so a single linear scan
3453
        // suffices.
3454
9
        deps_it = deps_by_parent.begin();
3455
64.2k
        for (auto& trim_entry : trim_data) {
3456
64.2k
            trim_entry.m_children_count = 0;
3457
64.2k
            trim_entry.m_children_offset = deps_it - deps_by_parent.begin();
3458
128k
            while (deps_it != deps_by_parent.end() && deps_it->first == trim_entry.m_index) {
3459
64.2k
                ++trim_entry.m_children_count;
3460
64.2k
                ++deps_it;
3461
64.2k
            }
3462
64.2k
        }
3463
9
        Assume(deps_it == deps_by_parent.end());
3464
3465
        // Build a heap of all transactions with 0 unmet dependencies.
3466
9
        std::make_heap(trim_heap.begin(), trim_heap.end(), cmp_fn);
3467
3468
        // Iterate over to-be-included transactions, and convert them to included transactions, or
3469
        // skip them if adding them would violate resource limits of the would-be cluster.
3470
        //
3471
        // It is possible that the heap empties without ever hitting either cluster limit, in case
3472
        // the implied graph (to be added dependencies plus implicit dependency between each
3473
        // original transaction and its predecessor in the linearization it came from) contains
3474
        // cycles. Such cycles will be removed entirely, because each of the transactions in the
3475
        // cycle permanently have unmet dependencies. However, this cannot occur in real scenarios
3476
        // where Trim() is called to deal with reorganizations that would violate cluster limits,
3477
        // as all added dependencies are in the same direction (from old mempool transactions to
3478
        // new from-block transactions); cycles require dependencies in both directions to be
3479
        // added.
3480
63.6k
        while (!trim_heap.empty()) {
3481
            // Move the best remaining transaction to the end of trim_heap.
3482
63.6k
            std::pop_heap(trim_heap.begin(), trim_heap.end(), cmp_fn);
3483
            // Pop it, and find its TrimTxData.
3484
63.6k
            auto& entry = *trim_heap.back();
3485
63.6k
            trim_heap.pop_back();
3486
3487
            // Initialize it as a singleton partition.
3488
63.6k
            entry.m_uf_parent = &entry;
3489
63.6k
            entry.m_uf_count = 1;
3490
63.6k
            entry.m_uf_size = entry.m_tx_size;
3491
3492
            // Find the distinct transaction partitions this entry depends on.
3493
63.6k
            current_deps.clear();
3494
63.6k
            for (auto& [par, chl] : std::span{deps_by_child}.subspan(entry.m_parent_offset, entry.m_parent_count)) {
3495
63.6k
                Assume(chl == entry.m_index);
3496
63.6k
                current_deps.push_back(find_fn(&*locate_fn(par)));
3497
63.6k
            }
3498
63.6k
            std::ranges::sort(current_deps);
3499
63.6k
            current_deps.erase(std::ranges::unique(current_deps).begin(), current_deps.end());
3500
3501
            // Compute resource counts.
3502
63.6k
            uint32_t new_count = 1;
3503
63.6k
            uint64_t new_size = entry.m_tx_size;
3504
63.6k
            for (TrimTxData* ptr : current_deps) {
3505
63.6k
                new_count += ptr->m_uf_count;
3506
63.6k
                new_size += ptr->m_uf_size;
3507
63.6k
            }
3508
            // Skip the entry if this would violate any limit.
3509
63.6k
            if (new_count > m_max_cluster_count || new_size > m_max_cluster_size) continue;
3510
3511
            // Union the partitions this transaction and all its dependencies are in together.
3512
63.6k
            auto rep = &entry;
3513
63.6k
            for (TrimTxData* ptr : current_deps) rep = union_fn(ptr, rep);
3514
            // Mark the entry as included (so the loop below will not remove the transaction).
3515
63.6k
            entry.m_deps_left = uint32_t(-1);
3516
            // Mark each to-be-added dependency involving this transaction as parent satisfied.
3517
63.6k
            for (auto& [par, chl] : std::span{deps_by_parent}.subspan(entry.m_children_offset, entry.m_children_count)) {
3518
63.6k
                Assume(par == entry.m_index);
3519
63.6k
                auto chl_it = locate_fn(chl);
3520
                // Reduce the number of unmet dependencies of chl_it, and if that brings the number
3521
                // to zero, add it to the heap of includable transactions.
3522
63.6k
                Assume(chl_it->m_deps_left > 0);
3523
63.6k
                if (--chl_it->m_deps_left == 0) {
3524
62.4k
                    trim_heap.push_back(chl_it);
3525
62.4k
                    std::push_heap(trim_heap.begin(), trim_heap.end(), cmp_fn);
3526
62.4k
                }
3527
63.6k
            }
3528
63.6k
        }
3529
3530
        // Remove all the transactions that were not processed above. Because nothing gets
3531
        // processed until/unless all its dependencies are met, this automatically guarantees
3532
        // that if a transaction is removed, all its descendants, or would-be descendants, are
3533
        // removed as well.
3534
64.2k
        for (const auto& trim_entry : trim_data) {
3535
64.2k
            if (trim_entry.m_deps_left != uint32_t(-1)) {
3536
595
                ret.push_back(m_entries[trim_entry.m_index].m_ref);
3537
595
                clusterset.m_to_remove.push_back(trim_entry.m_index);
3538
595
            }
3539
64.2k
        }
3540
9
    }
3541
4
    clusterset.m_group_data.reset();
3542
4
    clusterset.m_oversized = false;
3543
4
    Assume(!ret.empty());
3544
4
    return ret;
3545
32
}
3546
3547
size_t TxGraphImpl::GetMainMemoryUsage() noexcept
3548
472k
{
3549
    // Make sure splits/merges are applied, as memory usage may not be representative otherwise.
3550
472k
    SplitAll(/*up_to_level=*/0);
3551
472k
    ApplyDependencies(/*level=*/0);
3552
    // Compute memory usage
3553
472k
    size_t usage = /* From clusters */
3554
472k
                   m_main_clusterset.m_cluster_usage +
3555
                   /* From Entry objects. */
3556
472k
                   sizeof(Entry) * m_main_clusterset.m_txcount +
3557
                   /* From the chunk index. */
3558
472k
                   memusage::DynamicUsage(m_main_chunkindex);
3559
472k
    return usage;
3560
472k
}
3561
3562
} // namespace
3563
3564
TxGraph::Ref::~Ref()
3565
407k
{
3566
407k
    if (m_graph) {
3567
        // Inform the TxGraph about the Ref being destroyed.
3568
68.7k
        m_graph->UnlinkRef(m_index);
3569
68.7k
        m_graph = nullptr;
3570
68.7k
    }
3571
407k
}
3572
3573
TxGraph::Ref::Ref(Ref&& other) noexcept
3574
74.1k
{
3575
    // Inform the TxGraph of other that its Ref is being moved.
3576
74.1k
    if (other.m_graph) other.m_graph->UpdateRef(other.m_index, *this);
3577
    // Actually move the contents.
3578
74.1k
    std::swap(m_graph, other.m_graph);
3579
74.1k
    std::swap(m_index, other.m_index);
3580
74.1k
}
3581
3582
std::unique_ptr<TxGraph> MakeTxGraph(
3583
    unsigned max_cluster_count,
3584
    uint64_t max_cluster_size,
3585
    uint64_t acceptable_cost,
3586
    const std::function<std::strong_ordering(const TxGraph::Ref&, const TxGraph::Ref&)>& fallback_order) noexcept
3587
1.39k
{
3588
1.39k
    return std::make_unique<TxGraphImpl>(
3589
1.39k
        /*max_cluster_count=*/max_cluster_count,
3590
1.39k
        /*max_cluster_size=*/max_cluster_size,
3591
1.39k
        /*acceptable_cost=*/acceptable_cost,
3592
1.39k
        /*fallback_order=*/fallback_order);
3593
1.39k
}