LCOV - code coverage report
Current view: top level - src - txgraph.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 95.5 % 1623 1550
Test Date: 2026-02-16 05:51:08 Functions: 95.2 % 147 140
Branches: 73.4 % 1602 1176

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

Generated by: LCOV version 2.0-1