Coverage Report

Created: 2026-07-23 20:35

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