Coverage Report

Created: 2025-11-03 06:48

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