Coverage Report

Created: 2026-08-25 19:02

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/bitcoin/src/test/fuzz/txgraph.cpp
Line
Count
Source
1
// Copyright (c) The Bitcoin Core developers
2
// Distributed under the MIT software license, see the accompanying
3
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5
#include <cluster_linearize.h>
6
#include <test/fuzz/FuzzedDataProvider.h>
7
#include <test/fuzz/fuzz.h>
8
#include <test/util/cluster_linearize.h>
9
#include <test/util/random.h>
10
#include <txgraph.h>
11
#include <util/bitset.h>
12
#include <util/feefrac.h>
13
14
#include <algorithm>
15
#include <cstdint>
16
#include <iterator>
17
#include <map>
18
#include <memory>
19
#include <ranges>
20
#include <set>
21
#include <utility>
22
23
using namespace cluster_linearize;
24
25
namespace {
26
27
struct SimTxObject : public TxGraph::Ref
28
{
29
    // Use random uint64_t as txids for this simulation (0 = empty object).
30
    const uint64_t m_txid{0};
31
5.11k
    SimTxObject() noexcept = default;
32
389k
    explicit SimTxObject(uint64_t txid) noexcept : m_txid(txid) {}
33
};
34
35
/** Data type representing a naive simulated TxGraph, keeping all transactions (even from
36
 *  disconnected components) in a single DepGraph. Unlike the real TxGraph, this only models
37
 *  a single graph, and multiple instances are used to simulate main/staging. */
38
struct SimTxGraph
39
{
40
    /** Maximum number of transactions to support simultaneously. Set this higher than txgraph's
41
     *  cluster count, so we can exercise situations with more transactions than fit in one
42
     *  cluster. */
43
    static constexpr unsigned MAX_TRANSACTIONS = MAX_CLUSTER_COUNT_LIMIT * 2;
44
    /** Set type to use in the simulation. */
45
    using SetType = BitSet<MAX_TRANSACTIONS>;
46
    /** Data type for representing positions within SimTxGraph::graph. */
47
    using Pos = DepGraphIndex;
48
    /** Constant to mean "missing in this graph". */
49
    static constexpr auto MISSING = Pos(-1);
50
51
    /** The dependency graph (for all transactions in the simulation, regardless of
52
     *  connectivity/clustering). */
53
    DepGraph<SetType> graph;
54
    /** For each position in graph, which SimTxObject it corresponds with (if any). Use shared_ptr
55
     *  so that a SimTxGraph can be copied to create a staging one, while sharing Refs with
56
     *  the main graph. */
57
    std::array<std::shared_ptr<SimTxObject>, MAX_TRANSACTIONS> simmap;
58
    /** For each TxGraph::Ref in graph, the position it corresponds with. */
59
    std::map<const TxGraph::Ref*, Pos> simrevmap;
60
    /** The set of SimTxObject entries that have been removed, but not yet destroyed. */
61
    std::vector<std::shared_ptr<SimTxObject>> removed;
62
    /** Whether the graph is oversized (true = yes, false = no, std::nullopt = unknown). */
63
    std::optional<bool> oversized;
64
    /** The configured maximum number of transactions per cluster. */
65
    DepGraphIndex max_cluster_count;
66
    /** Which transactions have been modified in the graph since creation, either directly or by
67
     *  being in a cluster which includes modifications. Only relevant for the staging graph. */
68
    SetType modified;
69
    /** The configured maximum total size of transactions per cluster. */
70
    uint64_t max_cluster_size;
71
    /** Whether the corresponding real graph is known to be optimally linearized. */
72
    bool real_is_optimal{false};
73
74
    /** Construct a new SimTxGraph with the specified maximum cluster count and size. */
75
    explicit SimTxGraph(DepGraphIndex cluster_count, uint64_t cluster_size) :
76
5.11k
        max_cluster_count(cluster_count), max_cluster_size(cluster_size) {}
77
78
    // Permit copying and moving.
79
23.6k
    SimTxGraph(const SimTxGraph&) noexcept = default;
80
    SimTxGraph& operator=(const SimTxGraph&) noexcept = default;
81
0
    SimTxGraph(SimTxGraph&&) noexcept = default;
82
5.04k
    SimTxGraph& operator=(SimTxGraph&&) noexcept = default;
83
84
    /** Get the connected components within this simulated transaction graph. */
85
    std::vector<SetType> GetComponents()
86
209k
    {
87
209k
        auto todo = graph.Positions();
88
209k
        std::vector<SetType> ret;
89
        // Iterate over all connected components of the graph.
90
5.39M
        while (todo.Any()) {
  Branch (90:16): [True: 5.18M, False: 209k]
91
5.18M
            auto component = graph.FindConnectedComponent(todo);
92
5.18M
            ret.push_back(component);
93
5.18M
            todo -= component;
94
5.18M
        }
95
209k
        return ret;
96
209k
    }
97
98
    /** Check whether this graph is oversized (contains a connected component whose number of
99
     *  transactions exceeds max_cluster_count. */
100
    bool IsOversized()
101
4.71M
    {
102
4.71M
        if (!oversized.has_value()) {
  Branch (102:13): [True: 160k, False: 4.55M]
103
            // Only recompute when oversized isn't already known.
104
160k
            oversized = false;
105
3.67M
            for (auto component : GetComponents()) {
  Branch (105:33): [True: 3.67M, False: 160k]
106
3.67M
                if (component.Count() > max_cluster_count) oversized = true;
  Branch (106:21): [True: 61.0k, False: 3.61M]
107
3.67M
                uint64_t component_size{0};
108
7.13M
                for (auto i : component) component_size += graph.FeeRate(i).size;
  Branch (108:29): [True: 7.13M, False: 3.67M]
109
3.67M
                if (component_size > max_cluster_size) oversized = true;
  Branch (109:21): [True: 406k, False: 3.26M]
110
3.67M
            }
111
160k
        }
112
4.71M
        return *oversized;
113
4.71M
    }
114
115
    void MakeModified(DepGraphIndex index)
116
2.44M
    {
117
2.44M
        modified |= graph.GetConnectedComponent(graph.Positions(), index);
118
2.44M
    }
119
120
    /** Determine the number of (non-removed) transactions in the graph. */
121
2.94M
    DepGraphIndex GetTransactionCount() const { return graph.TxCount(); }
122
123
    /** Get the sum of all fees/sizes in the graph. */
124
    FeePerWeight SumAll() const
125
68.5k
    {
126
68.5k
        FeePerWeight ret;
127
2.69M
        for (auto i : graph.Positions()) {
  Branch (127:21): [True: 2.69M, False: 68.5k]
128
2.69M
            ret += graph.FeeRate(i);
129
2.69M
        }
130
68.5k
        return ret;
131
68.5k
    }
132
133
    /** Get the position where ref occurs in this simulated graph, or -1 if it does not. */
134
    Pos Find(const TxGraph::Ref* ref) const
135
18.2M
    {
136
18.2M
        auto it = simrevmap.find(ref);
137
18.2M
        if (it != simrevmap.end()) return it->second;
  Branch (137:13): [True: 18.1M, False: 194k]
138
194k
        return MISSING;
139
18.2M
    }
140
141
    /** Given a position in this simulated graph, get the corresponding SimTxObject. */
142
    SimTxObject* GetRef(Pos pos)
143
11.9M
    {
144
11.9M
        assert(graph.Positions()[pos]);
  Branch (144:9): [True: 11.9M, False: 0]
145
11.9M
        assert(simmap[pos]);
  Branch (145:9): [True: 11.9M, False: 0]
146
11.9M
        return simmap[pos].get();
147
11.9M
    }
148
149
    /** Add a new transaction to the simulation and the specified real graph. */
150
    void AddTransaction(TxGraph& txgraph, const FeePerWeight& feerate, uint64_t txid)
151
343k
    {
152
343k
        assert(graph.TxCount() < MAX_TRANSACTIONS);
  Branch (152:9): [True: 343k, False: 0]
153
343k
        auto simpos = graph.AddTransaction(feerate);
154
343k
        real_is_optimal = false;
155
343k
        MakeModified(simpos);
156
343k
        assert(graph.Positions()[simpos]);
  Branch (156:9): [True: 343k, False: 0]
157
343k
        simmap[simpos] = std::make_shared<SimTxObject>(txid);
158
343k
        txgraph.AddTransaction(*simmap[simpos], feerate);
159
343k
        auto ptr = simmap[simpos].get();
160
343k
        simrevmap[ptr] = simpos;
161
        // This may invalidate our cached oversized value.
162
343k
        if (oversized.has_value() && !*oversized) oversized = std::nullopt;
  Branch (162:13): [True: 115k, False: 227k]
  Branch (162:38): [True: 58.8k, False: 56.7k]
163
343k
    }
164
165
    /** Add a dependency between two positions in this graph. */
166
    void AddDependency(TxGraph::Ref* parent, TxGraph::Ref* child)
167
1.78M
    {
168
1.78M
        auto par_pos = Find(parent);
169
1.78M
        if (par_pos == MISSING) return;
  Branch (169:13): [True: 4.92k, False: 1.77M]
170
1.77M
        auto chl_pos = Find(child);
171
1.77M
        if (chl_pos == MISSING) return;
  Branch (171:13): [True: 3.44k, False: 1.77M]
172
1.77M
        graph.AddDependencies(SetType::Singleton(par_pos), chl_pos);
173
1.77M
        MakeModified(par_pos);
174
1.77M
        real_is_optimal = false;
175
        // This may invalidate our cached oversized value.
176
1.77M
        if (oversized.has_value() && !*oversized) oversized = std::nullopt;
  Branch (176:13): [True: 43.5k, False: 1.73M]
  Branch (176:38): [True: 38.8k, False: 4.66k]
177
1.77M
    }
178
179
    /** Modify the transaction fee of a ref, if it exists. */
180
    void SetTransactionFee(TxGraph::Ref* ref, int64_t fee)
181
11.8k
    {
182
11.8k
        auto pos = Find(ref);
183
11.8k
        if (pos == MISSING) return;
  Branch (183:13): [True: 3.94k, False: 7.87k]
184
        // No need to invoke MakeModified, because this equally affects main and staging.
185
7.87k
        real_is_optimal = false;
186
7.87k
        graph.FeeRate(pos).fee = fee;
187
7.87k
    }
188
189
    /** Remove the transaction in the specified position from the graph. */
190
    void RemoveTransaction(TxGraph::Ref* ref)
191
300k
    {
192
300k
        auto pos = Find(ref);
193
300k
        if (pos == MISSING) return;
  Branch (193:13): [True: 10.6k, False: 289k]
194
289k
        MakeModified(pos);
195
289k
        real_is_optimal = false;
196
289k
        graph.RemoveTransactions(SetType::Singleton(pos));
197
289k
        simrevmap.erase(simmap[pos].get());
198
        // Retain the TxGraph::Ref corresponding to this position, so the Ref destruction isn't
199
        // invoked until the simulation explicitly decided to do so.
200
289k
        removed.push_back(std::move(simmap[pos]));
201
289k
        simmap[pos].reset();
202
        // This may invalidate our cached oversized value.
203
289k
        if (oversized.has_value() && *oversized) oversized = std::nullopt;
  Branch (203:13): [True: 41.5k, False: 248k]
  Branch (203:38): [True: 36.5k, False: 5.04k]
204
289k
    }
205
206
    /** Destroy the transaction from the graph, including from the removed set. This will
207
     *  trigger TxGraph::Ref::~Ref. reset_oversize controls whether the cached oversized
208
     *  value is cleared (destroying does not clear oversizedness in TxGraph of the main
209
     *  graph while staging exists). */
210
    void DestroyTransaction(TxGraph::Ref* ref, bool reset_oversize)
211
51.7k
    {
212
51.7k
        auto pos = Find(ref);
213
51.7k
        if (pos == MISSING) {
  Branch (213:13): [True: 12.9k, False: 38.8k]
214
            // Wipe the ref, if it exists, from the removed vector. Use std::partition rather
215
            // than std::erase because we don't care about the order of the entries that
216
            // remain.
217
206k
            auto remove = std::partition(removed.begin(), removed.end(), [&](auto& arg) { return arg.get() != ref; });
218
12.9k
            removed.erase(remove, removed.end());
219
38.8k
        } else {
220
38.8k
            MakeModified(pos);
221
38.8k
            graph.RemoveTransactions(SetType::Singleton(pos));
222
38.8k
            real_is_optimal = false;
223
38.8k
            simrevmap.erase(simmap[pos].get());
224
38.8k
            simmap[pos].reset();
225
            // This may invalidate our cached oversized value.
226
38.8k
            if (reset_oversize && oversized.has_value() && *oversized) {
  Branch (226:17): [True: 25.1k, False: 13.6k]
  Branch (226:35): [True: 16.1k, False: 8.95k]
  Branch (226:60): [True: 5.55k, False: 10.6k]
227
5.55k
                oversized = std::nullopt;
228
5.55k
            }
229
38.8k
        }
230
51.7k
    }
231
232
    /** Construct the set with all positions in this graph corresponding to the specified
233
     *  TxGraph::Refs. All of them must occur in this graph and not be removed. */
234
    SetType MakeSet(std::span<TxGraph::Ref* const> arg)
235
1.12M
    {
236
1.12M
        SetType ret;
237
7.73M
        for (TxGraph::Ref* ptr : arg) {
  Branch (237:32): [True: 7.73M, False: 1.12M]
238
7.73M
            auto pos = Find(ptr);
239
7.73M
            assert(pos != Pos(-1));
  Branch (239:13): [True: 7.73M, False: 0]
240
7.73M
            ret.Set(pos);
241
7.73M
        }
242
1.12M
        return ret;
243
1.12M
    }
244
245
    /** Get the set of ancestors (desc=false) or descendants (desc=true) in this graph. */
246
    SetType GetAncDesc(TxGraph::Ref* arg, bool desc)
247
92.8k
    {
248
92.8k
        auto pos = Find(arg);
249
92.8k
        if (pos == MISSING) return {};
  Branch (249:13): [True: 24.9k, False: 67.9k]
250
67.9k
        return desc ? graph.Descendants(pos) : graph.Ancestors(pos);
  Branch (250:16): [True: 32.2k, False: 35.6k]
251
92.8k
    }
252
253
    /** Given a set of Refs (given as a vector of pointers), expand the set to include all its
254
     *  ancestors (desc=false) or all its descendants (desc=true) in this graph. */
255
    void IncludeAncDesc(std::vector<TxGraph::Ref*>& arg, bool desc)
256
60.6k
    {
257
60.6k
        std::vector<TxGraph::Ref*> ret;
258
78.9k
        for (auto ptr : arg) {
  Branch (258:23): [True: 78.9k, False: 60.6k]
259
78.9k
            auto simpos = Find(ptr);
260
78.9k
            if (simpos != MISSING) {
  Branch (260:17): [True: 53.5k, False: 25.4k]
261
105k
                for (auto i : desc ? graph.Descendants(simpos) : graph.Ancestors(simpos)) {
  Branch (261:29): [True: 105k, False: 53.5k]
  Branch (261:31): [True: 17.3k, False: 36.2k]
262
105k
                    ret.push_back(simmap[i].get());
263
105k
                }
264
53.5k
            } else {
265
25.4k
                ret.push_back(ptr);
266
25.4k
            }
267
78.9k
        }
268
        // Construct deduplicated version in input (do not use std::sort/std::unique for
269
        // deduplication as it'd rely on non-deterministic pointer comparison).
270
60.6k
        arg.clear();
271
130k
        for (auto ptr : ret) {
  Branch (271:23): [True: 130k, False: 60.6k]
272
130k
            if (std::find(arg.begin(), arg.end(), ptr) == arg.end()) {
  Branch (272:17): [True: 89.8k, False: 40.8k]
273
89.8k
                arg.push_back(ptr);
274
89.8k
            }
275
130k
        }
276
60.6k
    }
277
278
279
    /** Verify that set contains transactions from every oversized cluster, and nothing from
280
     *  non-oversized ones. */
281
    bool MatchesOversizedClusters(const SetType& set)
282
34.1k
    {
283
34.1k
        if (set.Any() && !IsOversized()) return false;
  Branch (283:13): [True: 34.1k, False: 0]
  Branch (283:26): [True: 0, False: 34.1k]
284
285
34.1k
        auto todo = graph.Positions();
286
34.1k
        if (!set.IsSubsetOf(todo)) return false;
  Branch (286:13): [True: 0, False: 34.1k]
287
288
        // Walk all clusters, and make sure all of set doesn't come from non-oversized clusters
289
314k
        while (todo.Any()) {
  Branch (289:16): [True: 280k, False: 34.1k]
290
280k
            auto component = graph.FindConnectedComponent(todo);
291
            // Determine whether component is oversized, due to either the size or count limit.
292
280k
            bool is_oversized = component.Count() > max_cluster_count;
293
280k
            uint64_t component_size{0};
294
1.76M
            for (auto i : component) component_size += graph.FeeRate(i).size;
  Branch (294:25): [True: 1.76M, False: 280k]
295
280k
            is_oversized |= component_size > max_cluster_size;
296
            // Check whether overlap with set matches is_oversized.
297
280k
            if (is_oversized != set.Overlaps(component)) return false;
  Branch (297:17): [True: 0, False: 280k]
298
280k
            todo -= component;
299
280k
        }
300
34.1k
        return true;
301
34.1k
    }
302
};
303
304
} // namespace
305
306
FUZZ_TARGET(txgraph)
307
5.11k
{
308
    // This is a big simulation test for TxGraph, which performs a fuzz-derived sequence of valid
309
    // operations on a TxGraph instance, as well as on a simpler (mostly) reimplementation (see
310
    // SimTxGraph above), comparing the outcome of functions that return a result, and finally
311
    // performing a full comparison between the two.
312
313
5.11k
    SeedRandomStateForTest(SeedRand::ZEROS);
314
5.11k
    FuzzedDataProvider provider(buffer.data(), buffer.size());
315
316
    /** Internal test RNG, used only for decisions which would require significant amount of data
317
     *  to be read from the provider, without realistically impacting test sensitivity, and for
318
     *  specialized test cases that are hard to perform more generically. */
319
5.11k
    InsecureRandomContext rng(provider.ConsumeIntegral<uint64_t>());
320
321
    /** Variable used whenever an empty SimTxObject is needed. */
322
5.11k
    SimTxObject empty_ref;
323
324
    /** The maximum number of transactions per (non-oversized) cluster we will use in this
325
     *  simulation. */
326
5.11k
    auto max_cluster_count = provider.ConsumeIntegralInRange<DepGraphIndex>(1, MAX_CLUSTER_COUNT_LIMIT);
327
    /** The maximum total size of transactions in a (non-oversized) cluster. */
328
5.11k
    auto max_cluster_size = provider.ConsumeIntegralInRange<uint64_t>(1, 0x3fffff * MAX_CLUSTER_COUNT_LIMIT);
329
    /** The amount of work to consider a cluster acceptably linearized. */
330
5.11k
    auto acceptable_cost = provider.ConsumeIntegralInRange<uint64_t>(0, 10000);
331
332
    /** The set of uint64_t "txid"s that have been assigned before. */
333
5.11k
    std::set<uint64_t> assigned_txids;
334
335
    // Construct a real graph, and a vector of simulated graphs (main, and possibly staging).
336
4.18M
    auto fallback_order = [&](const TxGraph::Ref& a, const TxGraph::Ref& b) noexcept {
337
4.18M
        uint64_t txid_a = static_cast<const SimTxObject&>(a).m_txid;
338
4.18M
        uint64_t txid_b = static_cast<const SimTxObject&>(b).m_txid;
339
4.18M
        assert(assigned_txids.contains(txid_a));
  Branch (339:9): [True: 4.18M, False: 0]
340
4.18M
        assert(assigned_txids.contains(txid_b));
  Branch (340:9): [True: 4.18M, False: 0]
341
4.18M
        return txid_a <=> txid_b;
342
4.18M
    };
343
5.11k
    auto real = MakeTxGraph(
344
5.11k
        /*max_cluster_count=*/max_cluster_count,
345
5.11k
        /*max_cluster_size=*/max_cluster_size,
346
5.11k
        /*acceptable_cost=*/acceptable_cost,
347
5.11k
        /*fallback_order=*/fallback_order);
348
349
5.11k
    std::vector<SimTxGraph> sims;
350
5.11k
    sims.reserve(2);
351
5.11k
    sims.emplace_back(max_cluster_count, max_cluster_size);
352
353
    /** Struct encapsulating information about a BlockBuilder that's currently live. */
354
5.11k
    struct BlockBuilderData
355
5.11k
    {
356
        /** BlockBuilder object from real. */
357
5.11k
        std::unique_ptr<TxGraph::BlockBuilder> builder;
358
        /** The set of transactions marked as included in *builder. */
359
5.11k
        SimTxGraph::SetType included;
360
        /** The set of transactions marked as included or skipped in *builder. */
361
5.11k
        SimTxGraph::SetType done;
362
        /** The last chunk feerate returned by *builder. IsEmpty() if none yet. */
363
5.11k
        FeePerWeight last_feerate;
364
365
5.11k
        BlockBuilderData(std::unique_ptr<TxGraph::BlockBuilder> builder_in) : builder(std::move(builder_in)) {}
366
5.11k
    };
367
368
    /** Currently active block builders. */
369
5.11k
    std::vector<BlockBuilderData> block_builders;
370
371
    /** Function to pick any SimTxObject (for either sim in sims: from sim.simmap or sim.removed, or the
372
     *  empty one). */
373
618k
    auto pick_fn = [&]() noexcept -> SimTxObject* {
374
618k
        size_t tx_count[2] = {sims[0].GetTransactionCount(), 0};
375
        /** The number of possible choices. */
376
618k
        size_t choices = tx_count[0] + sims[0].removed.size() + 1;
377
618k
        if (sims.size() == 2) {
  Branch (377:13): [True: 200k, False: 418k]
378
200k
            tx_count[1] = sims[1].GetTransactionCount();
379
200k
            choices += tx_count[1] + sims[1].removed.size();
380
200k
        }
381
        /** Pick one of them. */
382
618k
        auto choice = provider.ConsumeIntegralInRange<size_t>(0, choices - 1);
383
        // Consider both main and (if it exists) staging.
384
809k
        for (size_t level = 0; level < sims.size(); ++level) {
  Branch (384:32): [True: 718k, False: 91.2k]
385
718k
            auto& sim = sims[level];
386
718k
            if (choice < tx_count[level]) {
  Branch (386:17): [True: 486k, False: 231k]
387
                // Return from graph.
388
5.10M
                for (auto i : sim.graph.Positions()) {
  Branch (388:29): [True: 5.10M, False: 0]
389
5.10M
                    if (choice == 0) return sim.GetRef(i);
  Branch (389:25): [True: 486k, False: 4.61M]
390
4.61M
                    --choice;
391
4.61M
                }
392
486k
                assert(false);
  Branch (392:17): [Folded - Ignored]
393
231k
            } else {
394
231k
                choice -= tx_count[level];
395
231k
            }
396
231k
            if (choice < sim.removed.size()) {
  Branch (396:17): [True: 40.5k, False: 191k]
397
                // Return from removed.
398
40.5k
                return sim.removed[choice].get();
399
191k
            } else {
400
191k
                choice -= sim.removed.size();
401
191k
            }
402
231k
        }
403
        // Return empty.
404
618k
        assert(choice == 0);
  Branch (404:9): [True: 91.2k, False: 0]
405
91.2k
        return &empty_ref;
406
91.2k
    };
407
408
    /** Function to construct the correct fee-size diagram a real graph has based on its graph
409
     *  order (as reported by GetCluster(), so it works for both main and staging). */
410
6.27k
    auto get_diagram_fn = [&](TxGraph::Level level_select) -> std::vector<FeeFrac> {
411
6.27k
        int level = level_select == TxGraph::Level::MAIN ? 0 : sims.size() - 1;
  Branch (411:21): [True: 4.22k, False: 2.05k]
412
6.27k
        auto& sim = sims[level];
413
        // For every transaction in the graph, request its cluster, and throw them into a set.
414
6.27k
        std::set<std::vector<TxGraph::Ref*>> clusters;
415
263k
        for (auto i : sim.graph.Positions()) {
  Branch (415:21): [True: 263k, False: 6.27k]
416
263k
            auto ref = sim.GetRef(i);
417
263k
            clusters.insert(real->GetCluster(*ref, level_select));
418
263k
        }
419
        // Compute the chunkings of each (deduplicated) cluster.
420
6.27k
        size_t num_tx{0};
421
6.27k
        std::vector<FeeFrac> chunk_feerates;
422
156k
        for (const auto& cluster : clusters) {
  Branch (422:34): [True: 156k, False: 6.27k]
423
156k
            num_tx += cluster.size();
424
156k
            std::vector<SimTxGraph::Pos> linearization;
425
156k
            linearization.reserve(cluster.size());
426
263k
            for (auto refptr : cluster) linearization.push_back(sim.Find(refptr));
  Branch (426:30): [True: 263k, False: 156k]
427
218k
            for (const FeeFrac& chunk_feerate : ChunkLinearization(sim.graph, linearization)) {
  Branch (427:47): [True: 218k, False: 156k]
428
218k
                chunk_feerates.push_back(chunk_feerate);
429
218k
            }
430
156k
        }
431
        // Verify the number of transactions after deduplicating clusters. This implicitly verifies
432
        // that GetCluster on each element of a cluster reports the cluster transactions in the same
433
        // order.
434
6.27k
        assert(num_tx == sim.GetTransactionCount());
  Branch (434:9): [True: 6.27k, False: 0]
435
        // Sort by feerate only, since violating topological constraints within same-feerate
436
        // chunks won't affect diagram comparisons.
437
6.27k
        std::ranges::sort(chunk_feerates, std::greater<ByRatioNegSize<FeeFrac>>{});
438
6.27k
        return chunk_feerates;
439
6.27k
    };
440
441
729k
    LIMITED_WHILE (provider.remaining_bytes() > 0, 200) {
442
        // Read a one-byte command.
443
729k
        int command = provider.ConsumeIntegral<uint8_t>();
444
729k
        int orig_command = command;
445
446
        // Treat the lowest bit of a command as a flag (which selects a variant of some of the
447
        // operations), and the second-lowest bit as a way of selecting main vs. staging, and leave
448
        // the rest of the bits in command.
449
729k
        bool alt = command & 1;
450
729k
        TxGraph::Level level_select = (command & 2) ? TxGraph::Level::MAIN : TxGraph::Level::TOP;
  Branch (450:39): [True: 289k, False: 440k]
451
729k
        command >>= 2;
452
453
        /** Use the bottom 2 bits of command to select an entry in the block_builders vector (if
454
         *  any). These use the same bits as alt/level_select, so don't use those in actions below
455
         *  where builder_idx is used as well. */
456
729k
        int builder_idx = block_builders.empty() ? -1 : int((orig_command & 3) % block_builders.size());
  Branch (456:27): [True: 670k, False: 59.3k]
457
458
        // Provide convenient aliases for the top simulated graph (main, or staging if it exists),
459
        // one for the simulated graph selected based on level_select (for operations that can operate
460
        // on both graphs), and one that always refers to the main graph.
461
729k
        auto& top_sim = sims.back();
462
729k
        auto& sel_sim = level_select == TxGraph::Level::MAIN ? sims[0] : top_sim;
  Branch (462:25): [True: 289k, False: 440k]
463
729k
        auto& main_sim = sims[0];
464
465
        // Keep decrementing command for each applicable operation, until one is hit. Multiple
466
        // iterations may be necessary.
467
1.06M
        while (true) {
  Branch (467:16): [Folded - Ignored]
468
1.06M
            if ((block_builders.empty() || sims.size() > 1) && top_sim.GetTransactionCount() < SimTxGraph::MAX_TRANSACTIONS && command-- == 0) {
  Branch (468:18): [True: 964k, False: 100k]
  Branch (468:44): [True: 63.3k, False: 37.3k]
  Branch (468:64): [True: 1.01M, False: 15.7k]
  Branch (468:128): [True: 343k, False: 668k]
469
                // AddTransaction.
470
343k
                int64_t fee;
471
343k
                int32_t size;
472
343k
                if (alt) {
  Branch (472:21): [True: 8.63k, False: 334k]
473
                    // If alt is true, pick fee and size from the entire range.
474
8.63k
                    fee = provider.ConsumeIntegralInRange<int64_t>(-0x8000000000000, 0x7ffffffffffff);
475
8.63k
                    size = provider.ConsumeIntegralInRange<int32_t>(1, 0x3fffff);
476
334k
                } else {
477
                    // Otherwise, use smaller range which consume fewer fuzz input bytes, as just
478
                    // these are likely sufficient to trigger all interesting code paths already.
479
334k
                    fee = provider.ConsumeIntegral<uint8_t>();
480
334k
                    size = provider.ConsumeIntegralInRange<uint32_t>(1, 0xff);
481
334k
                }
482
343k
                FeePerWeight feerate{fee, size};
483
                // Pick a novel txid (and not 0, which is reserved for empty_ref).
484
343k
                uint64_t txid;
485
343k
                do {
486
343k
                    txid = rng.rand64();
487
343k
                } while (txid == 0 || assigned_txids.contains(txid));
  Branch (487:26): [True: 0, False: 343k]
  Branch (487:39): [True: 0, False: 343k]
488
343k
                assigned_txids.insert(txid);
489
                // Create the transaction in the simulation and the real graph.
490
343k
                top_sim.AddTransaction(*real, feerate, txid);
491
343k
                break;
492
721k
            } else if ((block_builders.empty() || sims.size() > 1) && top_sim.GetTransactionCount() + top_sim.removed.size() > 1 && command-- == 0) {
  Branch (492:25): [True: 630k, False: 91.4k]
  Branch (492:51): [True: 54.0k, False: 37.3k]
  Branch (492:71): [True: 635k, False: 49.1k]
  Branch (492:133): [True: 39.8k, False: 595k]
493
                // AddDependency.
494
39.8k
                auto par = pick_fn();
495
39.8k
                auto chl = pick_fn();
496
39.8k
                auto pos_par = top_sim.Find(par);
497
39.8k
                auto pos_chl = top_sim.Find(chl);
498
39.8k
                if (pos_par != SimTxGraph::MISSING && pos_chl != SimTxGraph::MISSING) {
  Branch (498:21): [True: 34.9k, False: 4.92k]
  Branch (498:55): [True: 31.4k, False: 3.44k]
499
                    // Determine if adding this would introduce a cycle (not allowed by TxGraph),
500
                    // and if so, skip.
501
31.4k
                    if (top_sim.graph.Ancestors(pos_par)[pos_chl]) break;
  Branch (501:25): [True: 7.51k, False: 23.9k]
502
31.4k
                }
503
32.3k
                top_sim.AddDependency(par, chl);
504
32.3k
                top_sim.real_is_optimal = false;
505
32.3k
                real->AddDependency(*par, *chl);
506
32.3k
                break;
507
681k
            } else if ((block_builders.empty() || sims.size() > 1) && top_sim.removed.size() < 100 && command-- == 0) {
  Branch (507:25): [True: 591k, False: 90.3k]
  Branch (507:51): [True: 52.9k, False: 37.3k]
  Branch (507:71): [True: 637k, False: 6.67k]
  Branch (507:103): [True: 18.2k, False: 619k]
508
                // RemoveTransaction. Either all its ancestors or all its descendants are also
509
                // removed (if any), to make sure TxGraph's reordering of removals and dependencies
510
                // has no effect.
511
18.2k
                std::vector<TxGraph::Ref*> to_remove;
512
18.2k
                to_remove.push_back(pick_fn());
513
18.2k
                top_sim.IncludeAncDesc(to_remove, alt);
514
                // The order in which these ancestors/descendants are removed should not matter;
515
                // randomly shuffle them.
516
18.2k
                std::shuffle(to_remove.begin(), to_remove.end(), rng);
517
21.2k
                for (TxGraph::Ref* ptr : to_remove) {
  Branch (517:40): [True: 21.2k, False: 18.2k]
518
21.2k
                    real->RemoveTransaction(*ptr);
519
21.2k
                    top_sim.RemoveTransaction(ptr);
520
21.2k
                }
521
18.2k
                break;
522
663k
            } else if (sel_sim.removed.size() > 0 && command-- == 0) {
  Branch (522:24): [True: 306k, False: 357k]
  Branch (522:54): [True: 5.31k, False: 300k]
523
                // ~Ref (of an already-removed transaction). Destroying a TxGraph::Ref has an
524
                // observable effect on the TxGraph it refers to, so this simulation permits doing
525
                // so separately from other actions on TxGraph.
526
527
                // Pick a Ref of sel_sim.removed to destroy. Note that the same Ref may still occur
528
                // in the other graph, and thus not actually trigger ~Ref yet (which is exactly
529
                // what we want, as destroying Refs is only allowed when it does not refer to an
530
                // existing transaction in either graph).
531
5.31k
                auto removed_pos = provider.ConsumeIntegralInRange<size_t>(0, sel_sim.removed.size() - 1);
532
5.31k
                if (removed_pos != sel_sim.removed.size() - 1) {
  Branch (532:21): [True: 3.20k, False: 2.10k]
533
3.20k
                    std::swap(sel_sim.removed[removed_pos], sel_sim.removed.back());
534
3.20k
                }
535
5.31k
                sel_sim.removed.pop_back();
536
5.31k
                break;
537
658k
            } else if (block_builders.empty() && command-- == 0) {
  Branch (537:24): [True: 571k, False: 87.2k]
  Branch (537:50): [True: 24.4k, False: 546k]
538
                // ~Ref (of any transaction).
539
24.4k
                std::vector<TxGraph::Ref*> to_destroy;
540
24.4k
                to_destroy.push_back(pick_fn());
541
27.0k
                while (true) {
  Branch (541:24): [Folded - Ignored]
542
                    // Keep adding either the ancestors or descendants the already picked
543
                    // transactions have in both graphs (main and staging) combined. Destroying
544
                    // will trigger deletions in both, so to have consistent TxGraph behavior, the
545
                    // set must be closed under ancestors, or descendants, in both graphs.
546
27.0k
                    auto old_size = to_destroy.size();
547
42.3k
                    for (auto& sim : sims) sim.IncludeAncDesc(to_destroy, alt);
  Branch (547:36): [True: 42.3k, False: 27.0k]
548
27.0k
                    if (to_destroy.size() == old_size) break;
  Branch (548:25): [True: 24.4k, False: 2.57k]
549
27.0k
                }
550
                // The order in which these ancestors/descendants are destroyed should not matter;
551
                // randomly shuffle them.
552
24.4k
                std::shuffle(to_destroy.begin(), to_destroy.end(), rng);
553
32.3k
                for (TxGraph::Ref* ptr : to_destroy) {
  Branch (553:40): [True: 32.3k, False: 24.4k]
554
84.1k
                    for (size_t level = 0; level < sims.size(); ++level) {
  Branch (554:44): [True: 51.7k, False: 32.3k]
555
51.7k
                        sims[level].DestroyTransaction(ptr, level == sims.size() - 1);
556
51.7k
                    }
557
32.3k
                }
558
24.4k
                break;
559
633k
            } else if (block_builders.empty() && command-- == 0) {
  Branch (559:24): [True: 546k, False: 87.2k]
  Branch (559:50): [True: 9.26k, False: 537k]
560
                // SetTransactionFee.
561
9.26k
                int64_t fee;
562
9.26k
                if (alt) {
  Branch (562:21): [True: 3.48k, False: 5.77k]
563
3.48k
                    fee = provider.ConsumeIntegralInRange<int64_t>(-0x8000000000000, 0x7ffffffffffff);
564
5.77k
                } else {
565
5.77k
                    fee = provider.ConsumeIntegral<uint8_t>();
566
5.77k
                }
567
9.26k
                auto ref = pick_fn();
568
9.26k
                real->SetTransactionFee(*ref, fee);
569
11.8k
                for (auto& sim : sims) {
  Branch (569:32): [True: 11.8k, False: 9.26k]
570
11.8k
                    sim.SetTransactionFee(ref, fee);
571
11.8k
                }
572
9.26k
                break;
573
624k
            } else if (command-- == 0) {
  Branch (573:24): [True: 10.8k, False: 613k]
574
                // GetTransactionCount.
575
10.8k
                assert(real->GetTransactionCount(level_select) == sel_sim.GetTransactionCount());
  Branch (575:17): [True: 10.8k, False: 0]
576
10.8k
                break;
577
613k
            } else if (command-- == 0) {
  Branch (577:24): [True: 8.67k, False: 605k]
578
                // Exists.
579
8.67k
                auto ref = pick_fn();
580
8.67k
                bool exists = real->Exists(*ref, level_select);
581
8.67k
                bool should_exist = sel_sim.Find(ref) != SimTxGraph::MISSING;
582
8.67k
                assert(exists == should_exist);
  Branch (582:17): [True: 8.67k, False: 0]
583
8.67k
                break;
584
605k
            } else if (command-- == 0) {
  Branch (584:24): [True: 15.3k, False: 589k]
585
                // IsOversized.
586
15.3k
                assert(sel_sim.IsOversized() == real->IsOversized(level_select));
  Branch (586:17): [True: 15.3k, False: 0]
587
15.3k
                break;
588
589k
            } else if (command-- == 0) {
  Branch (588:24): [True: 8.71k, False: 580k]
589
                // GetIndividualFeerate.
590
8.71k
                auto ref = pick_fn();
591
8.71k
                auto feerate = real->GetIndividualFeerate(*ref);
592
8.71k
                bool found{false};
593
12.1k
                for (auto& sim : sims) {
  Branch (593:32): [True: 12.1k, False: 8.71k]
594
12.1k
                    auto simpos = sim.Find(ref);
595
12.1k
                    if (simpos != SimTxGraph::MISSING) {
  Branch (595:25): [True: 6.35k, False: 5.78k]
596
6.35k
                        found = true;
597
6.35k
                        assert(feerate == sim.graph.FeeRate(simpos));
  Branch (597:25): [True: 6.35k, False: 0]
598
6.35k
                    }
599
12.1k
                }
600
8.71k
                if (!found) assert(feerate.IsEmpty());
  Branch (600:21): [True: 3.16k, False: 5.55k]
  Branch (600:29): [True: 3.16k, False: 0]
601
8.71k
                break;
602
580k
            } else if (!main_sim.IsOversized() && command-- == 0) {
  Branch (602:24): [True: 465k, False: 115k]
  Branch (602:51): [True: 7.32k, False: 457k]
603
                // GetMainChunkFeerate.
604
7.32k
                auto ref = pick_fn();
605
7.32k
                auto feerate = real->GetMainChunkFeerate(*ref);
606
7.32k
                auto simpos = main_sim.Find(ref);
607
7.32k
                if (simpos == SimTxGraph::MISSING) {
  Branch (607:21): [True: 2.53k, False: 4.79k]
608
2.53k
                    assert(feerate.IsEmpty());
  Branch (608:21): [True: 2.53k, False: 0]
609
4.79k
                } else {
610
                    // Just do some quick checks that the reported value is in range. A full
611
                    // recomputation of expected chunk feerates is done at the end.
612
4.79k
                    assert(feerate.size >= main_sim.graph.FeeRate(simpos).size);
  Branch (612:21): [True: 4.79k, False: 0]
613
4.79k
                    assert(feerate.size <= main_sim.SumAll().size);
  Branch (613:21): [True: 4.79k, False: 0]
614
4.79k
                }
615
7.32k
                break;
616
573k
            } else if (!sel_sim.IsOversized() && command-- == 0) {
  Branch (616:24): [True: 461k, False: 112k]
  Branch (616:50): [True: 12.3k, False: 448k]
617
                // GetAncestors/GetDescendants.
618
12.3k
                auto ref = pick_fn();
619
12.3k
                auto result = alt ? real->GetDescendants(*ref, level_select)
  Branch (619:31): [True: 6.43k, False: 5.96k]
620
12.3k
                                  : real->GetAncestors(*ref, level_select);
621
12.3k
                assert(result.size() <= max_cluster_count);
  Branch (621:17): [True: 12.3k, False: 0]
622
12.3k
                auto result_set = sel_sim.MakeSet(result);
623
12.3k
                assert(result.size() == result_set.Count());
  Branch (623:17): [True: 12.3k, False: 0]
624
12.3k
                auto expect_set = sel_sim.GetAncDesc(ref, alt);
625
12.3k
                assert(result_set == expect_set);
  Branch (625:17): [True: 12.3k, False: 0]
626
12.3k
                break;
627
561k
            } else if (!sel_sim.IsOversized() && command-- == 0) {
  Branch (627:24): [True: 448k, False: 112k]
  Branch (627:50): [True: 13.3k, False: 435k]
628
                // GetAncestorsUnion/GetDescendantsUnion.
629
13.3k
                std::vector<TxGraph::Ref*> refs;
630
                // Gather a list of up to 15 Ref pointers.
631
13.3k
                auto count = provider.ConsumeIntegralInRange<size_t>(0, 15);
632
13.3k
                refs.resize(count);
633
93.7k
                for (size_t i = 0; i < count; ++i) {
  Branch (633:36): [True: 80.4k, False: 13.3k]
634
80.4k
                    refs[i] = pick_fn();
635
80.4k
                }
636
                // Their order should not matter, shuffle them.
637
13.3k
                std::shuffle(refs.begin(), refs.end(), rng);
638
                // Invoke the real function, and convert to SimPos set.
639
13.3k
                auto result = alt ? real->GetDescendantsUnion(refs, level_select)
  Branch (639:31): [True: 6.38k, False: 6.97k]
640
13.3k
                                  : real->GetAncestorsUnion(refs, level_select);
641
13.3k
                auto result_set = sel_sim.MakeSet(result);
642
13.3k
                assert(result.size() == result_set.Count());
  Branch (642:17): [True: 13.3k, False: 0]
643
                // Compute the expected result.
644
13.3k
                SimTxGraph::SetType expect_set;
645
80.4k
                for (TxGraph::Ref* ref : refs) expect_set |= sel_sim.GetAncDesc(ref, alt);
  Branch (645:40): [True: 80.4k, False: 13.3k]
646
                // Compare.
647
13.3k
                assert(result_set == expect_set);
  Branch (647:17): [True: 13.3k, False: 0]
648
13.3k
                break;
649
547k
            } else if (!sel_sim.IsOversized() && command-- == 0) {
  Branch (649:24): [True: 435k, False: 112k]
  Branch (649:50): [True: 9.26k, False: 426k]
650
                // GetCluster.
651
9.26k
                auto ref = pick_fn();
652
9.26k
                auto result = real->GetCluster(*ref, level_select);
653
                // Check cluster count limit.
654
9.26k
                assert(result.size() <= max_cluster_count);
  Branch (654:17): [True: 9.26k, False: 0]
655
                // Require the result to be topologically valid and not contain duplicates.
656
9.26k
                auto left = sel_sim.graph.Positions();
657
9.26k
                uint64_t total_size{0};
658
55.5k
                for (auto refptr : result) {
  Branch (658:34): [True: 55.5k, False: 9.26k]
659
55.5k
                    auto simpos = sel_sim.Find(refptr);
660
55.5k
                    total_size += sel_sim.graph.FeeRate(simpos).size;
661
55.5k
                    assert(simpos != SimTxGraph::MISSING);
  Branch (661:21): [True: 55.5k, False: 0]
662
55.5k
                    assert(left[simpos]);
  Branch (662:21): [True: 55.5k, False: 0]
663
55.5k
                    left.Reset(simpos);
664
55.5k
                    assert(!sel_sim.graph.Ancestors(simpos).Overlaps(left));
  Branch (664:21): [True: 55.5k, False: 0]
665
55.5k
                }
666
                // Check cluster size limit.
667
9.26k
                assert(total_size <= max_cluster_size);
  Branch (667:17): [True: 9.26k, False: 0]
668
                // Require the set to be connected.
669
9.26k
                auto result_set = sel_sim.MakeSet(result);
670
9.26k
                assert(sel_sim.graph.IsConnected(result_set));
  Branch (670:17): [True: 9.26k, False: 0]
671
                // If ref exists, the result must contain it. If not, it must be empty.
672
9.26k
                auto simpos = sel_sim.Find(ref);
673
9.26k
                if (simpos != SimTxGraph::MISSING) {
  Branch (673:21): [True: 5.07k, False: 4.19k]
674
5.07k
                    assert(result_set[simpos]);
  Branch (674:21): [True: 5.07k, False: 0]
675
5.07k
                } else {
676
4.19k
                    assert(result_set.None());
  Branch (676:21): [True: 4.19k, False: 0]
677
4.19k
                }
678
                // Require the set not to have ancestors or descendants outside of it.
679
55.5k
                for (auto i : result_set) {
  Branch (679:29): [True: 55.5k, False: 9.26k]
680
55.5k
                    assert(sel_sim.graph.Ancestors(i).IsSubsetOf(result_set));
  Branch (680:21): [True: 55.5k, False: 0]
681
55.5k
                    assert(sel_sim.graph.Descendants(i).IsSubsetOf(result_set));
  Branch (681:21): [True: 55.5k, False: 0]
682
55.5k
                }
683
9.26k
                break;
684
538k
            } else if (command-- == 0) {
  Branch (684:24): [True: 9.60k, False: 529k]
685
                // HaveStaging.
686
9.60k
                assert((sims.size() == 2) == real->HaveStaging());
  Branch (686:17): [True: 9.60k, False: 0]
687
9.60k
                break;
688
529k
            } else if (sims.size() < 2 && command-- == 0) {
  Branch (688:24): [True: 312k, False: 216k]
  Branch (688:43): [True: 23.6k, False: 288k]
689
                // StartStaging.
690
23.6k
                sims.emplace_back(sims.back());
691
23.6k
                sims.back().modified = SimTxGraph::SetType{};
692
23.6k
                real->StartStaging();
693
23.6k
                break;
694
505k
            } else if (block_builders.empty() && sims.size() > 1 && command-- == 0) {
  Branch (694:24): [True: 435k, False: 70.1k]
  Branch (694:50): [True: 171k, False: 263k]
  Branch (694:69): [True: 5.04k, False: 166k]
695
                // CommitStaging.
696
5.04k
                real->CommitStaging();
697
                // Resulting main level is only guaranteed to be optimal if all levels are
698
5.57k
                const bool main_optimal = std::all_of(sims.cbegin(), sims.cend(), [](const auto &sim) { return sim.real_is_optimal; });
699
5.04k
                sims.erase(sims.begin());
700
5.04k
                sims.front().real_is_optimal = main_optimal;
701
5.04k
                break;
702
500k
            } else if (sims.size() > 1 && command-- == 0) {
  Branch (702:24): [True: 211k, False: 288k]
  Branch (702:43): [True: 16.1k, False: 195k]
703
                // AbortStaging.
704
16.1k
                real->AbortStaging();
705
16.1k
                sims.pop_back();
706
                // Reset the cached oversized value (if TxGraph::Ref destructions triggered
707
                // removals of main transactions while staging was active, then aborting will
708
                // cause it to be re-evaluated in TxGraph).
709
16.1k
                sims.back().oversized = std::nullopt;
710
16.1k
                break;
711
484k
            } else if (!main_sim.IsOversized() && command-- == 0) {
  Branch (711:24): [True: 379k, False: 104k]
  Branch (711:51): [True: 8.75k, False: 371k]
712
                // CompareMainOrder.
713
8.75k
                auto ref_a = pick_fn();
714
8.75k
                auto ref_b = pick_fn();
715
8.75k
                auto sim_a = main_sim.Find(ref_a);
716
8.75k
                auto sim_b = main_sim.Find(ref_b);
717
                // Both transactions must exist in the main graph.
718
8.75k
                if (sim_a == SimTxGraph::MISSING || sim_b == SimTxGraph::MISSING) break;
  Branch (718:21): [True: 3.02k, False: 5.72k]
  Branch (718:53): [True: 755, False: 4.97k]
719
4.97k
                auto cmp = real->CompareMainOrder(*ref_a, *ref_b);
720
                // Distinct transactions have distinct places.
721
4.97k
                if (sim_a != sim_b) assert(cmp != 0);
  Branch (721:21): [True: 2.87k, False: 2.09k]
  Branch (721:37): [True: 2.87k, False: 0]
722
                // Ancestors go before descendants.
723
4.97k
                if (main_sim.graph.Ancestors(sim_a)[sim_b]) assert(cmp >= 0);
  Branch (723:21): [True: 2.12k, False: 2.84k]
  Branch (723:61): [True: 2.12k, False: 0]
724
4.97k
                if (main_sim.graph.Descendants(sim_a)[sim_b]) assert(cmp <= 0);
  Branch (724:21): [True: 2.13k, False: 2.84k]
  Branch (724:63): [True: 2.13k, False: 0]
725
                // Do not verify consistency with chunk feerates, as we cannot easily determine
726
                // these here without making more calls to real, which could affect its internal
727
                // state. A full comparison is done at the end.
728
4.97k
                break;
729
475k
            } else if (!sel_sim.IsOversized() && command-- == 0) {
  Branch (729:24): [True: 373k, False: 101k]
  Branch (729:50): [True: 10.4k, False: 363k]
730
                // CountDistinctClusters.
731
10.4k
                std::vector<TxGraph::Ref*> refs;
732
                // Gather a list of up to 15 (or up to 255) Ref pointers.
733
10.4k
                auto count = provider.ConsumeIntegralInRange<size_t>(0, alt ? 255 : 15);
  Branch (733:73): [True: 2.91k, False: 7.54k]
734
10.4k
                refs.resize(count);
735
352k
                for (size_t i = 0; i < count; ++i) {
  Branch (735:36): [True: 342k, False: 10.4k]
736
342k
                    refs[i] = pick_fn();
737
342k
                }
738
                // Their order should not matter, shuffle them.
739
10.4k
                std::shuffle(refs.begin(), refs.end(), rng);
740
                // Invoke the real function.
741
10.4k
                auto result = real->CountDistinctClusters(refs, level_select);
742
                // Build a set with representatives of the clusters the Refs occur in the
743
                // simulated graph. For each, remember the lowest-index transaction SimPos in the
744
                // cluster.
745
10.4k
                SimTxGraph::SetType sim_reps;
746
342k
                for (auto ref : refs) {
  Branch (746:31): [True: 342k, False: 10.4k]
747
                    // Skip Refs that do not occur in the simulated graph.
748
342k
                    auto simpos = sel_sim.Find(ref);
749
342k
                    if (simpos == SimTxGraph::MISSING) continue;
  Branch (749:25): [True: 74.6k, False: 267k]
750
                    // Find the component that includes ref.
751
267k
                    auto component = sel_sim.graph.GetConnectedComponent(sel_sim.graph.Positions(), simpos);
752
                    // Remember the lowest-index SimPos in component, as a representative for it.
753
267k
                    assert(component.Any());
  Branch (753:21): [True: 267k, False: 0]
754
267k
                    sim_reps.Set(component.First());
755
267k
                }
756
                // Compare the number of deduplicated representatives with the value returned by
757
                // the real function.
758
10.4k
                assert(result == sim_reps.Count());
  Branch (758:17): [True: 10.4k, False: 0]
759
10.4k
                break;
760
464k
            } else if (command-- == 0) {
  Branch (760:24): [True: 18.6k, False: 446k]
761
                // DoWork.
762
18.6k
                uint64_t max_cost = provider.ConsumeIntegralInRange<uint64_t>(0, alt ? 10000 : 255);
  Branch (762:82): [True: 9.94k, False: 8.67k]
763
18.6k
                bool ret = real->DoWork(max_cost);
764
18.6k
                uint64_t cost_for_optimal{0};
765
44.9k
                for (unsigned level = 0; level < sims.size(); ++level) {
  Branch (765:42): [True: 26.3k, False: 18.6k]
766
                    // DoWork() will not optimize oversized levels, or the main level if a builder
767
                    // is present. Note that this impacts the DoWork() return value, as true means
768
                    // that non-optimal clusters may remain within such oversized or builder-having
769
                    // levels.
770
26.3k
                    if (sims[level].IsOversized()) continue;
  Branch (770:25): [True: 5.13k, False: 21.2k]
771
21.2k
                    if (level == 0 && !block_builders.empty()) continue;
  Branch (771:25): [True: 14.4k, False: 6.79k]
  Branch (771:39): [True: 4.01k, False: 10.4k]
772
                    // If neither of the two above conditions holds, and DoWork() returned true,
773
                    // then the level is optimal.
774
17.2k
                    if (ret) {
  Branch (774:25): [True: 8.08k, False: 9.13k]
775
8.08k
                        sims[level].real_is_optimal = true;
776
8.08k
                    }
777
                    // Compute how much work would be needed to make everything optimal.
778
464k
                    for (auto component : sims[level].GetComponents()) {
  Branch (778:41): [True: 464k, False: 17.2k]
779
464k
                        auto cost_opt_this_cluster = MaxOptimalLinearizationCost(component.Count());
780
464k
                        if (cost_opt_this_cluster > acceptable_cost) {
  Branch (780:29): [True: 25.6k, False: 438k]
781
                            // If the amount of work required to linearize this cluster
782
                            // optimally exceeds acceptable_cost, DoWork() may process it in two
783
                            // stages: once to acceptable, and once to optimal.
784
25.6k
                            cost_for_optimal += cost_opt_this_cluster + acceptable_cost;
785
438k
                        } else {
786
438k
                            cost_for_optimal += cost_opt_this_cluster;
787
438k
                        }
788
464k
                    }
789
17.2k
                }
790
18.6k
                if (!ret) {
  Branch (790:21): [True: 6.87k, False: 11.7k]
791
                    // DoWork can only have more work left if the requested amount of work
792
                    // was insufficient to linearize everything optimally within the levels it is
793
                    // allowed to touch.
794
6.87k
                    assert(max_cost <= cost_for_optimal);
  Branch (794:21): [True: 6.87k, False: 0]
795
6.87k
                }
796
18.6k
                break;
797
446k
            } else if (sims.size() == 2 && !sims[0].IsOversized() && !sims[1].IsOversized() && command-- == 0) {
  Branch (797:24): [True: 182k, False: 263k]
  Branch (797:44): [True: 150k, False: 32.0k]
  Branch (797:70): [True: 145k, False: 4.95k]
  Branch (797:96): [True: 31.8k, False: 113k]
798
                // GetMainStagingDiagrams()
799
31.8k
                auto [real_main_diagram, real_staged_diagram] = real->GetMainStagingDiagrams();
800
31.8k
                auto real_sum_main = std::accumulate(real_main_diagram.begin(), real_main_diagram.end(), FeeFrac{});
801
31.8k
                auto real_sum_staged = std::accumulate(real_staged_diagram.begin(), real_staged_diagram.end(), FeeFrac{});
802
31.8k
                auto real_gain = real_sum_staged - real_sum_main;
803
31.8k
                auto sim_gain = sims[1].SumAll() - sims[0].SumAll();
804
                // Just check that the total fee gained/lost and size gained/lost according to the
805
                // diagram matches the difference in these values in the simulated graph. A more
806
                // complete check of the GetMainStagingDiagrams result is performed at the end.
807
31.8k
                assert(sim_gain == real_gain);
  Branch (807:17): [True: 31.8k, False: 0]
808
                // Check that the feerates in each diagram are monotonically decreasing.
809
1.01M
                for (size_t i = 1; i < real_main_diagram.size(); ++i) {
  Branch (809:36): [True: 982k, False: 31.8k]
810
982k
                    assert(ByRatio{real_main_diagram[i]} <= ByRatio{real_main_diagram[i - 1]});
  Branch (810:21): [True: 982k, False: 0]
811
982k
                }
812
701k
                for (size_t i = 1; i < real_staged_diagram.size(); ++i) {
  Branch (812:36): [True: 669k, False: 31.8k]
813
669k
                    assert(ByRatio{real_staged_diagram[i]} <= ByRatio{real_staged_diagram[i - 1]});
  Branch (813:21): [True: 669k, False: 0]
814
669k
                }
815
31.8k
                break;
816
414k
            } else if (block_builders.size() < 4 && !main_sim.IsOversized() && command-- == 0) {
  Branch (816:24): [True: 398k, False: 15.8k]
  Branch (816:53): [True: 298k, False: 99.6k]
  Branch (816:80): [True: 3.25k, False: 295k]
817
                // GetBlockBuilder.
818
3.25k
                block_builders.emplace_back(real->GetBlockBuilder());
819
3.25k
                break;
820
411k
            } else if (!block_builders.empty() && command-- == 0) {
  Branch (820:24): [True: 57.7k, False: 353k]
  Branch (820:51): [True: 1.67k, False: 56.0k]
821
                // ~BlockBuilder.
822
1.67k
                block_builders.erase(block_builders.begin() + builder_idx);
823
1.67k
                break;
824
409k
            } else if (!block_builders.empty() && command-- == 0) {
  Branch (824:24): [True: 56.0k, False: 353k]
  Branch (824:51): [True: 7.48k, False: 48.5k]
825
                // BlockBuilder::GetCurrentChunk, followed by Include/Skip.
826
7.48k
                auto& builder_data = block_builders[builder_idx];
827
7.48k
                auto new_included = builder_data.included;
828
7.48k
                auto new_done = builder_data.done;
829
7.48k
                auto chunk = builder_data.builder->GetCurrentChunk();
830
7.48k
                if (chunk) {
  Branch (830:21): [True: 4.71k, False: 2.77k]
831
                    // Chunk feerates must be monotonously decreasing.
832
4.71k
                    if (!builder_data.last_feerate.IsEmpty()) {
  Branch (832:25): [True: 3.73k, False: 976]
833
3.73k
                        assert(ByRatio{chunk->second} <= ByRatio{builder_data.last_feerate});
  Branch (833:25): [True: 3.73k, False: 0]
834
3.73k
                    }
835
4.71k
                    builder_data.last_feerate = chunk->second;
836
                    // Verify the contents of GetCurrentChunk.
837
4.71k
                    FeePerWeight sum_feerate;
838
6.64k
                    for (TxGraph::Ref* ref : chunk->first) {
  Branch (838:44): [True: 6.64k, False: 4.71k]
839
                        // Each transaction in the chunk must exist in the main graph.
840
6.64k
                        auto simpos = main_sim.Find(ref);
841
6.64k
                        assert(simpos != SimTxGraph::MISSING);
  Branch (841:25): [True: 6.64k, False: 0]
842
                        // Verify the claimed chunk feerate.
843
6.64k
                        sum_feerate += main_sim.graph.FeeRate(simpos);
844
                        // Make sure no transaction is reported twice.
845
6.64k
                        assert(!new_done[simpos]);
  Branch (845:25): [True: 6.64k, False: 0]
846
6.64k
                        new_done.Set(simpos);
847
                        // The concatenation of all included transactions must be topologically valid.
848
6.64k
                        new_included.Set(simpos);
849
6.64k
                        assert(main_sim.graph.Ancestors(simpos).IsSubsetOf(new_included));
  Branch (849:25): [True: 6.64k, False: 0]
850
6.64k
                    }
851
4.71k
                    assert(sum_feerate == chunk->second);
  Branch (851:21): [True: 4.71k, False: 0]
852
4.71k
                } else {
853
                    // When we reach the end, if nothing was skipped, the entire graph should have
854
                    // been reported.
855
2.77k
                    if (builder_data.done == builder_data.included) {
  Branch (855:25): [True: 1.14k, False: 1.62k]
856
1.14k
                        assert(builder_data.done.Count() == main_sim.GetTransactionCount());
  Branch (856:25): [True: 1.14k, False: 0]
857
1.14k
                    }
858
2.77k
                }
859
                // Possibly invoke GetCurrentChunk() again, which should give the same result.
860
7.48k
                if ((orig_command % 7) >= 5) {
  Branch (860:21): [True: 2.28k, False: 5.20k]
861
2.28k
                    auto chunk2 = builder_data.builder->GetCurrentChunk();
862
2.28k
                    assert(chunk == chunk2);
  Branch (862:21): [True: 2.28k, False: 0]
863
2.28k
                }
864
                // Skip or include.
865
7.48k
                if ((orig_command % 5) >= 3) {
  Branch (865:21): [True: 4.66k, False: 2.81k]
866
                    // Skip.
867
4.66k
                    builder_data.builder->Skip();
868
4.66k
                } else {
869
                    // Include.
870
2.81k
                    builder_data.builder->Include();
871
2.81k
                    builder_data.included = new_included;
872
2.81k
                }
873
7.48k
                builder_data.done = new_done;
874
7.48k
                break;
875
402k
            } else if (!main_sim.IsOversized() && command-- == 0) {
  Branch (875:24): [True: 302k, False: 99.6k]
  Branch (875:51): [True: 13.7k, False: 288k]
876
                // GetWorstMainChunk.
877
13.7k
                auto [worst_chunk, worst_chunk_feerate] = real->GetWorstMainChunk();
878
                // Just do some sanity checks here. Consistency with GetBlockBuilder is checked
879
                // below.
880
13.7k
                if (main_sim.GetTransactionCount() == 0) {
  Branch (880:21): [True: 1.47k, False: 12.3k]
881
1.47k
                    assert(worst_chunk.empty());
  Branch (881:21): [True: 1.47k, False: 0]
882
1.47k
                    assert(worst_chunk_feerate.IsEmpty());
  Branch (882:21): [True: 1.47k, False: 0]
883
12.3k
                } else {
884
12.3k
                    assert(!worst_chunk.empty());
  Branch (884:21): [True: 12.3k, False: 0]
885
12.3k
                    SimTxGraph::SetType done;
886
12.3k
                    FeePerWeight sum;
887
33.0k
                    for (TxGraph::Ref* ref : worst_chunk) {
  Branch (887:44): [True: 33.0k, False: 12.3k]
888
                        // Each transaction in the chunk must exist in the main graph.
889
33.0k
                        auto simpos = main_sim.Find(ref);
890
33.0k
                        assert(simpos != SimTxGraph::MISSING);
  Branch (890:25): [True: 33.0k, False: 0]
891
33.0k
                        sum += main_sim.graph.FeeRate(simpos);
892
                        // Make sure the chunk contains no duplicate transactions.
893
33.0k
                        assert(!done[simpos]);
  Branch (893:25): [True: 33.0k, False: 0]
894
33.0k
                        done.Set(simpos);
895
                        // All elements are preceded by all their descendants.
896
33.0k
                        assert(main_sim.graph.Descendants(simpos).IsSubsetOf(done));
  Branch (896:25): [True: 33.0k, False: 0]
897
33.0k
                    }
898
12.3k
                    assert(sum == worst_chunk_feerate);
  Branch (898:21): [True: 12.3k, False: 0]
899
12.3k
                }
900
13.7k
                break;
901
388k
            } else if ((block_builders.empty() || sims.size() > 1) && command-- == 0) {
  Branch (901:25): [True: 341k, False: 46.9k]
  Branch (901:51): [True: 28.8k, False: 18.0k]
  Branch (901:71): [True: 12.0k, False: 358k]
902
                // Trim.
903
12.0k
                bool was_oversized = top_sim.IsOversized();
904
12.0k
                auto removed = real->Trim();
905
                // Verify that something was removed if and only if there was an oversized cluster.
906
12.0k
                assert(was_oversized == !removed.empty());
  Branch (906:17): [True: 12.0k, False: 0]
907
12.0k
                if (!was_oversized) break;
  Branch (907:21): [True: 8.65k, False: 3.39k]
908
3.39k
                auto removed_set = top_sim.MakeSet(removed);
909
                // The removed set must contain all its own descendants.
910
74.2k
                for (auto simpos : removed_set) {
  Branch (910:34): [True: 74.2k, False: 3.39k]
911
74.2k
                    assert(top_sim.graph.Descendants(simpos).IsSubsetOf(removed_set));
  Branch (911:21): [True: 74.2k, False: 0]
912
74.2k
                }
913
                // Something from every oversized cluster should have been removed, and nothing
914
                // else.
915
3.39k
                assert(top_sim.MatchesOversizedClusters(removed_set));
  Branch (915:17): [True: 3.39k, False: 0]
916
917
                // Apply all removals to the simulation, and verify the result is no longer
918
                // oversized. Don't query the real graph for oversizedness; it is compared
919
                // against the simulation anyway later.
920
74.2k
                for (auto simpos : removed_set) {
  Branch (920:34): [True: 74.2k, False: 3.39k]
921
74.2k
                    top_sim.RemoveTransaction(top_sim.GetRef(simpos));
922
74.2k
                }
923
3.39k
                assert(!top_sim.IsOversized());
  Branch (923:17): [True: 3.39k, False: 0]
924
3.39k
                break;
925
376k
            } else if ((block_builders.empty() || sims.size() > 1) &&
  Branch (925:25): [True: 330k, False: 45.3k]
  Branch (925:51): [True: 27.3k, False: 18.0k]
926
376k
                       top_sim.GetTransactionCount() > max_cluster_count && !top_sim.IsOversized() && command-- == 0) {
  Branch (926:24): [True: 205k, False: 152k]
  Branch (926:77): [True: 131k, False: 74.3k]
  Branch (926:103): [True: 30.7k, False: 100k]
927
                // Trim (special case which avoids apparent cycles in the implicit approximate
928
                // dependency graph constructed inside the Trim() implementation). This is worth
929
                // testing separately, because such cycles cannot occur in realistic scenarios,
930
                // but this is hard to replicate in general in this fuzz test.
931
932
                // First, we need to have dependencies applied and linearizations fixed to avoid
933
                // circular dependencies in implied graph; trigger it via whatever means.
934
30.7k
                real->CountDistinctClusters({}, TxGraph::Level::TOP);
935
936
                // Gather the current clusters.
937
30.7k
                auto clusters = top_sim.GetComponents();
938
939
                // Merge clusters randomly until at least one oversized one appears.
940
30.7k
                bool made_oversized = false;
941
30.7k
                auto merges_left = clusters.size() - 1;
942
906k
                while (merges_left > 0) {
  Branch (942:24): [True: 875k, False: 30.7k]
943
875k
                    --merges_left;
944
                    // Find positions of clusters in the clusters vector to merge together.
945
875k
                    auto par_cl = rng.randrange(clusters.size());
946
875k
                    auto chl_cl = rng.randrange(clusters.size() - 1);
947
875k
                    chl_cl += (chl_cl >= par_cl);
948
875k
                    Assume(chl_cl != par_cl);
949
                    // Add between 1 and 3 dependencies between them. As all are in the same
950
                    // direction (from the child cluster to parent cluster), no cycles are possible,
951
                    // regardless of what internal topology Trim() uses as approximation within the
952
                    // clusters.
953
875k
                    int num_deps = rng.randrange(3) + 1;
954
2.62M
                    for (int i = 0; i < num_deps; ++i) {
  Branch (954:37): [True: 1.75M, False: 875k]
955
                        // Find a parent transaction in the parent cluster.
956
1.75M
                        auto par_idx = rng.randrange(clusters[par_cl].Count());
957
1.75M
                        SimTxGraph::Pos par_pos = 0;
958
4.22M
                        for (auto j : clusters[par_cl]) {
  Branch (958:37): [True: 4.22M, False: 0]
959
4.22M
                            if (par_idx == 0) {
  Branch (959:33): [True: 1.75M, False: 2.47M]
960
1.75M
                                par_pos = j;
961
1.75M
                                break;
962
1.75M
                            }
963
2.47M
                            --par_idx;
964
2.47M
                        }
965
                        // Find a child transaction in the child cluster.
966
1.75M
                        auto chl_idx = rng.randrange(clusters[chl_cl].Count());
967
1.75M
                        SimTxGraph::Pos chl_pos = 0;
968
4.21M
                        for (auto j : clusters[chl_cl]) {
  Branch (968:37): [True: 4.21M, False: 0]
969
4.21M
                            if (chl_idx == 0) {
  Branch (969:33): [True: 1.75M, False: 2.46M]
970
1.75M
                                chl_pos = j;
971
1.75M
                                break;
972
1.75M
                            }
973
2.46M
                            --chl_idx;
974
2.46M
                        }
975
                        // Add dependency to both simulation and real TxGraph.
976
1.75M
                        auto par_ref = top_sim.GetRef(par_pos);
977
1.75M
                        auto chl_ref = top_sim.GetRef(chl_pos);
978
1.75M
                        top_sim.AddDependency(par_ref, chl_ref);
979
1.75M
                        real->AddDependency(*par_ref, *chl_ref);
980
1.75M
                    }
981
                    // Compute the combined cluster.
982
875k
                    auto par_cluster = clusters[par_cl];
983
875k
                    auto chl_cluster = clusters[chl_cl];
984
875k
                    auto new_cluster = par_cluster | chl_cluster;
985
                    // Remove the parent and child cluster from clusters.
986
33.3M
                    std::erase_if(clusters, [&](const auto& cl) noexcept { return cl == par_cluster || cl == chl_cluster; });
  Branch (986:83): [True: 875k, False: 32.5M]
  Branch (986:104): [True: 875k, False: 31.6M]
987
                    // Add the combined cluster.
988
875k
                    clusters.push_back(new_cluster);
989
                    // If this is the first merge that causes an oversized cluster to appear, pick
990
                    // a random number of further merges to appear.
991
875k
                    if (!made_oversized) {
  Branch (991:25): [True: 753k, False: 121k]
992
753k
                        made_oversized = new_cluster.Count() > max_cluster_count;
993
753k
                        if (!made_oversized) {
  Branch (993:29): [True: 723k, False: 30.1k]
994
723k
                            FeeFrac total;
995
4.49M
                            for (auto i : new_cluster) total += top_sim.graph.FeeRate(i);
  Branch (995:41): [True: 4.49M, False: 723k]
996
723k
                            if (uint32_t(total.size) > max_cluster_size) made_oversized = true;
  Branch (996:33): [True: 590, False: 723k]
997
723k
                        }
998
753k
                        if (made_oversized) merges_left = rng.randrange(clusters.size());
  Branch (998:29): [True: 30.7k, False: 723k]
999
753k
                    }
1000
875k
                }
1001
1002
                // Determine an upper bound on how many transactions are removed.
1003
30.7k
                uint32_t max_removed = 0;
1004
149k
                for (auto& cluster : clusters) {
  Branch (1004:36): [True: 149k, False: 30.7k]
1005
                    // Gather all transaction sizes in the to-be-combined cluster.
1006
149k
                    std::vector<uint32_t> sizes;
1007
1.61M
                    for (auto i : cluster) sizes.push_back(top_sim.graph.FeeRate(i).size);
  Branch (1007:33): [True: 1.61M, False: 149k]
1008
149k
                    auto sum_sizes = std::accumulate(sizes.begin(), sizes.end(), uint64_t{0});
1009
                    // Sort from large to small.
1010
149k
                    std::ranges::sort(sizes, std::greater{});
1011
                    // In the worst case, only the smallest transactions are removed.
1012
464k
                    while (sizes.size() > max_cluster_count || sum_sizes > max_cluster_size) {
  Branch (1012:28): [True: 296k, False: 167k]
  Branch (1012:64): [True: 18.0k, False: 149k]
1013
314k
                        sum_sizes -= sizes.back();
1014
314k
                        sizes.pop_back();
1015
314k
                        ++max_removed;
1016
314k
                    }
1017
149k
                }
1018
1019
                // Invoke Trim now on the definitely-oversized txgraph.
1020
30.7k
                auto removed = real->Trim();
1021
                // Verify that the number of removals is within range.
1022
30.7k
                assert(removed.size() >= 1);
  Branch (1022:17): [True: 30.7k, False: 0]
1023
30.7k
                assert(removed.size() <= max_removed);
  Branch (1023:17): [True: 30.7k, False: 0]
1024
                // The removed set must contain all its own descendants.
1025
30.7k
                auto removed_set = top_sim.MakeSet(removed);
1026
204k
                for (auto simpos : removed_set) {
  Branch (1026:34): [True: 204k, False: 30.7k]
1027
204k
                    assert(top_sim.graph.Descendants(simpos).IsSubsetOf(removed_set));
  Branch (1027:21): [True: 204k, False: 0]
1028
204k
                }
1029
                // Something from every oversized cluster should have been removed, and nothing
1030
                // else.
1031
30.7k
                assert(top_sim.MatchesOversizedClusters(removed_set));
  Branch (1031:17): [True: 30.7k, False: 0]
1032
1033
                // Apply all removals to the simulation, and verify the result is no longer
1034
                // oversized. Don't query the real graph for oversizedness; it is compared
1035
                // against the simulation anyway later.
1036
204k
                for (auto simpos : removed_set) {
  Branch (1036:34): [True: 204k, False: 30.7k]
1037
204k
                    top_sim.RemoveTransaction(top_sim.GetRef(simpos));
1038
204k
                }
1039
30.7k
                assert(!top_sim.IsOversized());
  Branch (1039:17): [True: 30.7k, False: 0]
1040
30.7k
                break;
1041
345k
            } else if (command-- == 0) {
  Branch (1041:24): [True: 10.3k, False: 335k]
1042
                // GetMainMemoryUsage().
1043
10.3k
                auto usage = real->GetMainMemoryUsage();
1044
                // Test stability.
1045
10.3k
                if (alt) {
  Branch (1045:21): [True: 4.30k, False: 6.07k]
1046
4.30k
                    auto usage2 = real->GetMainMemoryUsage();
1047
4.30k
                    assert(usage == usage2);
  Branch (1047:21): [True: 4.30k, False: 0]
1048
4.30k
                }
1049
                // Only empty graphs have 0 memory usage.
1050
10.3k
                if (main_sim.GetTransactionCount() == 0) {
  Branch (1050:21): [True: 1.49k, False: 8.89k]
1051
1.49k
                    assert(usage == 0);
  Branch (1051:21): [True: 1.49k, False: 0]
1052
8.89k
                } else {
1053
8.89k
                    assert(usage > 0);
  Branch (1053:21): [True: 8.89k, False: 0]
1054
8.89k
                }
1055
10.3k
                break;
1056
10.3k
            }
1057
1.06M
        }
1058
729k
    }
1059
1060
    // After running all modifications, perform an internal sanity check (before invoking
1061
    // inspectors that may modify the internal state).
1062
5.11k
    real->SanityCheck();
1063
1064
5.11k
    if (!sims[0].IsOversized()) {
  Branch (1064:9): [True: 4.22k, False: 891]
1065
        // If the main graph is not oversized, verify the total ordering implied by
1066
        // CompareMainOrder.
1067
        // First construct two distinct randomized permutations of the positions in sims[0].
1068
4.22k
        std::vector<SimTxGraph::Pos> vec1;
1069
175k
        for (auto i : sims[0].graph.Positions()) vec1.push_back(i);
  Branch (1069:21): [True: 175k, False: 4.22k]
1070
4.22k
        std::shuffle(vec1.begin(), vec1.end(), rng);
1071
4.22k
        auto vec2 = vec1;
1072
4.22k
        std::shuffle(vec2.begin(), vec2.end(), rng);
1073
4.22k
        if (vec1 == vec2) std::next_permutation(vec2.begin(), vec2.end());
  Branch (1073:13): [True: 730, False: 3.49k]
1074
        // Sort both according to CompareMainOrder. By having randomized starting points, the order
1075
        // of CompareMainOrder invocations is somewhat randomized as well.
1076
2.54M
        auto cmp = [&](SimTxGraph::Pos a, SimTxGraph::Pos b) noexcept {
1077
2.54M
            return real->CompareMainOrder(*sims[0].GetRef(a), *sims[0].GetRef(b)) < 0;
1078
2.54M
        };
1079
4.22k
        std::ranges::sort(vec1, cmp);
1080
4.22k
        std::ranges::sort(vec2, cmp);
1081
1082
        // Verify the resulting orderings are identical. This could only fail if the ordering was
1083
        // not total.
1084
4.22k
        assert(vec1 == vec2);
  Branch (1084:9): [True: 4.22k, False: 0]
1085
1086
        // Verify that the ordering is topological.
1087
4.22k
        auto todo = sims[0].graph.Positions();
1088
175k
        for (auto i : vec1) {
  Branch (1088:21): [True: 175k, False: 4.22k]
1089
175k
            todo.Reset(i);
1090
175k
            assert(!sims[0].graph.Ancestors(i).Overlaps(todo));
  Branch (1090:13): [True: 175k, False: 0]
1091
175k
        }
1092
4.22k
        assert(todo.None());
  Branch (1092:9): [True: 4.22k, False: 0]
1093
1094
        // If the real graph claims to be optimal (the last DoWork() call returned true), verify
1095
        // that calling Linearize on it does not improve it further.
1096
4.22k
        if (sims[0].real_is_optimal) {
  Branch (1096:13): [True: 807, False: 3.42k]
1097
807
            auto real_diagram = ChunkLinearization(sims[0].graph, vec1);
1098
143k
            auto fallback_order_sim = [&](DepGraphIndex a, DepGraphIndex b) noexcept {
1099
143k
                auto txid_a = sims[0].GetRef(a)->m_txid;
1100
143k
                auto txid_b = sims[0].GetRef(b)->m_txid;
1101
143k
                return txid_a <=> txid_b;
1102
143k
            };
1103
807
            auto [sim_lin, sim_optimal, _cost] = Linearize(sims[0].graph, 300000, rng.rand64(), fallback_order_sim, vec1);
1104
807
            PostLinearize(sims[0].graph, sim_lin);
1105
807
            auto sim_diagram = ChunkLinearization(sims[0].graph, sim_lin);
1106
807
            auto cmp = CompareChunks(real_diagram, sim_diagram);
1107
807
            assert(cmp == 0);
  Branch (1107:13): [True: 807, False: 0]
1108
1109
            // Verify consistency of cross-cluster chunk ordering with tie-break (equal-feerate
1110
            // prefix size).
1111
807
            auto real_chunking = ChunkLinearizationInfo(sims[0].graph, vec1);
1112
            /** Map with one entry per component of the sim main graph. Key is the first Pos of the
1113
             *  component. Value is the sum of all chunk sizes from that component seen
1114
             *  already, at the current chunk feerate. */
1115
807
            std::map<SimTxGraph::Pos, int32_t> comp_prefix_sizes;
1116
            /** Current chunk feerate. */
1117
807
            FeeFrac last_chunk_feerate;
1118
            /** Largest seen (equal-feerate chunk prefix size, max txid).  */
1119
807
            std::pair<int32_t, uint64_t> max_chunk_tiebreak{0, 0};
1120
38.5k
            for (const auto& chunk : real_chunking) {
  Branch (1120:36): [True: 38.5k, False: 807]
1121
                // If this is the first chunk with a strictly lower feerate, reset.
1122
38.5k
                if (ByRatio{chunk.feerate} < ByRatio{last_chunk_feerate}) {
  Branch (1122:21): [True: 8.87k, False: 29.6k]
1123
8.87k
                    comp_prefix_sizes.clear();
1124
8.87k
                    max_chunk_tiebreak = {0, 0};
1125
8.87k
                }
1126
38.5k
                last_chunk_feerate = chunk.feerate;
1127
                // Find which sim component this chunk belongs to.
1128
38.5k
                auto component = sims[0].graph.GetConnectedComponent(sims[0].graph.Positions(), chunk.transactions.First());
1129
38.5k
                assert(chunk.transactions.IsSubsetOf(component));
  Branch (1129:17): [True: 38.5k, False: 0]
1130
38.5k
                auto comp_key = component.First();
1131
38.5k
                auto& comp_prefix_size = comp_prefix_sizes[comp_key];
1132
38.5k
                comp_prefix_size += chunk.feerate.size;
1133
                // Determine the chunk's max txid.
1134
38.5k
                uint64_t chunk_max_txid{0};
1135
46.3k
                for (auto tx : chunk.transactions) {
  Branch (1135:30): [True: 46.3k, False: 38.5k]
1136
46.3k
                    auto txid = sims[0].GetRef(tx)->m_txid;
1137
46.3k
                    chunk_max_txid = std::max(txid, chunk_max_txid);
1138
46.3k
                }
1139
                // Verify consistency: within each group of equal-feerate chunks, the
1140
                // (equal-feerate chunk prefix size, max txid) must be increasing.
1141
38.5k
                std::pair<int32_t, uint64_t> chunk_tiebreak{comp_prefix_size, chunk_max_txid};
1142
38.5k
                assert(chunk_tiebreak > max_chunk_tiebreak);
  Branch (1142:17): [True: 38.5k, False: 0]
1143
38.5k
                max_chunk_tiebreak = chunk_tiebreak;
1144
38.5k
            }
1145
1146
            // Verify that within each cluster, the internal ordering matches that of the
1147
            // simulation if that is optimal too, since per-cluster optimal orderings are
1148
            // deterministic. Note that both have been PostLinearize()'ed.
1149
807
            if (sim_optimal) {
  Branch (1149:17): [True: 807, False: 0]
1150
25.7k
                for (const auto& component : sims[0].GetComponents()) {
  Branch (1150:44): [True: 25.7k, False: 807]
1151
25.7k
                    std::vector<DepGraphIndex> sim_chunk_lin, real_chunk_lin;
1152
2.42M
                    for (auto i : sim_lin) {
  Branch (1152:33): [True: 2.42M, False: 25.7k]
1153
2.42M
                        if (component[i]) sim_chunk_lin.push_back(i);
  Branch (1153:29): [True: 46.3k, False: 2.37M]
1154
2.42M
                    }
1155
2.42M
                    for (auto i : vec1) {
  Branch (1155:33): [True: 2.42M, False: 25.7k]
1156
2.42M
                        if (component[i]) real_chunk_lin.push_back(i);
  Branch (1156:29): [True: 46.3k, False: 2.37M]
1157
2.42M
                    }
1158
25.7k
                    assert(sim_chunk_lin == real_chunk_lin);
  Branch (1158:21): [True: 25.7k, False: 0]
1159
25.7k
                }
1160
807
            }
1161
1162
            // Verify that a fresh TxGraph, with the same transactions and txids, but constructed
1163
            // in a different order, and with a different RNG state, recreates the exact same
1164
            // ordering, showing that for optimal graphs, the full mempool ordering is
1165
            // deterministic.
1166
807
            auto real_redo = MakeTxGraph(
1167
807
                /*max_cluster_count=*/max_cluster_count,
1168
807
                /*max_cluster_size=*/max_cluster_size,
1169
807
                /*acceptable_cost=*/acceptable_cost,
1170
807
                /*fallback_order=*/fallback_order);
1171
            /** Vector (indexed by SimTxGraph::Pos) of TxObjects in real_redo). */
1172
807
            std::vector<std::optional<SimTxObject>> txobjects_redo;
1173
807
            txobjects_redo.resize(sims[0].graph.PositionRange());
1174
            // Recreate the graph's transactions with same feerate and txid.
1175
807
            std::vector<DepGraphIndex> positions;
1176
46.3k
            for (auto i : sims[0].graph.Positions()) positions.push_back(i);
  Branch (1176:25): [True: 46.3k, False: 807]
1177
807
            std::shuffle(positions.begin(), positions.end(), rng);
1178
46.3k
            for (auto i : positions) {
  Branch (1178:25): [True: 46.3k, False: 807]
1179
46.3k
                txobjects_redo[i].emplace(sims[0].GetRef(i)->m_txid);
1180
46.3k
                real_redo->AddTransaction(*txobjects_redo[i], FeePerWeight::FromFeeFrac(sims[0].graph.FeeRate(i)));
1181
46.3k
            }
1182
            // Recreate the graph's dependencies.
1183
807
            std::vector<std::pair<DepGraphIndex, DepGraphIndex>> deps;
1184
46.3k
            for (auto i : sims[0].graph.Positions()) {
  Branch (1184:25): [True: 46.3k, False: 807]
1185
46.3k
                for (auto j : sims[0].graph.GetReducedParents(i)) {
  Branch (1185:29): [True: 22.8k, False: 46.3k]
1186
22.8k
                    deps.emplace_back(j, i);
1187
22.8k
                }
1188
46.3k
            }
1189
807
            std::shuffle(deps.begin(), deps.end(), rng);
1190
22.8k
            for (auto [parent, child] : deps) {
  Branch (1190:39): [True: 22.8k, False: 807]
1191
22.8k
                real_redo->AddDependency(*txobjects_redo[parent], *txobjects_redo[child]);
1192
22.8k
            }
1193
            // Do work to reach optimality.
1194
807
            if (real_redo->DoWork(300000)) {
  Branch (1194:17): [True: 807, False: 0]
1195
                // Start from a random permutation.
1196
807
                auto vec_redo = vec1;
1197
807
                std::shuffle(vec_redo.begin(), vec_redo.end(), rng);
1198
807
                if (vec_redo == vec1) std::next_permutation(vec_redo.begin(), vec_redo.end());
  Branch (1198:21): [True: 103, False: 704]
1199
                // Sort it according to the main graph order in real_redo.
1200
356k
                auto cmp_redo = [&](SimTxGraph::Pos a, SimTxGraph::Pos b) noexcept {
1201
356k
                    return real_redo->CompareMainOrder(*txobjects_redo[a], *txobjects_redo[b]) < 0;
1202
356k
                };
1203
807
                std::ranges::sort(vec_redo, cmp_redo);
1204
                // Compare with the ordering we got from real.
1205
807
                assert(vec1 == vec_redo);
  Branch (1205:17): [True: 807, False: 0]
1206
807
            }
1207
807
        }
1208
1209
        // For every transaction in the total ordering, find a random one before it and after it,
1210
        // and compare their chunk feerates, which must be consistent with the ordering.
1211
179k
        for (size_t pos = 0; pos < vec1.size(); ++pos) {
  Branch (1211:30): [True: 175k, False: 4.22k]
1212
175k
            auto pos_feerate = real->GetMainChunkFeerate(*sims[0].GetRef(vec1[pos]));
1213
175k
            if (pos > 0) {
  Branch (1213:17): [True: 171k, False: 3.85k]
1214
171k
                size_t before = rng.randrange<size_t>(pos);
1215
171k
                auto before_feerate = real->GetMainChunkFeerate(*sims[0].GetRef(vec1[before]));
1216
171k
                assert(ByRatio{before_feerate} >= ByRatio{pos_feerate});
  Branch (1216:17): [True: 171k, False: 0]
1217
171k
            }
1218
175k
            if (pos + 1 < vec1.size()) {
  Branch (1218:17): [True: 171k, False: 3.85k]
1219
171k
                size_t after = pos + 1 + rng.randrange<size_t>(vec1.size() - 1 - pos);
1220
171k
                auto after_feerate = real->GetMainChunkFeerate(*sims[0].GetRef(vec1[after]));
1221
171k
                assert(ByRatio{after_feerate} <= ByRatio{pos_feerate});
  Branch (1221:17): [True: 171k, False: 0]
1222
171k
            }
1223
175k
        }
1224
1225
        // The same order should be obtained through a BlockBuilder as implied by CompareMainOrder,
1226
        // if nothing is skipped.
1227
4.22k
        auto builder = real->GetBlockBuilder();
1228
4.22k
        std::vector<SimTxGraph::Pos> vec_builder;
1229
4.22k
        std::vector<TxGraph::Ref*> last_chunk;
1230
4.22k
        FeePerWeight last_chunk_feerate;
1231
154k
        while (auto chunk = builder->GetCurrentChunk()) {
  Branch (1231:21): [True: 149k, False: 4.22k]
1232
149k
            FeePerWeight sum;
1233
175k
            for (TxGraph::Ref* ref : chunk->first) {
  Branch (1233:36): [True: 175k, False: 149k]
1234
                // The reported chunk feerate must match the chunk feerate obtained by asking
1235
                // it for each of the chunk's transactions individually.
1236
175k
                assert(real->GetMainChunkFeerate(*ref) == chunk->second);
  Branch (1236:17): [True: 175k, False: 0]
1237
                // Verify the chunk feerate matches the sum of the reported individual feerates.
1238
175k
                sum += real->GetIndividualFeerate(*ref);
1239
                // Chunks must contain transactions that exist in the graph.
1240
175k
                auto simpos = sims[0].Find(ref);
1241
175k
                assert(simpos != SimTxGraph::MISSING);
  Branch (1241:17): [True: 175k, False: 0]
1242
175k
                vec_builder.push_back(simpos);
1243
175k
            }
1244
149k
            assert(sum == chunk->second);
  Branch (1244:13): [True: 149k, False: 0]
1245
149k
            last_chunk = std::move(chunk->first);
1246
149k
            last_chunk_feerate = chunk->second;
1247
149k
            builder->Include();
1248
149k
        }
1249
4.22k
        assert(vec_builder == vec1);
  Branch (1249:9): [True: 4.22k, False: 0]
1250
1251
        // The last chunk returned by the BlockBuilder must match GetWorstMainChunk, in reverse.
1252
4.22k
        std::reverse(last_chunk.begin(), last_chunk.end());
1253
4.22k
        auto [worst_chunk, worst_chunk_feerate] = real->GetWorstMainChunk();
1254
4.22k
        assert(last_chunk == worst_chunk);
  Branch (1254:9): [True: 4.22k, False: 0]
1255
4.22k
        assert(last_chunk_feerate == worst_chunk_feerate);
  Branch (1255:9): [True: 4.22k, False: 0]
1256
1257
        // Check that the implied ordering gives rise to a combined diagram that matches the
1258
        // diagram constructed from the individual cluster linearization chunkings.
1259
4.22k
        auto main_real_diagram = get_diagram_fn(TxGraph::Level::MAIN);
1260
4.22k
        auto main_implied_diagram = ChunkLinearization(sims[0].graph, vec1);
1261
4.22k
        assert(CompareChunks(main_real_diagram, main_implied_diagram) == 0);
  Branch (1261:9): [True: 4.22k, False: 0]
1262
1263
4.22k
        if (sims.size() >= 2 && !sims[1].IsOversized()) {
  Branch (1263:13): [True: 2.15k, False: 2.07k]
  Branch (1263:33): [True: 2.05k, False: 106]
1264
            // When the staging graph is not oversized as well, call GetMainStagingDiagrams, and
1265
            // fully verify the result.
1266
2.05k
            auto [main_cmp_diagram, stage_cmp_diagram] = real->GetMainStagingDiagrams();
1267
            // Check that the feerates in each diagram are monotonically decreasing.
1268
47.8k
            for (size_t i = 1; i < main_cmp_diagram.size(); ++i) {
  Branch (1268:32): [True: 45.7k, False: 2.05k]
1269
45.7k
                assert(ByRatio{main_cmp_diagram[i]} <= ByRatio{main_cmp_diagram[i - 1]});
  Branch (1269:17): [True: 45.7k, False: 0]
1270
45.7k
            }
1271
37.1k
            for (size_t i = 1; i < stage_cmp_diagram.size(); ++i) {
  Branch (1271:32): [True: 35.1k, False: 2.05k]
1272
35.1k
                assert(ByRatio{stage_cmp_diagram[i]} <= ByRatio{stage_cmp_diagram[i - 1]});
  Branch (1272:17): [True: 35.1k, False: 0]
1273
35.1k
            }
1274
            // Treat the diagrams as sets of chunk feerates, and sort them in the same way so that
1275
            // std::set_difference can be used on them below. The exact ordering does not matter
1276
            // here, but it has to be consistent with the one used in main_real_diagram and
1277
            // stage_real_diagram).
1278
2.05k
            std::ranges::sort(main_cmp_diagram, std::greater<ByRatioNegSize<FeeFrac>>{});
1279
2.05k
            std::ranges::sort(stage_cmp_diagram, std::greater<ByRatioNegSize<FeeFrac>>{});
1280
            // Find the chunks that appear in main_diagram but are missing from main_cmp_diagram.
1281
            // This is allowed, because GetMainStagingDiagrams omits clusters in main unaffected
1282
            // by staging.
1283
2.05k
            std::vector<FeeFrac> missing_main_cmp;
1284
2.05k
            std::set_difference(main_real_diagram.begin(), main_real_diagram.end(),
1285
2.05k
                                main_cmp_diagram.begin(), main_cmp_diagram.end(),
1286
2.05k
                                std::inserter(missing_main_cmp, missing_main_cmp.end()),
1287
2.05k
                                std::greater<ByRatioNegSize<FeeFrac>>{});
1288
2.05k
            assert(main_cmp_diagram.size() + missing_main_cmp.size() == main_real_diagram.size());
  Branch (1288:13): [True: 2.05k, False: 0]
1289
            // Do the same for chunks in stage_diagram missing from stage_cmp_diagram.
1290
2.05k
            auto stage_real_diagram = get_diagram_fn(TxGraph::Level::TOP);
1291
2.05k
            std::vector<FeeFrac> missing_stage_cmp;
1292
2.05k
            std::set_difference(stage_real_diagram.begin(), stage_real_diagram.end(),
1293
2.05k
                                stage_cmp_diagram.begin(), stage_cmp_diagram.end(),
1294
2.05k
                                std::inserter(missing_stage_cmp, missing_stage_cmp.end()),
1295
2.05k
                                std::greater<ByRatioNegSize<FeeFrac>>{});
1296
2.05k
            assert(stage_cmp_diagram.size() + missing_stage_cmp.size() == stage_real_diagram.size());
  Branch (1296:13): [True: 2.05k, False: 0]
1297
            // The missing chunks must be equal across main & staging (otherwise they couldn't have
1298
            // been omitted).
1299
2.05k
            assert(missing_main_cmp == missing_stage_cmp);
  Branch (1299:13): [True: 2.05k, False: 0]
1300
1301
            // The missing part must include at least all transactions in staging which have not been
1302
            // modified, or been in a cluster together with modified transactions, since they were
1303
            // copied from main. Note that due to the reordering of removals w.r.t. dependency
1304
            // additions, it is possible that the real implementation found more unaffected things.
1305
2.05k
            FeeFrac missing_real;
1306
31.6k
            for (const auto& feerate : missing_main_cmp) missing_real += feerate;
  Branch (1306:38): [True: 31.6k, False: 2.05k]
1307
2.05k
            FeeFrac missing_expected = sims[1].graph.FeeRate(sims[1].graph.Positions() - sims[1].modified);
1308
            // Note that missing_real.fee < missing_expected.fee is possible to due the presence of
1309
            // negative-fee transactions.
1310
2.05k
            assert(missing_real.size >= missing_expected.size);
  Branch (1310:13): [True: 2.05k, False: 0]
1311
2.05k
        }
1312
4.22k
    }
1313
1314
5.11k
    assert(real->HaveStaging() == (sims.size() > 1));
  Branch (1314:5): [True: 5.11k, False: 0]
1315
1316
    // Try to run a full comparison, for both TxGraph::Level::MAIN and TxGraph::Level::TOP in
1317
    // TxGraph inspector functions that support both.
1318
10.2k
    for (auto level : {TxGraph::Level::TOP, TxGraph::Level::MAIN}) {
  Branch (1318:21): [True: 10.2k, False: 5.11k]
1319
10.2k
        auto& sim = level == TxGraph::Level::TOP ? sims.back() : sims.front();
  Branch (1319:21): [True: 5.11k, False: 5.11k]
1320
        // Compare simple properties of the graph with the simulation.
1321
10.2k
        assert(real->IsOversized(level) == sim.IsOversized());
  Branch (1321:9): [True: 10.2k, False: 0]
1322
10.2k
        assert(real->GetTransactionCount(level) == sim.GetTransactionCount());
  Branch (1322:9): [True: 10.2k, False: 0]
1323
        // If the graph (and the simulation) are not oversized, perform a full comparison.
1324
10.2k
        if (!sim.IsOversized()) {
  Branch (1324:13): [True: 8.52k, False: 1.71k]
1325
8.52k
            auto todo = sim.graph.Positions();
1326
            // Iterate over all connected components of the resulting (simulated) graph, each of which
1327
            // should correspond to a cluster in the real one.
1328
212k
            while (todo.Any()) {
  Branch (1328:20): [True: 203k, False: 8.52k]
1329
203k
                auto component = sim.graph.FindConnectedComponent(todo);
1330
203k
                todo -= component;
1331
                // Iterate over the transactions in that component.
1332
351k
                for (auto i : component) {
  Branch (1332:29): [True: 351k, False: 203k]
1333
                    // Check its individual feerate against simulation.
1334
351k
                    assert(sim.graph.FeeRate(i) == real->GetIndividualFeerate(*sim.GetRef(i)));
  Branch (1334:21): [True: 351k, False: 0]
1335
                    // Check its ancestors against simulation.
1336
351k
                    auto expect_anc = sim.graph.Ancestors(i);
1337
351k
                    auto anc = sim.MakeSet(real->GetAncestors(*sim.GetRef(i), level));
1338
351k
                    assert(anc.Count() <= max_cluster_count);
  Branch (1338:21): [True: 351k, False: 0]
1339
351k
                    assert(anc == expect_anc);
  Branch (1339:21): [True: 351k, False: 0]
1340
                    // Check its descendants against simulation.
1341
351k
                    auto expect_desc = sim.graph.Descendants(i);
1342
351k
                    auto desc = sim.MakeSet(real->GetDescendants(*sim.GetRef(i), level));
1343
351k
                    assert(desc.Count() <= max_cluster_count);
  Branch (1343:21): [True: 351k, False: 0]
1344
351k
                    assert(desc == expect_desc);
  Branch (1344:21): [True: 351k, False: 0]
1345
                    // Check the cluster the transaction is part of.
1346
351k
                    auto cluster = real->GetCluster(*sim.GetRef(i), level);
1347
351k
                    assert(cluster.size() <= max_cluster_count);
  Branch (1347:21): [True: 351k, False: 0]
1348
351k
                    assert(sim.MakeSet(cluster) == component);
  Branch (1348:21): [True: 351k, False: 0]
1349
                    // Check that the cluster is reported in a valid topological order (its
1350
                    // linearization).
1351
351k
                    std::vector<DepGraphIndex> simlin;
1352
351k
                    SimTxGraph::SetType done;
1353
351k
                    uint64_t total_size{0};
1354
5.45M
                    for (TxGraph::Ref* ptr : cluster) {
  Branch (1354:44): [True: 5.45M, False: 351k]
1355
5.45M
                        auto simpos = sim.Find(ptr);
1356
5.45M
                        assert(sim.graph.Descendants(simpos).IsSubsetOf(component - done));
  Branch (1356:25): [True: 5.45M, False: 0]
1357
5.45M
                        done.Set(simpos);
1358
5.45M
                        assert(sim.graph.Ancestors(simpos).IsSubsetOf(done));
  Branch (1358:25): [True: 5.45M, False: 0]
1359
5.45M
                        simlin.push_back(simpos);
1360
5.45M
                        total_size += sim.graph.FeeRate(simpos).size;
1361
5.45M
                    }
1362
                    // Check cluster size.
1363
351k
                    assert(total_size <= max_cluster_size);
  Branch (1363:21): [True: 351k, False: 0]
1364
                    // Construct a chunking object for the simulated graph, using the reported cluster
1365
                    // linearization as ordering, and compare it against the reported chunk feerates.
1366
351k
                    if (sims.size() == 1 || level == TxGraph::Level::MAIN) {
  Branch (1366:25): [True: 170k, False: 180k]
  Branch (1366:45): [True: 90.0k, False: 90.8k]
1367
261k
                        auto simlinchunk = ChunkLinearizationInfo(sim.graph, simlin);
1368
261k
                        DepGraphIndex idx{0};
1369
1.98M
                        for (auto& chunk : simlinchunk) {
  Branch (1369:42): [True: 1.98M, False: 261k]
1370
                            // Require that the chunks of cluster linearizations are connected (this must
1371
                            // be the case as all linearizations inside are PostLinearized).
1372
1.98M
                            assert(sim.graph.IsConnected(chunk.transactions));
  Branch (1372:29): [True: 1.98M, False: 0]
1373
                            // Check the chunk feerates of all transactions in the cluster.
1374
5.63M
                            while (chunk.transactions.Any()) {
  Branch (1374:36): [True: 3.65M, False: 1.98M]
1375
3.65M
                                assert(chunk.transactions[simlin[idx]]);
  Branch (1375:33): [True: 3.65M, False: 0]
1376
3.65M
                                chunk.transactions.Reset(simlin[idx]);
1377
3.65M
                                assert(chunk.feerate == real->GetMainChunkFeerate(*cluster[idx]));
  Branch (1377:33): [True: 3.65M, False: 0]
1378
3.65M
                                ++idx;
1379
3.65M
                            }
1380
1.98M
                        }
1381
261k
                    }
1382
351k
                }
1383
203k
            }
1384
8.52k
        }
1385
10.2k
    }
1386
1387
    // Sanity check again (because invoking inspectors may modify internal unobservable state).
1388
5.11k
    real->SanityCheck();
1389
1390
    // Kill the block builders.
1391
5.11k
    block_builders.clear();
1392
    // Kill the TxGraph object.
1393
5.11k
    real.reset();
1394
    // Kill the simulated graphs, with all remaining Refs in it. If any, this verifies that Refs
1395
    // can outlive the TxGraph that created them.
1396
5.11k
    sims.clear();
1397
5.11k
}