# Ranked Enumeration for MSO on Trees via Knowledge Compilation

Antoine Amarilli ✠ ID

LTCI, Télécom Paris, Institut polytechnique de Paris, France

Pierre Bourhis ✠ ID

Univ. Lille, CNRS, Inria, Centrale Lille, UMR 9189 CRISTAL, F-59000 Lille, France

Florent Capelli ✠ ID

Univ. Artois, CNRS, UMR 8188, Centre de Recherche en Informatique de Lens (CRIL), F-62300 Lens, France

Mikaël Monet ✠ ID

Université de Lille, CNRS, Inria, UMR 9189 - CRISTAL, F-59000 Lille, France

## Abstract

We study the problem of enumerating the satisfying assignments for certain circuit classes from knowledge compilation, where assignments are ranked in a specific order. In particular, we show how this problem can be used to efficiently perform ranked enumeration of the answers to MSO queries over trees, with the order being given by a ranking function satisfying a subset-monotonicity property.

Assuming that the number of variables is constant, we show that we can enumerate the satisfying assignments in ranked order for so-called multivalued circuits that are smooth, decomposable, and in negation normal form (smooth multivalued DNNF). There is no preprocessing and the enumeration delay is linear in the size of the circuit times the number of values, plus a logarithmic term in the number of assignments produced so far. If we further assume that the circuit is deterministic (smooth multivalued d-DNNF), we can achieve linear-time preprocessing in the circuit, and the delay only features the logarithmic term.

**2012 ACM Subject Classification** Information systems → Relational database model

**Keywords and phrases** Enumeration, knowledge compilation, monadic second-order logic

**Funding** Antoine Amarilli: Partially supported by the ANR project EQUUS ANR-19-CE48-0019, by the Deutsche Forschungsgemeinschaft (DFG, German Research Foundation) - 431183758, and by the ANR project ANR-18-CE23-0003-02 ("CQFD"). This work was done in part while the author was visiting the Simons Institute for the Theory of Computing.

Florent Capelli: This work was supported by project ANR KCODA, ANR-20-CE48-0004.

Mikaël Monet: This work was done in part while the author was visiting the Simons Institute for the Theory of Computing.

## 1 Introduction

Data management tasks often require the evaluation of queries on large datasets, in settings where the number of query answers may be very large. For this reason, the framework of enumeration algorithms has been proposed as a way to distinguish the preprocessing time of query evaluation algorithms and the maximal delay between two successive answers [32, 38]. Enumeration algorithms have been studied in several contexts: for conjunctive queries [7] and unions of conjunctive queries [9, 15] over relational databases; for first-order logic over bounded-degree structures [23], structures with local bounded expansion [33], and nowhere dense graphs [31]; and for monadic second-order logic (MSO) over trees [6, 25, 2].

We focus on the setting of MSO over trees. In this context, the following enumeration result is already known. For any fixed MSO query *Q* (i.e., in data complexity) where the free
variables are assumed to be first-order, considering the answers of $Q$ on a tree $T$ given as input (i.e., the functions that map the variables of $Q$ to nodes of $T$ in a way that satisfies $Q$), we can enumerate them with linear preprocessing on the tree $T$ and with constant delay. If the free variables are second-order, then the delay is output-linear, i.e., linear in each produced answer [6, 2]. Further results are known when the query is not fixed but given as input as a potentially non-deterministic automaton [3, 4], or when maintaining the enumeration structure under tree updates [28, 4].

However, despite their favorable delay bounds, a shortcoming of these enumeration algorithms is that they enumerate answers in an opaque order which cannot be controlled. This is in contrast with application settings where answers should be enumerated, e.g., by decreasing order of relevance, or focusing on the *top-k* most relevant answers. This justifies the need for enumeration algorithms that can produce answers in a user-defined order, even if they do so at the expense of higher delay bounds.

This task, called *ranked enumeration*, has recently been studied in various contexts. For instance, Carmeli et al. [16, 12, 13] study for which order functions one can efficiently perform ranked direct access to the answers of conjunctive queries: here, efficient ranked direct access implies efficient ranked enumeration. Ranked enumeration has also been studied to support order-by operators on factorized databases [8]. Other works have studied ranked enumeration for document spanners [21], which relate to the evaluation of MSO queries over words. Closer to applications, some works have studied the ranked enumeration of conjunctive query answers, e.g., Deep et al. [20, 19] or Tziavelis et al. [36, 37]. Variants of in-order enumeration have been also studied on knowledge compilation circuit classes, for instance *top-k*, with a pseudo-polynomial time algorithm [10]. Closest to the present work, Bourhis et al. [11] have studied enumeration on *words* where the ranking function on answers is expressed in the formalism of MSO cost functions. They show that enumeration can be performed with linear preprocessing, with a delay between answers which is no longer constant but logarithmic in the size of the input word. However, their result does not apply in the more general context of trees.

**Contributions.** In this paper, we embark on the study of efficient ranked enumeration algorithms for the answers to MSO queries on trees, assuming that all free variables are first-order. We define this task by assigning *scores* to each so-called *singleton assignment* [$x \rightarrow d$] describing that variable *x* is assigned tree node *d*, and combining these values into a *ranking function* while assuming a *subset-monotonicity property* [37]: intuitively, when extending two partial assignments in the same manner, then the order between them does not change. This setting covers many ranking functions, e.g., those defined by order, sum, or a lexicographic order on the variables. Our main contribution is then to show the following results on the data complexity of ranked enumeration for MSO queries on trees:

**► Result 1.** For any fixed MSO query $Q(x_1, \dots, x_n)$ with free first-order variables, given as input a tree $T$ and a subset-monotone ranking function $w$ on the partial assignments of $x_1, \dots, x_n$ to nodes of $T$, we can enumerate the answers to $Q$ on $T$ in nonincreasing order of scores according to $w$ with a preprocessing time of $O(|T|)$ and a delay of $O(\log(K+1))$, where $K$ is the number of answers produced so far.

Note that, as the total number of answers is at most $|T|^n$, and as $n$ is constant in data complexity, the delay of $O(\log(K+1))$ can alternatively be bounded by $O(n \log |T|)$, or $O(\log |T|)$. This matches the bound of [11] on words, though their notion of rank is different. Further, our bound shows that the first answers can be produced faster, e.g., for *top-k* computation.
Our results for MSO queries on trees are shown in the general framework of *circuit-based enumeration methods*, introduced by [2]. In this framework, enumeration results are achieved by first translating the task to a class of structured circuits from knowledge compilation, and then proposing an enumeration algorithm that works directly on the structured class. This makes it possible to re-use enumeration algorithms across a variety of problems that compile to circuits. In this paper, as our task consists in enumerating assignments (from first-order variables of an MSO query to tree nodes), we phrase our results in terms of *multivalued circuits*. These circuits generalize Boolean circuits by allowing variables to take values in a larger domain than {0, 1}: intuitively, the domain will be the set of the tree nodes. We assume that circuits are *decomposable*, i.e., that no variable has a path to two different inputs of a ^-gate: this yields *multivalued DNNFs*, which generalize usual DNNFs. We also assume that the circuits are *smooth*: intuitively, no variable is omitted when combining partial assignments at an ^-gate. Multivalued circuits can be smoothed while preserving decomposability, in quadratic time or faster in some cases [34]. Smooth multivalued DNNF circuits can alternatively be understood as factorized databases, but we do not impose that they are *normal* [30], i.e., the depth can be arbitrary.

Our enumeration task for MSO on trees thus amounts to the enumeration of satisfying assignments of smooth multivalued DNNFs, following a ranking function which we assume to be subset-monotone. However, we are not aware of existing results for ranked enumeration on circuits in the knowledge compilation literature. For this reason, the second contribution of this paper is to show efficient enumeration algorithms on these smooth multivalued DNNFs.

We first present an algorithm for this task that runs with no preprocessing and polynomial delay. The algorithm can be seen as an instance of the Lawler-Murty [26, 29] procedure. We show:

**Result 2.** For any constant $n \in \mathbb{N}$, given a smooth multivalued DNNF circuit $C$ with domain $D$ and with $n$ variables, given a subset-monotone ranking function $w$, we can enumerate the satisfying assignments of $C$ in nonincreasing order of scores according to $w$ with delay $O(|D| \times |C| + \log(K+1))$, where $K$ is the number of assignments produced so far.

We then show a second algorithm, which allows for a better delay bound at the expense of making an additional assumption on the circuit; it is with this algorithm that we prove Result 1. The additional assumption is that the circuit is *deterministic*: intuitively, no partial assignment is captured twice. This corresponds to the class of *smooth multivalued d-DNNF circuits*. For our task of enumerating MSO query answers, the determinism property can intuitively be enforced on circuits when we compute them using an deterministic tree automaton to represent the query. We then show:

**Result 3.** For any constant $n \in \mathbb{N}$, given a smooth multivalued *d-DNNF* circuit *C* with *n* variables, given a subset-monotone ranking function *w*, we can enumerate the satisfying assignments of *C* in nonincreasing order of scores according to *w* with preprocessing time *O*(*|C|*) and delay *O*(*log*(*K* + 1)), where *K* is the number of assignments produced so far.

**Paper structure.** We give preliminary definitions in Section 2. We first study in Section 3 the ranked enumeration problem for smooth multivalued DNNF circuits (Result 2). We then move on to a more efficient algorithm on smooth multivalued d-DNNF circuits (Result 3) in Section 4. We show how to apply the second algorithm to ranked enumeration for the answers to MSO queries (Result 1) in Section 5. We conclude in Section 6.
## 2 Preliminaries

For $n \in \mathbb{N}$ we write $[n]$ the set $\{1, \dots, n\}$.

**Assignments.** For two finite sets $D$ of values and $X$ of variables, an assignment on domain $D$ and variables $X$ is a mapping from $X$ to $D$. We write $D^X$ the set of such assignments. We can see assignments as sets of singleton assignments, where a singleton assignment is an expression of the form $[x \to d]$ with $x \in X$ and $d \in D$.

Two assignments $\tau \in D^Y$ and $\sigma \in D^Z$ are compatible, written $\tau \simeq \sigma$, if we have $\tau(x) = \sigma(x)$ for every $x \in Y \cap Z$. In this case, we denote by $\tau \bowtie \sigma$ the assignment of $D^{Y\cup Z}$ defined following the natural join, i.e., for $y \in Y \setminus Z$ we set $(\tau \bowtie \sigma)(y) := \tau(y)$, for $z \in Z \setminus Y$ we set $(\tau \bowtie \sigma)(z) := \sigma(z)$, and for $x \in Z \cap Y$, we set $(\tau \bowtie \sigma)(x)$ to the common value $\tau(x) = \sigma(x)$. Two assignments $\tau \in D^Y$ and $\sigma \in D^Z$ are disjoint if $Y \cap Z = \emptyset$: then they are always compatible and $\tau \bowtie \sigma$ corresponds to the relational product, which we write $\tau \times \sigma$.

Given $R \subseteq D^Y$ and $S \subseteq D^Z$, we define $R \wedge S = \{\tau \bowtie \sigma \mid \tau \in R, \sigma \in S, \tau \simeq \sigma\}$: this is a subset of $D^{Y \cup Z}$. Note how, if the domain is $D = \{0, 1\}$, then this corresponds to the usual conjunction for Boolean functions, and in general we can see it as a relational join, or a relational product whenever $Y \cap Z = \emptyset$. Further, we define $R \vee S = \{\tau \in D^{Y \cup Z} \mid \tau|_Y \in R \text{ or } \tau|_Z \in S\}$, which is again a subset of $D^{Y \cup Z}$. Again observe how, when $D = \{0, 1\}$, this corresponds to disjunction; and in general we can see this as relational union except that assignments over $Y$ and $Z$ are each implicitly completed in all possible ways to assignments over $Y \cup Z$.

**Multivalued circuits.** A multivalued circuit $C$ on domain $D$ and variables $X$ is a DAG with labeled vertices which are called *gates*. The circuit also has a distinguished gate $r$ called the *output gate of $C$*. Gates having no incoming edges are called *inputs of $C$*. Moreover, we have:

- Every input of $D$ is labeled with a pair of the form $\langle x : d \rangle$ with $x \in X$ and $d \in D$;

- Every other gate of $D$ is labeled with either $\vee$ (a $\vee$-gate) or $\wedge$ (a $\wedge$-gate). We denote by $|C|$ the number of edges in $C$.

Given a gate $v$ of $C$, the *inputs of $v$* are the gates $w$ of $C$ such that there is a directed edge from $w$ to $v$. The *set of variables below $v$*, denoted by $\text{var}(v)$, is then the set of variables $x \in X$ such that there is an input $w$ which is labeled by $\langle x : d \rangle$ for some $d \in D$ and which has a directed path to $v$. Equivalently, if $v$ is an input labeled by $\langle x : d \rangle$ then $\text{var}(v) := \{x\}$, otherwise $\text{var}(v) := \bigcup_{i=1}^k \text{var}(v_i)$ where $v_1, \dots, v_k$ are the inputs of $v$. We assume that the set $X$ of variables of the circuit is equal to $\text{var}(r)$ for $r$ the output gate of $C$: this can be enforced without loss of generality up to removing useless variables from $X$.

For each gate $v$ of $C$, the *set of assignments rel$(v) \subseteq D^{\text{var}(v)}$ of $v$* is defined inductively as follows. If $v$ is an input labeled by $\langle x : d \rangle$, then $\text{rel}(v)$ contains only the assignment $[x \mapsto d]$. Otherwise, if $v$ is an internal gate with inputs $v_1, \dots, v_k$ then $\text{rel}(v) := \text{rel}(v_1) \text{ op } \dots \text{ op } \text{rel}(v_k)$ where $\text{op} \in \{\vee, \wedge\}$ is the label of $v$. The *set of assignments rel$(C)$ of $C$* is that of its output gate. Note that, if $D = \{0, 1\}$, then the set of assignments of $C$ precisely corresponds to its satisfying valuations when we see $C$ as a Boolean circuit in the usual sense.

We say that a $\wedge$-gate $v$ is *decomposable* if all its inputs are on disjoint sets of variables; formally, for every pair of inputs $v_1 \neq v_2$ of $v$, we have $\text{var}(v_1) \cap \text{var}(v_2) = \emptyset$. A $\vee$-gate $v$ is *smooth* if all its inputs have the same set of variables (so that implicit completion does not occur); formally, for every pair of inputs $v_1, v_2$ of $v$, we have $\text{var}(v_1) = \text{var}(v_2)$. A $\vee$-gate $v$ is *deterministic* if every assignment of $v$ is computed by only one of its inputs; formally, for every pair of inputs $v_1 \neq v_2$ of $v$, if $\tau \in \text{rel}(v)$ then either $\tau|_{\text{var}(v_1)} \notin \text{rel}(v_1)$ or $\tau|_{\text{var}(v_2)} \notin \text{rel}(v_2)$.
Let $v$ be an internal gate with inputs $v_1, \dots, v_k$. Observe that if $v$ is decomposable, then $\mathrm{rel}(v) = \times_{i=1}^k \mathrm{rel}(v_i)$. If $v$ is smooth then $\mathrm{rel}(v) = \bigcup_{i=1}^k \mathrm{rel}(v_i)$. If moreover $v$ is deterministic, then $\mathrm{rel}(v) = \biguplus_{i=1}^k \mathrm{rel}(v_i)$, where $\uplus$ denotes disjoint union. Accordingly, we denote decomposable $\wedge$-nodes as $\times$-nodes, denote smooth $\vee$-nodes as $\bigcup$-nodes, and denote smooth deterministic $\vee$-nodes as $\uplus$-nodes.

A multivalued circuit is decomposable (resp., smooth, deterministic) if every $\wedge$-gate is decomposable (resp., every $\vee$-gate is smooth, every $\vee$-gate is deterministic). A multivalued DNNF on domain $D$ and variables $X$ is then a decomposable multivalued circuit on $D$ and $X$. A multivalued $d$-DNNF on domain $D$ and variables $X$ is a deterministic multivalued DNNF on $D$ and $X$. In all this paper, we only work with circuits that are both decomposable and smooth, i.e., smooth multivalued DNNFs. Note that smoothness can be ensured on Boolean circuits in quadratic time [34], and the same can be done on multivalued circuits.

**Ranking functions.** Our notion of ranking functions will give a score to each assignment, but to state their properties we define them on partial assignments. Formally, a *partial assignment* is a mapping $\nu : X \to D \cup \{\perp\}$, where $\perp$ is a fresh symbol representing *undefined*. We denote by $\overline{D^X}$ the set of partial assignments on domain $D$ and variables $X$. The *support* $\mathrm{supp}(\nu)$ of $\nu$ is the subset of $X$ on which $\nu$ is defined. We extend the definitions of compatibility, of $\perp$, and of disjointness, to partial assignments in the following way. Two partial assignments $\tau \in \overline{D^Y}$ and $\sigma \in \overline{D^Z}$ are *compatible*, again written $\tau \simeq \sigma$, when for every $x \in Y \cap Z$, if $\tau(x) \neq \perp$ and $\sigma(x) \neq \perp$ then $\tau(x) = \sigma(x)$. In this case, we denote by $\tau \bowtie \sigma$ the partial assignment of $\overline{D^{Y \cup Z}}$ defined by: for $y \in Y \setminus Z$ we have $(\tau \bowtie \sigma)(y) := \tau(y)$, for $z \in Z \setminus Y$ we have $(\tau \bowtie \sigma)(z) := \sigma(z)$, and for $x \in Z \cap Y$, if $\tau(x) \neq \perp$ then $(\tau \bowtie \sigma)(x) = \tau(x)$, otherwise $(\tau \bowtie \sigma)(x) = \sigma(x)$. We call $\tau$ and $\sigma$ *disjoint* if $Y \cap Z = \emptyset$; then again they are always compatible and we write $\tau \times \sigma$ for $\tau \bowtie \sigma$.

We then consider ranking functions defined on partial assignments $\overline{D^X}$, on which we will impose *subset-monotonicity*. Formally, a $(D, X)$-ranking function $w$ is a function$^1 \overline{D^X} \to \mathbb{R}$ that gives a score to every partial assignment. Such a ranking function induces a weak ordering$^2 \preceq$ on $\overline{D^X}$, with $\mu \preceq \mu'$ defined as $w(\mu) \le w(\mu')$. We always assume that ranking functions can be computed efficiently, i.e., with running time that only depends on $X$, not $D$.

By a slight notational abuse, we define the score $w(\tau)$ of partial assignment $\tau \in \overline{D^Y}$ with $Y \subseteq X$ by seeing $\tau$ as a partial assignment on $X$ which is implicitly extended by assigning $\perp$ to every $z \in X \setminus Y$. Following earlier work [20, 37, 19], we then restrict our study to ranking functions that are *subset-monotone* [37]:

**Definition 2.1.** A $(D, X)$-ranking function $w : \overline{D^X} \to \mathbb{R}$ is subset-monotone if for every $Y \subseteq X$ and partial assignments $\tau_1, \tau_2 \in \overline{D^Y}$ such that $w(\tau_1) \le w(\tau_2)$, for every partial assignment $\sigma \in \overline{D^{X \setminus Y}}$ (so disjoint with $\tau_1$ and $\tau_2$), we have $w(\sigma \times \tau_1) \le w(\sigma \times \tau_2)$.

We use in particular the following consequence of subset-monotonicity (see Appendix A), where we call $\tau \in \overline{D^X}$ maximal (or maximum) for $w : \overline{D^X} \to \mathbb{R}$ when for every $\tau' \in \overline{D^X}$ we have $w(\tau') \le \tau(\tau)$:

<footnote n="1">¹ As usual, when we write $\mathbb{R}$, we assume a suitable representation, e.g., as floating-point numbers.</footnote>

<footnote n="2">² Recall that a weak ordering $\preceq$ on $A$ is a total preorder on $A$, i.e., $\preceq$ is transitive and we have either $x \preceq y$ or $y \preceq x$ for every $x, y \in A$. In particular, it can be the case that two distinct elements $x$ and $y$ are tied, i.e., $x \preceq y$ and $y \preceq x$.</footnote>
**Lemma 2.2.** Let $R \subseteq \overline{D^Y}$ and $S \subseteq \overline{D^Z}$ with $Y \cap Z = \emptyset$, and let $w : \overline{D^{Y \cup Z}} \to \mathbb{R}$ be subset-monotone. If $\tau$ is a maximal element of $R$ and $\sigma$ is a maximal element of $S$ with respect to $w$, then $\tau \times \sigma$ is a maximal element of $R \wedge S$ with respect to $w$.

We give a few examples of subset-monotone ranking functions. Let $W: X \times D \to \mathbb{R}$ be a function assigning scores to singleton assignments, and define the $(D, X)$-ranking function $sum_W: \overline{D^X} \to \mathbb{R}$ by $sum_W(\tau) = \sum_{x \in X, \tau(x) \neq \perp} W(x, \tau(x))$. Then $sum_W$ is subset-monotone. Similarly define $max_W: \overline{D^X} \to \mathbb{R}$ by $max_W(\tau) = \max_{x \in X, \tau(x) \neq \perp} W(x, \tau(x))$, or $prod_W$ in a similar manner (with non-negative scores for singletons); then these are again subset-monotone. In particular, we can use $sum_W$ to encode lexicographic orderings on $\overline{D^X}$.

**Enumeration and problem statement.** Our goal in this article is to efficiently enumerate the satisfying assignments of circuits in nonincreasing order according to a ranking function. We will in particular apply this for the ranked enumeration of the answers to MSO queries on trees, as we will explain in Section 5. We call this problem **RankEnum**. Formally, the input to **RankEnum** consists of a multivalued circuit *C* on domain *D* and variables *X*, and a (*D*, *X*)-ranking function *w* that is subset-monotone. The output to enumerate consists of all of *rel(C)*, without duplicates, in nonincreasing order of scores (with ties broken arbitrarily).

Formally, we work in the RAM model on words of logarithmic size [1], where memory cells can represent integers of value polynomial in the input length, and on which arithmetic operations take constant time. We will in particular allocate arrays of polynomial size in constant time, using lazy initialization [24]. We measure the performance of our algorithms in the framework of *enumeration algorithms*, where we distinguish two phases. First, in the *preprocessing phase*, the algorithm reads the input and builds internal data structures. We measure the running time of this phase as a function of the input; in general the best possible bound is *linear preprocessing*, e.g., preprocessing in $O(|C|)$. Second, in the *enumeration phase*, the algorithm produces the assignments, one after the other, without duplicates, and in nonincreasing order of scores; the order of assignments that are tied according to the ranking function is not specified. The *delay* is the maximal time that the enumeration phase can take to produce the next assignment, or to conclude that none are left. We measure the delay as a function of the input, as a function of the produced assignments (which each have size $|X|$), and also as a function of the number of results that have been produced so far. The best delay is *output-linear delay*, i.e., $O(|X|)$, which can be achieved for (non-ranked) enumeration of MSO queries on trees [6, 25, 2]. In our results, we will always fix $|X|$ to a constant (for technical reasons explained in the next section), so the corresponding bound would be *constant delay*, but, like [11], we will not be able to achieve it. Also note that the memory usage of the enumeration phase is not bounded by the delay, but can grow as enumeration progresses.

**Brodal queues.** Similar to [11], our algorithms in this paper will use priority queues, in a specific implementation called a (*functional*) *Brodal queue* [14]. Intuitively, Brodal queues are priority queues which support union operations in $O(1)$, and which are *purely functional* in the sense that operations return a queue without destroying the input queue(s). More precisely, a *Brodal queue* is a data structure which stores a set of priority-data pairs of the form ($p: \text{foo}, d: \text{bar}$) where foo is a real number and bar an arbitrary piece of data, supporting operations defined below. Brodal queues are *purely functional and persistent*, i.e., for any operation applied to some input Brodal queues, we obtain as output a new Brodal queue $Q'$, such that the input queues can still be used. Note that the structures of $Q'$ and of the input Brodal queues may be sharing locations in memory; this is in fact necessary, e.g.,
to guarantee constant-time bounds. However, this is done transparently, and both $Q'$ and
the input Brodal queues can be used afterwards<fnref n="3" />. Brodal queues support the following:

- Initialize, in time $O(1)$, which produces an empty queue;

- Push, in time $O(1)$, which adds to $Q$ a priority-data pair;

- Find-Max, in time $O(1)$, which either indicates that $Q$ is empty or otherwise returns some pair ($\mathbf{p}$: foo, $\mathbf{d}$: bar) with foo being maximal among the priority-data pairs stored in $Q$ (ties are broken arbitrarily);

- Pop-Max, in time $O(\log(|Q|))$, which either indicates that $Q$ is empty or returns two values: first the pair $p$ returned by Find-Max, second a queue storing all the pairs of $Q$ except $p$;

- Union, in time $O(1)$, which takes as input a second Brodal queue $Q'$ and returns a queue over the elements of $Q$ and $Q'$.

### 3 Ranked Enumeration for Smooth Multivalued DNNFs

In this section, we start the presentation of our technical results by giving our algorithm to solve the ranked enumeration problem for DNNFs under subset-monotone orders. This is Result 2 from the introduction, which we restate below:

**Theorem 3.1.** For any constant $n \in \mathbb{N}$, we can solve the Rank Enum problem on an input smooth multivalued DNNF circuit $C$ on domain $D$ and variables $X$ with $|X| = n$ and a subset-monotone $(D, X)$-ranking function with no preprocessing and with delay $O(|D| \times |C| + \log(K+1))$, where $K$ is the number of assignments produced so far.

Note how the number $n$ of variables is assumed to be constant in the result statement. This is for a technical reason: we will need to store partial assignments in memory, but in the RAM model we can only index polynomially many memory locations [24, page 3], so we must ensure that the total number of assignments is polynomial. The circuit itself and the domain can however be arbitrarily large, following the application to MSO queries over trees studied in Section 5: the variables of the circuit will be the variables of the MSO query (which is fixed because we will work in data complexity), and the size of the circuit and that of the domain will be linear in the size of the tree (which represents the data).

Our algorithm can be seen as an instance of the Lawler-Murty [26, 29] procedure, that has been previously used to enumerate paths in DAGs in decreasing order of weight in [37]. Interestingly, the result does not require that the input circuit is deterministic. However, it is less efficient than the method presented in Section 4 where determinism is exploited.

We prove Theorem 3.1 in the rest of this section. Let us fix a smooth multivalued DNNF $C$ on domain $D$ and variables $X$, and a subset-monotone ranking function $w: \overline{D^X} \to \mathbb{R}$. For a partial assignment $\tau$, we denote by $w_C(\tau) = \max\{w(\tau \times \sigma) \mid \sigma \in D^{X\setminus\text{supp}(\tau)}$ and $\tau \times \sigma \in \text{rel}(C)\}$ the score of the maximal completion of $\tau$ to a satisfying assignment of $C$ if it exists and $w_C(\tau) = \perp$ if no such completion exists. Our algorithm relies on the following folklore observation:

**Lemma 3.2.** Given a partial assignment $\tau$, one can compute $w_C(\tau)$ in time $O(|C|)$.

<footnote n="3">³ This is similar to how persistent linked lists can be modified by removing the head element or concatenating with a new head element. Such operations can run in constant time and return the modified version of the list without invalidating the original list; with both lists sharing some memory locations in a transparent fashion.</footnote>
<caption>Algorithm 1 Algorithm for Theorem 3.1</caption>

**Data:** Smooth multivalued DNNF C with n variables, subset-monotone ranking function w.

**Result:** Enumeration of the satisfying assignments of C in nonincreasing order of scores by w.

1. $Q \leftarrow$ empty priority queue;
2. Push the empty assignment $[]$ into $Q$ with priority $w_C([])$;
3. **while** $Q$ is not empty **do**
4. &nbsp;&nbsp;&nbsp;&nbsp;Pop into $\gamma$ the assignment with maximum $w_C$-score from $Q$;
5. &nbsp;&nbsp;&nbsp;&nbsp;**for** $j \leftarrow |\text{supp}(\gamma)| + 1$ **to** $n$ **do**
6. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;**foreach** $d \in D$ **do**
7. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Construct $\alpha_d = \gamma \times \langle x_j : d \rangle$;
8. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Compute $w_C(\alpha_d)$ using Lemma 3.2;
9. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;**end**
10. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\[ \gamma \leftarrow \alpha_{d_0} \text{ such that } w_C(\alpha_{d_0}) \text{ is not } \perp \text{ and is maximal;} \]
11. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Push into $Q$ all $\alpha_{d'}$ for $d' \neq d_0$ where $w_C(\alpha_{d'}) \neq \perp$, with priority $w_C(\alpha_{d'})$;
12. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;**end**
13. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Output $\gamma$;
14. **end**

**Proof sketch.** We condition C on $\tau$ in linear time, obtaining $C'$, and then compute in a bottom-up manner for every gate $C'$ some assignment of $\text{rel}(g)$ of maximal score, relying on smoothness and decomposability. See Appendix B for more details. ◀

With this in place, we are ready to describe the algorithm. Notice that our definition of multivalued circuits implies that $\text{rel}(C)$ can never be empty, because all gates except input gates have inputs, and the circuit is decomposable. We fix an arbitrary order on $X = \{x_1, \dots, x_n\}$ and, for $i \in \{1, \dots, n+1\}$, we denote by $X_{<i}$ the set $\{x_1, \dots, x_{i-1}\}$ (which is empty for $i=1$). A partial assignment $\tau \in \overline{D}^X$ is called a *prefix assignment* if $\text{supp}(\tau) = X_{<i}$ for some $i \in \{1, \dots, n+1\}$.

The enumeration algorithm is then illustrated as Algorithm 1, which we paraphrase in text below. The algorithm uses a variable $\gamma$ holding a prefix assignment and a priority queue $Q$ containing prefix assignments. The priorities in the queue are the $w_C$-score, i.e., the priority of each prefix assignment is the score returned by $w_C$ on this assignment. We initialize $Q$ to contain only the empty partial assignment (i.e., the assignment that maps every variable to $\perp$, denoted $[]$ in Algorithm 1): note that the $w_C$-score of $[]$ is not $\perp$ because $\text{rel}(C) \neq \emptyset$. We then do the following until the queue is empty. We pop (i.e., call $\text{Pop-Max}$) from the queue a prefix assignment (of maximal $w_C$-score) that we assign to $\gamma$; we will inductively see that $\gamma$ is a prefix assignment of $D^{<i}$ for some $i \in \{1, \dots, n+1\}$ and that its $w_C$-score is not $\perp$. We then do the following for $j := i$ to $n$ (i.e., potentially zero times, in case $i = n+1$ already). For every possible choice of domain element $d \in D$, we let $\alpha_d$ be the prefix assignment that extends $\gamma$ by assigning $x_i$ to $d$, and we compute the value $w_C(\alpha_d)$ using Lemma 3.2. Among these values, the definition of $w_C$ ensures that one has a $w_C$-score which is not $\perp$, because this is true of $\gamma$. We thus pick a value $d_0 \in D$ such that $w_C(\alpha_{d_0})$ is maximal (in particular non-$\perp$). We set $\gamma$ to $\alpha_{d_0}$, and we push into $Q$ all other prefix assignments $\alpha_{d'}$ for $d' \neq d_0$ for which we have $w_C(\alpha_{d'}) \neq \perp$. Once we have run this for all values of $j$, we have $i = n+1$, hence $\gamma$ is a total assignment, and we output it. We then
continue processing the remaining contents of the queue.

**Correctness of the algorithm.** We show in Appendix B that the following invariants hold at the beginning and end of every while loop iteration:

1. For every $\tau \in Q$, no satisfying assignment of $C$ compatible with $\tau$ has been outputted so far;

2. For every $\tau, \tau' \in Q$, if $\tau \neq \tau'$ then $\tau \not\approx \tau'$;

3. For every $\sigma \in \text{rel}(C)$ that has not yet been outputted by the algorithm, there exists some $i \in \{1, \dots, n+1\}$ such that $\sigma|_{X_{<i}} \in Q$ (in fact, the previous point then implies there is at most one such $i$);

4. The number of elements in $Q$ is at most $n \times |D| \times (K+1)$, where $K$ is the number of assignments produced so far.

We explain next why they imply correctness.

**► Claim 3.3.** *Algorithm 1 terminates, enumerates rel($C$) without duplicates and in non-increasing order, and runs with delay $O(|D| \times |C| + \log(K+1))$ with $K$ the number of assignments produced so far.*

**Proof.** We first show that the algorithm terminates. Indeed, notice that we pop a prefix assignment from the queue at the beginning of every while loop iteration. Let us show that, once a prefix assignment $\tau$ has been popped from $Q$, it cannot be pushed again into $Q$ for the rest of the algorithm’s execution. Indeed, observe that once we pop $\tau$ from $Q$, we will first push to $Q$ assignments that are strict extensions of $\tau$ (hence different from $\tau$), and then output a satisfying assignment $\tau'$ of $C$ that is compatible with $\tau$, after which the current iteration of the while loop ends. Now, by invariant (1), no partial assignment compatible with $\tau'$ can ever be added to $Q$, and in particular it is the case that $\tau$ cannot ever be added to $Q$. Thus the queue becomes empty and the algorithm terminates.

Since the queue eventually becomes empty, by invariant (3), the algorithm outputs at least all of $\text{rel}(C)$. The fact that there are no duplicates follows from invariant (1), using a similar reasoning to how we proved termination. Furthermore, it is clear that only assignments of $\text{rel}(C)$ are ever outputted. Therefore the algorithm indeed enumerates exactly all of $\text{rel}(C)$ with no duplicates.

To check that assignments are enumerated in nonincreasing order, consider an iteration of the while loop where we output $\tau \in \text{rel}(C)$. Let $\sigma \in \text{rel}(C)$ be an assignment that has not yet been outputted, and assume by contradiction that $w(\tau) < w(\sigma)$. Consider the prefix assignment $\gamma$ that was popped from the queue $Q$ at the beginning of that iteration; clearly by construction we have $w_C(\gamma) = w(\tau)$. But by invariant (3), there exists a prefix assignment $\gamma'$ in $Q$ of which $\sigma$ is a completion, hence for this $\gamma'$ we have $w_C(\gamma') \ge w(\sigma)$ by definition of $w_C$, and this is strictly bigger than $w(\gamma)$, contradicting the fact that $\gamma$ had maximal priority.

Last, we check that the delay between any two consecutive outputs is indeed $O(|D| \times |C| + \log(K+1))$. The $O(|D| \times |C|)$ term corresponds to the at most $n \times |D|$ applications of Lemma 3.2 during a for loop until we produce the next satisfying assignment (remember that $n$ is constant so it is not reflected in the delay). The $O(\log(K+1))$ term corresponds to the unique pop operation performed on the priority queue during a while loop iteration. Indeed, by invariant (4) the queue contains less than $n \times |D| \times (K+1)$ prefix assignments and the complexity of a pop operation is logarithmic in this. Since $n$ is constant we obtain $O(\log|D| + \log(K+1))$, and the $O(\log|D|)$ gets absorbed in the $O(|D| \times |C|)$ term. ◀

Thus, up to showing that the invariants hold (see Appendix B), we have concluded the proof of Theorem 3.1.
## 4 Ranked Enumeration for Smooth Multivalued d-DNNFs

Having shown our polynomial-delay ranked enumeration algorithm for DNNF circuits, we move on in this section to our main technical contribution. Specifically, we present an algorithm for smooth multivalued DNNF circuits that are further assumed to be *deterministic*, but which achieves linear-time preprocessing and delay $O(\log(K+1))$, where $K$ denotes the number of satisfying assignments produced so far. This proves Result 3, which we restate below:

**Theorem 4.1.** For any constant $n \in \mathbb{N}$, we can solve the RankEnumeration problem on an input smooth multivalued d-DNNF circuit $C$ with $n$ variables and a subset-monotone ranking function, with preprocessing $O(|C|)$ and delay $O(\log(K+1))$, where $K$ is the number of assignments produced so far.

Let us fix for this section the set $X$ of variables of $C$ (with $|X| = n$) and the domain $D$.

The rest of this section is devoted to proving Theorem 4.1. It is structured in three subsections, corresponding to the three main technical difficulties to overcome. First, we explain in Section 4.1 the preprocessing phase of the algorithm, where in particular we use Brodal queues to quickly “jump” over $\mathcal{U}$-gates. Second, in Section 4.2, we present a simple algorithm, that we call the *A ⊙ B ranked enumeration algorithm*, which conveys in a self-contained fashion the idea of how we handle $\times$-gate during the enumeration phase of the main algorithm. Last, we present the enumeration phase in Section 4.3.

### 4.1 Preprocessing Phase

The preprocessing phase is itself subdivided in four steps, described next.

**Preprocessing: first step.** We preprocess $C$ in $O(|C|)$ to ensure that the $\times$-gates of the circuit always have exactly two inputs. This can easily be done as follows. Remember that our definition of multivalued circuits does not allow $\times$-gates with no inputs, so this case does not occur. We can then eliminate $\times$-gates with one input by replacing them by their single input. Next, we can rewrite $\times$-gates with more than two inputs to replace them by a tree of $\times$-gates with two inputs. For simplicity, let us call $C$ again the resulting smooth multivalued d-DNNF circuit in which $\times$-gates always have exactly two inputs.

**Preprocessing: second step.** We compute, for every gate $g$ of $C$ the value $\#g := |\text{rel}(g)|$. This can clearly be done in linear time again, by a bottom-up traversal of $C$ and using decomposability, determinism and smoothness. Note that $\#g$ has value at most $|D|^n$, which is polynomial (as $n$ is a constant), so this fits into one memory cell.

**Preprocessing: third step.** The third step begins by initializing for every gate $g$ of $C$ an empty Brodal queue $B_g$. We then populate those queues by a (linear-time) bottom-up traversal of the circuit, described next. This traversal will add to each queue $B_g$ some priority-data pairs of the form $(\mathbf{p} : w(\tau), \mathbf{d} : (g', 1, \tau))$ where $g'$ has a (possibly empty) directed path to $g$ and $\tau \in \text{rel}(g)$. We will shortly explain what is the exact content of these queues at the end of this third preprocessing step, but we already point out one invariant: once we are done processing a gate $g$ in the traversal, then $B_g$ contains at least one priority-data pair of this form, i.e., it is non-empty.

The traversal proceeds as follows:
■ If $g$ is an input gate labeled with $\langle x : d \rangle$ corresponding to the singleton assignment $\alpha = [x \mapsto d]$, then we push into $B_g$ the priority-data pair corresponding to this assignment: $(\mathbf{p} : w(\alpha), \mathbf{d} : (g, 1, \alpha))$.

■ If $g$ is a $\times$-gate with inputs $g_1$ and $g_2$ then we call Find-Max on the Brodal queues $B_{g_1}$ and $B_{g_2}$ of the inputs. These gates $g_1$ and $g_2$ have already been processed, so the queues $B_{g_1}$ and $B_{g_2}$ are non-empty, and we obtain priority-data pairs $(\mathbf{p} : w(\tau_1), \mathbf{d} : (g'_1, 1, \tau_1))$ and $(\mathbf{p} : w(\tau_2), \mathbf{d} : (g'_2, 1, \tau_2))$, where $\tau_1 \in \text{rel}(g_1)$ and $\tau_2 \in \text{rel}(g_2)$. We push into $B_g$ the pair $(\mathbf{p} : w(\tau_1 \times \tau_2), \mathbf{d} : (g, 1, \tau_1 \times \tau_2))$.

■ If $g$ is a $\oplus$-gate with input gates $g_1, \dots, g_m$ then we set $B_g$ to be the union of $B_{g_1}, \dots, B_{g_m}$; recall that the union operation on two Brodal queues can be done in $O(1)$, so that this union is linear in $m$.

It is clear that this third preprocessing step takes time $O(|C|)$. To describe what the queues contain at the end of this step, we need to define the notion of *exit gate* of a $\oplus$-gate:

**Definition 4.2.** For a $\oplus$-gate $g$ of $C$, an *exit gate* of $g$ is a gate $g'$ which is not a $\oplus$-gate (i.e., a $\times$-gate or an input of the circuit) such that there is a path from $g'$ to $g$ where every gate except $g'$ on this path is a $\oplus$-gate. We denote by $\text{exit}(g)$ the set of exit gates for $g$.

We can then characterize what the queues contain:

**Claim 4.3.** When the third preprocessing step finishes, the queues $B_g$ are as follows.

■ If $g$ is an input gate corresponding to the singleton assignment $\alpha = [x \mapsto d]$ then $B_g$ contains only the pair $(\mathbf{p} : w(\alpha), \mathbf{d} : (g, 1, \alpha))$.

■ If $g$ is a $\times$-gate then $B_g$ contains only one pair, which is of the form $(\mathbf{p} : w(\tau), \mathbf{d} : (g, 1, \tau))$ where $\tau$ is some satisfying assignment of $g$ of maximal score among $\text{rel}(g)$.

■ If $g$ is a $\oplus$-gate then $B_g$ contains exactly the following: for every exit gate $g'$ of $g$, the queue $B_g$ contains one pair of the form $(\mathbf{p} : w(\tau), \mathbf{d} : (g', 1, \tau))$ where $\tau$ is some satisfying assignment of $g'$ of maximal score among $\text{rel}(g')$.

This implies, in particular, that for every $g \in C$ the queue $B_g$ contains a pair $(\mathbf{p} : w(\tau), \mathbf{d} : (g', 1, \tau))$ (possibly with $g' = g$) where $\tau$ is a satisfying assignment of $g$ of maximal score among $\text{rel}(g)$.

**Proof of Claim 4.3.** It is routine to prove this by bottom-up induction, in particular using Lemma 2.2 for the case of $\times$-gates. ◀

This concludes the third preprocessing step. Intuitively, the Brodal queues computed at this step will allow us to jump directly to the exits of $\oplus$-gates, without spending time traversing potentially long paths of $\oplus$-gates. Thanks to the constant-time union operation on Brodal queues, this third step takes linear time, and in fact this is the only part of the proof where we need this bound on the union operation. More precisely, in the remainder of the algorithm, we will only use on priority queues $Q$ the operations `Initialize`, `Push` and `Find-Max` (in $O(1)$) and `Pop-Max` (in $O(\log |Q|)$).

**Preprocessing: fourth step.** In the fourth and last preprocessing step, we define some more data structures on every gate $g$ of $C$.

First, we define for every gate $g$ a priority queue $Q_g$. For all input gates and $\oplus$-gates, we simply set $Q_g := B_g$, but for $\times$-gates we will define $Q_g$ to be new priority queues. Once this is done, we will only use the priority queues $Q_g$, and can forget about the priority queues $B_g$. We construct $Q_g$ for each $\times$-gate $g$ separately, in $O(1)$ time, as follows. Letting $g_1$ and $g_2$ be the inputs to $g$, we call Find-Max on $B_g$. By Claim 4.3, we obtain a pair
(p : w(τ), d : (g, 1, τ)) where τ is some satisfying assignment of g of maximal score among rel(g). We split τ into τ₁ × τ₂ where τᵢ ∈ rel(gᵢ) for i ∈ {1, 2}, and we define the priority queue Qg to contain one priority-data pair, namely, (p : w(τ), d : (1, 1, τ₁, τ₂)).

Second, we allocate for every gate g a table T_g of size #g (indexed starting from 1), that will later hold satisfying assignments of g in nonincreasing order of scores, stored into contiguous memory cells starting at the beginning of T_g. We do not bother initializing these tables, but we initialize integers i_g to 0, that will store the current number of assignments stored in T_g.

Last, we also initialize to 0 a bidimensional bit table R_g for every ×-gate g, of size #g₁ × #g₂ with g₁, g₂ the two inputs of g. This can be done in O(1) with the technique of lazy initialization, see e.g., [24, Section 2.5]. The role of these tables will be explained later.

This concludes the description of the preprocessing phase of our algorithm. In what follows, we will rely on the priority queues Q_g, the tables T_g, the integers i_g storing their size, and the tables R_g. The following should then be clear:

**Claim 4.4.** Once we finish the fourth preprocessing step (concluding the preprocessing), all integers i_g are 0, all tables T_g and R_g are empty, and the queues Q_g contain the following.

- If g is an input gate corresponding to the singleton assignment α = [x ↦→ d], then Q_g contains only the pair (p : w(α), d : (g, 1, α)).

- If g is a ×-gate with inputs g₁, g₂, then Q_g contains only one priority-data pair which is of the form (p : w(τ₁ × τ₂), d : (1, 1, τ₁, τ₂)), where τ₁ × τ₂ is some satisfying assignment of g of maximal score among rel(g).

- If g is a ⊕-gate, then Q_g contains, for every exit gate g' of g, one pair of the form (p : w(τ), d : (g', 1, τ)) where τ is some satisfying assignment of g' of maximal score among rel(g').

Again, this in particular implies that each $Q_g$ stores a satisfying assignment of g of maximal score (but the way in which it is represented depends on the type of g).

## 4.2 $A \odot B$ Ranked Enumeration Algorithm

Having described the preprocessing phase, we present in this section a component of the enumeration phase of our algorithm, called the *A $\odot$ B ranked enumeration* algorithm. This simple algorithm will be used at every $\times$-gate *g* during the enumeration phase to enumerate all ways to combine the assignments of the two inputs of *g*.

Let $\odot: \mathbb{R} \times \mathbb{R} \rightarrow \mathbb{R}$ be an operation which is computable in $O(1)$ and such that, for all $a \le a'$ and $b \le b'$ we have $a \odot b \le a' \odot b'$ (this is similar to subset-monotonicity, and is in fact equivalent; cf. Lemma A.1 in the appendix). We explain in this section how, given as input two tables (indexed starting from 1) A, B of reals of size $n_1, n_2$ sorted in nonincreasing order, we can enumerate the set of integer pairs $\{(i, j) \mid (i, j) \in \{1, \dots, n_1\} \times \{1, \dots, n_2\}\}$, in nonincreasing order of the score $A[i] \odot B[j]$, with $O(1)$ preprocessing and a delay $O(\log K)$ where K is the number of pairs outputted so far.

Intuitively, this will be applied at every $\times$-gate *g*, with $[n_1]$ (resp., $[n_2]$) representing the satisfying valuations of the first (resp., second) input of *g* sorted in a nonincreasing order, and $A[l]$ (resp., $B[l]$) representing the score of those valuations according to the ranking function.

The algorithm is shown in Algorithm 2, but we also paraphrase it in text with more explanations. We initialize a two-dimensional bit table *R* of size *n*₁ × *n*₂ to contain only zeroes (again using lazy initialization [24, Section 2.5]), whose role will be to remember which pairs have been seen so far, and a priority queue *Q* containing only the pair (*p* :
■ **Algorithm 2** Algorithm for $A \odot B$ ranked enumeration

**Data:** Two arrays $A, B$ of real numbers of size $n_1, n_2$ (indexed from 1), sorted in nonincreasing order; An operation $\odot$ as described in the main text.

**Result:** An enumeration of the pairs $\{(i, j) | (i, j) \in \{1, \dots, n_1\} \times \{1, \dots, n_2\}\}$ in nonincreasing order of the score $A[i] \odot B[j]$

1. $R \leftarrow$ bidimensional array of size $n_1 \times n_2$ lazily initialized to 0;

2. $Q \leftarrow$ empty priority queue;

3. Push (1, 1) into $Q$ with priority $A[1] \odot B[1]$;

4. $R[1, 1] \leftarrow$ true;

5. **while** $Q$ is not empty **do**

6. &nbsp;&nbsp;&nbsp;&nbsp;Pop into $(i, j)$ the pair with maximal priority from $Q$;

7. &nbsp;&nbsp;&nbsp;&nbsp;Output $(i, j)$;

8. &nbsp;&nbsp;&nbsp;&nbsp;**for** $(p, q) \in \{(i + 1, j), (i, j + 1)\}$ **do**

9. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;**if** $p \le n_1$ and $q \le n_2$ and $R[p][q] = 0$ **then**
10. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Push $(p, q)$ into $Q$ with priority $A[p] \odot B[q]$;
11. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$R[p][q] \leftarrow$ true;

12. &nbsp;&nbsp;&nbsp;&nbsp;end

13. &nbsp;&nbsp;&nbsp;&nbsp;end

14. end

$A[1] \odot B[1]$, **d**: (1, 1)); we set $R[1, 1]$ to true because the pair (1, 1) has been seen. Then, while the queue is not empty, we do the following. We pop (call Pop-Max) from $Q$, obtaining a priority-data pair of the form ($\mathbf{p}$: $A[i] \odot B[j]$, **d**: $(i, j)$). We output the pair $(i, j)$. Then, for each $(p, q) \in \{(i + 1, j), (i, j + 1)\}$ that is in the $[n_1] \times [n_2]$ grid, if the pair $(p, q)$ has not been seen before, then we push into $Q$ the pair ($\mathbf{p}$: $A[p] \odot B[q]$, **d**: $(p, q)$) and mark $(p, q)$ as seen in $R$. We show the following, with a full proof in Appendix C.1.

**Claim 4.5.** *This $A \odot B$ ranked enumeration algorithm is correct and runs with the stated complexity.*

**Proof sketch.** The proof is simple and hinges on the following two invariants:

1. For any pair $(i, j)$ not enumerated so far, there exists a pair $(i', j')$ (possibly $(i, j) = (i', j')$) such that $(i', j')$ is in $Q$, and a simple path in the $[n_1] \times [n_2]$ grid from $(i', j')$ to $(i, j)$ with nondecreasing first and second coordinates such that none of the pairs in that path have been outputted yet.

2. The queue contains at most $K + 1$ pairs for $K$ the number of pairs outputted so far. ◀

## 4.3 Enumeration Phase

We last move on to the enumeration phase. We first give a high-level description of how the enumeration phase works, before presenting the details.

**The operation Get(g, j).** We will define a recursive operation Get, running in complexity $O(\log(K + 1))$, that applies to a gate g and integer $1 \le j \le i_g + 1$ and does the following. If $j \le i_g$ then Get(g, j) simply returns the satisfying assignment of g that is stored in $T_g[j]$ (i.e., this assignment has already been computed). Otherwise, if $j = i_g + 1$, then Get(g, j) finds the next assignment to be enumerated, inserts it into $T_g$, and returns that assignment. Note that, in this case, calling Get(g, j) modifies the memory for g and some other gates g'.
Specifically, it modifies the tables $T_g'$ and $R_{g'}$, the queues $Q_{g'}$, and the integers $i_g'$ for various gates $g'$ having a directed path to $g$ (i.e., including $g' = g$).

When we are not executing an operation *Get*, the memory will satisfy the following invariants, for every *g* of *C*:

- The table $T_g$ contains assignments $\tau \in \text{rel}(g)$, ordered by nonincreasing score and with no duplicates; and $i_g$ is the current size of $T_g$;

- For any assignment $\tau \in \text{rel}(g)$ that does not occur in $T_g$, it is no larger than the last assignment in $T_g$, i.e., we have $w(\tau) \le w(T_g[i_g])$.

- The queues $Q_g$ will also satisfy some invariants, which will be presented later.

- The tables $R_g$ for the ×-gates record whether we have already seen pairs of satisfying assignments of the two children, similarly to how this is done in the $A \odot B$ algorithm. The tables $T_g$ store the assignments in the order in which we find them, which is compatible with the ranking function. This allows us, in particular, to obtain in constant time the j-th satisfying assignment of $\text{rel}(g)$ if it has already been computed, i.e., if $j \le i_g$. The reason why we keep the assignments in the tables $T_g$ is because we may reach the gate $g$ via many different paths throughout the enumeration, and these paths may be at many different stages of the enumeration on $g$.

At the top level, if we can implement *Get* while satisfying the invariants above, then the enumeration phase of the algorithm is simple to describe: for *j* ranging from 1 to *#r*, we output *Get*(*r*, *j*), where *r* is the output gate of *C*.

**Implementing Get.** We first explain the intended semantics of data values in the queues $Q_b$:

- If $g$ is a $\oplus$-gate then $Q_b$ will always contain pairs of the form ($\mathbf{p}$ : $w(\tau)$, $\mathbf{d}$ : ($g'$, $j$, $\tau$)) where $g' \in \text{exit}(g)$ and $j \in \{1, \dots, i_{g'} + 1\}$ and $\tau \in \text{rel}(g')$, and the idea is that at the end of the enumeration $\tau$ will be stored at position $j$ in $T_{g'}$.

- If $g$ is a $\times$-gate, letting $g'_1$ and $g'_2$ be the input gates, then $Q_b$ will always contain pairs of the form ($\mathbf{p}$ : $w(\tau_1 \times \tau_2)$, $\mathbf{d}$ : ($j_1, j_2, \tau_1, \tau_2$)) with $\tau_i \in \text{rel}(g_i)$ and at the end of the enumeration $\tau_i$ will be at position $j_i$ in $T_{g_i}$ with $j_i \in \{1, \dots, i_{g'_i} + 1\}$ for all $i \in \{1, 2\}$.

- If $g$ is an input gate, then $Q_b$ initially contains the only assignment captured by $g$, becomes empty the first time we call $\text{Get}(g, 1)$, and remains empty thereafter.

The implementation of *Get* is given in Algorithm 3. Intuitively, the algorithm for $\oplus$-gates simply consists of interleaving the maximal assignments of its exit gates, similarly to how one builds a sorted list for the union of two or more sorted lists. Here, determinism ensures that we do not get duplicates. The algorithm for $\times$-gates proceeds similarly to the $A \odot B$ algorithm, as explained in the previous section.

This concludes the presentation of the function *Get*, and with it that of the enumeration phase of the algorithm. The discussion of the delay bound is deferred to Appendix C.2.

## 5 Application to Monadic Second-Order Queries

Having presented our results on ranked enumeration for smooth multivalued DNNFs and d-DNNFs, we present their consequences in this section for the problem of ranked enumeration of MSO query answers on trees. We first present some preliminaries on trees and MSO, formally define the evaluation problem, and explain how to reduce it to our results on circuits.

**Trees and MSO on trees.** We fix a finite set $\Lambda$ of tree labels. A $\Lambda$-tree is then a tree $T$ whose nodes carry a label from $\Lambda$, and which is rooted, ordered, binary, and full, i.e., every
■ **Algorithm 3** Implementation of Get(g, j) for the enumeration phase

**Data:** The tables $T_g, R_g$, queues $Q_g$, integers $\#g, i_g$, ranking function $w$, a gate $g$, and integer $j \in \{1, \dots, i_g + 1\}$.

**Result:** The $j$-th satisfying assignment of $g$.

1. **if** $j \le i_g$ **then** return $T_g[j]$;
   // From now on, we have $j = i_g + 1$

2. **if** $g$ is an input gate **then**

3. | ($\mathbf{p} : \delta, \mathbf{d} : (g, 1, \tau')$) $\leftarrow$ Pop from $Q_j$;

4. | $\tau \leftarrow \tau'$;

5. **end**

6. **else if** $g$ is a $\omega$-gate **then**

7. | ($\mathbf{p} : \delta, \mathbf{d} : (g', j', \tau')$) $\leftarrow$ Pop from $Q_j$;

8. | $\tau \leftarrow \tau'$;

9. **if** $j' + 1 \le \#g'$ **then**

10. | $\tau'' \leftarrow \text{Get}(g', j' + 1)$;

11. | Push into $Q_g$ the priority-data pair ($\mathbf{p} : w(\tau'')$, $\mathbf{d} : (g', j' + 1, \tau'')$);

12. **end**

13. **end**

14. **else if** $g$ is a $\times$ gate **then**

15. | ($\mathbf{p} : \delta, \mathbf{d} : (j_1, j_2, \tau_1, \tau_2)$) $\leftarrow$ Pop from $Q_j$;

16. | $\tau \leftarrow \tau_1 \times \tau_2$;

17. **for** $(p, q) \in \{(j_1 + 1, j_2), (j_1, j_2 + 1)\}$ **do**

18. | **if** $p \le \#g_1$ and $q \le \#g_2$ and $R_g[p][q] = \text{false}$ **then**

19. | $\tau'_1 \leftarrow \text{Get}(g_1, p)$;

20. | $\tau'_2 \leftarrow \text{Get}(g_2, q)$;

21. | $\tau' \leftarrow \tau'_1 \times \tau'_2$;

22. | Push into $Q_g$ the priority-data pair ($\mathbf{p} : w(\tau')$, $\mathbf{d} : (p, q, \tau')$);

23. | $R_g[p][q] \leftarrow \text{true}$;

24. **end**

25. **end**

26. **end**

27. $T_g[i_g + 1] \leftarrow \tau$;

28. $i_g \leftarrow i_g + 1$;

29. **return** $\tau$
node has either no children (a *leaf*) or exactly one *left child* and one *right child* (an *internal node*). We often abuse notation and write *T* to refer to its set of nodes.

We consider *monadic second-order logic* (MSO) on trees, which extends first-order logic with quantification over sets. The signature of MSO on Λ-trees allows us to refer to the left child and right child relationships along with unary predicates referring to the node labels; and it can express, e.g., the set of descendants of a node. We only consider MSO queries where the free variables are first-order. We omit the precise semantics of MSO; see, e.g., [27].

Fixing an MSO query $\Phi(x_1, \dots, x_n)$ on $\Lambda$-trees, given a $\Lambda$-tree $T$, the answers of $\Phi$ on $T$ are the assignments $\alpha$ on variables $X = \{x_1, \dots, x_n\}$ and domain $T$ such that $\Phi(\alpha)$ holds on $T$ in the usual sense. It is known that, for any such query $\Phi$, given $T$ and an assignment $\alpha$ from $X$ to $T$, we can check whether $\Phi(\alpha(X))$ holds in linear time. What is more, given $T$, we can enumerate the answers of $\Phi$ on $T$ with linear preprocessing and constant delay [6, 25, 2].

We now define *ranked enumeration*. For a tree $T$ and variables $X = \{x_1, \dots, x_n\}$, a $(T, X)$-ranking function is simply a ranking function as in Section 2, whose domain is the set of nodes of $T$. We still assume that ranking functions are subset-monotone. The *ranked enumeration* problem for a fixed MSO query $\Phi$ with variables $X$, also denoted RankObj, takes an input a tree $T$ and a subset-monotone $(T, X)$-ranking function $w$, and must enumerate all answers of $\Phi$ on $T$, without duplicates, in nonincreasing order of scores (with ties broken arbitrarily).

**Ranked enumeration for MSO.** We are now ready to restate Result 1 from the introduction:

**Theorem 5.1.** For any fixed tree signature $\Lambda$ and MSO query $\Phi$ on variables $X$ on $\Lambda$-trees, given a $\Lambda$-tree $T$ and a subset-monotone $(T, X)$-ranking function $w$, we can solve the RankObj problem for $\Phi$ on $T$ and $w$ with preprocessing time $O(|T|)$ and delay $O(\log(K+1))$ where $K$ is the number of answers produced so far.

Recall that, as the total number of answers is at most $|T|^{|X|}$ and $|X|$ is constant, then this implies a delay bound of $O(\log|T|)$. The result is simply shown by constructing a smooth multivalued d-DNNF representing the query answers. This can be done in linear time with existing techniques (we provide a self-contained proof in Appendix D):

**Proposition 5.2 ([2, 4]).** For any fixed tree signature $\Lambda$ and MSO query $\Phi$ on variables $X$ on $\Lambda$-trees, given a $\Lambda$-tree $T$, we can check in time $O(|T|)$ if $\Phi$ has some answers on $T$, and if yes we can build in time $O(|T|)$ a smooth multivalued d-DNNF $C$ on domain $T$ and variables $X$ such that $rel(C)$ is precisely the set of answers of $\Phi$ on $T$.

Note that we exclude the case where $\Phi$ has no answer on $T$, because our definition of multivalued circuits does not allow them to capture an empty set of assignments; of course we can do this check in the preprocessing, and if there are no answers then enumeration is trivial.

These results are intuitively shown by translating the MSO query to a tree automaton, and then computing a provenance circuit of this automaton by a kind of product construction [5]. The resulting circuit is a smooth multivalued DNNF, and is additionally a d-DNNF if the automaton is deterministic. We can then show Theorem 5.1 simply by performing the compilation (Proposition 5.2) as part of the preprocessing, and then invoking the enumeration algorithm of Section 4 (Theorem 4.1). Notice that we could also use the algorithm of Section 3 (Theorem 3.1), in particular if it is easier to obtain a nondeterministic tree automaton for the query, as its provenance circuit would then be a non-deterministic DNNF [4].
# 6 Conclusion

We have studied the problem of ranked enumeration for tractable circuit classes from knowledge compilation, namely, DNNFs and d-DNNFs, in the setting of multivalued circuits so as to apply these results to ranked enumeration for MSO query answers on trees. We have shown that the latter task can be solved with linear-time preprocessing and delay logarithmic in the number of answers produced so far, in particular logarithmic delay in the input tree in data complexity. This result on trees is the analogue of a previous result on words [11], achieving the same bounds but for a different notion of ranking functions.

We leave several questions open for future work. For instance, our efficient algorithms always assume that the input circuits are smooth: although this can be ensured “for free” in the setting of MSO on trees, it is generally quadratic to enforce on an arbitrary input circuit [34]. It may be possible to perform enumeration directly on non-smooth circuits, or on implicitly smoothed circuits, e.g., with special gates as in [2]. It would also be natural to study this problem in combined complexity, or for free second-order variables, though our algorithms cannot work on the RAM model if we need to store a superpolynomial number of assignments in memory. Last, it may be possible to extend our algorithms to more general ranking functions than the one we study, for instance by leveraging the framework of MSO cost functions used in [11], or using weighted logics [22], or possibly replacing subset-monotonicity by a weaker guarantee.

Last, it would be interesting to study whether our results can extend to the support of *updates*, e.g., reweighting updates to the ranking functions, or updates on the underlying circuits or (for MSO queries) on the tree, as in [28] or [4]. However, this is more difficult than the case of updates for non-ranked enumeration, because our algorithms use larger intermediate structures which are more challenging to maintain.

## References

1 Alfred V. Aho, John E. Hopcroft, and Jeffrey D. Ullman. *The design and analysis of computer algorithms*. Addison-Wesley, 1974.

2 Antoine Amarilli, Pierre Bourhis, Louis Jachiet, and Stefan Mengel. A circuit-based approach to efficient enumeration. In *ICALP*, 2017. doi:10.4230/LIPIcs.ICALP.2017.111.

3 Antoine Amarilli, Pierre Bourhis, Stefan Mengel, and Matthias Niewerth. Constant-delay enumeration for nondeterministic document spanners. In *ICDT*, 2019. doi:10.4230/LIPIcs. ICDT.2019.22.

4 Antoine Amarilli, Pierre Bourhis, Stefan Mengel, and Matthias Niewerth. Enumeration on trees with tractable combined complexity and efficient updates. In *PODS*, 2019. doi: 10.1145/3294052.3319702.

5 Antoine Amarilli, Pierre Bourhis, and Pierre Senellart. Provenance circuits for trees and treelike instances. In *ICALP*, 2015. doi:10.1007/978-3-662-47666-6_5.

6 Guillaume Bagan. MSO queries on tree decomposable structures are computable with linear delay. In *CSL*, 2006. doi:10.1007/11874683_11.

7 Guillaume Bagan, Arnaud Durand, and Étienne Grandjean. On acyclic conjunctive queries and constant delay enumeration. In *CSL*, 2007. doi:10.1007/978-3-540-74915-8_18.

8 Nurzhan Bakibayev, Tomáš Kociský, Dan Olteanu, and Jakub Závodný. Aggregation and ordering in factorised databases. *PVLDB*, 6(14), 2013.

9 Christoph Berkholz, Jens Keppeler, and Nicole Schweikardt. Answering UCQs under updates and in the presence of integrity constraints. In *ICDT*, 2018. doi:10.4230/LIPIcs.ICDT.2018.8.
10 Pierre Bourhis, Laurence Duchien, Jérémie Dusart, Emmanuel Lonca, Pierre Marquis, and Clément Quinton. Pseudo polynomial-time top-k algorithms for d-dnnf circuits. CoRR, 2022. URL: https://arxiv.org/abs/2202.05938.

11 Pierre Bourhis, Alejandro Grez, Louis Jachiet, and Cristian Riveros. Ranked enumeration of MSO logic on words. In ICDT, 2021.

12 Karl Bringmann, Nofar Carmeli, and Stefan Mengel. Tight fine-grained bounds for direct access on join queries. In PODS, 2022.

13 Karl Bringmann, Nofar Carmeli, and Stefan Mengel. Tight fine-grained bounds for direct access on join queries. CoRR, abs/2201.02401, 2022.

14 Gerth Stølting Brodal and Chris Okasaki. Optimal purely functional priority queues. Journal of Functional Programming, 6(6), 1996.

15 Nofar Carmeli and Markus Kröll. On the enumeration complexity of unions of conjunctive queries. TODS, 46(2), 2021. doi:10.1145/3450263.

16 Nofar Carmeli, Nikolaos Tziavelis, Wolfgang Gatterbauer, Benny Kimelfeld, and Mirek Riedewald. Tractable orders for direct access to ranked answers of conjunctive queries. TODS, 48(1), 2023.

17 H. Comon, M. Dauchet, R. Gilleron, C. Löding, F. Jacquemard, D. Lugiez, S. Tison, and M. Tommasi. Tree automata: Techniques and applications, 2007. URL: http://tata.gforge.inria.fr/.

18 Adnan Darwiche and Pierre Marquis. A knowledge compilation map. Journal of Artificial Intelligence Research, 17, 2002.

19 Shaleen Deep, Xiao Hu, and Paraschos Koutris. Ranked enumeration of join queries with projections. arXiv preprint arXiv:2201.05566, 2022.

20 Shaleen Deep and Paraschos Koutris. Ranked enumeration of conjunctive query results. arXiv preprint arXiv:1902.02698, 2019.

21 Johannes Doleschal, Benny Kimelfeld, Wim Martens, and Liat Peterfreund. Weight annotation in information extraction. Logical Methods in Computer Science, 18, 2022.

22 Manfred Droste and Paul Gastin. Weighted automata and weighted logics. In ICALP. Springer, 2005.

23 Arnaud Durand and Étienne Grandjean. First-order queries on structures of bounded degree are computable with constant delay. TOCL, 8(4), 2007. doi:10.1145/1276920.1276923.

24 Étienne Grandjean and Louis Jachiet. Which arithmetic operations can be performed in constant time in the RAM model with addition? arXiv preprint arXiv:2206.13851, 2022.

25 Wojciech Kazana and Luc Segoufin. Enumeration of monadic second-order queries on trees. TOCL, 14(4), 2013. doi:10.1145/2528928.

26 Eugene L Lawler. A procedure for computing the k best solutions to discrete optimization problems and its application to the shortest path problem. Management science, 18(7), 1972.

27 Leonid Libkin. Elements of finite model theory. Springer, 2004.

28 Katja Losemann and Wim Martens. MSO queries on trees: Enumerating answers under updates. In CSL-LICS, 2014. doi:10.1145/2603088.2603137.

29 Katta G Murty. An algorithm for ranking all the assignments in order of increasing cost. Operations research, 16(3), 1968.

30 Dan Olteanu and Jakub Závodný. Size bounds for factorised representations of query results. TODS, 40(1), 2015.

31 Nicole Schweikardt, Luc Segoufin, and Alexandre Vigny. Enumeration for FO queries over nowhere dense graphs. JACM, 69(3), 2022. doi:10.1145/3517035.

32 Luc Segoufin. A glimpse on constant delay enumeration (invited talk). In STACS, 2014. URL: https://hal.inria.fr/hal-01070893/document.

33 Luc Segoufin and Alexandre Vigny. Constant delay enumeration for FO queries over databases with local bounded expansion. In ICDT, 2017. doi:10.4230/LIPIcs.ICDT.2017.20.

34 Andy Shih, Guy Van den Broeck, Paul Beame, and Antoine Amarilli. Smoothing structured decomposable circuits. In NeurIPS, 2019.
35 James W. Thatcher and Jesse B. Wright. Generalized finite automata theory with an application to a decision problem of second-order logic. *Math. Systems Theory*, 2(1), 1968.

36 Nikolaos Tziavelis, Deepak Ajwani, Wolfgang Gatterbauer, Mirek Riedewald, and Xiaofeng Yang. Optimal algorithms for ranked enumeration of answers to full conjunctive queries. *PVLDB*, 13(9), 2020.

37 Nikolaos Tziavelis, Wolfgang Gatterbauer, and Mirek Riedewald. Any-k algorithms for enumerating ranked answers to conjunctive queries. *arXiv preprint arXiv:2205.05649*, 2022.

38 Kunihiro Wasa. Enumeration of enumeration algorithms. *CoRR*, 2016. URL: https://arxiv.org/abs/1605.05102.
A Proofs for Section 2 (Preliminaries)

**Lemma 2.2.** Let $R \subseteq \overline{D^Y}$ and $S \subseteq \overline{D^Z}$ with $Y \cap Z = \emptyset$, and let $w : \overline{D^{Y \cup Z}} \to \mathbb{R}$ be subset-monotone. If $\tau$ is a maximal element of $R$ and $\sigma$ is a maximal element of $S$ with respect to $w$, then $\tau \times \sigma$ is a maximal element of $R \wedge S$ with respect to $w$.

Lemma 2.2 is a direct consequence of the following lemma:

**Lemma A.1.** A $(D, X)$-ranking function $w$ is subset-monotone if and only if the following holds: for every partial assignments $\tau_1, \tau_2$ and $\sigma_1, \sigma_2$, if $\tau_i$ is disjoint from $\sigma_i$ for each $i \in \{1, 2\}$ and $w(\tau_1) \le w(\tau_2)$ and $w(\sigma_1) \le w(\sigma_2)$, then we have $w(\tau_1 \times \sigma_1) \le w(\tau_2 \times \sigma_2)$.

**Proof.** The right to left implication is obvious as we can apply the property with $\sigma_1 = \sigma_2$ to recover the definition of subset-monotone. For the other way around, assume $w$ to be subset-monotone and let $\tau_1, \tau_2, \sigma_1, \sigma_2$ be partial assignments as in the statement. By subset-monotonicity, first by applying the property with $\sigma = \sigma_1$ and then with $\sigma = \tau_2$, and using transitivity, we have $w(\tau_1 \times \sigma_1) \le w(\tau_2 \times \sigma_1) \le w(\tau_2 \times \sigma_2)$. $\quad \blacksquare$

We point out here that the converse of Lemma 2.2 is not necessarily true, i.e., it is not always the case that every maximal assignment $\tau$ of a subset-monotone ranking function $w: \overline{D^{Y \cup Z}} \to \mathbb{R}$ with $Y \cap Z = \emptyset$ can be decomposed as $\tau = \tau_1 \times \tau_2$ with $\tau_1$ some maximal assignment of $\overline{D^Y}$ and $\tau_2$ some maximal assignment of $\overline{D^Z}$. We show an example of this phenomenon below.

**Example A.2.** Take $D = \{a\}$, $Y = \{y\}$, $Z = \{z\}$ with $y \neq z$, and consider the ranking function $w: \overline{D^{\{y,z\}}} \to \mathbb{R}$ defined by

$$ w(\sigma) = \begin{cases} 0 & \text{if } \sigma(y) = \sigma(z) = \perp \\ 50 & \text{if } \sigma(y) = \perp \text{ and } \sigma(z) = a \\ 100 & \text{if } \sigma(y) = a \text{ and } \sigma(z) = \perp \\ 100 & \text{if } \sigma(y) = a \text{ and } \sigma(z) = a \end{cases} \tag{1} $$

The reader is invited to check that $w$ is subset-monotone but does not satisfy the property mentioned above (take $\tau = [y \to a, z \to \perp]$).

B Proofs for Section 3 (Ranked Enumeration for Smooth Multivalued DNNFs)

**Lemma 3.2.** Given a partial assignment $\tau$, one can compute $w_C(\tau)$ in time $O(|C|)$.

**Proof.** Let $X$ be the variables of $C$.

It is enough to show that we can compute, given a smooth multivalued DNNF $C'$ and monotone ranking function $w'$, some $\sigma' \in \text{rel}(C')$ that maximizes $w'(\sigma')$, in $O(|C'|)$. Indeed, if this is the case we can first compute the conditioning<fnref n="4" /> $C'$ of $C$ on $\tau$ in time $O(|C'|)$: specifically, $C'$ is a multivalued circuit on domain $D$ and variables $X \setminus \text{supp}(\tau)$ such that, for $\sigma' \in D^{X \setminus \text{supp}(\tau)}$ we have that $\sigma' \in \text{rel}(C')$ iff $\tau \times \sigma' \in \text{rel}(C)$. Then, letting $w'$ be the ranking function on $\overline{D^{X \setminus \text{supp}(\tau)}}$ defined by $w'(\sigma') := w(\sigma' \times \tau)$ (which is subset-monotone),

<footnote n="4">⁴ See [18, Definition 5.4] for the definition of conditioning on Boolean circuits, which easily adapts to multivalued circuits.</footnote>
find one such $\sigma' \in \text{rel}(C')$ in time $O(|C|)$, and then return $w(\sigma' \times \tau)$. This is correct thanks to subset-monotonicity of $w$, more precisely, by Lemma 2.2.

Now the algorithm to do this proceeds by bottom-up induction as follows: for each gate $v$ of $C'$, we compute $\sigma_v \in \text{rel}(v)$ such that $w'(\sigma_v) = \max\{w'(\sigma) \mid \sigma \in \text{rel}(v)\}$. If $v$ is an input then $\text{rel}(v)$ is a singleton assignment, and we let $\sigma_v$ be this assignment. Now, if $v$ is a $\times$-gate with inputs $v_1, \dots, v_k$, we let $\sigma_v = \sigma_{v_1} \times \dots \times \sigma_{v_k}$. By Lemma 2.2, $\sigma_v$ is maximal for $\text{rel}(v)$ if each $\sigma_{v_i}$ is maximal for $\text{rel}(v_i)$ which is the case by induction. Finally, if $v$ is a $\cup$-gate with input $v_1, \dots, v_k$, we define $\sigma_v = \arg \max_{i=1}^k w'(\sigma_{v_i})$, which is clearly maximal in $\text{rel}(v) = \cup_{i=1}^k \text{rel}(v_i)$ if $\sigma_{v_i}$ is maximal in $\text{rel}(v_i)$ for each $i$ because $v$ is smooth, which is the case by induction. $\quad$

**► Claim B.1.** *Invariants (1–4) hold.*

*Proof.* These invariants clearly hold at the beginning of the first while loop iteration because then $Q$ contains only the empty assignment.

Assuming that the invariants hold at the beginning of some while loop iteration when $Q$ is not empty, let us show they still hold at the end of that iteration. Write $Q$ the queue at the beginning of that iteration, $\alpha^{i-1} \in D^{<i}$ the prefix assignment that is popped from the queue and initially assigned to $\gamma$ and, for $j \in \{i, \dots, n\}$, write $\alpha^j$ the value of $\gamma$ after the for loop for this value of $j$, with $\alpha^j = \alpha_{d_j}^{j-1} (= \alpha^{j-1} \times \langle x_j : d_j \rangle)$. Define also $D'_i = \{d' \in D \mid d' \neq d_i \text{ and } w_C(\alpha_{d_j}^{i-1}) \neq \perp\}$. Letting $Q'$ be the queue after this while loop iteration, observe that $Q' = (Q \setminus \{\alpha^{i-1}\}) \cup \bigcup_{i=1}^n \{\alpha_{d_j}^{i-1} \mid d' \in D_i\}$. We check that the invariants hold for $Q'$.

We first check invariant (1): let $\tau \in Q'$. There are two cases. First, if $\tau \in Q \setminus \{\alpha^{i-1}\}$, then, by induction hypothesis using invariant (1), no satisfying assignment of $C$ compatible with $\tau$ had been outputted before $\alpha^n$. Now, $\tau$ is an extension of $\alpha^{i-1}$ and $\alpha^{i-1}$ is not compatible with $\tau$ by induction hypothesis of invariant (2) on $Q$. Therefore $\alpha^n$ cannot be compatible with $\tau$ either. Second, if $\tau$ is one of the $\alpha_{d_j}^{i-1}$ then by construction it is not compatible with the assignment $\alpha^n$ that we output at this iteration. Moreover since $\tau$ is an extension of $\alpha^{i-1}$, by induction hypothesis with invariant (2) on $Q$ again we cannot have outputted an assignment compatible with $\tau$ before this iteration. Thus, in both cases, (1) holds for $Q'$.

Invariant (2) is easy to check, again because every $\tau$ of the form $\alpha_{d_j}^{i-1}$ is an extension of $\alpha^{i-1}$ and $\alpha^{i-1}$ is incompatible with every $\tau \in Q \setminus \{\alpha^{i-1}\}$ by induction hypothesis.

To check invariant (3), consider $\sigma \in \text{rel}(C)$. By induction hypothesis with the same invariant, there is some $i \in \{1, \dots, n+1\}$ such that $\sigma|_{X_{<i}} \in Q$. So if $\sigma|_{X_{<i}}$ is not $\alpha^{i-1}$ then the claim is immediate. Otherwise, we can see that we either produce $\sigma$ or add to $Q'$ some assignment that extends $\alpha^{i-1}$ and is compatible with $\sigma$.

Finally, invariant (4) is also trivial to show by applying induction hypothesis to $Q$ and observing that $\bigcup_{i=1}^n \{\alpha_{d_j}^{i-1} \mid j \in D_i\}$ has at most $n \times |D|$ elements. $\quad$

# C Proofs for Section 4 (Ranked Enumeration for Smooth Multivalued d-DNNFs)

## C.1 Proof of Claim 4.5

**► Claim 4.5.** *This $A \odot B$ ranked enumeration algorithm is correct and runs with the stated complexity.*

*Proof.* We claim that the following invariants hold at the beginning and end of every while loop iteration. To simplify notation, when we talk of the $\odot$-score of a pair $(i, j) \in [n_1] \times [n_2]$ we mean the score $A[i] \odot B[j]$.
1. For any pair $(i, j)$ not enumerated so far, there exists a pair $(i', j')$ (possibly $(i, j) = (i', j')$) such that $(i', j')$ is in $Q$, and a simple path in the $[n_1] \times [n_2]$ grid from $(i', j')$ to $(i, j)$ with nondecreasing first and second coordinates<fnref n="5" /> such that none of the pairs in that path have been outputted yet.

2. The queue contains at most $K+1$ pairs where $K$ is the number of pairs outputted so far. Before proving that these invariants hold, let us argue that they imply the claim. It is clear that the algorithm terminates thanks to the array $R$: once a pair is added to the queue its $R$-value is set to true (and never set to false again), so it cannot be put back into $Q$ anymore, and so the queue eventually becomes empty.

We then show that the algorithm enumerates all of $[n_1] \times [n_2]:$ indeed, assume by contradiction that the algorithm terminates and that some pair $(i, j)$ has not been outputted. The queue is empty, but invariant (1) implies that there is still an element $(i', j')$ in the queue, a contradiction. It is also clear by construction that the algorithm only enumerates pairs of $[n_1] \times [n_2]$. It is clear that it does not enumerate the same pair twice thanks to the table $R$: we only add each pair at most once to the queue, hence it will be popped and enumerated at most once. The claim for the delay is also clear thanks to invariant (2).

Last, we show that the pairs are enumerated in nonincreasing order of $\odot$-score. Assume by way of contradiction that pair $(i_1, j_1)$ is enumerated before pair $(i_2, j_2)$ and that $A[i_1] \odot B[j_1] < A[i_2] \odot B[j_2]$. Now, consider the beginning of the while-loop iteration where we are about to pop $(i_1, j_1)$ from $Q$. Since $(i_2, j_2)$ has not been enumerated yet, by invariant (1) there exists $(i'', j'')$ in $Q$ with $\odot$-score at least that of $(i_2, j_2)$ (by monotonicity of $\odot$ along the path); this contradicts the fact that $(i_1, j_1)$ has maximal priority when we pop it from $Q$.

We now prove the invariants. They are true before the first while loop iteration: indeed, nothing has been outputted yet so invariant (2) holds. Further, the queue only contains the pair $(1, 1)$, and the subset-monotonicity-like property that we assumed on the function $\odot$ implies that, for any pair $(i, j)$ of the grid $[n_1] \times [n_2]$, the path $(1, 1), \dots, (1, j), (2, j), \dots, (i, j)$ is a nondecreasing path from $(1, 1)$ to $(i, j)$ satisfying the invariant.

Assume that the invariants are true at the beginning of some while loop iteration and the queue is not empty, and let us show that they still hold at the end of that iteration. Call $Q$ the state of the queue before that iteration, $(i, j)$ the pair that is popped, and $Q'$ the state of the queue afterwards. Invariant (2) is clear by induction hypothesis: we popped a pair and added at most two during that iteration.

Now for invariant (1), assume by contradiction that there exists a pair $(i_1, j_1)$ which has not been enumerated after the end of that iteration and which does not satisfy the invariant. In particular, we have not enumerated $(i_1, j_1)$ before that iteration, so applying the induction hypothesis we obtain a pair $(i', j')$ (possibly $(i_1, j_1) = (i', j')$) such that $(i', j')$ is in $Q$ and a simple path in the $[n_1] \times [n_2]$ grid from $(i', j')$ to $(i_1, j_1)$ with nondecreasing first and second coordinates such that none of the pairs in that path have been outputted before that iteration. If $(i, j)$ is not one of the pairs of that path then we are done because this path still satisfies the conditions at the end of the iteration. Otherwise, consider the pair $(u, v)$ after $(i, j)$ in that path. Then $(u, v)$ is either to the right of $(i, j)$ or above $(i, j)$ because the path has nondecreasing first and second coordinates. Hence, either $(u, v)$ is already in $Q$ (and therefore will also be in $Q'$), or it is not in $Q$ and has been pushed into $Q'$ when extracting $(i, j)$. So the path starting at $(u, v)$ is a valid witnessing path.

This establishes that the invariants hold and concludes the proof of Claim 4.5. ◀

<footnote n="5">⁵ More precisely, if we see $(1, 1)$ as being at the bottom left of the grid, then the path always goes either up or right.</footnote>
## C.2 Correctness of the Enumeration Phase (Section 4.3)

The fact that algorithm correctly enumerates $rel(C)$ in nonincreasing order of scores and without duplicates follows from the invariants and observations that we have already hinted at during the presentation of the algorithm (we do not give the full details of the proof). Thus, what remains to be shown is the $O(\log K)$ bound on the delay.

Observe that the delay is simply the total time it takes for a call of the operation **Get** on the output gate *r* of *C* to finish; call such a call a *top-level call*. Now, during a top-level call, notice that for every gate *g*', the queue $Q_{g'}$ grows by at most one element, just like in the $A \oplus B$ algorithm: this is because, thanks to decomposability, the “trace” of the algorithm is a tree, hence **Get** is called at most once on *g*' during any top-level call. Therefore, after *K* assignments have been outputted, each queue has size at most *K* + 1.

Moreover thanks to the way we “jump” $\oplus$-gates by directly going to their exit nodes and thanks to decomposability, the total number of recursive calls to **Get** caused by a top-level call is linear in the number *n* of variables, which is constant. The bound follows, since during a call of **Get**(*g*) for some gate *g*, not counting the time for the recursive calls of **Get** on descendants of *g*, we do a constant amount of computation plus exactly one call to **Pop-Max** on $Q_g$, which is of logarithmic complexity.

# D Self-Contained Proof of Proposition 5.2

In this appendix, we now explain how to prove Proposition 5.2 with the circuit definitions of the present paper. We re-state that this self-contained proof is provided only for convenience, and that it features no conceptual contributions relative to existing results [2, 4].

**Changing the MSO query.** Given the tree alphabet $\Lambda$ used in the MSO query, and letting $X$ be the set of variables, we work with an extended alphabet $\Gamma := \Lambda \times 2^X$. We say that a $\Gamma$-tree $T$ is *well-formed* if, for each $x \in X$, there is precisely one tree node $n$ of $T$ such that, writing $(\lambda, s)$ the label of $n$, we have $x \in s$. For a $\Lambda$-tree $T$, given an assignment $\alpha$ on domain $T$ and variables $X$, we write $T_\alpha$ the well-formed $\Gamma$-tree where we label each node with the subset of variables assigned to that node, formally, $T_\alpha$ has the same skeleton as $T$ and the label of a node $n$ in $T_\alpha$ is $(\lambda, s)$ where $\lambda \in \Lambda$ is the label of $n$ in $T$ and $s$ is the subset of $X$ such that $\alpha(x) = n$ for all $x \in s$. For a MSO query $\Phi$ on $\Lambda$-trees with variables $X$, we denote by $\Phi'$ the Boolean query on $\Gamma$-trees which accepts precisely the $\Gamma$-trees $T'$ that are well-formed and where, letting $T$ be the $\Lambda$-tree obtained from $T'$ by projecting the labels on their first component, and letting $\alpha$ be the unique assignment such that $T' = T_\alpha$, then $\Phi(\alpha)$ holds on $T$. We claim:

* Claim D.1. The query $\Phi'$ can be expressed in MSO.*

**Proof.** We can clearly express in MSO that the tree is well-formed. Further, once the tree is asserted to be well-formed, we can quantify variables $x_1, \dots, x_n$ that are assigned to the unique tree nodes that respectively have $x_1, \dots, x_n$ in their label, and then evaluate the original query $\Phi$. $\blacksquare$

**Tree automata.** We use the notion of *bottom-up deterministic tree automata*:

* **Definition D.2.** Let $\Gamma$ be an alphabet. A $\Gamma$-bottom-up deterministic tree automaton (bDTA) consists of a finite set $Q$ of states, an initial function $\iota: \Gamma \to Q$, a transition function $\delta: Q \times Q \times \Gamma \to Q$, and a subset $F \subseteq Q$ of final states.
We omit the standard definitions of what it means for a bDTA to *accept* a tree [17]. We always assume that bDTAs are *trimmed*, i.e., for every state *q*, there is a tree accepted by *A* on which state *q* appears: this can be enforced in linear time on *A* by removing useless states, provided that the language of *A* is non-empty.

It is well-known [35] that the Boolean MSO query $\Phi'$ on $\Gamma$-trees can be translated to a $\Gamma$-bDTA $A$ which is *equivalent* in the sense that, for any $\Gamma$-tree $T$, the bDTA $A$ accepts $T$ iff $T$ satisfies $\Phi'$. We will use $A$ to construct the circuit and prove Proposition 5.2. We will also need the notion of a *well-formed* bDTA:

**Definition D.3.** Let $\Lambda$ be a tree alphabet, $X$ be a set of variables, and let $\Gamma := \Lambda \times 2^X$. A $\Gamma$-bDTA is well-formed if it accepts only well-formed trees.

We make an immediate observation on such bDTAs:

**Claim D.4.** *Given a well-formed $\Gamma$-bDTA $A$ with state set $Q$, writing $\Gamma = \Lambda \times 2^X$, there is a function $\text{dom}: Q \to 2^X$ with the following property: for any $\Gamma$-tree $T$, letting $q$ be the state obtained at the root when evaluating $A$ on $T$, then the subset of variables of $X$ that occurs in the labels of the nodes of $T$ is precisely $\text{dom}(q)$. Formally, we have $\text{dom}(q) = \bigcup_{n \in T} \pi_2(n)$, where $\pi_2: T \to 2^X$ maps every node of $T$ to the second component of its label. What is more, if $q \in Q$ is final then $\text{dom}(q) = X$.*

Accordingly, the *domain* $\text{dom}(q)$ of a state $q \in Q$ of such a bDTA is the subset of variables to which it is sent by this function.

**Proof of Claim D.4.** As $A$ is trimmed, we know that for every state $q$ there is a $\Gamma$-tree $T$ accepted by $A$ such that $q$ appears in the run of $A$ on $T$. As $A$ is well-formed, we know that $T$ is well-formed. Let $T'$ be a subtree rooted at some node which is mapped to $q$ in this run. Define $\text{dom}(q)$ to be the set $Y$ of variables occurring in the labels of $T'$.

To show that this definition is consistent, let us assume by contradiction that there is another $\Gamma$-tree $T_2$ accepted by $A$ such that $q$ appears in the run of $A$ on $T_2$, and let $T'_2$ be a subtree rooted at some node which is mapped to $q$ in this run. Assume by contradiction that the set of variables occurring in the labels of $T'_2$ is different, say $Y'$ with $Y' \neq Y$. Let $T_3$ be the tree obtained from $T$ by replacing the subtree $T'$ with $T'_2$.

We claim that $T_3$ is not well-formed. Indeed, as $T$ is well-formed and the variables occurring in the labels of $T'$ are $Y$, then the variables occurring in the labels of $T \setminus T'$ are $X \setminus Y$, and as $Y \neq Y'$, we know that either $X \setminus Y$ and $Y'$ are not disjoint (i.e., a variable occurs twice) or $(X \setminus Y) \cup Y' \neq X$ (i.e., a variable in missing). In both cases, $T_3$ is not well-formed. But $A$ accepts $T_3$, because it maps the root of $T'_2$ in $T_3$ to $q$ by hypothesis, and then the run can be completed like in $T \setminus T'$ and $T_3$ is accepted.

Thus, $A$ accepts the tree $T_3$ which is not well-formed, contradicting the assumption that $A$ is well-formed.

The last sentence of the claim is simply by observing that if $q$ is final then any tree $T$ where the root is mapped by $A$ to $q$ is accepted by $A$, so as $A$ is well-formed it must be the case that $T$ is well-formed so that $\text{dom}(q)$, the set of all variables occurring in $T$, must be $X$.

**Provenance circuits for tree automata.** We finally claim that we can construct provenance circuits:

**Proposition D.5.** Let $\Lambda$ be an alphabet, let $X$ be a non-empty set of variables, let $\Gamma := \Lambda \times 2^X$. Given a well-formed $\Gamma$-bDTA $A$ whose language is non-empty, given a $\Lambda$-tree $T$, we
can build in time $O(|A| \times |T|)$ a smooth multivalued $d$-DNNF circuit $C$ on domain $T$ and variables $X$ such that $\text{rel}(C)$ is precisely the set of assignments $\alpha$ such that $A$ accepts $T_\alpha$.

**Proof.** In this proof, we will construct a variant of smooth multivalued $d$-DNNF circuits where we allow $\cup$-gates and $\times$-gates with no inputs. Intuitively, for a $\cup$-gate $g$ with no input we have $\text{rel}(g) = \emptyset$, and for a $\times$-gate $g$ with no input we have $\text{rel}(g) = \{\emptyset\}$. One can show that, given such a circuit, we can rewrite it in linear time to a smooth multivalued $d$-DNNF without such gates, simply by eliminating all such gates bottom-up (see [2] for similar results). Note that, as the set of variables is non-empty and as the language of $A$ is non-empty, the resulting smooth multivalued $d$-DNNF $D$ is such that $\text{rel}(D) \neq \emptyset$ and $\emptyset \notin \text{rel}(D)$.

Let $Q$ be the state set of $A$, let $\iota$ be its initial function, let $\delta$ be its transition function, let $F$ be its set of final states. We use Claim D.4 to define the function $\text{dom}$ on $Q$. We create one $\cup$-gate $g_{n,q}$ for every state $q \in Q$ and node $n \in T$, intuitively denoting that the automaton is at state $q$ at node $n$.

For every leaf node $n$ of $T$, letting $\lambda$ be the label of $n$, for every subset $Y \subseteq X$, we create a $\times$-gate having as input the variables $\langle y : n \rangle$ for each $y \in Y$ (possibly none), with a wire to the gate $g_{n,q}$ where $q := \iota((\lambda, Y))$.

For every internal node $n$ of $T$ with children $n_1$ and $n_2$, letting $\lambda$ be the label of $n$, for any pair of states $q_1$ and $q_2$ such that $Y_1 := \text{dom}(q_1)$ and $Y_2 := \text{dom}(q_2)$ are disjoint, for any $Y \subseteq X \setminus (Y_1 \cup Y_2)$, we create a $\times$-gate having as inputs $g_{n_1,q_1}$, $g_{n_2,q_2}$, and the variables $\langle y : n \rangle$ for each $y \in Y$ (possibly none), with a wire to the gate $g_{n,q}$ where $q := \delta(q_1, q_2, (\lambda, Y))$.

Last, for the root node $n_0$ of $T$, we create a $\lor$-gate having as input all gates $g_{n_0,q}$ for $q \in F$, and set it to be the output gate.

This construction runs in time $O(|A| \times |T|)$. We first check that the circuit is decomposable. For this, we show by an immediate induction that, for any $n \in T$ and $q \in Q$, then $\text{var}(g_{n,q}) = \text{dom}(q)$. In particular, $\text{dom}(C) = X$. Decomposability is then clear. For smoothness, it is again easy to check that for every $n \in T$ and $q \in Q$, for every gate $g_{q,n}$, its inputs (if any) are $\times$-gates whose domain is $\text{dom}(q)$. Further, for the output gate, its inputs are gates of the form $g_{n_0,q}$ where $q$ is final so $\text{dom}(q) = X$.

We next show an invariant: for every node $n$ of $T$, for every state $q$ of $Q$, then $\text{rel}(g_{n,q})$ is precisely the set of partial assignments $\alpha$ of $X$ to the subtree $T_n$ of $T$ rooted at $n$ such that $A$ maps the root of $(T_n)_\alpha$ to $q$, where $(T_n)_\alpha$ denotes as expected the $\Gamma$-tree obtained from the $\Lambda$-tree $T_n$ by setting the second component in $2^X$ of every node $n'$ according to the subset of the variables of $X$ that are mapped to $n'$ by $\alpha$. (Note that $(T_n)_\alpha$ is not necessarily well-formed because $\alpha$ is a partial assignment.)

The invariant is shown by induction. If $n$ is a leaf, letting $\lambda$ its label, then indeed for every $Y \subseteq 2^X$ the partial assignment mapping the variables of $Y$ to $n$ is captured by the gate $g_{n,\iota(\lambda,Y)}$. If $n$ is an internal node with children $n_1$ and $n_2$ and label $\lambda$, we show both directions. First, consider a partial assignment $\alpha$ in $\text{rel}(g_{n,q})$ for some $q$. By construction of the circuit, it must witness that there are partial assignments $\alpha_1$ of $Y_1$ to $T_{n_1}$ in $\text{rel}(g_{n_1,q_1})$ and $\alpha_2$ of $Y_2$ to $T_{n_2}$ in $\text{rel}(g_{n_2,q_2})$ and $\alpha'$ of $Y$ to $n$, such that $Y_1$ and $Y_2$ and $Y$ are pairwise disjoint and $\alpha = \alpha_1 \times \alpha_2 \times \alpha$, and such that $\delta(q_1, q_2, (\lambda, Y)) = q$. By induction hypothesis, this means that the automaton maps the root of $(T_{n_1})_{\alpha_1}$ to state $q_1$ and the root of $(T_{n_2})_{\alpha_2}$ to state $q_2$, so that it maps the root of $T$ to state $q$. Conversely, consider a partial assignment $\alpha$ such that the root of $(T_n)_\alpha$ is mapped by $A$ to $q$. Consider the restrictions $\alpha_1, \alpha_2$, and $\alpha'$ of $\alpha$ to $T_{n_1}, T_{n_2}$, and $n$ respectively. It must be the case that the root of $(T_{n_1})_{\alpha_1}$ is mapped by $A$ to some state $q_1$, the root of $(T_{n_2})_{\alpha_2}$ is mapped by $A$ to some state $q_2$, and we have $\delta(q_1, q_2, (\lambda, Y)) = q$, where $Y$ is the set of variables mapped by $\alpha'$. Now, by induction hypothesis, we have $\alpha_1 \in \text{rel}(g_{n_1,q_1})$ and $\alpha_2 \in \text{rel}(g_{n_1,q_2})$. Thus the construction of the circuit
witnesses that $rel(g_{n,q})$ contains $\alpha$.

The inductive claim implies that the circuit is deterministic. Indeed, the root gate is deterministic because, if the same $\alpha$ is captured by two different inputs $g_{n_0,q}$ and $g_{n_0,q'}$ of the root gate with $q \neq q'$, then the root of the tree $T_\alpha$ would be mapped both to $q$ and $q'$ by $A$, contradicting the determinism of $A$. Further, for any $n \in T$ and $q \in Q$, we show that $g_{q,n}$ is deterministic. This is immediate if $n$ is a leaf because the gates $g_{q,n}$ then have at most one input, so let us assume that $n$ is an internal node with children $n_1$ and $n_2$. Let us assume by contradiction that the same partial assignment $\alpha$ is in $rel(g)$ and $rel(g')$ for two different inputs of $g_{q,n}$. Let $Y$ be the set of variables mapped to $n$ by $\alpha$, let $Y_1$ and $Y_2$ be the set of variables mapped to nodes of $T_{n_1}$ and $T_{n_2}$ respectively. The sets $Y$ and $Y_1$ and $Y_2$ must be pairwise disjoint. By the consideration on the domains of gates, the two inputs of $g_{q,n}$ must be two $\times$-gates taking the conjunction of the variables $\langle y : n \rangle$ for $y \in Y$. If they are different gates, it must be the case that the two other gates that they conjoin are of the form $g_{n_1,q_1}$ and $g_{n_2,q_2}$ for the first gate, and $g_{n_1,q'_1}$ and $g_{n_2,q'_2}$ for the second gate, with $(q_1, q_2) \neq (q'_1, q'_2)$. But it must be the case by the invariant that the root of $(T_{n_1})_{\alpha_1}$ is mapped by $A$ to both $q_1$ and $q'_1$, and that the root of $(T_{n_2})_{\alpha_2}$ is mapped by $A$ to both $q_2$ and $q'_2$. So $q_1 = q'_1$ and $q_2 = q'_2$, a contradiction.

Last, the inductive claim applied to the root implies that $rel(C)$ is the set of assignments $\alpha$ such that $A$ accepts $T_\alpha$, which is what we wanted to show.

Thus we have established that the circuit is a smooth multivalued d-DNNF with the correct semantics, which concludes the proof. ◀

Finally, the proof of Proposition 5.2 follows by using Claim D.1 to construct $\Phi'$, by constructing the equivalent bDTA $A$, and finally by using Proposition D.5 to build the circuit.