[#cluster_linearize-SpanningForestState]
= xref:cluster_linearize.adoc[cluster&lowbar;linearize]::SpanningForestState
:relfileprefix: ../
:mrdocs:

Class to represent the internal state of the spanning&hyphen;forest linearization (SFL) algorithm&period;

== Synopsis

Declared in `&lt;cluster&lowbar;linearize&period;h&gt;`

[source,cpp,subs="verbatim,replacements,macros,-callouts"]
----
template&lt;
    typename SetType,
    typename CostModel = xref:cluster_linearize/SFLDefaultCostModel.adoc[SFLDefaultCostModel]&gt;
class SpanningForestState;
----

== Description

At all times, each dependency is marked as either &quot;active&quot; or &quot;inactive&quot;&period; The subset of active dependencies is the state of the SFL algorithm&period; The implementation maintains several other values to speed up operations, but everything is ultimately a function of what that subset of active dependencies is&period;

Given such a subset, define a chunk as the set of transactions that are connected through active dependencies (ignoring their parent&sol;child direction)&period; Thus, every state implies a particular partitioning of the graph into chunks (including potential singletons)&period; In the extreme, each transaction may be in its own chunk, or in the other extreme all transactions may form a single chunk&period; A chunk&apos;s feerate is its total fee divided by its total size&period;

The algorithm consists of switching dependencies between active and inactive&period; The final linearization that is produced at the end consists of these chunks, sorted from high to low feerate, each individually sorted in an arbitrary but topological (&equals; no child before parent) way&period;

We define four quality properties the state can have&colon;

* acyclic&colon; The state is acyclic whenever no cycle of active dependencies exists within the graph, ignoring the parent&sol;child direction&period; This is equivalent to saying that within each chunk the set of active dependencies form a tree, and thus the overall set of active dependencies in the graph form a spanning forest, giving the algorithm its name&period; Being acyclic is also equivalent to every chunk of N transactions having exactly N&hyphen;1 active dependencies&period;

For example in a diamond graph, D&hyphen;&gt;&lcub;B,C&rcub;&hyphen;&gt;A, the 4 dependencies cannot be simultaneously active&period; If at least one is inactive, the state is acyclic&period;

The algorithm maintains an acyclic state at _all_ times as an invariant&period; This implies that activating a dependency always corresponds to merging two chunks, and that deactivating one always corresponds to splitting two chunks&period;

* topological&colon; We say the state is topological whenever it is acyclic and no inactive dependency exists between two distinct chunks such that the child chunk has higher or equal feerate than the parent chunk&period;

The relevance is that whenever the state is topological, the produced output linearization will be topological too (i&period;e&period;, not have children before parents)&period; Note that the &quot;or equal&quot; part of the definition matters&colon; if not, one can end up in a situation with mutually&hyphen;dependent equal&hyphen;feerate chunks that cannot be linearized&period; For example C&hyphen;&gt;&lcub;A,B&rcub; and D&hyphen;&gt;&lcub;A,B&rcub;, with C&hyphen;&gt;A and D&hyphen;&gt;B active&period; The AC chunk depends on DB through C&hyphen;&gt;B, and the BD chunk depends on AC through D&hyphen;&gt;A&period; Merging them into a single ABCD chunk fixes this&period;

The algorithm attempts to keep the state topological as much as possible, so it can be interrupted to produce an output whenever, but will sometimes need to temporarily deviate from it when improving the state&period;

* optimal&colon; For every active dependency, define its top and bottom set as the set of transactions in the chunks that would result if the dependency were deactivated&semi; the top being the one with the dependency&apos;s parent, and the bottom being the one with the child&period; Note that due to acyclicity, every deactivation splits a chunk exactly in two&period;

We say the state is optimal whenever it is topological and it has no active dependency whose top feerate is strictly higher than its bottom feerate&period; The relevance is that it can be proven that whenever the state is optimal, the produced linearization will also be optimal (in the convexified feerate diagram sense)&period; It can also be proven that for every graph at least one optimal state exists&period;

Note that it is possible for the SFL state to not be optimal, but the produced linearization to still be optimal&period; This happens when the chunks of a state are identical to those of an optimal state, but the exact set of active dependencies within a chunk differ in such a way that the state optimality condition is not satisfied&period; Thus, the state being optimal is more a &quot;the eventual output is _known_ to be optimal&quot;&period;

* minimal&colon; We say the state is minimal when it is&colon;
* acyclic
* topological, except that inactive dependencies between equal&hyphen;feerate chunks are allowed as long as they do not form a loop&period;
* like optimal, no active dependencies whose top feerate is strictly higher than the bottom feerate are allowed&period;
* no chunk contains a proper non&hyphen;empty subset which includes all its own in&hyphen;chunk dependencies of the same feerate as the chunk itself&period;

A minimal state effectively corresponds to an optimal state, where every chunk has been split into its minimal equal&hyphen;feerate components&period;

The algorithm terminates whenever a minimal state is reached&period;

This leads to the following high&hyphen;level algorithm&colon;

* Start with all dependencies inactive, and thus all transactions in their own chunk&period; This is definitely acyclic&period;
* Activate dependencies (merging chunks) until the state is topological&period;
* Loop until optimal (no dependencies with higher&hyphen;feerate top than bottom), or time runs out&colon;
* Deactivate a violating dependency, potentially making the state non&hyphen;topological&period;
* Activate other dependencies to make the state topological again&period;
* If there is time left and the state is optimal&colon;
* Attempt to split chunks into equal&hyphen;feerate parts without mutual dependencies between them&period; When this succeeds, recurse into them&period;
* If no such chunks can be found, the state is minimal&period;
* Output the chunks from high to low feerate, each internally sorted topologically&period;

When merging, we always either&colon;

* Merge upwards&colon; merge a chunk with the lowest&hyphen;feerate other chunk it depends on, among those with lower or equal feerate than itself&period;
* Merge downwards&colon; merge a chunk with the highest&hyphen;feerate other chunk that depends on it, among those with higher or equal feerate than itself&period;

Using these strategies in the improvement loop above guarantees that the output linearization after a deactivate &plus; merge step is never worse or incomparable (in the convexified feerate diagram sense) than the output linearization that would be produced before the step&period; With that, we can refine the high&hyphen;level algorithm to&colon;

* Start with all dependencies inactive&period;
* Perform merges as described until none are possible anymore, making the state topological&period;
* Loop until optimal or time runs out&colon;
* Pick a dependency D to deactivate among those with higher feerate top than bottom&period;
* Deactivate D, causing the chunk it is in to split into top T and bottom B&period;
* Do an upwards merge of T, if possible&period; If so, repeat the same with the merged result&period;
* Do a downwards merge of B, if possible&period; If so, repeat the same with the merged result&period;
* Split chunks further to obtain a minimal state, see below&period;
* Output the chunks from high to low feerate, each internally sorted topologically&period;

Instead of performing merges arbitrarily to make the initial state topological, it is possible to do so guided by an existing linearization&period; This has the advantage that the state&apos;s would&hyphen;be output linearization is immediately as good as the existing linearization it was based on&colon;

* Start with all dependencies inactive&period;
* For each transaction t in the existing linearization&colon;
* Find the chunk C that transaction is in (which will be singleton)&period;
* Do an upwards merge of C, if possible&period; If so, repeat the same with the merged result&period; No downwards merges are needed in this case&period;

After reaching an optimal state, it can be transformed into a minimal state by attempting to split chunks further into equal&hyphen;feerate parts&period; To do so, pick a specific transaction in each chunk (the pivot), and rerun the above split&hyphen;then&hyphen;merge procedure again&colon;

* first, while pretending the pivot transaction has an infinitesimally higher (or lower) fee than it really has&period; If a split exists with the pivot in the top part (or bottom part), this will find it&period;
* if that fails to split, repeat while pretending the pivot transaction has an infinitesimally lower (or higher) fee&period; If a split exists with the pivot in the bottom part (or top part), this will find it&period;
* if either succeeds, repeat the procedure for the newly found chunks to split them further&period; If not, the chunk is already minimal&period; If the chunk can be split into equal&hyphen;feerate parts, then the pivot must exist in either the top or bottom part of that potential split&period; By trying both with the same pivot, if a split exists, it will be found&period;

What remains to be specified are a number of heuristics&colon;

* How to decide which chunks to merge&colon;
* The merge upwards and downward rules specify that the lowest&hyphen;feerate respectively highest&hyphen;feerate candidate chunk is merged with, but if there are multiple equal&hyphen;feerate candidates, a uniformly random one among them is picked&period;

* How to decide what dependency to activate (when merging chunks)&colon;
* After picking two chunks to be merged (see above), a uniformly random dependency between the two chunks is activated&period;

* How to decide which chunk to find a dependency to split in&colon;
* A round&hyphen;robin queue of chunks to improve is maintained&period; The initial ordering of this queue is uniformly randomly permuted&period;

* How to decide what dependency to deactivate (when splitting chunks)&colon;
* Inside the selected chunk (see above), among the dependencies whose top feerate is strictly higher than its bottom feerate in the selected chunk, if any, a uniformly random dependency is deactivated&period;
* After every split, it is possible that the top and the bottom chunk merge with each other again in the merge sequence (through a top&hyphen;&gt;bottom dependency, not through the deactivated one, which was bottom&hyphen;&gt;top)&period; Call this a self&hyphen;merge&period; If a self&hyphen;merge does not occur after a split, the resulting linearization is strictly improved (the area under the convexified feerate diagram increases by at least gain&sol;2), while self&hyphen;merges do not change it&period;

* How to decide the exact output linearization&colon;
* When there are multiple equal&hyphen;feerate chunks with no dependencies between them, pick the smallest one first&period; If there are multiple smallest ones, pick the one that contains the last transaction (according to the provided fallback order) last (note that this is not the same as picking the chunk with the first transaction first)&period;
* Within chunks, pick among all transactions without missing dependencies the one with the highest individual feerate&period; If there are multiple ones with the same individual feerate, pick the smallest first&period; If there are multiple with the same fee and size, pick the one that sorts first according to the fallback order first&period;

== Member Functions

[cols="1,4"]
|===
| Name| Description
| xref:cluster_linearize/SpanningForestState/2constructor.adoc[`SpanningForestState`]         [.small]#[constructor]#
| Construct a spanning forest for the given DepGraph, with every transaction in its own chunk (not topological)&period;
| xref:cluster_linearize/SpanningForestState/GetCost.adoc[`GetCost`] 
| Determine how much work was performed so far&period;
| xref:cluster_linearize/SpanningForestState/GetDiagram.adoc[`GetDiagram`] 
| Get the diagram for the current state, which must be topological&period; Test&hyphen;only&period;
| xref:cluster_linearize/SpanningForestState/GetLinearization.adoc[`GetLinearization`] 
| Construct a topologically&hyphen;valid linearization from the current forest state&period; Must be topological&period; fallback&lowbar;order is a comparator that defines a strong order for DepGraphIndexes in this cluster, used to order equal&hyphen;feerate transactions and chunks&period;
| xref:cluster_linearize/SpanningForestState/LoadLinearization.adoc[`LoadLinearization`] 
| Load an existing linearization&period; Must be called immediately after constructor&period; The result is topological if the linearization is valid&period; Otherwise, MakeTopological still needs to be called&period;
| xref:cluster_linearize/SpanningForestState/MakeTopological.adoc[`MakeTopological`] 
| Make state topological&period; Can be called after constructing, or after LoadLinearization&period;
| xref:cluster_linearize/SpanningForestState/MinimizeStep.adoc[`MinimizeStep`] 
| Try to reduce a chunk&apos;s size&period; Returns false if all chunks are minimal, true otherwise&period;
| xref:cluster_linearize/SpanningForestState/OptimizeStep.adoc[`OptimizeStep`] 
| Try to improve the forest&period; Returns false if it is optimal, true otherwise&period;
| xref:cluster_linearize/SpanningForestState/SanityCheck.adoc[`SanityCheck`] 
| Verify internal consistency of the data structure&period;
| xref:cluster_linearize/SpanningForestState/StartMinimizing.adoc[`StartMinimizing`] 
| Initialize data structure for minimizing the chunks&period; Can only be called if state is known to be optimal&period; OptimizeStep() cannot be called anymore afterwards&period;
| xref:cluster_linearize/SpanningForestState/StartOptimizing.adoc[`StartOptimizing`] 
| Initialize the data structure for optimization&period; It must be topological already&period;
|===



[.small]#Created with https://www.mrdocs.com[MrDocs]#
