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