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