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 : : #ifndef BITCOIN_CLUSTER_LINEARIZE_H
6 : : #define BITCOIN_CLUSTER_LINEARIZE_H
7 : :
8 : : #include <algorithm>
9 : : #include <cstdint>
10 : : #include <numeric>
11 : : #include <optional>
12 : : #include <utility>
13 : : #include <vector>
14 : :
15 : : #include <attributes.h>
16 : : #include <memusage.h>
17 : : #include <random.h>
18 : : #include <span.h>
19 : : #include <util/feefrac.h>
20 : : #include <util/vecdeque.h>
21 : :
22 : : namespace cluster_linearize {
23 : :
24 : : /** Data type to represent transaction indices in DepGraphs and the clusters they represent. */
25 : : using DepGraphIndex = uint32_t;
26 : :
27 : : /** Data structure that holds a transaction graph's preprocessed data (fee, size, ancestors,
28 : : * descendants). */
29 : : template<typename SetType>
30 [ + + + - : 7009 : class DepGraph
+ - ][ + -
+ - + - +
- + - ]
31 : : {
32 : : /** Information about a single transaction. */
33 : : struct Entry
34 : : {
35 : : /** Fee and size of transaction itself. */
36 : 50090 : FeeFrac feerate;
37 : : /** All ancestors of the transaction (including itself). */
38 : 50090 : SetType ancestors;
39 : : /** All descendants of the transaction (including itself). */
40 : 50090 : SetType descendants;
41 : :
42 : : /** Equality operator (primarily for testing purposes). */
43 [ + - + - : 100180 : friend bool operator==(const Entry&, const Entry&) noexcept = default;
- + ]
44 : :
45 : : /** Construct an empty entry. */
46 : 75582 : Entry() noexcept = default;
47 : : /** Construct an entry with a given feerate, ancestor set, descendant set. */
48 : 82274 : Entry(const FeeFrac& f, const SetType& a, const SetType& d) noexcept : feerate(f), ancestors(a), descendants(d) {}
49 : : };
50 : :
51 : : /** Data for each transaction. */
52 : : std::vector<Entry> entries;
53 : :
54 : : /** Which positions are used. */
55 : : SetType m_used;
56 : :
57 : : public:
58 : : /** Equality operator (primarily for testing purposes). */
59 : 1883 : friend bool operator==(const DepGraph& a, const DepGraph& b) noexcept
60 : : {
61 [ + - ]: 1883 : if (a.m_used != b.m_used) return false;
62 : : // Only compare the used positions within the entries vector.
63 [ + + + + ]: 52695 : for (auto idx : a.m_used) {
64 [ + - ]: 50090 : if (a.entries[idx] != b.entries[idx]) return false;
65 : : }
66 : : return true;
67 : : }
68 : :
69 : : // Default constructors.
70 : 1664 : DepGraph() noexcept = default;
71 : : DepGraph(const DepGraph&) noexcept = default;
72 : : DepGraph(DepGraph&&) noexcept = default;
73 : 330 : DepGraph& operator=(const DepGraph&) noexcept = default;
74 : 5133 : DepGraph& operator=(DepGraph&&) noexcept = default;
75 : :
76 : : /** Construct a DepGraph object given another DepGraph and a mapping from old to new.
77 : : *
78 : : * @param depgraph The original DepGraph that is being remapped.
79 : : *
80 : : * @param mapping A span such that mapping[i] gives the position in the new DepGraph
81 : : * for position i in the old depgraph. Its size must be equal to
82 : : * depgraph.PositionRange(). The value of mapping[i] is ignored if
83 : : * position i is a hole in depgraph (i.e., if !depgraph.Positions()[i]).
84 : : *
85 : : * @param pos_range The PositionRange() for the new DepGraph. It must equal the largest
86 : : * value in mapping for any used position in depgraph plus 1, or 0 if
87 : : * depgraph.TxCount() == 0.
88 : : *
89 : : * Complexity: O(N^2) where N=depgraph.TxCount().
90 : : */
91 [ - + ]: 2814 : DepGraph(const DepGraph<SetType>& depgraph, std::span<const DepGraphIndex> mapping, DepGraphIndex pos_range) noexcept : entries(pos_range)
92 : : {
93 [ - + ]: 2814 : Assume(mapping.size() == depgraph.PositionRange());
94 : 2814 : Assume((pos_range == 0) == (depgraph.TxCount() == 0));
95 [ + + ]: 77919 : for (DepGraphIndex i : depgraph.Positions()) {
96 : 75105 : auto new_idx = mapping[i];
97 : 75105 : Assume(new_idx < pos_range);
98 : : // Add transaction.
99 : 75105 : entries[new_idx].ancestors = SetType::Singleton(new_idx);
100 : 75105 : entries[new_idx].descendants = SetType::Singleton(new_idx);
101 : 75105 : m_used.Set(new_idx);
102 : : // Fill in fee and size.
103 : 75105 : entries[new_idx].feerate = depgraph.entries[i].feerate;
104 : : }
105 [ + + ]: 77919 : for (DepGraphIndex i : depgraph.Positions()) {
106 : : // Fill in dependencies by mapping direct parents.
107 : 75105 : SetType parents;
108 [ + + + + ]: 321075 : for (auto j : depgraph.GetReducedParents(i)) parents.Set(mapping[j]);
109 : 75105 : AddDependencies(parents, mapping[i]);
110 : : }
111 : : // Verify that the provided pos_range was correct (no unused positions at the end).
112 [ + - ]: 4551 : Assume(m_used.None() ? (pos_range == 0) : (pos_range == m_used.Last() + 1));
113 : 2814 : }
114 : :
115 : : /** Get the set of transactions positions in use. Complexity: O(1). */
116 [ + + + + : 97952 : const SetType& Positions() const noexcept { return m_used; }
+ - + - +
+ + + + +
+ - + + +
+ + - + -
+ - + - +
- + - ]
117 : : /** Get the range of positions in this DepGraph. All entries in Positions() are in [0, PositionRange() - 1]. */
118 [ - + - + : 69078 : DepGraphIndex PositionRange() const noexcept { return entries.size(); }
- + - + -
+ ][ - + -
+ + + - +
- + - + +
- - + - +
- + + - -
+ + - - +
- + - + +
- - + + -
- + - + -
+ + - - +
+ - - + -
+ - + + -
- + + - -
+ - + - +
+ - - + +
- - + - +
- + - + -
+ ]
119 : : /** Get the number of transactions in the graph. Complexity: O(1). */
120 [ - + - + ]: 574417 : auto TxCount() const noexcept { return m_used.Count(); }
[ + - + -
+ + + - +
- + - + -
+ - + - +
- + - + -
- + - + -
+ - + - +
- + - + -
+ - + -
+ ]
121 : : /** Get the feerate of a given transaction i. Complexity: O(1). */
122 [ + - + + : 365853 : const FeeFrac& FeeRate(DepGraphIndex i) const noexcept { return entries[i].feerate; }
+ - + + +
- + + + -
+ + + - +
+ ]
123 : : /** Get the mutable feerate of a given transaction i. Complexity: O(1). */
124 [ + - + - ]: 449 : FeeFrac& FeeRate(DepGraphIndex i) noexcept { return entries[i].feerate; }
125 : : /** Get the ancestors of a given transaction i. Complexity: O(1). */
126 [ + - + + : 29886036 : const SetType& Ancestors(DepGraphIndex i) const noexcept { return entries[i].ancestors; }
- + ][ + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ - + - +
+ + - + -
+ - + - +
- + - - +
- + + - +
- - + + -
- + - + -
+ + - + -
- + - + +
- + - - +
- + + - +
- - + + -
- + - + -
+ + - ]
127 : : /** Get the descendants of a given transaction i. Complexity: O(1). */
128 [ + - ][ + + : 1880126 : const SetType& Descendants(DepGraphIndex i) const noexcept { return entries[i].descendants; }
+ + + - +
- - + - +
- + - + -
+ - + - +
- + - + -
+ - + -
+ ]
129 : :
130 : : /** Add a new unconnected transaction to this transaction graph (in the first available
131 : : * position), and return its DepGraphIndex.
132 : : *
133 : : * Complexity: O(1) (amortized, due to resizing of backing vector).
134 : : */
135 : 82274 : DepGraphIndex AddTransaction(const FeeFrac& feefrac) noexcept
136 : : {
137 : : static constexpr auto ALL_POSITIONS = SetType::Fill(SetType::Size());
138 [ + - ]: 82274 : auto available = ALL_POSITIONS - m_used;
139 [ + - ]: 130199 : Assume(available.Any());
140 : 82274 : DepGraphIndex new_idx = available.First();
141 [ - + + - ]: 82274 : if (new_idx == entries.size()) {
142 : 82274 : entries.emplace_back(feefrac, SetType::Singleton(new_idx), SetType::Singleton(new_idx));
143 : : } else {
144 : 0 : entries[new_idx] = Entry(feefrac, SetType::Singleton(new_idx), SetType::Singleton(new_idx));
145 : : }
146 : 82274 : m_used.Set(new_idx);
147 : 82274 : return new_idx;
148 : : }
149 : :
150 : : /** Remove the specified positions from this DepGraph.
151 : : *
152 : : * The specified positions will no longer be part of Positions(), and dependencies with them are
153 : : * removed. Note that due to DepGraph only tracking ancestors/descendants (and not direct
154 : : * dependencies), if a parent is removed while a grandparent remains, the grandparent will
155 : : * remain an ancestor.
156 : : *
157 : : * Complexity: O(N) where N=TxCount().
158 : : */
159 : 1178 : void RemoveTransactions(const SetType& del) noexcept
160 : : {
161 : 1178 : m_used -= del;
162 : : // Remove now-unused trailing entries.
163 [ + + - + : 5653 : while (!entries.empty() && !m_used[entries.size() - 1]) {
+ + ]
164 : 4475 : entries.pop_back();
165 : : }
166 : : // Remove the deleted transactions from ancestors/descendants of other transactions. Note
167 : : // that the deleted positions will retain old feerate and dependency information. This does
168 : : // not matter as they will be overwritten by AddTransaction if they get used again.
169 [ + + ]: 2067 : for (auto& entry : entries) {
170 : 889 : entry.ancestors &= m_used;
171 : 889 : entry.descendants &= m_used;
172 : : }
173 : 1178 : }
174 : :
175 : : /** Modify this transaction graph, adding multiple parents to a specified child.
176 : : *
177 : : * Complexity: O(N) where N=TxCount().
178 : : */
179 : 162993 : void AddDependencies(const SetType& parents, DepGraphIndex child) noexcept
180 : : {
181 [ + + ]: 162993 : Assume(m_used[child]);
182 : 258843 : Assume(parents.IsSubsetOf(m_used));
183 : : // Compute the ancestors of parents that are not already ancestors of child.
184 [ + + ]: 162993 : SetType par_anc;
185 [ + + + + ]: 852343 : for (auto par : parents - Ancestors(child)) {
186 : 1051368 : par_anc |= Ancestors(par);
187 : : }
188 [ + + ]: 162993 : par_anc -= Ancestors(child);
189 : : // Bail out if there are no such ancestors.
190 [ + + ]: 162993 : if (par_anc.None()) return;
191 : : // To each such ancestor, add as descendants the descendants of the child.
192 : 123628 : const auto& chl_des = entries[child].descendants;
193 [ + + ]: 993350 : for (auto anc_of_par : par_anc) {
194 : 1398904 : entries[anc_of_par].descendants |= chl_des;
195 : : }
196 : : // To each descendant of the child, add those ancestors.
197 [ + + + + ]: 295325 : for (auto dec_of_chl : Descendants(child)) {
198 : 199233 : entries[dec_of_chl].ancestors |= par_anc;
199 : : }
200 : : }
201 : :
202 : : /** Compute the (reduced) set of parents of node i in this graph.
203 : : *
204 : : * This returns the minimal subset of the parents of i whose ancestors together equal all of
205 : : * i's ancestors (unless i is part of a cycle of dependencies). Note that DepGraph does not
206 : : * store the set of parents; this information is inferred from the ancestor sets.
207 : : *
208 : : * Complexity: O(N) where N=Ancestors(i).Count() (which is bounded by TxCount()).
209 : : */
210 [ + + ]: 5197503 : SetType GetReducedParents(DepGraphIndex i) const noexcept
211 : : {
212 [ + + ]: 5197503 : SetType parents = Ancestors(i);
213 : 5197503 : parents.Reset(i);
214 [ + + + + : 32913180 : for (auto parent : parents) {
+ + ]
215 [ + + ]: 26193982 : if (parents[parent]) {
216 : 22130624 : parents -= Ancestors(parent);
217 : 22130624 : parents.Set(parent);
218 : : }
219 : : }
220 : 5197503 : return parents;
221 : : }
222 : :
223 : : /** Compute the (reduced) set of children of node i in this graph.
224 : : *
225 : : * This returns the minimal subset of the children of i whose descendants together equal all of
226 : : * i's descendants (unless i is part of a cycle of dependencies). Note that DepGraph does not
227 : : * store the set of children; this information is inferred from the descendant sets.
228 : : *
229 : : * Complexity: O(N) where N=Descendants(i).Count() (which is bounded by TxCount()).
230 : : */
231 [ + + ]: 50070 : SetType GetReducedChildren(DepGraphIndex i) const noexcept
232 : : {
233 [ + + ]: 50070 : SetType children = Descendants(i);
234 : 50070 : children.Reset(i);
235 [ + + + + : 293106 : for (auto child : children) {
+ + ]
236 [ + + ]: 233772 : if (children[child]) {
237 : 167192 : children -= Descendants(child);
238 : 167192 : children.Set(child);
239 : : }
240 : : }
241 : 50070 : return children;
242 : : }
243 : :
244 : : /** Compute the aggregate feerate of a set of nodes in this graph.
245 : : *
246 : : * Complexity: O(N) where N=elems.Count().
247 : : **/
248 : : FeeFrac FeeRate(const SetType& elems) const noexcept
249 : : {
250 : : FeeFrac ret;
251 : : for (auto pos : elems) ret += entries[pos].feerate;
252 : : return ret;
253 : : }
254 : :
255 : : /** Get the connected component within the subset "todo" that contains tx (which must be in
256 : : * todo).
257 : : *
258 : : * Two transactions are considered connected if they are both in `todo`, and one is an ancestor
259 : : * of the other in the entire graph (so not just within `todo`), or transitively there is a
260 : : * path of transactions connecting them. This does mean that if `todo` contains a transaction
261 : : * and a grandparent, but misses the parent, they will still be part of the same component.
262 : : *
263 : : * Complexity: O(ret.Count()).
264 : : */
265 : 246488 : SetType GetConnectedComponent(const SetType& todo, DepGraphIndex tx) const noexcept
266 : : {
267 : 246488 : Assume(todo[tx]);
268 : 246488 : Assume(todo.IsSubsetOf(m_used));
269 : 246488 : auto to_add = SetType::Singleton(tx);
270 : 246488 : SetType ret;
271 : : do {
272 : 497156 : SetType old = ret;
273 [ + - + + ]: 1822206 : for (auto add : to_add) {
274 : 827894 : ret |= Descendants(add);
275 : 827894 : ret |= Ancestors(add);
276 : : }
277 [ + + ]: 497156 : ret &= todo;
278 : 497156 : to_add = ret - old;
279 [ + + ]: 497156 : } while (to_add.Any());
280 : 246488 : return ret;
281 : : }
282 : :
283 : : /** Find some connected component within the subset "todo" of this graph.
284 : : *
285 : : * Specifically, this finds the connected component which contains the first transaction of
286 : : * todo (if any).
287 : : *
288 : : * Complexity: O(ret.Count()).
289 : : */
290 [ - + ]: 246488 : SetType FindConnectedComponent(const SetType& todo) const noexcept
291 : : {
292 [ - + ]: 246488 : if (todo.None()) return todo;
293 : 246488 : return GetConnectedComponent(todo, todo.First());
294 : : }
295 : :
296 : : /** Determine if a subset is connected.
297 : : *
298 : : * Complexity: O(subset.Count()).
299 : : */
300 : 246076 : bool IsConnected(const SetType& subset) const noexcept
301 : : {
302 [ - + ]: 246076 : return FindConnectedComponent(subset) == subset;
303 : : }
304 : :
305 : : /** Determine if this entire graph is connected.
306 : : *
307 : : * Complexity: O(TxCount()).
308 : : */
309 : : bool IsConnected() const noexcept { return IsConnected(m_used); }
310 : :
311 : : /** Append the entries of select to list in a topologically valid order.
312 : : *
313 : : * Complexity: O(select.Count() * log(select.Count())).
314 : : */
315 : : void AppendTopo(std::vector<DepGraphIndex>& list, const SetType& select) const noexcept
316 : : {
317 : : DepGraphIndex old_len = list.size();
318 : : for (auto i : select) list.push_back(i);
319 : : std::sort(list.begin() + old_len, list.end(), [&](DepGraphIndex a, DepGraphIndex b) noexcept {
320 : : const auto a_anc_count = entries[a].ancestors.Count();
321 : : const auto b_anc_count = entries[b].ancestors.Count();
322 : : if (a_anc_count != b_anc_count) return a_anc_count < b_anc_count;
323 : : return a < b;
324 : : });
325 : : }
326 : :
327 : : /** Check if this graph is acyclic. */
328 : 62046 : bool IsAcyclic() const noexcept
329 : : {
330 [ + + + - : 394624 : for (auto i : Positions()) {
+ + ]
331 [ + - ]: 271112 : if ((Ancestors(i) & Descendants(i)) != SetType::Singleton(i)) {
332 : : return false;
333 : : }
334 : : }
335 : : return true;
336 : : }
337 : :
338 : : unsigned CountDependencies() const noexcept
339 : : {
340 : : unsigned ret = 0;
341 : : for (auto i : Positions()) {
342 : : ret += GetReducedParents(i).Count();
343 : : }
344 : : return ret;
345 : : }
346 : :
347 : : /** Reduce memory usage if possible. No observable effect. */
348 : 6403 : void Compact() noexcept
349 : : {
350 : 6403 : entries.shrink_to_fit();
351 : : }
352 : :
353 : 74399 : size_t DynamicMemoryUsage() const noexcept
354 : : {
355 [ - + ]: 74399 : return memusage::DynamicUsage(entries);
356 : : }
357 : : };
358 : :
359 : : /** A set of transactions together with their aggregate feerate. */
360 : : template<typename SetType>
361 : : struct SetInfo
362 : : {
363 : : /** The transactions in the set. */
364 : : SetType transactions;
365 : : /** Their combined fee and size. */
366 : : FeeFrac feerate;
367 : :
368 : : /** Construct a SetInfo for the empty set. */
369 : 5071895 : SetInfo() noexcept = default;
370 : :
371 : : /** Construct a SetInfo for a specified set and feerate. */
372 : : SetInfo(const SetType& txn, const FeeFrac& fr) noexcept : transactions(txn), feerate(fr) {}
373 : :
374 : : /** Construct a SetInfo for a given transaction in a depgraph. */
375 : 5391453 : explicit SetInfo(const DepGraph<SetType>& depgraph, DepGraphIndex pos) noexcept :
376 : 5391453 : transactions(SetType::Singleton(pos)), feerate(depgraph.FeeRate(pos)) {}
377 : :
378 : : /** Construct a SetInfo for a set of transactions in a depgraph. */
379 : : explicit SetInfo(const DepGraph<SetType>& depgraph, const SetType& txn) noexcept :
380 : : transactions(txn), feerate(depgraph.FeeRate(txn)) {}
381 : :
382 : : /** Add a transaction to this SetInfo (which must not yet be in it). */
383 : : void Set(const DepGraph<SetType>& depgraph, DepGraphIndex pos) noexcept
384 : : {
385 : : Assume(!transactions[pos]);
386 : : transactions.Set(pos);
387 : : feerate += depgraph.FeeRate(pos);
388 : : }
389 : :
390 : : /** Add the transactions of other to this SetInfo (no overlap allowed). */
391 : 35515700 : SetInfo& operator|=(const SetInfo& other) noexcept
392 : : {
393 : 58316106 : Assume(!transactions.Overlaps(other.transactions));
394 : 35515700 : transactions |= other.transactions;
395 : 35515700 : feerate += other.feerate;
396 : 35515700 : return *this;
397 : : }
398 : :
399 : : /** Remove the transactions of other from this SetInfo (which must be a subset). */
400 : 15931624 : SetInfo& operator-=(const SetInfo& other) noexcept
401 : : {
402 : 26148459 : Assume(other.transactions.IsSubsetOf(transactions));
403 : 15931624 : transactions -= other.transactions;
404 : 15931624 : feerate -= other.feerate;
405 : 15931624 : return *this;
406 : : }
407 : :
408 : : /** Compute the difference between this and other SetInfo (which must be a subset). */
409 : : SetInfo operator-(const SetInfo& other) const noexcept
410 : : {
411 : : Assume(other.transactions.IsSubsetOf(transactions));
412 : : return {transactions - other.transactions, feerate - other.feerate};
413 : : }
414 : :
415 : : /** Swap two SetInfo objects. */
416 : : friend void swap(SetInfo& a, SetInfo& b) noexcept
417 : : {
418 : : swap(a.transactions, b.transactions);
419 : : swap(a.feerate, b.feerate);
420 : : }
421 : :
422 : : /** Permit equality testing. */
423 : : friend bool operator==(const SetInfo&, const SetInfo&) noexcept = default;
424 : : };
425 : :
426 : : /** Compute the chunks of linearization as SetInfos. */
427 : : template<typename SetType>
428 : 67014 : std::vector<SetInfo<SetType>> ChunkLinearizationInfo(const DepGraph<SetType>& depgraph, std::span<const DepGraphIndex> linearization) noexcept
429 : : {
430 : 67014 : std::vector<SetInfo<SetType>> ret;
431 [ + + ]: 386572 : for (DepGraphIndex i : linearization) {
432 : : /** The new chunk to be added, initially a singleton. */
433 : 319558 : SetInfo<SetType> new_chunk(depgraph, i);
434 : : // As long as the new chunk has a higher feerate than the last chunk so far, absorb it.
435 [ + + + + ]: 348795 : while (!ret.empty() && new_chunk.feerate >> ret.back().feerate) {
436 : 29237 : new_chunk |= ret.back();
437 : 29237 : ret.pop_back();
438 : : }
439 : : // Actually move that new chunk into the chunking.
440 : 319558 : ret.emplace_back(std::move(new_chunk));
441 : : }
442 : 67014 : return ret;
443 : : }
444 : :
445 : : /** Compute the feerates of the chunks of linearization. Identical to ChunkLinearizationInfo, but
446 : : * only returns the chunk feerates, not the corresponding transaction sets. */
447 : : template<typename SetType>
448 : 406 : std::vector<FeeFrac> ChunkLinearization(const DepGraph<SetType>& depgraph, std::span<const DepGraphIndex> linearization) noexcept
449 : : {
450 : 406 : std::vector<FeeFrac> ret;
451 [ + + ]: 2532 : for (DepGraphIndex i : linearization) {
452 : : /** The new chunk to be added, initially a singleton. */
453 : 2126 : auto new_chunk = depgraph.FeeRate(i);
454 : : // As long as the new chunk has a higher feerate than the last chunk so far, absorb it.
455 [ + + + + ]: 3001 : while (!ret.empty() && new_chunk >> ret.back()) {
456 : 875 : new_chunk += ret.back();
457 : 875 : ret.pop_back();
458 : : }
459 : : // Actually move that new chunk into the chunking.
460 : 2126 : ret.push_back(std::move(new_chunk));
461 : : }
462 : 406 : return ret;
463 : : }
464 : :
465 : : /** Concept for function objects that return std::strong_ordering when invoked with two Args. */
466 : : template<typename F, typename Arg>
467 : : concept StrongComparator =
468 : : std::regular_invocable<F, Arg, Arg> &&
469 : : std::is_same_v<std::invoke_result_t<F, Arg, Arg>, std::strong_ordering>;
470 : :
471 : : /** Simple default transaction ordering function for SpanningForestState::GetLinearization() and
472 : : * Linearize(), which just sorts by DepGraphIndex. */
473 : : using IndexTxOrder = std::compare_three_way;
474 : :
475 : : /** A default cost model for SFL for SetType=BitSet<64>, based on benchmarks.
476 : : *
477 : : * The numbers here were obtained in February 2026 by:
478 : : * - For a variety of machines:
479 : : * - Running a fixed collection of ~385000 clusters found through random generation and fuzzing,
480 : : * optimizing for difficulty of linearization.
481 : : * - Linearize each ~3000 times, with different random seeds. Sometimes without input
482 : : * linearization, sometimes with a bad one.
483 : : * - Gather cycle counts for each of the operations included in this cost model,
484 : : * broken down by their parameters.
485 : : * - Correct the data by subtracting the runtime of obtaining the cycle count.
486 : : * - Drop the 5% top and bottom samples from each cycle count dataset, and compute the average
487 : : * of the remaining samples.
488 : : * - For each operation, fit a least-squares linear function approximation through the samples.
489 : : * - Rescale all machine expressions to make their total time match, as we only care about
490 : : * relative cost of each operation.
491 : : * - Take the per-operation average of operation expressions across all machines, to construct
492 : : * expressions for an average machine.
493 : : * - Approximate the result with integer coefficients. Each cost unit corresponds to somewhere
494 : : * between 0.5 ns and 2.5 ns, depending on the hardware.
495 : : */
496 : : class SFLDefaultCostModel
497 : : {
498 : : uint64_t m_cost{0};
499 : :
500 : : public:
501 : 191464 : inline void InitializeBegin() noexcept {}
502 : 191464 : inline void InitializeEnd(int num_txns, int num_deps) noexcept
503 : : {
504 : : // Cost of initialization.
505 : 191464 : m_cost += 39 * num_txns;
506 : : // Cost of producing linearization at the end.
507 : 191464 : m_cost += 48 * num_txns + 4 * num_deps;
508 : : }
509 : : inline void GetLinearizationBegin() noexcept {}
510 : : inline void GetLinearizationEnd(int num_txns, int num_deps) noexcept
511 : : {
512 : : // Note that we account for the cost of the final linearization at the beginning (see
513 : : // InitializeEnd), because the cost budget decision needs to be made before calling
514 : : // GetLinearization.
515 : : // This function exists here to allow overriding it easily for benchmark purposes.
516 : : }
517 : : inline void MakeTopologicalBegin() noexcept {}
518 : 98644 : inline void MakeTopologicalEnd(int num_chunks, int num_steps) noexcept
519 : : {
520 : 98644 : m_cost += 20 * num_chunks + 28 * num_steps;
521 : : }
522 : : inline void StartOptimizingBegin() noexcept {}
523 : 191464 : inline void StartOptimizingEnd(int num_chunks) noexcept { m_cost += 13 * num_chunks; }
524 : : inline void ActivateBegin() noexcept {}
525 : 4591606 : inline void ActivateEnd(int num_deps) noexcept { m_cost += 10 * num_deps + 1; }
526 : : inline void DeactivateBegin() noexcept {}
527 : 1311653 : inline void DeactivateEnd(int num_deps) noexcept { m_cost += 11 * num_deps + 8; }
528 : : inline void MergeChunksBegin() noexcept {}
529 : 4591606 : inline void MergeChunksMid(int num_txns) noexcept { m_cost += 2 * num_txns; }
530 : 4591606 : inline void MergeChunksEnd(int num_steps) noexcept { m_cost += 3 * num_steps + 5; }
531 : : inline void PickMergeCandidateBegin() noexcept {}
532 : 9217112 : inline void PickMergeCandidateEnd(int num_steps) noexcept { m_cost += 8 * num_steps; }
533 : : inline void PickChunkToOptimizeBegin() noexcept {}
534 : 2560287 : inline void PickChunkToOptimizeEnd(int num_steps) noexcept { m_cost += num_steps + 4; }
535 : : inline void PickDependencyToSplitBegin() noexcept {}
536 : 2560287 : inline void PickDependencyToSplitEnd(int num_txns) noexcept { m_cost += 8 * num_txns + 9; }
537 : : inline void StartMinimizingBegin() noexcept {}
538 : 191464 : inline void StartMinimizingEnd(int num_chunks) noexcept { m_cost += 18 * num_chunks; }
539 : : inline void MinimizeStepBegin() noexcept {}
540 : 2129873 : inline void MinimizeStepMid(int num_txns) noexcept { m_cost += 11 * num_txns + 11; }
541 : 286968 : inline void MinimizeStepEnd(bool split) noexcept { m_cost += 17 * split + 7; }
542 : :
543 : 5073088 : inline uint64_t GetCost() const noexcept { return m_cost; }
544 : : };
545 : :
546 : : /** Class to represent the internal state of the spanning-forest linearization (SFL) algorithm.
547 : : *
548 : : * At all times, each dependency is marked as either "active" or "inactive". The subset of active
549 : : * dependencies is the state of the SFL algorithm. The implementation maintains several other
550 : : * values to speed up operations, but everything is ultimately a function of what that subset of
551 : : * active dependencies is.
552 : : *
553 : : * Given such a subset, define a chunk as the set of transactions that are connected through active
554 : : * dependencies (ignoring their parent/child direction). Thus, every state implies a particular
555 : : * partitioning of the graph into chunks (including potential singletons). In the extreme, each
556 : : * transaction may be in its own chunk, or in the other extreme all transactions may form a single
557 : : * chunk. A chunk's feerate is its total fee divided by its total size.
558 : : *
559 : : * The algorithm consists of switching dependencies between active and inactive. The final
560 : : * linearization that is produced at the end consists of these chunks, sorted from high to low
561 : : * feerate, each individually sorted in an arbitrary but topological (= no child before parent)
562 : : * way.
563 : : *
564 : : * We define four quality properties the state can have:
565 : : *
566 : : * - acyclic: The state is acyclic whenever no cycle of active dependencies exists within the
567 : : * graph, ignoring the parent/child direction. This is equivalent to saying that within
568 : : * each chunk the set of active dependencies form a tree, and thus the overall set of
569 : : * active dependencies in the graph form a spanning forest, giving the algorithm its
570 : : * name. Being acyclic is also equivalent to every chunk of N transactions having
571 : : * exactly N-1 active dependencies.
572 : : *
573 : : * For example in a diamond graph, D->{B,C}->A, the 4 dependencies cannot be
574 : : * simultaneously active. If at least one is inactive, the state is acyclic.
575 : : *
576 : : * The algorithm maintains an acyclic state at *all* times as an invariant. This implies
577 : : * that activating a dependency always corresponds to merging two chunks, and that
578 : : * deactivating one always corresponds to splitting two chunks.
579 : : *
580 : : * - topological: We say the state is topological whenever it is acyclic and no inactive dependency
581 : : * exists between two distinct chunks such that the child chunk has higher or equal
582 : : * feerate than the parent chunk.
583 : : *
584 : : * The relevance is that whenever the state is topological, the produced output
585 : : * linearization will be topological too (i.e., not have children before parents).
586 : : * Note that the "or equal" part of the definition matters: if not, one can end up
587 : : * in a situation with mutually-dependent equal-feerate chunks that cannot be
588 : : * linearized. For example C->{A,B} and D->{A,B}, with C->A and D->B active. The AC
589 : : * chunk depends on DB through C->B, and the BD chunk depends on AC through D->A.
590 : : * Merging them into a single ABCD chunk fixes this.
591 : : *
592 : : * The algorithm attempts to keep the state topological as much as possible, so it
593 : : * can be interrupted to produce an output whenever, but will sometimes need to
594 : : * temporarily deviate from it when improving the state.
595 : : *
596 : : * - optimal: For every active dependency, define its top and bottom set as the set of transactions
597 : : * in the chunks that would result if the dependency were deactivated; the top being the
598 : : * one with the dependency's parent, and the bottom being the one with the child. Note
599 : : * that due to acyclicity, every deactivation splits a chunk exactly in two.
600 : : *
601 : : * We say the state is optimal whenever it is topological and it has no active
602 : : * dependency whose top feerate is strictly higher than its bottom feerate. The
603 : : * relevance is that it can be proven that whenever the state is optimal, the produced
604 : : * linearization will also be optimal (in the convexified feerate diagram sense). It can
605 : : * also be proven that for every graph at least one optimal state exists.
606 : : *
607 : : * Note that it is possible for the SFL state to not be optimal, but the produced
608 : : * linearization to still be optimal. This happens when the chunks of a state are
609 : : * identical to those of an optimal state, but the exact set of active dependencies
610 : : * within a chunk differ in such a way that the state optimality condition is not
611 : : * satisfied. Thus, the state being optimal is more a "the eventual output is *known*
612 : : * to be optimal".
613 : : *
614 : : * - minimal: We say the state is minimal when it is:
615 : : * - acyclic
616 : : * - topological, except that inactive dependencies between equal-feerate chunks are
617 : : * allowed as long as they do not form a loop.
618 : : * - like optimal, no active dependencies whose top feerate is strictly higher than
619 : : * the bottom feerate are allowed.
620 : : * - no chunk contains a proper non-empty subset which includes all its own in-chunk
621 : : * dependencies of the same feerate as the chunk itself.
622 : : *
623 : : * A minimal state effectively corresponds to an optimal state, where every chunk has
624 : : * been split into its minimal equal-feerate components.
625 : : *
626 : : * The algorithm terminates whenever a minimal state is reached.
627 : : *
628 : : *
629 : : * This leads to the following high-level algorithm:
630 : : * - Start with all dependencies inactive, and thus all transactions in their own chunk. This is
631 : : * definitely acyclic.
632 : : * - Activate dependencies (merging chunks) until the state is topological.
633 : : * - Loop until optimal (no dependencies with higher-feerate top than bottom), or time runs out:
634 : : * - Deactivate a violating dependency, potentially making the state non-topological.
635 : : * - Activate other dependencies to make the state topological again.
636 : : * - If there is time left and the state is optimal:
637 : : * - Attempt to split chunks into equal-feerate parts without mutual dependencies between them.
638 : : * When this succeeds, recurse into them.
639 : : * - If no such chunks can be found, the state is minimal.
640 : : * - Output the chunks from high to low feerate, each internally sorted topologically.
641 : : *
642 : : * When merging, we always either:
643 : : * - Merge upwards: merge a chunk with the lowest-feerate other chunk it depends on, among those
644 : : * with lower or equal feerate than itself.
645 : : * - Merge downwards: merge a chunk with the highest-feerate other chunk that depends on it, among
646 : : * those with higher or equal feerate than itself.
647 : : *
648 : : * Using these strategies in the improvement loop above guarantees that the output linearization
649 : : * after a deactivate + merge step is never worse or incomparable (in the convexified feerate
650 : : * diagram sense) than the output linearization that would be produced before the step. With that,
651 : : * we can refine the high-level algorithm to:
652 : : * - Start with all dependencies inactive.
653 : : * - Perform merges as described until none are possible anymore, making the state topological.
654 : : * - Loop until optimal or time runs out:
655 : : * - Pick a dependency D to deactivate among those with higher feerate top than bottom.
656 : : * - Deactivate D, causing the chunk it is in to split into top T and bottom B.
657 : : * - Do an upwards merge of T, if possible. If so, repeat the same with the merged result.
658 : : * - Do a downwards merge of B, if possible. If so, repeat the same with the merged result.
659 : : * - Split chunks further to obtain a minimal state, see below.
660 : : * - Output the chunks from high to low feerate, each internally sorted topologically.
661 : : *
662 : : * Instead of performing merges arbitrarily to make the initial state topological, it is possible
663 : : * to do so guided by an existing linearization. This has the advantage that the state's would-be
664 : : * output linearization is immediately as good as the existing linearization it was based on:
665 : : * - Start with all dependencies inactive.
666 : : * - For each transaction t in the existing linearization:
667 : : * - Find the chunk C that transaction is in (which will be singleton).
668 : : * - Do an upwards merge of C, if possible. If so, repeat the same with the merged result.
669 : : * No downwards merges are needed in this case.
670 : : *
671 : : * After reaching an optimal state, it can be transformed into a minimal state by attempting to
672 : : * split chunks further into equal-feerate parts. To do so, pick a specific transaction in each
673 : : * chunk (the pivot), and rerun the above split-then-merge procedure again:
674 : : * - first, while pretending the pivot transaction has an infinitesimally higher (or lower) fee
675 : : * than it really has. If a split exists with the pivot in the top part (or bottom part), this
676 : : * will find it.
677 : : * - if that fails to split, repeat while pretending the pivot transaction has an infinitesimally
678 : : * lower (or higher) fee. If a split exists with the pivot in the bottom part (or top part), this
679 : : * will find it.
680 : : * - if either succeeds, repeat the procedure for the newly found chunks to split them further.
681 : : * If not, the chunk is already minimal.
682 : : * If the chunk can be split into equal-feerate parts, then the pivot must exist in either the top
683 : : * or bottom part of that potential split. By trying both with the same pivot, if a split exists,
684 : : * it will be found.
685 : : *
686 : : * What remains to be specified are a number of heuristics:
687 : : *
688 : : * - How to decide which chunks to merge:
689 : : * - The merge upwards and downward rules specify that the lowest-feerate respectively
690 : : * highest-feerate candidate chunk is merged with, but if there are multiple equal-feerate
691 : : * candidates, a uniformly random one among them is picked.
692 : : *
693 : : * - How to decide what dependency to activate (when merging chunks):
694 : : * - After picking two chunks to be merged (see above), a uniformly random dependency between the
695 : : * two chunks is activated.
696 : : *
697 : : * - How to decide which chunk to find a dependency to split in:
698 : : * - A round-robin queue of chunks to improve is maintained. The initial ordering of this queue
699 : : * is uniformly randomly permuted.
700 : : *
701 : : * - How to decide what dependency to deactivate (when splitting chunks):
702 : : * - Inside the selected chunk (see above), among the dependencies whose top feerate is strictly
703 : : * higher than its bottom feerate in the selected chunk, if any, a uniformly random dependency
704 : : * is deactivated.
705 : : * - After every split, it is possible that the top and the bottom chunk merge with each other
706 : : * again in the merge sequence (through a top->bottom dependency, not through the deactivated
707 : : * one, which was bottom->top). Call this a self-merge. If a self-merge does not occur after
708 : : * a split, the resulting linearization is strictly improved (the area under the convexified
709 : : * feerate diagram increases by at least gain/2), while self-merges do not change it.
710 : : *
711 : : * - How to decide the exact output linearization:
712 : : * - When there are multiple equal-feerate chunks with no dependencies between them, output a
713 : : * uniformly random one among the ones with no missing dependent chunks first.
714 : : * - Within chunks, repeatedly pick a uniformly random transaction among those with no missing
715 : : * dependencies.
716 : : */
717 : : template<typename SetType, typename CostModel = SFLDefaultCostModel>
718 : : class SpanningForestState
719 : : {
720 : : private:
721 : : /** Internal RNG. */
722 : : InsecureRandomContext m_rng;
723 : :
724 : : /** Data type to represent indexing into m_tx_data. */
725 : : using TxIdx = DepGraphIndex;
726 : : /** Data type to represent indexing into m_set_info. Use the smallest type possible to improve
727 : : * cache locality. */
728 : : using SetIdx = std::conditional_t<(SetType::Size() <= 0xff),
729 : : uint8_t,
730 : : std::conditional_t<(SetType::Size() <= 0xffff),
731 : : uint16_t,
732 : : uint32_t>>;
733 : : /** An invalid SetIdx. */
734 : : static constexpr SetIdx INVALID_SET_IDX = SetIdx(-1);
735 : :
736 : : /** Structure with information about a single transaction. */
737 : 5101895 : struct TxData {
738 : : /** The top set for every active child dependency this transaction has, indexed by child
739 : : * TxIdx. Only defined for indexes in active_children. */
740 : : std::array<SetIdx, SetType::Size()> dep_top_idx;
741 : : /** The set of parent transactions of this transaction. Immutable after construction. */
742 : : SetType parents;
743 : : /** The set of child transactions of this transaction. Immutable after construction. */
744 : : SetType children;
745 : : /** The set of child transactions reachable through an active dependency. */
746 : : SetType active_children;
747 : : /** Which chunk this transaction belongs to. */
748 : : SetIdx chunk_idx;
749 : : };
750 : :
751 : : /** The set of all TxIdx's of transactions in the cluster indexing into m_tx_data. */
752 : : SetType m_transaction_idxs;
753 : : /** The set of all chunk SetIdx's. This excludes the SetIdxs that refer to active
754 : : * dependencies' tops. */
755 : : SetType m_chunk_idxs;
756 : : /** The set of all SetIdx's that appear in m_suboptimal_chunks. Note that they do not need to
757 : : * be chunks: some of these sets may have been converted to a dependency's top set since being
758 : : * added to m_suboptimal_chunks. */
759 : : SetType m_suboptimal_idxs;
760 : : /** Information about each transaction (and chunks). Keeps the "holes" from DepGraph during
761 : : * construction. Indexed by TxIdx. */
762 : : std::vector<TxData> m_tx_data;
763 : : /** Information about each set (chunk, or active dependency top set). Indexed by SetIdx. */
764 : : std::vector<SetInfo<SetType>> m_set_info;
765 : : /** For each chunk, indexed by SetIdx, the set of out-of-chunk reachable transactions, in the
766 : : * upwards (.first) and downwards (.second) direction. */
767 : : std::vector<std::pair<SetType, SetType>> m_reachable;
768 : : /** A FIFO of chunk SetIdxs for chunks that may be improved still. */
769 : : VecDeque<SetIdx> m_suboptimal_chunks;
770 : : /** A FIFO of chunk indexes with a pivot transaction in them, and a flag to indicate their
771 : : * status:
772 : : * - bit 1: currently attempting to move the pivot down, rather than up.
773 : : * - bit 2: this is the second stage, so we have already tried moving the pivot in the other
774 : : * direction.
775 : : */
776 : : VecDeque<std::tuple<SetIdx, TxIdx, unsigned>> m_nonminimal_chunks;
777 : :
778 : : /** The DepGraph we are trying to linearize. */
779 : : const DepGraph<SetType>& m_depgraph;
780 : :
781 : : /** Accounting for the cost of this computation. */
782 : : CostModel m_cost;
783 : :
784 : : /** Pick a random transaction within a set (which must be non-empty). */
785 : 1791942 : TxIdx PickRandomTx(const SetType& tx_idxs) noexcept
786 : : {
787 : 2899342 : Assume(tx_idxs.Any());
788 : 1791942 : unsigned pos = m_rng.randrange<unsigned>(tx_idxs.Count());
789 [ + - + - ]: 4393441 : for (auto tx_idx : tx_idxs) {
790 [ + + ]: 3708899 : if (pos == 0) return tx_idx;
791 : 1916957 : --pos;
792 : : }
793 : 0 : Assume(false);
794 : 0 : return TxIdx(-1);
795 : : }
796 : :
797 : : /** Find the set of out-of-chunk transactions reachable from tx_idxs, both in upwards and
798 : : * downwards direction. Only used by SanityCheck to verify the precomputed reachable sets in
799 : : * m_reachable that are maintained by Activate/Deactivate. */
800 : : std::pair<SetType, SetType> GetReachable(const SetType& tx_idxs) const noexcept
801 : : {
802 : : SetType parents, children;
803 : : for (auto tx_idx : tx_idxs) {
804 : : const auto& tx_data = m_tx_data[tx_idx];
805 : : parents |= tx_data.parents;
806 : : children |= tx_data.children;
807 : : }
808 : : return {parents - tx_idxs, children - tx_idxs};
809 : : }
810 : :
811 : : /** Make the inactive dependency from child to parent, which must not be in the same chunk
812 : : * already, active. Returns the merged chunk idx. */
813 : 4591606 : SetIdx Activate(TxIdx parent_idx, TxIdx child_idx) noexcept
814 : : {
815 : : m_cost.ActivateBegin();
816 : : // Gather and check information about the parent and child transactions.
817 [ + - ]: 4591606 : auto& parent_data = m_tx_data[parent_idx];
818 : 4591606 : auto& child_data = m_tx_data[child_idx];
819 [ + - ]: 4591606 : Assume(parent_data.children[child_idx]);
820 : 4591606 : Assume(!parent_data.active_children[child_idx]);
821 : : // Get the set index of the chunks the parent and child are currently in. The parent chunk
822 : : // will become the top set of the newly activated dependency, while the child chunk will be
823 : : // grown to become the merged chunk.
824 : 4591606 : auto parent_chunk_idx = parent_data.chunk_idx;
825 : 4591606 : auto child_chunk_idx = child_data.chunk_idx;
826 : 4591606 : Assume(parent_chunk_idx != child_chunk_idx);
827 : 4591606 : Assume(m_chunk_idxs[parent_chunk_idx]);
828 : 4591606 : Assume(m_chunk_idxs[child_chunk_idx]);
829 : 4591606 : auto& top_info = m_set_info[parent_chunk_idx];
830 : 4591606 : auto& bottom_info = m_set_info[child_chunk_idx];
831 : :
832 : : // Consider the following example:
833 : : //
834 : : // A A There are two chunks, ABC and DEF, and the inactive E->C dependency
835 : : // / \ / \ is activated, resulting in a single chunk ABCDEF.
836 : : // B C B C
837 : : // : ==> | Dependency | top set before | top set after | change
838 : : // D E D E B->A | AC | ACDEF | +DEF
839 : : // \ / \ / C->A | AB | AB |
840 : : // F F F->D | D | D |
841 : : // F->E | E | ABCE | +ABC
842 : : //
843 : : // The common pattern here is that any dependency which has the parent or child of the
844 : : // dependency being activated (E->C here) in its top set, will have the opposite part added
845 : : // to it. This is true for B->A and F->E, but not for C->A and F->D.
846 : : //
847 : : // Traverse the old parent chunk top_info (ABC in example), and add bottom_info (DEF) to
848 : : // every dependency's top set which has the parent (C) in it. At the same time, change the
849 : : // chunk_idx for each to be child_chunk_idx, which becomes the set for the merged chunk.
850 [ + + + + ]: 45500505 : for (auto tx_idx : top_info.transactions) {
851 [ + + ]: 39211734 : auto& tx_data = m_tx_data[tx_idx];
852 : 39211734 : tx_data.chunk_idx = child_chunk_idx;
853 [ + + + + ]: 79507275 : for (auto dep_child_idx : tx_data.active_children) {
854 [ + + ]: 34620128 : auto& dep_top_info = m_set_info[tx_data.dep_top_idx[dep_child_idx]];
855 [ + + ]: 34620128 : if (dep_top_info.transactions[parent_idx]) dep_top_info |= bottom_info;
856 : : }
857 : : }
858 : : // Traverse the old child chunk bottom_info (DEF in example), and add top_info (ABC) to
859 : : // every dependency's top set which has the child (E) in it.
860 [ + + + + ]: 26352879 : for (auto tx_idx : bottom_info.transactions) {
861 [ + + ]: 20064108 : auto& tx_data = m_tx_data[tx_idx];
862 [ + + + + ]: 39253388 : for (auto dep_child_idx : tx_data.active_children) {
863 [ + + ]: 15472502 : auto& dep_top_info = m_set_info[tx_data.dep_top_idx[dep_child_idx]];
864 [ + + ]: 15472502 : if (dep_top_info.transactions[child_idx]) dep_top_info |= top_info;
865 : : }
866 : : }
867 : : // Merge top_info into bottom_info, which becomes the merged chunk.
868 : 4591606 : bottom_info |= top_info;
869 : : // Compute merged sets of reachable transactions from the new chunk, based on the input
870 : : // chunks' reachable sets.
871 : 4591606 : m_reachable[child_chunk_idx].first |= m_reachable[parent_chunk_idx].first;
872 : 4591606 : m_reachable[child_chunk_idx].second |= m_reachable[parent_chunk_idx].second;
873 : 4591606 : m_reachable[child_chunk_idx].first -= bottom_info.transactions;
874 : 4591606 : m_reachable[child_chunk_idx].second -= bottom_info.transactions;
875 : : // Make parent chunk the set for the new active dependency.
876 : 4591606 : parent_data.dep_top_idx[child_idx] = parent_chunk_idx;
877 : 4591606 : parent_data.active_children.Set(child_idx);
878 : 4591606 : m_chunk_idxs.Reset(parent_chunk_idx);
879 : : // Return the newly merged chunk.
880 : 4591606 : m_cost.ActivateEnd(/*num_deps=*/bottom_info.transactions.Count() - 1);
881 : 4591606 : return child_chunk_idx;
882 : : }
883 : :
884 : : /** Make a specified active dependency inactive. Returns the created parent and child chunk
885 : : * indexes. */
886 : 1311653 : std::pair<SetIdx, SetIdx> Deactivate(TxIdx parent_idx, TxIdx child_idx) noexcept
887 : : {
888 : : m_cost.DeactivateBegin();
889 : : // Gather and check information about the parent transactions.
890 : 1311653 : auto& parent_data = m_tx_data[parent_idx];
891 : 1311653 : Assume(parent_data.children[child_idx]);
892 : 1311653 : Assume(parent_data.active_children[child_idx]);
893 : : // Get the top set of the active dependency (which will become the parent chunk) and the
894 : : // chunk set the transactions are currently in (which will become the bottom chunk).
895 : 1311653 : auto parent_chunk_idx = parent_data.dep_top_idx[child_idx];
896 : 1311653 : auto child_chunk_idx = parent_data.chunk_idx;
897 : 1311653 : Assume(parent_chunk_idx != child_chunk_idx);
898 : 1311653 : Assume(m_chunk_idxs[child_chunk_idx]);
899 : 1311653 : Assume(!m_chunk_idxs[parent_chunk_idx]); // top set, not a chunk
900 : 1311653 : auto& top_info = m_set_info[parent_chunk_idx];
901 : 1311653 : auto& bottom_info = m_set_info[child_chunk_idx];
902 : :
903 : : // Remove the active dependency.
904 : 1311653 : parent_data.active_children.Reset(child_idx);
905 : 1311653 : m_chunk_idxs.Set(parent_chunk_idx);
906 : 1311653 : auto ntx = bottom_info.transactions.Count();
907 : : // Subtract the top_info from the bottom_info, as it will become the child chunk.
908 : 1311653 : bottom_info -= top_info;
909 : : // See the comment above in Activate(). We perform the opposite operations here, removing
910 : : // instead of adding. Simultaneously, aggregate the top/bottom's union of parents/children.
911 : 1311653 : SetType top_parents, top_children;
912 [ + + + + ]: 17737589 : for (auto tx_idx : top_info.transactions) {
913 [ + + ]: 15921124 : auto& tx_data = m_tx_data[tx_idx];
914 : 15921124 : tx_data.chunk_idx = parent_chunk_idx;
915 [ + + ]: 76347697 : top_parents |= tx_data.parents;
916 : 15921124 : top_children |= tx_data.children;
917 [ + + + + ]: 33349370 : for (auto dep_child_idx : tx_data.active_children) {
918 [ + + ]: 14609471 : auto& dep_top_info = m_set_info[tx_data.dep_top_idx[dep_child_idx]];
919 [ + + ]: 14609471 : if (dep_top_info.transactions[parent_idx]) dep_top_info -= bottom_info;
920 : : }
921 : : }
922 : 1311653 : SetType bottom_parents, bottom_children;
923 [ + + + + ]: 14225573 : for (auto tx_idx : bottom_info.transactions) {
924 [ + + ]: 12409108 : auto& tx_data = m_tx_data[tx_idx];
925 [ + + ]: 59742322 : bottom_parents |= tx_data.parents;
926 : 12409108 : bottom_children |= tx_data.children;
927 [ + + + + ]: 25919856 : for (auto dep_child_idx : tx_data.active_children) {
928 [ + + ]: 11097455 : auto& dep_top_info = m_set_info[tx_data.dep_top_idx[dep_child_idx]];
929 [ + + ]: 11097455 : if (dep_top_info.transactions[child_idx]) dep_top_info -= top_info;
930 : : }
931 : : }
932 : : // Compute the new sets of reachable transactions for each new chunk, based on the
933 : : // top/bottom parents and children computed above.
934 : 1311653 : m_reachable[parent_chunk_idx].first = top_parents - top_info.transactions;
935 : 1311653 : m_reachable[parent_chunk_idx].second = top_children - top_info.transactions;
936 : 1311653 : m_reachable[child_chunk_idx].first = bottom_parents - bottom_info.transactions;
937 : 1311653 : m_reachable[child_chunk_idx].second = bottom_children - bottom_info.transactions;
938 : : // Return the two new set idxs.
939 : 1311653 : m_cost.DeactivateEnd(/*num_deps=*/ntx - 1);
940 : 1311653 : return {parent_chunk_idx, child_chunk_idx};
941 : : }
942 : :
943 : : /** Activate a dependency from the bottom set to the top set, which must exist. Return the
944 : : * index of the merged chunk. */
945 : 4591606 : SetIdx MergeChunks(SetIdx top_idx, SetIdx bottom_idx) noexcept
946 : : {
947 : : m_cost.MergeChunksBegin();
948 [ + - ]: 4591606 : Assume(m_chunk_idxs[top_idx]);
949 : 4591606 : Assume(m_chunk_idxs[bottom_idx]);
950 [ + - ]: 4591606 : auto& top_chunk_info = m_set_info[top_idx];
951 : 4591606 : auto& bottom_chunk_info = m_set_info[bottom_idx];
952 : : // Count the number of dependencies between bottom_chunk and top_chunk.
953 : 4591606 : unsigned num_deps{0};
954 [ + + + + ]: 45500505 : for (auto tx_idx : top_chunk_info.transactions) {
955 : 39211734 : auto& tx_data = m_tx_data[tx_idx];
956 : 39211734 : num_deps += (tx_data.children & bottom_chunk_info.transactions).Count();
957 : : }
958 : 4591606 : m_cost.MergeChunksMid(/*num_txns=*/top_chunk_info.transactions.Count());
959 : 4591606 : Assume(num_deps > 0);
960 : : // Uniformly randomly pick one of them and activate it.
961 : 4591606 : unsigned pick = m_rng.randrange(num_deps);
962 : 4591606 : unsigned num_steps = 0;
963 [ + - + - ]: 18142365 : for (auto tx_idx : top_chunk_info.transactions) {
964 : 16445200 : ++num_steps;
965 [ + + ]: 16445200 : auto& tx_data = m_tx_data[tx_idx];
966 [ + + ]: 16445200 : auto intersect = tx_data.children & bottom_chunk_info.transactions;
967 : 16445200 : auto count = intersect.Count();
968 [ + + ]: 16445200 : if (pick < count) {
969 [ + - + - ]: 7703290 : for (auto child_idx : intersect) {
970 [ + + ]: 6006125 : if (pick == 0) {
971 : 4591606 : m_cost.MergeChunksEnd(/*num_steps=*/num_steps);
972 : 4591606 : return Activate(tx_idx, child_idx);
973 : : }
974 : 1414519 : --pick;
975 : : }
976 : 0 : Assume(false);
977 : : break;
978 : : }
979 : 11853594 : pick -= count;
980 : : }
981 : 0 : Assume(false);
982 : 0 : return INVALID_SET_IDX;
983 : : }
984 : :
985 : : /** Activate a dependency from chunk_idx to merge_chunk_idx (if !DownWard), or a dependency
986 : : * from merge_chunk_idx to chunk_idx (if DownWard). Return the index of the merged chunk. */
987 : : template<bool DownWard>
988 : 3784400 : SetIdx MergeChunksDirected(SetIdx chunk_idx, SetIdx merge_chunk_idx) noexcept
989 : : {
990 : : if constexpr (DownWard) {
991 : 483683 : return MergeChunks(chunk_idx, merge_chunk_idx);
992 : : } else {
993 : 3300717 : return MergeChunks(merge_chunk_idx, chunk_idx);
994 : : }
995 : : }
996 : :
997 : : /** Determine which chunk to merge chunk_idx with, or INVALID_SET_IDX if none. */
998 : : template<bool DownWard>
999 : 9217112 : SetIdx PickMergeCandidate(SetIdx chunk_idx) noexcept
1000 : : {
1001 : : m_cost.PickMergeCandidateBegin();
1002 : : /** Information about the chunk. */
1003 : 9217112 : Assume(m_chunk_idxs[chunk_idx]);
1004 : 9217112 : auto& chunk_info = m_set_info[chunk_idx];
1005 : : // Iterate over all chunks reachable from this one. For those depended-on chunks,
1006 : : // remember the highest-feerate (if DownWard) or lowest-feerate (if !DownWard) one.
1007 : : // If multiple equal-feerate candidate chunks to merge with exist, pick a random one
1008 : : // among them.
1009 : :
1010 : : /** The minimum feerate (if downward) or maximum feerate (if upward) to consider when
1011 : : * looking for candidate chunks to merge with. Initially, this is the original chunk's
1012 : : * feerate, but is updated to be the current best candidate whenever one is found. */
1013 : 9217112 : FeeFrac best_other_chunk_feerate = chunk_info.feerate;
1014 : : /** The chunk index for the best candidate chunk to merge with. INVALID_SET_IDX if none. */
1015 : 9217112 : SetIdx best_other_chunk_idx = INVALID_SET_IDX;
1016 : : /** We generate random tiebreak values to pick between equal-feerate candidate chunks.
1017 : : * This variable stores the tiebreak of the current best candidate. */
1018 : 9217112 : uint64_t best_other_chunk_tiebreak{0};
1019 : :
1020 : : /** Which parent/child transactions we still need to process the chunks for. */
1021 : 9217112 : auto todo = DownWard ? m_reachable[chunk_idx].second : m_reachable[chunk_idx].first;
1022 : 9217112 : unsigned steps = 0;
1023 [ + + ]: 58019486 : while (todo.Any()) {
1024 : 26098873 : ++steps;
1025 : : // Find a chunk for a transaction in todo, and remove all its transactions from todo.
1026 [ + + ]: 26098873 : auto reached_chunk_idx = m_tx_data[todo.First()].chunk_idx;
1027 : 26098873 : auto& reached_chunk_info = m_set_info[reached_chunk_idx];
1028 [ + + ]: 26098873 : todo -= reached_chunk_info.transactions;
1029 : : // See if it has an acceptable feerate.
1030 [ + + ]: 5113072 : auto cmp = DownWard ? FeeRateCompare(best_other_chunk_feerate, reached_chunk_info.feerate)
1031 [ + + ]: 20985801 : : FeeRateCompare(reached_chunk_info.feerate, best_other_chunk_feerate);
1032 [ + + ]: 26098873 : if (cmp > 0) continue;
1033 [ + + ]: 6898246 : uint64_t tiebreak = m_rng.rand64();
1034 [ + + + + ]: 6898246 : if (cmp < 0 || tiebreak >= best_other_chunk_tiebreak) {
1035 : 5262734 : best_other_chunk_feerate = reached_chunk_info.feerate;
1036 : 5262734 : best_other_chunk_idx = reached_chunk_idx;
1037 : 5262734 : best_other_chunk_tiebreak = tiebreak;
1038 : : }
1039 : : }
1040 [ - + ]: 9217112 : Assume(steps <= m_set_info.size());
1041 : :
1042 : 9217112 : m_cost.PickMergeCandidateEnd(/*num_steps=*/steps);
1043 : 9217112 : return best_other_chunk_idx;
1044 : : }
1045 : :
1046 : : /** Perform an upward or downward merge step, on the specified chunk. Returns the merged chunk,
1047 : : * or INVALID_SET_IDX if no merge took place. */
1048 : : template<bool DownWard>
1049 : 9217112 : SetIdx MergeStep(SetIdx chunk_idx) noexcept
1050 : : {
1051 : 9217112 : auto merge_chunk_idx = PickMergeCandidate<DownWard>(chunk_idx);
1052 [ + + ]: 9217112 : if (merge_chunk_idx == INVALID_SET_IDX) return INVALID_SET_IDX;
1053 : 3784400 : chunk_idx = MergeChunksDirected<DownWard>(chunk_idx, merge_chunk_idx);
1054 : 3784400 : Assume(chunk_idx != INVALID_SET_IDX);
1055 : 3784400 : return chunk_idx;
1056 : : }
1057 : :
1058 : : /** Perform an upward or downward merge sequence on the specified chunk. */
1059 : : template<bool DownWard>
1060 : 436272 : void MergeSequence(SetIdx chunk_idx) noexcept
1061 : : {
1062 : 436272 : Assume(m_chunk_idxs[chunk_idx]);
1063 : 49056 : while (true) {
1064 : 485328 : auto merged_chunk_idx = MergeStep<DownWard>(chunk_idx);
1065 [ + + ]: 485328 : if (merged_chunk_idx == INVALID_SET_IDX) break;
1066 : 49056 : chunk_idx = merged_chunk_idx;
1067 : : }
1068 : : // Add the chunk to the queue of improvable chunks, if it wasn't already there.
1069 [ + + ]: 436272 : if (!m_suboptimal_idxs[chunk_idx]) {
1070 : 424196 : m_suboptimal_idxs.Set(chunk_idx);
1071 : 424196 : m_suboptimal_chunks.push_back(chunk_idx);
1072 : : }
1073 : 436272 : }
1074 : :
1075 : : /** Split a chunk, and then merge the resulting two chunks to make the graph topological
1076 : : * again. */
1077 : 1024685 : void Improve(TxIdx parent_idx, TxIdx child_idx) noexcept
1078 : : {
1079 : : // Deactivate the specified dependency, splitting it into two new chunks: a top containing
1080 : : // the parent, and a bottom containing the child. The top should have a higher feerate.
1081 [ + + ]: 1024685 : auto [parent_chunk_idx, child_chunk_idx] = Deactivate(parent_idx, child_idx);
1082 : :
1083 : : // At this point we have exactly two chunks which may violate topology constraints (the
1084 : : // parent chunk and child chunk that were produced by deactivation). We can fix
1085 : : // these using just merge sequences, one upwards and one downwards, avoiding the need for a
1086 : : // full MakeTopological.
1087 [ + + ]: 1024685 : const auto& parent_reachable = m_reachable[parent_chunk_idx].first;
1088 [ + + ]: 1024685 : const auto& child_chunk_txn = m_set_info[child_chunk_idx].transactions;
1089 [ + + ]: 1024685 : if (parent_reachable.Overlaps(child_chunk_txn)) {
1090 : : // The parent chunk has a dependency on a transaction in the child chunk. In this case,
1091 : : // the parent needs to merge back with the child chunk (a self-merge), and no other
1092 : : // merges are needed. Special-case this, so the overhead of PickMergeCandidate and
1093 : : // MergeSequence can be avoided.
1094 : :
1095 : : // In the self-merge, the roles reverse: the parent chunk (from the split) depends
1096 : : // on the child chunk, so child_chunk_idx is the "top" and parent_chunk_idx is the
1097 : : // "bottom" for MergeChunks.
1098 : 806549 : auto merged_chunk_idx = MergeChunks(child_chunk_idx, parent_chunk_idx);
1099 [ + - ]: 806549 : if (!m_suboptimal_idxs[merged_chunk_idx]) {
1100 : 806549 : m_suboptimal_idxs.Set(merged_chunk_idx);
1101 : 806549 : m_suboptimal_chunks.push_back(merged_chunk_idx);
1102 : : }
1103 : : } else {
1104 : : // Merge the top chunk with lower-feerate chunks it depends on.
1105 : 218136 : MergeSequence<false>(parent_chunk_idx);
1106 : : // Merge the bottom chunk with higher-feerate chunks that depend on it.
1107 : 218136 : MergeSequence<true>(child_chunk_idx);
1108 : : }
1109 : 1024685 : }
1110 : :
1111 : : /** Determine the next chunk to optimize, or INVALID_SET_IDX if none. */
1112 : 2560287 : SetIdx PickChunkToOptimize() noexcept
1113 : : {
1114 : : m_cost.PickChunkToOptimizeBegin();
1115 : 2560287 : unsigned steps{0};
1116 [ + - ]: 2567296 : while (!m_suboptimal_chunks.empty()) {
1117 : 2567296 : ++steps;
1118 : : // Pop an entry from the potentially-suboptimal chunk queue.
1119 : 2567296 : SetIdx chunk_idx = m_suboptimal_chunks.front();
1120 : 2567296 : Assume(m_suboptimal_idxs[chunk_idx]);
1121 : 2567296 : m_suboptimal_idxs.Reset(chunk_idx);
1122 : 2567296 : m_suboptimal_chunks.pop_front();
1123 [ + + ]: 2567296 : if (m_chunk_idxs[chunk_idx]) {
1124 : 2560287 : m_cost.PickChunkToOptimizeEnd(/*num_steps=*/steps);
1125 : 2560287 : return chunk_idx;
1126 : : }
1127 : : // If what was popped is not currently a chunk, continue. This may
1128 : : // happen when a split chunk merges in Improve() with one or more existing chunks that
1129 : : // are themselves on the suboptimal queue already.
1130 : : }
1131 : 0 : m_cost.PickChunkToOptimizeEnd(/*num_steps=*/steps);
1132 : 0 : return INVALID_SET_IDX;
1133 : : }
1134 : :
1135 : : /** Find a (parent, child) dependency to deactivate in chunk_idx, or (-1, -1) if none. */
1136 : 2560287 : std::pair<TxIdx, TxIdx> PickDependencyToSplit(SetIdx chunk_idx) noexcept
1137 : : {
1138 : : m_cost.PickDependencyToSplitBegin();
1139 [ + - ]: 2560287 : Assume(m_chunk_idxs[chunk_idx]);
1140 [ + - ]: 2560287 : auto& chunk_info = m_set_info[chunk_idx];
1141 : :
1142 : : // Remember the best dependency {par, chl} seen so far.
1143 : 2560287 : std::pair<TxIdx, TxIdx> candidate_dep = {TxIdx(-1), TxIdx(-1)};
1144 : 2560287 : uint64_t candidate_tiebreak = 0;
1145 : : // Iterate over all transactions.
1146 [ + + + + ]: 33780523 : for (auto tx_idx : chunk_info.transactions) {
1147 [ + + ]: 30300018 : const auto& tx_data = m_tx_data[tx_idx];
1148 : : // Iterate over all active child dependencies of the transaction.
1149 [ + + + + ]: 63677564 : for (auto child_idx : tx_data.active_children) {
1150 [ + + ]: 27739731 : auto& dep_top_info = m_set_info[tx_data.dep_top_idx[child_idx]];
1151 : : // Skip if this dependency is ineligible (the top chunk that would be created
1152 : : // does not have higher feerate than the chunk it is currently part of).
1153 [ + + ]: 27739731 : auto cmp = FeeRateCompare(dep_top_info.feerate, chunk_info.feerate);
1154 [ + + ]: 27739731 : if (cmp <= 0) continue;
1155 : : // Generate a random tiebreak for this dependency, and reject it if its tiebreak
1156 : : // is worse than the best so far. This means that among all eligible
1157 : : // dependencies, a uniformly random one will be chosen.
1158 : 4431778 : uint64_t tiebreak = m_rng.rand64();
1159 [ + + ]: 4431778 : if (tiebreak < candidate_tiebreak) continue;
1160 : : // Remember this as our (new) candidate dependency.
1161 : 1981229 : candidate_dep = {tx_idx, child_idx};
1162 : 1981229 : candidate_tiebreak = tiebreak;
1163 : : }
1164 : : }
1165 : 2560287 : m_cost.PickDependencyToSplitEnd(/*num_txns=*/chunk_info.transactions.Count());
1166 : 2560287 : return candidate_dep;
1167 : : }
1168 : :
1169 : : public:
1170 : : /** Construct a spanning forest for the given DepGraph, with every transaction in its own chunk
1171 : : * (not topological). */
1172 : 191464 : explicit SpanningForestState(const DepGraph<SetType>& depgraph LIFETIMEBOUND, uint64_t rng_seed, const CostModel& cost = CostModel{}) noexcept :
1173 [ - + ]: 191464 : m_rng(rng_seed), m_depgraph(depgraph), m_cost(cost)
1174 : : {
1175 : 191464 : m_cost.InitializeBegin();
1176 : 191464 : m_transaction_idxs = depgraph.Positions();
1177 [ - + ]: 191464 : auto num_transactions = m_transaction_idxs.Count();
1178 [ - + ]: 191464 : m_tx_data.resize(depgraph.PositionRange());
1179 : 191464 : m_set_info.resize(num_transactions);
1180 : 191464 : m_reachable.resize(num_transactions);
1181 : 191464 : size_t num_chunks = 0;
1182 : 191464 : size_t num_deps = 0;
1183 [ + + + + ]: 5339023 : for (auto tx_idx : m_transaction_idxs) {
1184 : : // Fill in transaction data.
1185 : 5071895 : auto& tx_data = m_tx_data[tx_idx];
1186 : 5071895 : tx_data.parents = depgraph.GetReducedParents(tx_idx);
1187 [ + + + + ]: 21591157 : for (auto parent_idx : tx_data.parents) {
1188 : 15033243 : m_tx_data[parent_idx].children.Set(tx_idx);
1189 : : }
1190 : 5071895 : num_deps += tx_data.parents.Count();
1191 : : // Create a singleton chunk for it.
1192 : 5071895 : tx_data.chunk_idx = num_chunks;
1193 : 5071895 : m_set_info[num_chunks++] = SetInfo(depgraph, tx_idx);
1194 : : }
1195 : : // Set the reachable transactions for each chunk to the transactions' parents and children.
1196 [ + + ]: 5263359 : for (SetIdx chunk_idx = 0; chunk_idx < num_transactions; ++chunk_idx) {
1197 [ + - ]: 6948790 : auto& tx_data = m_tx_data[m_set_info[chunk_idx].transactions.First()];
1198 : 5071895 : m_reachable[chunk_idx].first = tx_data.parents;
1199 : 5071895 : m_reachable[chunk_idx].second = tx_data.children;
1200 : : }
1201 : 191464 : Assume(num_chunks == num_transactions);
1202 : : // Mark all chunk sets as chunks.
1203 : 191464 : m_chunk_idxs = SetType::Fill(num_chunks);
1204 : 191464 : m_cost.InitializeEnd(/*num_txns=*/num_chunks, /*num_deps=*/num_deps);
1205 : 191464 : }
1206 : :
1207 : : /** Load an existing linearization. Must be called immediately after constructor. The result is
1208 : : * topological if the linearization is valid. Otherwise, MakeTopological still needs to be
1209 : : * called. */
1210 : 144732 : void LoadLinearization(std::span<const DepGraphIndex> old_linearization) noexcept
1211 : : {
1212 : : // Add transactions one by one, in order of existing linearization.
1213 [ + + ]: 3959652 : for (DepGraphIndex tx_idx : old_linearization) {
1214 : 3814920 : auto chunk_idx = m_tx_data[tx_idx].chunk_idx;
1215 : : // Merge the chunk upwards, as long as merging succeeds.
1216 : : while (true) {
1217 : 6596109 : chunk_idx = MergeStep<false>(chunk_idx);
1218 [ + + ]: 6596109 : if (chunk_idx == INVALID_SET_IDX) break;
1219 : : }
1220 : : }
1221 : 144732 : }
1222 : :
1223 : : /** Make state topological. Can be called after constructing, or after LoadLinearization. */
1224 : 98644 : void MakeTopological() noexcept
1225 : : {
1226 : : m_cost.MakeTopologicalBegin();
1227 : 98644 : Assume(m_suboptimal_chunks.empty());
1228 : : /** What direction to initially merge chunks in; one of the two directions is enough. This
1229 : : * is sufficient because if a non-topological inactive dependency exists between two
1230 : : * chunks, at least one of the two chunks will eventually be processed in a direction that
1231 : : * discovers it - either the lower chunk tries upward, or the upper chunk tries downward.
1232 : : * Chunks that are the result of the merging are always tried in both directions. */
1233 : 98644 : unsigned init_dir = m_rng.randbool();
1234 : : /** Which chunks are the result of merging, and thus need merge attempts in both
1235 : : * directions. */
1236 : 98644 : SetType merged_chunks;
1237 : : // Mark chunks as suboptimal.
1238 : 98644 : m_suboptimal_idxs = m_chunk_idxs;
1239 [ + + + + ]: 1735955 : for (auto chunk_idx : m_chunk_idxs) {
1240 : 1596659 : m_suboptimal_chunks.emplace_back(chunk_idx);
1241 : : // Randomize the initial order of suboptimal chunks in the queue.
1242 : 1596659 : SetIdx j = m_rng.randrange<SetIdx>(m_suboptimal_chunks.size());
1243 [ + + ]: 1596659 : if (j != m_suboptimal_chunks.size() - 1) {
1244 : 1322438 : std::swap(m_suboptimal_chunks.back(), m_suboptimal_chunks[j]);
1245 : : }
1246 : : }
1247 : 98644 : unsigned chunks = m_chunk_idxs.Count();
1248 : 98644 : unsigned steps = 0;
1249 [ + + ]: 2400629 : while (!m_suboptimal_chunks.empty()) {
1250 : 2301985 : ++steps;
1251 : : // Pop an entry from the potentially-suboptimal chunk queue.
1252 : 2301985 : SetIdx chunk_idx = m_suboptimal_chunks.front();
1253 : 2301985 : m_suboptimal_chunks.pop_front();
1254 [ + + ]: 2301985 : Assume(m_suboptimal_idxs[chunk_idx]);
1255 [ + + ]: 2301985 : m_suboptimal_idxs.Reset(chunk_idx);
1256 : : // If what was popped is not currently a chunk, continue. This may
1257 : : // happen when it was merged with something else since being added.
1258 [ + + ]: 2301985 : if (!m_chunk_idxs[chunk_idx]) continue;
1259 : : /** What direction(s) to attempt merging in. 1=up, 2=down, 3=both. */
1260 [ + + ]: 1888984 : unsigned direction = merged_chunks[chunk_idx] ? 3 : init_dir + 1;
1261 : 1888984 : int flip = m_rng.randbool();
1262 [ + + ]: 4182177 : for (int i = 0; i < 2; ++i) {
1263 [ + + ]: 3247348 : if (i ^ flip) {
1264 [ + + ]: 1636090 : if (!(direction & 1)) continue;
1265 : : // Attempt to merge the chunk upwards.
1266 : 1057425 : auto result_up = MergeStep<false>(chunk_idx);
1267 [ + + ]: 1057425 : if (result_up != INVALID_SET_IDX) {
1268 [ + - ]: 501988 : if (!m_suboptimal_idxs[result_up]) {
1269 : 501988 : m_suboptimal_idxs.Set(result_up);
1270 : 501988 : m_suboptimal_chunks.push_back(result_up);
1271 : : }
1272 : 501988 : merged_chunks.Set(result_up);
1273 : 320326 : break;
1274 : : }
1275 : : } else {
1276 [ + + ]: 1611258 : if (!(direction & 2)) continue;
1277 : : // Attempt to merge the chunk downwards.
1278 : 1078250 : auto result_down = MergeStep<true>(chunk_idx);
1279 [ + + ]: 1078250 : if (result_down != INVALID_SET_IDX) {
1280 [ + + ]: 452167 : if (!m_suboptimal_idxs[result_down]) {
1281 : 203338 : m_suboptimal_idxs.Set(result_down);
1282 : 203338 : m_suboptimal_chunks.push_back(result_down);
1283 : : }
1284 : 452167 : merged_chunks.Set(result_down);
1285 : 288819 : break;
1286 : : }
1287 : : }
1288 : : }
1289 : : }
1290 : 98644 : m_cost.MakeTopologicalEnd(/*num_chunks=*/chunks, /*num_steps=*/steps);
1291 : 98644 : }
1292 : :
1293 : : /** Initialize the data structure for optimization. It must be topological already. */
1294 : 191464 : void StartOptimizing() noexcept
1295 : : {
1296 : : m_cost.StartOptimizingBegin();
1297 [ + - ]: 191464 : Assume(m_suboptimal_chunks.empty());
1298 : : // Mark chunks suboptimal.
1299 : 191464 : m_suboptimal_idxs = m_chunk_idxs;
1300 [ + + + + ]: 1603679 : for (auto chunk_idx : m_chunk_idxs) {
1301 : 1336551 : m_suboptimal_chunks.push_back(chunk_idx);
1302 : : // Randomize the initial order of suboptimal chunks in the queue.
1303 : 1336551 : SetIdx j = m_rng.randrange<SetIdx>(m_suboptimal_chunks.size());
1304 [ + + ]: 1336551 : if (j != m_suboptimal_chunks.size() - 1) {
1305 : 950435 : std::swap(m_suboptimal_chunks.back(), m_suboptimal_chunks[j]);
1306 : : }
1307 : : }
1308 : 191464 : m_cost.StartOptimizingEnd(/*num_chunks=*/m_suboptimal_chunks.size());
1309 : 191464 : }
1310 : :
1311 : : /** Try to improve the forest. Returns false if it is optimal, true otherwise. */
1312 : 2560287 : bool OptimizeStep() noexcept
1313 : : {
1314 : 2560287 : auto chunk_idx = PickChunkToOptimize();
1315 [ + - ]: 2560287 : if (chunk_idx == INVALID_SET_IDX) {
1316 : : // No improvable chunk was found, we are done.
1317 : : return false;
1318 : : }
1319 [ + + ]: 2560287 : auto [parent_idx, child_idx] = PickDependencyToSplit(chunk_idx);
1320 [ + + ]: 2560287 : if (parent_idx == TxIdx(-1)) {
1321 : : // Nothing to improve in chunk_idx. Need to continue with other chunks, if any.
1322 : 1535602 : return !m_suboptimal_chunks.empty();
1323 : : }
1324 : : // Deactivate the found dependency and then make the state topological again with a
1325 : : // sequence of merges.
1326 : 1024685 : Improve(parent_idx, child_idx);
1327 : 1024685 : return true;
1328 : : }
1329 : :
1330 : : /** Initialize data structure for minimizing the chunks. Can only be called if state is known
1331 : : * to be optimal. OptimizeStep() cannot be called anymore afterwards. */
1332 : 191464 : void StartMinimizing() noexcept
1333 : : {
1334 : : m_cost.StartMinimizingBegin();
1335 [ + - ]: 191464 : m_nonminimal_chunks.clear();
1336 [ + - ]: 191464 : m_nonminimal_chunks.reserve(m_transaction_idxs.Count());
1337 : : // Gather all chunks, and for each, add it with a random pivot in it, and a random initial
1338 : : // direction, to m_nonminimal_chunks.
1339 [ + + + + ]: 1772759 : for (auto chunk_idx : m_chunk_idxs) {
1340 : 1505631 : TxIdx pivot_idx = PickRandomTx(m_set_info[chunk_idx].transactions);
1341 : 1505631 : m_nonminimal_chunks.emplace_back(chunk_idx, pivot_idx, m_rng.randbits<1>());
1342 : : // Randomize the initial order of nonminimal chunks in the queue.
1343 : 1505631 : SetIdx j = m_rng.randrange<SetIdx>(m_nonminimal_chunks.size());
1344 [ + + ]: 1505631 : if (j != m_nonminimal_chunks.size() - 1) {
1345 : 1104648 : std::swap(m_nonminimal_chunks.back(), m_nonminimal_chunks[j]);
1346 : : }
1347 : : }
1348 : 191464 : m_cost.StartMinimizingEnd(/*num_chunks=*/m_nonminimal_chunks.size());
1349 : 191464 : }
1350 : :
1351 : : /** Try to reduce a chunk's size. Returns false if all chunks are minimal, true otherwise. */
1352 : 2321337 : bool MinimizeStep() noexcept
1353 : : {
1354 : : // If the queue of potentially-non-minimal chunks is empty, we are done.
1355 [ + + ]: 2321337 : if (m_nonminimal_chunks.empty()) return false;
1356 : : m_cost.MinimizeStepBegin();
1357 : : // Pop an entry from the potentially-non-minimal chunk queue.
1358 : 2129873 : auto [chunk_idx, pivot_idx, flags] = m_nonminimal_chunks.front();
1359 : 2129873 : m_nonminimal_chunks.pop_front();
1360 [ + - ]: 2129873 : auto& chunk_info = m_set_info[chunk_idx];
1361 : : /** Whether to move the pivot down rather than up. */
1362 : 2129873 : bool move_pivot_down = flags & 1;
1363 : : /** Whether this is already the second stage. */
1364 : 2129873 : bool second_stage = flags & 2;
1365 : :
1366 : : // Find a random dependency whose top and bottom set feerates are equal, and which has
1367 : : // pivot in bottom set (if move_pivot_down) or in top set (if !move_pivot_down).
1368 : 2129873 : std::pair<TxIdx, TxIdx> candidate_dep;
1369 : 2129873 : uint64_t candidate_tiebreak{0};
1370 : 2129873 : bool have_any = false;
1371 : : // Iterate over all transactions.
1372 [ + + + + ]: 11440731 : for (auto tx_idx : chunk_info.transactions) {
1373 [ + + ]: 8457948 : const auto& tx_data = m_tx_data[tx_idx];
1374 : : // Iterate over all active child dependencies of the transaction.
1375 [ + + + + ]: 15988293 : for (auto child_idx : tx_data.active_children) {
1376 [ + + ]: 6328075 : const auto& dep_top_info = m_set_info[tx_data.dep_top_idx[child_idx]];
1377 : : // Skip if this dependency does not have equal top and bottom set feerates. Note
1378 : : // that the top cannot have higher feerate than the bottom, or OptimizeSteps would
1379 : : // have dealt with it.
1380 [ + + ]: 6328075 : if (dep_top_info.feerate << chunk_info.feerate) continue;
1381 : 3048110 : have_any = true;
1382 : : // Skip if this dependency does not have pivot in the right place.
1383 [ + + ]: 3048110 : if (move_pivot_down == dep_top_info.transactions[pivot_idx]) continue;
1384 : : // Remember this as our chosen dependency if it has a better tiebreak.
1385 : 2407103 : uint64_t tiebreak = m_rng.rand64() | 1;
1386 [ + + ]: 2407103 : if (tiebreak > candidate_tiebreak) {
1387 : 622384 : candidate_tiebreak = tiebreak;
1388 : 622384 : candidate_dep = {tx_idx, child_idx};
1389 : : }
1390 : : }
1391 : : }
1392 [ + + ]: 2129873 : m_cost.MinimizeStepMid(/*num_txns=*/chunk_info.transactions.Count());
1393 : : // If no dependencies have equal top and bottom set feerate, this chunk is minimal.
1394 [ + + ]: 2129873 : if (!have_any) return true;
1395 : : // If all found dependencies have the pivot in the wrong place, try moving it in the other
1396 : : // direction. If this was the second stage already, we are done.
1397 [ + + ]: 337931 : if (candidate_tiebreak == 0) {
1398 : : // Switch to other direction, and to second phase.
1399 : 50963 : flags ^= 3;
1400 [ + - ]: 50963 : if (!second_stage) m_nonminimal_chunks.emplace_back(chunk_idx, pivot_idx, flags);
1401 : 50963 : return true;
1402 : : }
1403 : :
1404 : : // Otherwise, deactivate the dependency that was found.
1405 [ + + ]: 286968 : auto [parent_chunk_idx, child_chunk_idx] = Deactivate(candidate_dep.first, candidate_dep.second);
1406 : : // Determine if there is a dependency from the new bottom to the new top (opposite from the
1407 : : // dependency that was just deactivated).
1408 [ + + ]: 286968 : auto& parent_reachable = m_reachable[parent_chunk_idx].first;
1409 [ + + ]: 286968 : auto& child_chunk_txn = m_set_info[child_chunk_idx].transactions;
1410 [ + + ]: 286968 : if (parent_reachable.Overlaps(child_chunk_txn)) {
1411 : : // A self-merge is needed. Note that the child_chunk_idx is the top, and
1412 : : // parent_chunk_idx is the bottom, because we activate a dependency in the reverse
1413 : : // direction compared to the deactivation above.
1414 : 657 : auto merged_chunk_idx = MergeChunks(child_chunk_idx, parent_chunk_idx);
1415 : : // Re-insert the chunk into the queue, in the same direction. Note that the chunk_idx
1416 : : // will have changed.
1417 : 657 : m_nonminimal_chunks.emplace_back(merged_chunk_idx, pivot_idx, flags);
1418 : 657 : m_cost.MinimizeStepEnd(/*split=*/false);
1419 : : } else {
1420 : : // No self-merge happens, and thus we have found a way to split the chunk. Create two
1421 : : // smaller chunks, and add them to the queue. The one that contains the current pivot
1422 : : // gets to continue with it in the same direction, to minimize the number of times we
1423 : : // alternate direction. If we were in the second phase already, the newly created chunk
1424 : : // inherits that too, because we know no split with the pivot on the other side is
1425 : : // possible already. The new chunk without the current pivot gets a new randomly-chosen
1426 : : // one.
1427 [ + + ]: 286311 : if (move_pivot_down) {
1428 : 80006 : auto parent_pivot_idx = PickRandomTx(m_set_info[parent_chunk_idx].transactions);
1429 : 80006 : m_nonminimal_chunks.emplace_back(parent_chunk_idx, parent_pivot_idx, m_rng.randbits<1>());
1430 : 80006 : m_nonminimal_chunks.emplace_back(child_chunk_idx, pivot_idx, flags);
1431 : : } else {
1432 : 206305 : auto child_pivot_idx = PickRandomTx(m_set_info[child_chunk_idx].transactions);
1433 : 206305 : m_nonminimal_chunks.emplace_back(parent_chunk_idx, pivot_idx, flags);
1434 : 206305 : m_nonminimal_chunks.emplace_back(child_chunk_idx, child_pivot_idx, m_rng.randbits<1>());
1435 : : }
1436 [ + + ]: 286311 : if (m_rng.randbool()) {
1437 : 142766 : std::swap(m_nonminimal_chunks.back(), m_nonminimal_chunks[m_nonminimal_chunks.size() - 2]);
1438 : : }
1439 : 286311 : m_cost.MinimizeStepEnd(/*split=*/true);
1440 : : }
1441 : : return true;
1442 : : }
1443 : :
1444 : : /** Construct a topologically-valid linearization from the current forest state. Must be
1445 : : * topological. fallback_order is a comparator that defines a strong order for DepGraphIndexes
1446 : : * in this cluster, used to order equal-feerate transactions and chunks.
1447 : : *
1448 : : * Specifically, the resulting order consists of:
1449 : : * - The chunks of the current SFL state, sorted by (in decreasing order of priority):
1450 : : * - topology (parents before children)
1451 : : * - highest chunk feerate first
1452 : : * - smallest chunk size first
1453 : : * - the chunk with the lowest maximum transaction, by fallback_order, first
1454 : : * - The transactions within a chunk, sorted by (in decreasing order of priority):
1455 : : * - topology (parents before children)
1456 : : * - highest tx feerate first
1457 : : * - smallest tx size first
1458 : : * - the lowest transaction, by fallback_order, first
1459 : : */
1460 : 191464 : std::vector<DepGraphIndex> GetLinearization(const StrongComparator<DepGraphIndex> auto& fallback_order) noexcept
1461 : : {
1462 : : m_cost.GetLinearizationBegin();
1463 : : /** The output linearization. */
1464 : 191464 : std::vector<DepGraphIndex> ret;
1465 [ - + ]: 191464 : ret.reserve(m_set_info.size());
1466 : : /** A heap with all chunks (by set index) that can currently be included, sorted by
1467 : : * chunk feerate (high to low), chunk size (small to large), and by least maximum element
1468 : : * according to the fallback order (which is the second pair element). */
1469 : 191464 : std::vector<std::pair<SetIdx, TxIdx>> ready_chunks;
1470 : : /** For every chunk, indexed by SetIdx, the number of unmet dependencies the chunk has on
1471 : : * other chunks (not including dependencies within the chunk itself). */
1472 [ - + - + ]: 191464 : std::vector<TxIdx> chunk_deps(m_set_info.size(), 0);
1473 : : /** For every transaction, indexed by TxIdx, the number of unmet dependencies the
1474 : : * transaction has. */
1475 [ - + + - ]: 191464 : std::vector<TxIdx> tx_deps(m_tx_data.size(), 0);
1476 : : /** A heap with all transactions within the current chunk that can be included, sorted by
1477 : : * tx feerate (high to low), tx size (small to large), and fallback order. */
1478 : 191464 : std::vector<TxIdx> ready_tx;
1479 : : // Populate chunk_deps and tx_deps.
1480 : 191464 : unsigned num_deps{0};
1481 [ + + + + ]: 5339023 : for (TxIdx chl_idx : m_transaction_idxs) {
1482 : 5071895 : const auto& chl_data = m_tx_data[chl_idx];
1483 : 5071895 : tx_deps[chl_idx] = chl_data.parents.Count();
1484 : 5071895 : num_deps += tx_deps[chl_idx];
1485 : 5071895 : auto chl_chunk_idx = chl_data.chunk_idx;
1486 : 5071895 : auto& chl_chunk_info = m_set_info[chl_chunk_idx];
1487 : 5071895 : chunk_deps[chl_chunk_idx] += (chl_data.parents - chl_chunk_info.transactions).Count();
1488 : : }
1489 : : /** Function to compute the highest element of a chunk, by fallback_order. */
1490 : 1983406 : auto max_fallback_fn = [&](SetIdx chunk_idx) noexcept {
1491 [ + - ]: 1791942 : auto& chunk = m_set_info[chunk_idx].transactions;
[ + - + - ]
1492 : 1791942 : auto it = chunk.begin();
1493 : 1791942 : DepGraphIndex ret = *it;
1494 : 1791942 : ++it;
1495 [ + + ][ + + : 5071895 : while (it != chunk.end()) {
+ + + + +
+ + + ]
1496 [ + + ][ + - : 6552553 : if (fallback_order(*it, ret) > 0) ret = *it;
+ - + - +
- + - + -
+ - + - +
- + - ]
1497 : 3279953 : ++it;
1498 : : }
1499 : 1791942 : return ret;
1500 : : };
1501 : : /** Comparison function for the transaction heap. Note that it is a max-heap, so
1502 : : * tx_cmp_fn(a, b) == true means "a appears after b in the linearization". */
1503 : 8773768 : auto tx_cmp_fn = [&](const auto& a, const auto& b) noexcept {
1504 : : // Bail out for identical transactions.
1505 [ + - ][ + - : 8582304 : if (a == b) return false;
+ - + - +
- + - ]
1506 : : // First sort by increasing transaction feerate.
1507 [ + + ][ + + : 8582304 : auto& a_feerate = m_depgraph.FeeRate(a);
+ + + + +
+ + + ]
1508 : 8582304 : auto& b_feerate = m_depgraph.FeeRate(b);
1509 [ + + ][ + + : 8582304 : auto feerate_cmp = FeeRateCompare(a_feerate, b_feerate);
+ + + + +
+ + + ]
1510 [ + + ][ + + : 8582304 : if (feerate_cmp != 0) return feerate_cmp < 0;
+ + + + +
+ + + ]
1511 : : // Then by decreasing transaction size.
1512 [ - + ][ + + : 3466882 : if (a_feerate.size != b_feerate.size) {
+ + + + +
+ + + ]
1513 : 3400 : return a_feerate.size > b_feerate.size;
1514 : : }
1515 : : // Tie-break by decreasing fallback_order.
1516 [ + + + - : 6904482 : auto fallback_cmp = fallback_order(a, b);
+ + + - +
+ + - + +
+ - + + +
- ]
1517 [ + - ][ + - : 3463482 : if (fallback_cmp != 0) return fallback_cmp > 0;
+ - + - +
- + - ]
1518 : : // This should not be hit, because fallback_order defines a strong ordering.
1519 : 0 : Assume(false);
1520 : 0 : return a < b;
1521 : : };
1522 : : // Construct a heap with all chunks that have no out-of-chunk dependencies.
1523 : : /** Comparison function for the chunk heap. Note that it is a max-heap, so
1524 : : * chunk_cmp_fn(a, b) == true means "a appears after b in the linearization". */
1525 : 5429154 : auto chunk_cmp_fn = [&](const auto& a, const auto& b) noexcept {
1526 : : // Bail out for identical chunks.
1527 [ + - ][ + - : 5237690 : if (a.first == b.first) return false;
+ - + - +
- + - ]
1528 : : // First sort by increasing chunk feerate.
1529 [ + + ][ + + : 5237690 : auto& chunk_feerate_a = m_set_info[a.first].feerate;
+ + + + +
+ + + ]
1530 : 5237690 : auto& chunk_feerate_b = m_set_info[b.first].feerate;
1531 [ + + ][ + + : 5237690 : auto feerate_cmp = FeeRateCompare(chunk_feerate_a, chunk_feerate_b);
+ + + + +
+ + + ]
1532 [ + + ][ + + : 5237690 : if (feerate_cmp != 0) return feerate_cmp < 0;
+ + + + +
+ + + ]
1533 : : // Then by decreasing chunk size.
1534 [ - + ][ + + : 1842163 : if (chunk_feerate_a.size != chunk_feerate_b.size) {
+ + + + +
+ + + ]
1535 : 69084 : return chunk_feerate_a.size > chunk_feerate_b.size;
1536 : : }
1537 : : // Tie-break by decreasing fallback_order.
1538 [ + - + - : 3504193 : auto fallback_cmp = fallback_order(a.second, b.second);
+ - + - +
- + - + -
+ - + - +
- ]
1539 [ + - ][ + - : 1773079 : if (fallback_cmp != 0) return fallback_cmp > 0;
+ - + - +
- + - ]
1540 : : // This should not be hit, because fallback_order defines a strong ordering.
1541 : 0 : Assume(false);
1542 : 0 : return a.second < b.second;
1543 : : };
1544 : : // Construct a heap with all chunks that have no out-of-chunk dependencies.
1545 [ + + + + ]: 2059070 : for (SetIdx chunk_idx : m_chunk_idxs) {
1546 [ + + ]: 1791942 : if (chunk_deps[chunk_idx] == 0) {
1547 : 460934 : ready_chunks.emplace_back(chunk_idx, max_fallback_fn(chunk_idx));
1548 : : }
1549 : : }
1550 : 191464 : std::make_heap(ready_chunks.begin(), ready_chunks.end(), chunk_cmp_fn);
1551 : : // Pop chunks off the heap.
1552 [ + + ]: 1983406 : while (!ready_chunks.empty()) {
1553 : 1791942 : auto [chunk_idx, _rnd] = ready_chunks.front();
1554 [ + - ]: 1791942 : std::pop_heap(ready_chunks.begin(), ready_chunks.end(), chunk_cmp_fn);
1555 : 1791942 : ready_chunks.pop_back();
1556 [ + - ]: 1791942 : Assume(chunk_deps[chunk_idx] == 0);
1557 [ + - ]: 1791942 : const auto& chunk_txn = m_set_info[chunk_idx].transactions;
1558 : : // Build heap of all includable transactions in chunk.
1559 : 1791942 : Assume(ready_tx.empty());
1560 [ + + + + ]: 7548379 : for (TxIdx tx_idx : chunk_txn) {
1561 [ + + ]: 5071895 : if (tx_deps[tx_idx] == 0) ready_tx.push_back(tx_idx);
1562 : : }
1563 : 1791942 : Assume(!ready_tx.empty());
1564 : 1791942 : std::make_heap(ready_tx.begin(), ready_tx.end(), tx_cmp_fn);
1565 : : // Pick transactions from the ready heap, append them to linearization, and decrement
1566 : : // dependency counts.
1567 [ + + ]: 6863837 : while (!ready_tx.empty()) {
1568 : : // Pop an element from the tx_ready heap.
1569 : 5071895 : auto tx_idx = ready_tx.front();
1570 : 5071895 : std::pop_heap(ready_tx.begin(), ready_tx.end(), tx_cmp_fn);
1571 : 5071895 : ready_tx.pop_back();
1572 : : // Append to linearization.
1573 : 5071895 : ret.push_back(tx_idx);
1574 : : // Decrement dependency counts.
1575 [ + + ]: 5071895 : auto& tx_data = m_tx_data[tx_idx];
1576 [ + + + + ]: 21082456 : for (TxIdx chl_idx : tx_data.children) {
1577 [ + + ]: 15033243 : auto& chl_data = m_tx_data[chl_idx];
1578 : : // Decrement tx dependency count.
1579 : 15033243 : Assume(tx_deps[chl_idx] > 0);
1580 [ + + + + ]: 15033243 : if (--tx_deps[chl_idx] == 0 && chunk_txn[chl_idx]) {
1581 : : // Child tx has no dependencies left, and is in this chunk. Add it to the tx heap.
1582 : 2667616 : ready_tx.push_back(chl_idx);
1583 : 2667616 : std::push_heap(ready_tx.begin(), ready_tx.end(), tx_cmp_fn);
1584 : : }
1585 : : // Decrement chunk dependency count if this is out-of-chunk dependency.
1586 [ + + ]: 15033243 : if (chl_data.chunk_idx != chunk_idx) {
1587 [ + + ]: 8149488 : Assume(chunk_deps[chl_data.chunk_idx] > 0);
1588 [ + + ]: 8149488 : if (--chunk_deps[chl_data.chunk_idx] == 0) {
1589 : : // Child chunk has no dependencies left. Add it to the chunk heap.
1590 : 1331008 : ready_chunks.emplace_back(chl_data.chunk_idx, max_fallback_fn(chl_data.chunk_idx));
1591 : 1331008 : std::push_heap(ready_chunks.begin(), ready_chunks.end(), chunk_cmp_fn);
1592 : : }
1593 : : }
1594 : : }
1595 : : }
1596 : : }
1597 [ - + - + ]: 191464 : Assume(ret.size() == m_set_info.size());
1598 : 191464 : m_cost.GetLinearizationEnd(/*num_txns=*/m_set_info.size(), /*num_deps=*/num_deps);
1599 : 191464 : return ret;
1600 : 191464 : }
1601 : :
1602 : : /** Get the diagram for the current state, which must be topological. Test-only.
1603 : : *
1604 : : * The linearization produced by GetLinearization() is always at least as good (in the
1605 : : * CompareChunks() sense) as this diagram, but may be better.
1606 : : *
1607 : : * After an OptimizeStep(), the diagram will always be at least as good as before. Once
1608 : : * OptimizeStep() returns false, the diagram will be equivalent to that produced by
1609 : : * GetLinearization(), and optimal.
1610 : : *
1611 : : * After a MinimizeStep(), the diagram cannot change anymore (in the CompareChunks() sense),
1612 : : * but its number of segments can increase still. Once MinimizeStep() returns false, the number
1613 : : * of chunks of the produced linearization will match the number of segments in the diagram.
1614 : : */
1615 : : std::vector<FeeFrac> GetDiagram() const noexcept
1616 : : {
1617 : : std::vector<FeeFrac> ret;
1618 : : for (auto chunk_idx : m_chunk_idxs) {
1619 : : ret.push_back(m_set_info[chunk_idx].feerate);
1620 : : }
1621 : : std::sort(ret.begin(), ret.end(), std::greater{});
1622 : : return ret;
1623 : : }
1624 : :
1625 : : /** Determine how much work was performed so far. */
1626 : 5073088 : uint64_t GetCost() const noexcept { return m_cost.GetCost(); }
1627 : :
1628 : : /** Verify internal consistency of the data structure. */
1629 : : void SanityCheck() const
1630 : : {
1631 : : //
1632 : : // Verify dependency parent/child information, and build list of (active) dependencies.
1633 : : //
1634 : : std::vector<std::pair<TxIdx, TxIdx>> expected_dependencies;
1635 : : std::vector<std::pair<TxIdx, TxIdx>> all_dependencies;
1636 : : std::vector<std::pair<TxIdx, TxIdx>> active_dependencies;
1637 : : for (auto parent_idx : m_depgraph.Positions()) {
1638 : : for (auto child_idx : m_depgraph.GetReducedChildren(parent_idx)) {
1639 : : expected_dependencies.emplace_back(parent_idx, child_idx);
1640 : : }
1641 : : }
1642 : : for (auto tx_idx : m_transaction_idxs) {
1643 : : for (auto child_idx : m_tx_data[tx_idx].children) {
1644 : : all_dependencies.emplace_back(tx_idx, child_idx);
1645 : : if (m_tx_data[tx_idx].active_children[child_idx]) {
1646 : : active_dependencies.emplace_back(tx_idx, child_idx);
1647 : : }
1648 : : }
1649 : : }
1650 : : std::sort(expected_dependencies.begin(), expected_dependencies.end());
1651 : : std::sort(all_dependencies.begin(), all_dependencies.end());
1652 : : assert(expected_dependencies == all_dependencies);
1653 : :
1654 : : //
1655 : : // Verify the chunks against the list of active dependencies
1656 : : //
1657 : : SetType chunk_cover;
1658 : : for (auto chunk_idx : m_chunk_idxs) {
1659 : : const auto& chunk_info = m_set_info[chunk_idx];
1660 : : // Verify that transactions in the chunk point back to it. This guarantees
1661 : : // that chunks are non-overlapping.
1662 : : for (auto tx_idx : chunk_info.transactions) {
1663 : : assert(m_tx_data[tx_idx].chunk_idx == chunk_idx);
1664 : : }
1665 : : assert(!chunk_cover.Overlaps(chunk_info.transactions));
1666 : : chunk_cover |= chunk_info.transactions;
1667 : : // Verify the chunk's transaction set: start from an arbitrary chunk transaction,
1668 : : // and for every active dependency, if it contains the parent or child, add the
1669 : : // other. It must have exactly N-1 active dependencies in it, guaranteeing it is
1670 : : // acyclic.
1671 : : assert(chunk_info.transactions.Any());
1672 : : SetType expected_chunk = SetType::Singleton(chunk_info.transactions.First());
1673 : : while (true) {
1674 : : auto old = expected_chunk;
1675 : : size_t active_dep_count{0};
1676 : : for (const auto& [par, chl] : active_dependencies) {
1677 : : if (expected_chunk[par] || expected_chunk[chl]) {
1678 : : expected_chunk.Set(par);
1679 : : expected_chunk.Set(chl);
1680 : : ++active_dep_count;
1681 : : }
1682 : : }
1683 : : if (old == expected_chunk) {
1684 : : assert(expected_chunk.Count() == active_dep_count + 1);
1685 : : break;
1686 : : }
1687 : : }
1688 : : assert(chunk_info.transactions == expected_chunk);
1689 : : // Verify the chunk's feerate.
1690 : : assert(chunk_info.feerate == m_depgraph.FeeRate(chunk_info.transactions));
1691 : : // Verify the chunk's reachable transactions.
1692 : : assert(m_reachable[chunk_idx] == GetReachable(expected_chunk));
1693 : : // Verify that the chunk's reachable transactions don't include its own transactions.
1694 : : assert(!m_reachable[chunk_idx].first.Overlaps(chunk_info.transactions));
1695 : : assert(!m_reachable[chunk_idx].second.Overlaps(chunk_info.transactions));
1696 : : }
1697 : : // Verify that together, the chunks cover all transactions.
1698 : : assert(chunk_cover == m_depgraph.Positions());
1699 : :
1700 : : //
1701 : : // Verify transaction data.
1702 : : //
1703 : : assert(m_transaction_idxs == m_depgraph.Positions());
1704 : : for (auto tx_idx : m_transaction_idxs) {
1705 : : const auto& tx_data = m_tx_data[tx_idx];
1706 : : // Verify it has a valid chunk index, and that chunk includes this transaction.
1707 : : assert(m_chunk_idxs[tx_data.chunk_idx]);
1708 : : assert(m_set_info[tx_data.chunk_idx].transactions[tx_idx]);
1709 : : // Verify parents/children.
1710 : : assert(tx_data.parents == m_depgraph.GetReducedParents(tx_idx));
1711 : : assert(tx_data.children == m_depgraph.GetReducedChildren(tx_idx));
1712 : : // Verify active_children is a subset of children.
1713 : : assert(tx_data.active_children.IsSubsetOf(tx_data.children));
1714 : : // Verify each active child's dep_top_idx points to a valid non-chunk set.
1715 : : for (auto child_idx : tx_data.active_children) {
1716 : : assert(tx_data.dep_top_idx[child_idx] < m_set_info.size());
1717 : : assert(!m_chunk_idxs[tx_data.dep_top_idx[child_idx]]);
1718 : : }
1719 : : }
1720 : :
1721 : : //
1722 : : // Verify active dependencies' top sets.
1723 : : //
1724 : : for (const auto& [par_idx, chl_idx] : active_dependencies) {
1725 : : // Verify the top set's transactions: it must contain the parent, and for every
1726 : : // active dependency, except the chl_idx->par_idx dependency itself, if it contains the
1727 : : // parent or child, it must contain both. It must have exactly N-1 active dependencies
1728 : : // in it, guaranteeing it is acyclic.
1729 : : SetType expected_top = SetType::Singleton(par_idx);
1730 : : while (true) {
1731 : : auto old = expected_top;
1732 : : size_t active_dep_count{0};
1733 : : for (const auto& [par2_idx, chl2_idx] : active_dependencies) {
1734 : : if (par_idx == par2_idx && chl_idx == chl2_idx) continue;
1735 : : if (expected_top[par2_idx] || expected_top[chl2_idx]) {
1736 : : expected_top.Set(par2_idx);
1737 : : expected_top.Set(chl2_idx);
1738 : : ++active_dep_count;
1739 : : }
1740 : : }
1741 : : if (old == expected_top) {
1742 : : assert(expected_top.Count() == active_dep_count + 1);
1743 : : break;
1744 : : }
1745 : : }
1746 : : assert(!expected_top[chl_idx]);
1747 : : auto& dep_top_info = m_set_info[m_tx_data[par_idx].dep_top_idx[chl_idx]];
1748 : : assert(dep_top_info.transactions == expected_top);
1749 : : // Verify the top set's feerate.
1750 : : assert(dep_top_info.feerate == m_depgraph.FeeRate(dep_top_info.transactions));
1751 : : }
1752 : :
1753 : : //
1754 : : // Verify m_suboptimal_chunks.
1755 : : //
1756 : : SetType suboptimal_idxs;
1757 : : for (size_t i = 0; i < m_suboptimal_chunks.size(); ++i) {
1758 : : auto chunk_idx = m_suboptimal_chunks[i];
1759 : : assert(!suboptimal_idxs[chunk_idx]);
1760 : : suboptimal_idxs.Set(chunk_idx);
1761 : : }
1762 : : assert(m_suboptimal_idxs == suboptimal_idxs);
1763 : :
1764 : : //
1765 : : // Verify m_nonminimal_chunks.
1766 : : //
1767 : : SetType nonminimal_idxs;
1768 : : for (size_t i = 0; i < m_nonminimal_chunks.size(); ++i) {
1769 : : auto [chunk_idx, pivot, flags] = m_nonminimal_chunks[i];
1770 : : assert(m_tx_data[pivot].chunk_idx == chunk_idx);
1771 : : assert(!nonminimal_idxs[chunk_idx]);
1772 : : nonminimal_idxs.Set(chunk_idx);
1773 : : }
1774 : : assert(nonminimal_idxs.IsSubsetOf(m_chunk_idxs));
1775 : : }
1776 : : };
1777 : :
1778 : : /** Find or improve a linearization for a cluster.
1779 : : *
1780 : : * @param[in] depgraph Dependency graph of the cluster to be linearized.
1781 : : * @param[in] max_cost Upper bound on the amount of work that will be done.
1782 : : * @param[in] rng_seed A random number seed to control search order. This prevents peers
1783 : : * from predicting exactly which clusters would be hard for us to
1784 : : * linearize.
1785 : : * @param[in] fallback_order A comparator to order transactions, used to sort equal-feerate
1786 : : * chunks and transactions. See SpanningForestState::GetLinearization
1787 : : * for details.
1788 : : * @param[in] old_linearization An existing linearization for the cluster, or empty.
1789 : : * @param[in] is_topological (Only relevant if old_linearization is not empty) Whether
1790 : : * old_linearization is topologically valid.
1791 : : * @return A tuple of:
1792 : : * - The resulting linearization. It is guaranteed to be at least as
1793 : : * good (in the feerate diagram sense) as old_linearization.
1794 : : * - A boolean indicating whether the result is guaranteed to be
1795 : : * optimal with minimal chunks.
1796 : : * - How many optimization steps were actually performed.
1797 : : */
1798 : : template<typename SetType>
1799 : 191464 : std::tuple<std::vector<DepGraphIndex>, bool, uint64_t> Linearize(
1800 : : const DepGraph<SetType>& depgraph,
1801 : : uint64_t max_cost,
1802 : : uint64_t rng_seed,
1803 : : const StrongComparator<DepGraphIndex> auto& fallback_order,
1804 : : std::span<const DepGraphIndex> old_linearization = {},
1805 : : bool is_topological = true) noexcept
1806 : : {
1807 : : /** Initialize a spanning forest data structure for this cluster. */
1808 [ + + ]: 191464 : SpanningForestState forest(depgraph, rng_seed);
1809 [ + + ]: 191464 : if (!old_linearization.empty()) {
1810 : 144732 : forest.LoadLinearization(old_linearization);
1811 [ + + ]: 144732 : if (!is_topological) forest.MakeTopological();
1812 : : } else {
1813 : 46732 : forest.MakeTopological();
1814 : : }
1815 : : // Make improvement steps to it until we hit the max_iterations limit, or an optimal result
1816 : : // is found.
1817 [ + - ]: 191464 : if (forest.GetCost() < max_cost) {
1818 : 191464 : forest.StartOptimizing();
1819 : : do {
1820 [ + + ]: 2560287 : if (!forest.OptimizeStep()) break;
1821 [ + - ]: 2368823 : } while (forest.GetCost() < max_cost);
1822 : : }
1823 : : // Make chunk minimization steps until we hit the max_iterations limit, or all chunks are
1824 : : // minimal.
1825 : 191464 : bool optimal = false;
1826 [ + - ]: 191464 : if (forest.GetCost() < max_cost) {
1827 : 191464 : forest.StartMinimizing();
1828 : : do {
1829 [ + + ]: 2321337 : if (!forest.MinimizeStep()) {
1830 : : optimal = true;
1831 : : break;
1832 : : }
1833 [ + - ]: 2129873 : } while (forest.GetCost() < max_cost);
1834 : : }
1835 : 191464 : return {forest.GetLinearization(fallback_order), optimal, forest.GetCost()};
1836 : 191464 : }
1837 : :
1838 : : /** Improve a given linearization.
1839 : : *
1840 : : * @param[in] depgraph Dependency graph of the cluster being linearized.
1841 : : * @param[in,out] linearization On input, an existing linearization for depgraph. On output, a
1842 : : * potentially better linearization for the same graph.
1843 : : *
1844 : : * Postlinearization guarantees:
1845 : : * - The resulting chunks are connected.
1846 : : * - If the input has a tree shape (either all transactions have at most one child, or all
1847 : : * transactions have at most one parent), the result is optimal.
1848 : : * - Given a linearization L1 and a leaf transaction T in it. Let L2 be L1 with T moved to the end,
1849 : : * optionally with its fee increased. Let L3 be the postlinearization of L2. L3 will be at least
1850 : : * as good as L1. This means that replacing transactions with same-size higher-fee transactions
1851 : : * will not worsen linearizations through a "drop conflicts, append new transactions,
1852 : : * postlinearize" process.
1853 : : */
1854 : : template<typename SetType>
1855 [ - + ]: 5264 : void PostLinearize(const DepGraph<SetType>& depgraph, std::span<DepGraphIndex> linearization)
1856 : : {
1857 : : // This algorithm performs a number of passes (currently 2); the even ones operate from back to
1858 : : // front, the odd ones from front to back. Each results in an equal-or-better linearization
1859 : : // than the one started from.
1860 : : // - One pass in either direction guarantees that the resulting chunks are connected.
1861 : : // - Each direction corresponds to one shape of tree being linearized optimally (forward passes
1862 : : // guarantee this for graphs where each transaction has at most one child; backward passes
1863 : : // guarantee this for graphs where each transaction has at most one parent).
1864 : : // - Starting with a backward pass guarantees the moved-tree property.
1865 : : //
1866 : : // During an odd (forward) pass, the high-level operation is:
1867 : : // - Start with an empty list of groups L=[].
1868 : : // - For every transaction i in the old linearization, from front to back:
1869 : : // - Append a new group C=[i], containing just i, to the back of L.
1870 : : // - While L has at least one group before C, and the group immediately before C has feerate
1871 : : // lower than C:
1872 : : // - If C depends on P:
1873 : : // - Merge P into C, making C the concatenation of P+C, continuing with the combined C.
1874 : : // - Otherwise:
1875 : : // - Swap P with C, continuing with the now-moved C.
1876 : : // - The output linearization is the concatenation of the groups in L.
1877 : : //
1878 : : // During even (backward) passes, i iterates from the back to the front of the existing
1879 : : // linearization, and new groups are prepended instead of appended to the list L. To enable
1880 : : // more code reuse, both passes append groups, but during even passes the meanings of
1881 : : // parent/child, and of high/low feerate are reversed, and the final concatenation is reversed
1882 : : // on output.
1883 : : //
1884 : : // In the implementation below, the groups are represented by singly-linked lists (pointing
1885 : : // from the back to the front), which are themselves organized in a singly-linked circular
1886 : : // list (each group pointing to its predecessor, with a special sentinel group at the front
1887 : : // that points back to the last group).
1888 : : //
1889 : : // Information about transaction t is stored in entries[t + 1], while the sentinel is in
1890 : : // entries[0].
1891 : :
1892 : : /** Index of the sentinel in the entries array below. */
1893 : : static constexpr DepGraphIndex SENTINEL{0};
1894 : : /** Indicator that a group has no previous transaction. */
1895 : : static constexpr DepGraphIndex NO_PREV_TX{0};
1896 : :
1897 : :
1898 : : /** Data structure per transaction entry. */
1899 : 74159 : struct TxEntry
1900 : : {
1901 : : /** The index of the previous transaction in this group; NO_PREV_TX if this is the first
1902 : : * entry of a group. */
1903 : : DepGraphIndex prev_tx;
1904 : :
1905 : : // The fields below are only used for transactions that are the last one in a group
1906 : : // (referred to as tail transactions below).
1907 : :
1908 : : /** Index of the first transaction in this group, possibly itself. */
1909 : : DepGraphIndex first_tx;
1910 : : /** Index of the last transaction in the previous group. The first group (the sentinel)
1911 : : * points back to the last group here, making it a singly-linked circular list. */
1912 : : DepGraphIndex prev_group;
1913 : : /** All transactions in the group. Empty for the sentinel. */
1914 : : SetType group;
1915 : : /** All dependencies of the group (descendants in even passes; ancestors in odd ones). */
1916 : : SetType deps;
1917 : : /** The combined fee/size of transactions in the group. Fee is negated in even passes. */
1918 : : FeeFrac feerate;
1919 : : };
1920 : :
1921 : : // As an example, consider the state corresponding to the linearization [1,0,3,2], with
1922 : : // groups [1,0,3] and [2], in an odd pass. The linked lists would be:
1923 : : //
1924 : : // +-----+
1925 : : // 0<-P-- | 0 S | ---\ Legend:
1926 : : // +-----+ |
1927 : : // ^ | - digit in box: entries index
1928 : : // /--------------F---------+ G | (note: one more than tx value)
1929 : : // v \ | | - S: sentinel group
1930 : : // +-----+ +-----+ +-----+ | (empty feerate)
1931 : : // 0<-P-- | 2 | <--P-- | 1 | <--P-- | 4 T | | - T: tail transaction, contains
1932 : : // +-----+ +-----+ +-----+ | fields beyond prev_tv.
1933 : : // ^ | - P: prev_tx reference
1934 : : // G G - F: first_tx reference
1935 : : // | | - G: prev_group reference
1936 : : // +-----+ |
1937 : : // 0<-P-- | 3 T | <--/
1938 : : // +-----+
1939 : : // ^ |
1940 : : // \-F-/
1941 : : //
1942 : : // During an even pass, the diagram above would correspond to linearization [2,3,0,1], with
1943 : : // groups [2] and [3,0,1].
1944 : :
1945 : 5264 : std::vector<TxEntry> entries(depgraph.PositionRange() + 1);
1946 : :
1947 : : // Perform two passes over the linearization.
1948 [ + + ]: 15792 : for (int pass = 0; pass < 2; ++pass) {
1949 : 10528 : int rev = !(pass & 1);
1950 : : // Construct a sentinel group, identifying the start of the list.
1951 : 10528 : entries[SENTINEL].prev_group = SENTINEL;
1952 : 10528 : Assume(entries[SENTINEL].feerate.IsEmpty());
1953 : :
1954 : : // Iterate over all elements in the existing linearization.
1955 [ + + ]: 148318 : for (DepGraphIndex i = 0; i < linearization.size(); ++i) {
1956 : : // Even passes are from back to front; odd passes from front to back.
1957 [ + + ]: 137790 : DepGraphIndex idx = linearization[rev ? linearization.size() - 1 - i : i];
1958 : : // Construct a new group containing just idx. In even passes, the meaning of
1959 : : // parent/child and high/low feerate are swapped.
1960 [ + + ]: 137790 : DepGraphIndex cur_group = idx + 1;
1961 [ + + ]: 137790 : entries[cur_group].group = SetType::Singleton(idx);
1962 [ + + + + ]: 137790 : entries[cur_group].deps = rev ? depgraph.Descendants(idx): depgraph.Ancestors(idx);
1963 : 137790 : entries[cur_group].feerate = depgraph.FeeRate(idx);
1964 [ + + ]: 137790 : if (rev) entries[cur_group].feerate.fee = -entries[cur_group].feerate.fee;
1965 : 137790 : entries[cur_group].prev_tx = NO_PREV_TX; // No previous transaction in group.
1966 : 137790 : entries[cur_group].first_tx = cur_group; // Transaction itself is first of group.
1967 : : // Insert the new group at the back of the groups linked list.
1968 : 137790 : entries[cur_group].prev_group = entries[SENTINEL].prev_group;
1969 : 137790 : entries[SENTINEL].prev_group = cur_group;
1970 : :
1971 : : // Start merge/swap cycle.
1972 : 137790 : DepGraphIndex next_group = SENTINEL; // We inserted at the end, so next group is sentinel.
1973 : 137790 : DepGraphIndex prev_group = entries[cur_group].prev_group;
1974 : : // Continue as long as the current group has higher feerate than the previous one.
1975 [ + + ]: 152499 : while (entries[cur_group].feerate >> entries[prev_group].feerate) {
1976 : : // prev_group/cur_group/next_group refer to (the last transactions of) 3
1977 : : // consecutive entries in groups list.
1978 [ + + ]: 14709 : Assume(cur_group == entries[next_group].prev_group);
1979 : 14709 : Assume(prev_group == entries[cur_group].prev_group);
1980 : : // The sentinel has empty feerate, which is neither higher or lower than other
1981 : : // feerates. Thus, the while loop we are in here guarantees that cur_group and
1982 : : // prev_group are not the sentinel.
1983 : 14709 : Assume(cur_group != SENTINEL);
1984 : 14709 : Assume(prev_group != SENTINEL);
1985 [ + + ]: 14709 : if (entries[cur_group].deps.Overlaps(entries[prev_group].group)) {
1986 : : // There is a dependency between cur_group and prev_group; merge prev_group
1987 : : // into cur_group. The group/deps/feerate fields of prev_group remain unchanged
1988 : : // but become unused.
1989 : 14706 : entries[cur_group].group |= entries[prev_group].group;
1990 : 14706 : entries[cur_group].deps |= entries[prev_group].deps;
1991 : 14706 : entries[cur_group].feerate += entries[prev_group].feerate;
1992 : : // Make the first of the current group point to the tail of the previous group.
1993 : 14706 : entries[entries[cur_group].first_tx].prev_tx = prev_group;
1994 : : // The first of the previous group becomes the first of the newly-merged group.
1995 : 14706 : entries[cur_group].first_tx = entries[prev_group].first_tx;
1996 : : // The previous group becomes whatever group was before the former one.
1997 : 14706 : prev_group = entries[prev_group].prev_group;
1998 : 14706 : entries[cur_group].prev_group = prev_group;
1999 : : } else {
2000 : : // There is no dependency between cur_group and prev_group; swap them.
2001 : 3 : DepGraphIndex preprev_group = entries[prev_group].prev_group;
2002 : : // If PP, P, C, N were the old preprev, prev, cur, next groups, then the new
2003 : : // layout becomes [PP, C, P, N]. Update prev_groups to reflect that order.
2004 : 3 : entries[next_group].prev_group = prev_group;
2005 : 3 : entries[prev_group].prev_group = cur_group;
2006 : 3 : entries[cur_group].prev_group = preprev_group;
2007 : : // The current group remains the same, but the groups before/after it have
2008 : : // changed.
2009 : 3 : next_group = prev_group;
2010 : 3 : prev_group = preprev_group;
2011 : : }
2012 : : }
2013 : : }
2014 : :
2015 : : // Convert the entries back to linearization (overwriting the existing one).
2016 : 10528 : DepGraphIndex cur_group = entries[0].prev_group;
2017 : 10528 : DepGraphIndex done = 0;
2018 [ + + ]: 133612 : while (cur_group != SENTINEL) {
2019 : 123084 : DepGraphIndex cur_tx = cur_group;
2020 : : // Traverse the transactions of cur_group (from back to front), and write them in the
2021 : : // same order during odd passes, and reversed (front to back) in even passes.
2022 [ + + ]: 123084 : if (rev) {
2023 : : do {
2024 [ + + ]: 68895 : *(linearization.begin() + (done++)) = cur_tx - 1;
2025 [ + + ]: 68895 : cur_tx = entries[cur_tx].prev_tx;
2026 [ + + ]: 68895 : } while (cur_tx != NO_PREV_TX);
2027 : : } else {
2028 : : do {
2029 [ + + ]: 68895 : *(linearization.end() - (++done)) = cur_tx - 1;
2030 [ + + ]: 68895 : cur_tx = entries[cur_tx].prev_tx;
2031 [ + + ]: 68895 : } while (cur_tx != NO_PREV_TX);
2032 : : }
2033 : 123084 : cur_group = entries[cur_group].prev_group;
2034 : : }
2035 : 10528 : Assume(done == linearization.size());
2036 : : }
2037 : 5264 : }
2038 : :
2039 : : } // namespace cluster_linearize
2040 : :
2041 : : #endif // BITCOIN_CLUSTER_LINEARIZE_H
|