Manuscript Offprint
arXiv:2611.00128SPARQLcirc: Probabilistic Query Evaluation with Provenance Circuits
Jingcheng Wu University of Stuttgart Stuttgart, Germany jingcheng.wu@ki.uni-stuttgart.de
Daniel Hernández University of Stuttgart Stuttgart, Germany daniel.hernandez@ki.uni-stuttgart.de
Ratan Bahadur Thapa University of Stuttgart Stuttgart, Germany ratan.thapa@ki.uni-stuttgart.de
Steffen Staab* University of Stuttgart Stuttgart, Germany steffen.staab@ki.uni-stuttgart.de
Abstract
Probabilistic query evaluation (PQE) computes the probability of every answer of a query over a tuple-independent probabilistic knowledge graph. We study exact PQE for SPARQL over graphs accessed through SPARQL 1.1 endpoints. Shared triples among the derivations of an answer make exact PQE #P-hard in general. Knowledge compilation of the Boolean provenance of every answer yields exact probabilities, and the provenance formulas of different answers can share subformulas. We propose SPARQLcirc, which rewrites a SPARQL query into CONSTRUCT queries that name every gate by its content, so that the results of independent queries form one Boolean provenance circuit for all answers. The rewriting covers joins, unions, projection, filters, OPTIONAL, difference and transitive closures. SPARQLcirc compiles the circuit and computes the exact probability of every answer by weighted model counting. For the evaluation, we draw random probabilities for the triples of WatDiv and gMark and the statements of Wikidata and evaluate the CONSTRUCT queries on GraphDB, Fuseki and Oxigraph. The ratio of the end-to-end time of PQE with SPARQLcirc to that of PQE by compiling the provenance expressions of the SPARQL provenance rewriting NPCS decreases with the number of derivations.
CCS Concepts
- Information systems → Resource Description Framework (RDF); Data provenance; * Theory of computation → Incomplete, inconsistent, and uncertain databases.
1 Introduction
Information extraction and link prediction produce triples with confidence scores [10, 13, 21, 22], and statistical signal detection derives drug interactions with association scores from adverse-event reports [55]. A probabilistic knowledge graph treats every score as the probability that the triple holds [12]. In RDF, the probability annotates the triple through standard reification, named graphs, RDF-star or Wikidata statement nodes [9, 11, 35, 38, 43]. In Figure 1, every :interactsWith triple carries an identifier
and a probability. Knowledge graphs with annotated triples, such as Wikidata, are queried through SPARQL endpoints [43, 62]. A SPARQL query can return the probabilities of the matched triples, but the SPARQL semantics assigns no probability to an answer [34]. A public SPARQL endpoint accepts only SPARQL requests, and the endpoint administrator alone can extend the query engine. For a probabilistic knowledge graph accessed only through a public endpoint on the Web, the probability of every answer must therefore be computed from the results of SPARQL queries.

Figure 1: Probabilistic drug-interaction graph. Every edge is an :interactsWith triple with its identifier and probability.
In the tuple-independent model of probabilistic databases, every subgraph of a probabilistic knowledge graph is a possible world, and every triple occurs independently with its probability [12, 54]. The marginal probability of an answer is the total probability of the worlds in which the answer occurs. Probabilistic query evaluation (PQE) computes the marginal probability of every answer. Top-k query evaluation ranks the answers by marginal probability [48]. The Boolean provenance of an answer is the Boolean function over the triples that is true exactly in the worlds in which the answer occurs, so the marginal probability is the probability that the Boolean provenance is true [54]. The identifiers of Figure 1 also denote the Boolean variables of their triples. The query
SELECT ?z WHERE { :Aspirin :interactsWith ?x . ?x :interactsWith ?y . ?y :interactsWith ?z } retrieves the drugs that Aspirin reaches in three :interactsWith steps. The Boolean provenance is for Clopidogrel and for Omeprazole. A derivation of an answer is the conjunction of the triples of one match. Omeprazole has two derivations and Clopidogrel one.
Derivations that share triples are correlated events. The two derivations of Omeprazole have probabilities 0.680 and 0.471 and
*Also with University of Southampton.
both contain . Treating the derivations as independent events gives , whereas factoring out gives the correct marginal probability . Even for some fixed basic graph patterns, exact PQE is #P-hard in the size of the graph [15, 61]. Knowledge compilation translates the Boolean provenance into a compiled form, from which weighted model counting computes the marginal probability in time linear in the size of the form [17, 54]. A provenance circuit is a directed acyclic graph that represents Boolean provenance with triples as leaves and with products , sums and differences as gates [19, 52]. Derivations of different answers can also share triples and subformulas. A single circuit represents a shared subformula once and gives every answer a root gate [19, 52].
SPARQL property paths with the operator + or * compute transitive closures. On a graph with a cycle, a closure can connect two nodes by infinitely many walks. In Figure 1, the walks of :Aspirin :interactsWith+ ?y from Aspirin to Warfarin can repeat the cycle. Provenance that counts the walks becomes a power series with infinitely many terms [33], and the series for Warfarin is . In contrast, by the absorption law , the Boolean provenance of every answer equals a disjunction over finitely many walks [19]. The law removes the conjunction of every walk that contains all triples of a shorter walk between the same nodes, and for Warfarin the disjunction equals . For transitive closure, positive provenance formulas require super-polynomial size in the worst case, whereas polynomial-size circuits exist for every graph [19, 23].
SPARQLprov and NPCS rewrite a query into SPARQL queries, so that an endpoint without extensions returns the provenance of every answer [6, 36]. SPARQLprov returns tables that encode expression structure and node identifiers. NPCS constructs and aggregates expression strings inside the endpoint. Both rewritings return one provenance expression per answer, and a subexpression that several answers share is therefore repeated in each expression. The probability of every answer is then computed by compiling its expression outside the endpoint. A SPARQL property path returns only the pairs of nodes that its walks connect, and SPARQLprov and NPCS cover only patterns without transitive closures. In relational databases, ProvSQL covers recursive reachability queries, builds one circuit for all answers and names every inner gate by hashing its operator and operands [50–52]. ProvSQL runs inside PostgreSQL as an engine extension, but engine extensions on a public endpoint can be installed only by its administrator.
SPARQL CONSTRUCT queries can return the gates of a circuit as triples, but a blank node in the template denotes a fresh node for every solution. Two gates that different solutions or queries emit therefore coincide only if both receive the same IRI. The name of a gate is a canonical syntactic description of the gate. A SPARQL 1.1 query can hash the name of a gate into its IRI with built-in hash functions, and equal names yield equal IRIs in every query and on every engine. The results of independent CONSTRUCT queries then form one circuit, because the triples that two queries emit for one gate share the IRI of the gate. Repeated edges occur once in the merged RDF graph, and by Boolean idempotence and the merge preserves the Boolean function of every gate.
We propose SPARQL, a rewriting method for exact PQE. SPARQL translates a SPARQL query into a plan of SPARQL 1.1
CONSTRUCT queries whose results form one Boolean provenance circuit for all answers. For a transitive closure from a start node that a constant or a preceding pattern fixes, each round of SPARQL 1.1 requests emits the gates of one walk length. SPARQL compiles the root of every answer with an existing knowledge compiler and computes the probability of the answer by weighted model counting. With random probabilities for the triples of WatDiv [1], gMark [7] and the 1.78 billion statements of Wikidata [62], we compare SPARQL on GraphDB [44], Fuseki [56] and Oxigraph [45] with plain query evaluation and NPCS. We make three contributions:
-
Gate names that SPARQL 1.1 queries compute from the content of the gates, so that independent CONSTRUCT queries yield one circuit on any engine (Section 4.1).
-
A rewriting of queries with OPTIONAL, difference and transitive closures into plans of CONSTRUCT queries, a factored plan in which derivations share the gates of common parts, and a proof that every answer has a root and that the root denotes its Boolean provenance (Sections 4.2–4.5).
-
An evaluation on WatDiv, gMark and Wikidata in which the ratio of the end-to-end time of PQE with one circuit for all answers to that with per-answer provenance expressions decreases with the number of derivations (Section 5).
Section 6 relates SPARQL to probabilistic relational and RDF databases, SPARQL provenance and provenance under recursion.
2 Preliminaries
RDF and SPARQL. Following Pérez et al. [46], we define a fragment of SPARQL as follows. The set contains the IRIs, the blank nodes, the literals and the variables, and . An RDF graph is a finite subset of , a triple pattern belongs to , and a solution mapping is a partial function with domain . A blank node in a query acts as a variable [34]. Mappings and are compatible when both agree on . A path-free pattern is generated by
A basic graph pattern (BGP) is represented by [34, 46], so the empty BGP returns only the empty mapping. The condition combines Boolean connectives, comparisons and arithmetic operators with the SPARQL 1.1 built-ins of Appendix B. In , the condition mentions only variables that every mapping of binds. A query is a pattern with . Evaluation of on an RDF graph returns a multiset [4, 34], and denotes the mappings with positive multiplicity. The difference [40] retains a mapping of exactly when no mapping of is compatible with it, and without a filter abbreviates [34].
A closure-free property-path expression is generated by , with (inverse, sequence and alternative). is the binary relation that SPARQL assigns to on [34], and is its transitive closure. For , a closure atom is a pattern with closure-free , source and target variable . For a source and a target , the mapping is when is a constant and when is a variable. For , the atom returns once for every pair with when is a constant and when is ?y. For , the atom returns once for every such pair of , where the set of zero-length pairs contains when is a constant and for every subject or object of a triple of when is a variable [34]. A closure atom with a variable source is source-bound when is an operand of a join or the right operand of a difference and, on every graph, every mapping of the join of the operands before binds the source. The fragment extends this grammar with closure atoms whose source is a constant or that are source-bound.
A CONSTRUCT query pairs a pattern with a template , a finite set of triple patterns. On an RDF graph , we call the mappings in the rows of the query, and the query returns the RDF graph that contains the instance of every row . The instance consists of the RDF triples among the triples that result from when every variable of is replaced by its value [34].
Reification. Four encodings give every triple of an RDF graph an identifier : an RDF-star annotation occurrenceOf [35], a standard reification [9], a named graph that holds [11], or a Wikidata statement node of best rank [43]. SPARQL-star queries read the RDF-star annotation through quoted triple patterns [35], and SPARQL 1.1 queries read the other three encodings. The reified graph replaces every blank node of by a fresh Skolem IRI [14], contains the resulting triples and represents each of them in one of the encodings. Following SPARQLprov and NPCS [6, 36], the reification reif of a triple pattern matches the encoding of every triple that matches and binds ?t to the identifier of the triple.
Possible worlds and PQE. A probabilistic knowledge graph is an RDF graph in which every triple carries a Boolean variable and a probability [12, 54]. Each triple has one distinct identifier in . Under tuple independence, a possible world has probability . A mapping is an answer of a query when for some world . The marginal probability of the answer is .
Boolean provenance. Geerts et al. define the provenance of SPARQL over spm-semirings, which extend commutative semirings with a difference [32]. The homomorphism that maps to , to and to yields the Boolean provenance of a mapping for a pattern . Over , the Boolean provenance has the following cases. For a triple pattern , when contains exactly the variables of and , and otherwise. The other cases are
where the join ranges over decompositions into pairwise compatible mappings, and is when satisfies and otherwise. Let denote the valuation that assigns to exactly when . For a closure atom, is the Boolean function over with exactly when returns on , and for every other . For every , the commutation of the provenance with spm-semiring homomorphisms [32] and the definition of yield
Provenance circuits. Following Deutch et al. [19] and ProvSQL [52], a provenance circuit over is a finite set of gates whose child relation is acyclic. A gate is a leaf , a sum gate or a product gate with a finite set of children, or a difference gate with a finite set of minuend children and one subtrahend child . ProvSQL restricts difference gates to one minuend. A partial function root maps solution mappings to gates, and root is the root of . By recursion over the child relation, the Boolean semantics of a gate is for a leaf , for an -gate, for an -gate, and
for an -gate, so and denote and .
Knowledge compilation and weighted model counting. The weighted model count WMC() of a Boolean function sums over the satisfying assignments of the product of the weights of their literals [49]. With the weights on and on , Equation (1) yields . Knowledge compilation translates a Boolean function into a deterministic decomposable negation normal form (d-DNNF) or an ordered binary decision diagram (OBDD), and every OBDD is a d-DNNF [17]. A d-DNNF is a circuit in which negation occurs only on variables, the children of every conjunction have pairwise disjoint sets of variables and the children of every disjunction are mutually exclusive [17]. With the weights above, the weighted model counts of the children therefore multiply at a conjunction and add at a disjunction, and one bottom-up pass computes the weighted model count of a d-DNNF in linear time. The d-DNNF
represents the Boolean provenance of Omeprazole, and the pass yields the marginal probability 0.774.
3 Problem Definition
Definition 3.1 (Problem). Given a query Q of S and the probability for the identifier of every , the problem is to compute for every answer of Q from the results of SPARQL 1.1 requests, or SPARQL-star requests for the RDF-star annotation, to an endpoint that stores .
By Equation (1), equals WMC( ), so it suffices that the results of such requests form a provenance circuit in which the root of every answer denotes .
4 Provenance Circuits from SPARQL 1.1 Queries
In this section, we rewrite a query into a plan of SPARQL 1.1 CONSTRUCT queries whose results form one Boolean provenance circuit for all answers. Let , and be the triple patterns of the running query in their order of occurrence. The rewriting maps the algebra expression to a plan with one query for the join and one for the projection. The two queries share the WHERE clause and appear as one query below.
CONSTRUCT { ?g a c:Times ; c:in ?t1, ?t2, ?t3 . ?r a c:Plus ; c:in ?g ; c:answerRoot "vars:z" ; c:bind:z ?z } WHERE { << :Aspirin :interactsWith ?x >> :occurrenceOf ?t1 . << ?x :interactsWith ?y >> :occurrenceOf ?t2 . << ?y :interactsWith ?z >> :occurrenceOf ?t3 . BIND(KEY_TIMES(?t1, ?t2, ?t3) AS ?g) BIND(KEY_PLUS(A, "Proj{z}(...)", ?z) AS ?r) }
(3)
The shared WHERE clause matches the reifications of the three triple patterns and binds the identifiers ?t1, ?t2 and ?t3 of the matched triples. The two BIND expressions name the product gate ?g and the root ?r by KEY_TIMES and KEY_PLUS of Definition 4.1. For every row, the template emits one triple per gate for its kind (c:Times or c:Plus) and one c:in triple per edge to a child. The last template line marks ?r as a root and records the value of ?z.
Over , the plan emits the product gates and below the root of Omeprazole and the product gate below the root of Clopidogrel. The merged RDF graph of the emitted triples is the circuit of Figure 2, and two product gates share each of the leaves and . The plan depends on the query alone, and the circuit on the query and the data. SPARQL reads the circuit, compiles every root and computes its weighted model count: 0.774 for Omeprazole and 0.359 for Clopidogrel.

Figure 2: The circuit that the plan of the running query emits. The shared leaves and (orange) occur once.
Section 4.1 names the gates. Sections 4.2 to 4.4 give the plans for the operators, for basic graph patterns and for transitive closures, and Section 4.5 defines sound and complete plans, gives the Boolean functions of the named gates, states that the plans are sound and complete and compiles the circuit to compute the probabilities. Appendix A proves the lemmas and theorems of this section.
4.1 Gate names and merging
SPARQL merges the results of all queries of the plan into one RDF graph. All triples with one gate IRI describe one gate. An RDF graph contains every triple at most once, so an edge emitted by several rows or queries occurs once. One copy of an edge preserves the value of every gate exactly when sum and product are idempotent. Boolean functions are idempotent, whereas the provenance polynomials of satisfy [33].
The IRI of every gate other than a leaf is the value of a BIND expression, which reads one row. The row of a join binds the gates of all operands, so a product gate is named after the list of its children, in which a gate repeats when two operands match the same triple. The edges into a sum or difference gate come from the rows that carry one mapping. Each of these rows contributes
one derivation, and the rows can belong to several queries. All rows of one mapping bind the same values, so a sum or difference gate is named after its subpattern and the bindings of its mapping. Definition 4.1 adapts the gate names of ProvSQL [50] and the node identifiers of SPARQLprov [36] to SPARQL 1.1 queries, and hash-consing names the nodes of terms in the same way [25].
Definition 4.1 (Gate names). Let encode an RDF term by its term kind, lexical form, datatype and lower-cased language tag, and let (unbound) be a distinct token for an unbound variable. Let be a serialization of a subpattern such that two subpatterns have equal serializations exactly when they are equal up to the order of the operands of joins and unions and up to repeated operands of a union. A leaf is named by the identifier of its triple. The key expressions for a letter , a tag , variables and variables in the lexicographic order of their names are
where hashes its arguments, sort orders them by the lexicographic order of their hashes, computes of the value of , and marks the sum gate of a union, a projection, the outer projection and the subtrahend of a difference, respectively. The name of a gate on a row is the tuple of the arguments of , and its IRI is the value of the key expression.
Since is commutative but depends on the order of its arguments, KEY_TIMES sorts the children before hashing, so the name of a product gate is invariant under permutations of the operands of a join. In the plan (3), the row that binds ?t1, ?t2 and ?t3 to , and names its product gate , and a query that lists the triple patterns in the order , , names the same gate. The root of Omeprazole is named . The query names the root of Omeprazole with another tag, and that root denotes . A name without the tag merges the two roots and gives Omeprazole the function in the running query instead of . Conversely, gates with the same Boolean function can have distinct names, because a BIND expression computes a name from the values of one row, whereas the function of a gate depends on all gates below it. For example, and have the same Boolean provenance, but their sum gates have distinct tags.
4.2 Path-free patterns
The rewriting translates a SELECT query into a plan of CONSTRUCT queries, as in (3). For every subpattern , Definition 4.2 defines a rewritten pattern and the queries of . The rows of bind the mappings of and their gates. The queries of output these gates and their edges to the gates of the operands.
Definition 4.2 (Rewriting). Let be a subpattern of a query that is not a closure atom, and let be a variable, called the gate variable of . The rewritten pattern , the CONSTRUCT queries of and the plan are defined by recursion on .
(1) If is a triple pattern , then and .
(2) If , then, for fresh variables ,
BIND(KEY_TIMES() AS ),
WHERE ,
.
(3) If , then, for fresh variables , the tuple of the variables in scope at in lexicographic order and ,
BIND(KEY_PLUS(U, , ) AS ),
WHERE
BIND(KEY_PLUS(U, , ) AS ,
.
(4) If , then, for a fresh variable and the tuple of the variables in in lexicographic order,
BIND(KEY_PLUS(P, , ) AS ),
WHERE
BIND(KEY_PLUS(P, , ) AS ,
.
(5) If , then ,
FILTER() and .
(6) If , then, for fresh variables and and the tuple of the variables in scope at in lexicographic order,
BIND(KEY_MINUS(, ) AS ),
WHERE
BIND(KEY_PLUS(S, , ) AS
,
WHERE
BIND(KEY_PLUS(S, , ) AS ,
.
For a query , item (4) applies with and the letter A in place of the letter P. For every row of with restriction to , the gate is the root of , and the template of additionally contains the c:answerRoot and c:bind: triples of (3).
We highlight the difference DIFF of item (6). An OPTIONAL without a filter abbreviates a union of a join and a difference (Section 2), and the identities of Appendix A reduce MINUS to differences. For a mapping of , the difference negates the disjunction over all mappings of that are compatible with . The negation does not distribute over the disjunction and must therefore cover all rows of the join of and that extend . SPARQLprov [36] combines the rows of in a post-processing step that decodes the results, and NPCs [5] groups them by inside the endpoint. SPARQL_circ instead splits the difference into two CONSTRUCT queries. The subtrahend query names the sum gate after alone and binds in every row before the join with
, so the edges of all rows of merge at . The minuend query evaluates only and makes the subtrahend of the difference gate .
Example 4.3 (Difference). The query
SELECT ?x WHERE { :Aspirin :interactsWith ?x
MINUS { ?x :interactsWith ?y } }
returns the drugs with which Aspirin interacts and which interact with no drug. Since both operands of MINUS bind ?x, the MINUS pattern equals the difference for , in which Warfarin has the Boolean provenance . The join of and has the rows and for Warfarin. A single query that emits one -gate per row of the join yields the circuit of Figure 3(a), which denotes and is therefore true in a world with the triples of and but without the triple of , although D removes Warfarin in this world. Under item (6), the subtrahend query collects both rows in , and the minuend query emits , so Figure 3(b) denotes .

→ child or minuend

(b)
subtrahend
Figure 3: Circuits for Warfarin in Example 4.3: (a) one -gate per row of the join, (b) the two queries of item (6).
The plan contains one query for every join and every projection, one for every branch of a union and two for every difference. Every query reads only at the endpoint, so the queries are independent and can run concurrently.
4.3 Factored basic graph patterns
We call the plan of Definition 4.2 the flat plan. It creates one product gate per derivation and therefore repeats every part that derivations share. A basic graph pattern with triple patterns has up to derivations. In Figure 2, the product gates and of Omeprazole both contain . For a query that projects a basic graph pattern, the factored plan instead builds the circuit by variable elimination [18] so that derivations share the gates of their common parts.
Definition 4.4 (Factored plan). Let , and let contain the variables of outside . A factor with scope maps some mappings of to gates, and its value at a mapping of a superset of is its value at the restriction to . The base factor has the set of the variables of as its scope and maps every mapping with to the leaf . Eliminating a variable replaces the set of the factors whose scopes contain by a factor whose scope contains their other variables. For a mapping of , let contain the values such that every factor of is defined at . If , then
The factored plan eliminates the variables of in some order. The root of an answer is the sum gate over the product of the remaining factors at . The gate is named by a tag of and and the values of , and the other gates as in Definitions 4.1 and 4.2.
For the running query, . Eliminating ?x first multiplies and , so has the scope and maps Metformin to and Lisinopril to . Eliminating ?y then multiplies and , so has the scope and maps Omeprazole to and Clopidogrel to . The induced width of an elimination order is the largest , so the order (?x, ?y) has induced width 1. The root of Omeprazole denotes .
LEMMA 4.5. Assume that distinct names have distinct IRIs. For every elimination order and every mapping , the roots of in the factored plan and in the flat plan denote the same Boolean function.
With an elimination order of induced width , the factored plan creates gates below the roots for fixed [18], whereas the flat plan creates up to product gates. For example, if Aspirin reaches Metformin through drugs and Metformin interacts with drugs, the flat plan creates product gates for these walks and the factored plan (Appendix F).
SPARQL_circ writes the rows of every factor into a private namespace with SPARQL 1.1 Update, and every elimination reads the factors that earlier queries wrote there. The eliminations therefore run in sequence and need a writable endpoint.
4.4 Transitive closures
For a closure-free , an -step is a pair . The joins of Definition 4.2 match a fixed number of triples, whereas a closure atom matches walks of -steps of unbounded length. As in the factored plan, SPARQL_circ applies variable elimination along the walks, eliminates one node per step and builds one level per walk length. The levels form a variant of the Bellman–Ford circuit of Fan et al. [23]. For nodes and , a gate built by recursion on satisfies exactly when (Appendix G). For a source , let contain and every node that -steps reach from , let contain the -steps between nodes of , and let . Level 1 maps every node to a gate for the walks of length 1 from to , and level sums out the last node of the walks of level from the product of and :
The closure gate of v is
where is the last level. The construction stops at the first empty level and runs at most n levels, because a longer walk repeats a node and is absorbed by the walk without the repeated segment.
For the query SELECT ?y WHERE { :Aspirin :interactsWith+ ?y } over the graph of Figure 1, contains the seven drugs, and Figure 4 shows the levels, where a circle is the sum gate of a drug at one level, labeled by the initial of the drug, and an arrow multiplies

Figure 4: Levels 1 to 7 of :Aspirin :interactsWith+ ?y.
by the gate of one step. At level 2, the sum gate of Metformin adds the product of the level-1 gate of Warfarin with and the product of the level-1 gate of Ibuprofen with , and denotes . The cycle through Warfarin, Lisinopril and Clopidogrel returns to Aspirin at level 4 and keeps every level nonempty, so the construction runs levels. The closure gate of Warfarin sums the levels 1 and 5, and absorbs the level-5 product for the walk around the cycle.
For a source-bound closure atom (Section 2), the input relation contains the mappings of the rows of the operands before . The set contains the sources that binds, or only when the source is a constant, and the plan runs the construction once for every source . For a target returned from , the mapping has the gate . For , is instead the zero-length gate of , which is for a constant source and the sum gate over the leaves of the triples of with subject or object for a variable source. The plan materializes the mappings and their gates as a relation, and reads the relation in place of the reification of a triple pattern. In the pattern \{\ :Aspirin :interactsWith\ ?x\ .\ ?x\ :interactsWith+ ?y\ }, the triple pattern binds the source ?x, so , and the row with ?x = Warfarin and ?y = Lisinopril has the product gate . A path pattern with a constant target reduces to a closure atom (Appendix A).
THEOREM 4.6. Assume that distinct names have distinct IRIs. Let be a closure atom in a query of , let , and let be a target that the construction returns from , with when is ?y. For every possible world , exactly when returns on , so denotes .
For every source, the levels form an acyclic circuit with gates. SPARQL_circ emits the gates and level 1 with CONSTRUCT queries and every further level with one more round. By default, every round writes its level into a private namespace with SPARQL 1.1 Update, where the next round reads it. If C forms the whole query, every round can instead send the previous level in a VALUES clause, so that the construction runs on a read-only endpoint. If C is a proper subpattern of the query, the materialization of its relation requires a writable endpoint.
4.5 Correctness and probabilities
Definition 4.7 (Soundness and completeness). A plan for a query Q is sound if every mapping with a root in its circuit over satisfies
and complete if this circuit has a root for every answer of Q.
Distinct names share an IRI only if their 128-bit hashes collide. For N gates, the probability of a collision is below in the random-oracle model (Appendix B).
In the circuit of a sound and complete plan, the weighted model count of the root of every answer is the marginal probability of the answer, and every mapping without a root has probability 0.
The plan evaluates its queries once over , and every world is a subset of . By induction on the subpatterns of , every answer of is therefore the restriction of a row of and receives a root. Conversely, other rows can restrict to mappings that returns in no world, because item (6) of Definition 4.2 keeps every row of the minuend in the rewritten pattern of a difference. For , every mapping of is compatible with itself, and the difference gate of denotes . A mapping that is not an answer can therefore receive a root, and soundness requires this root to denote .
Section 2 defines the function of a gate by recursion over the child relation, so this relation must be acyclic. The gates of a triple pattern are the leaves that its matches bind, and the gates of any other subpattern are the gates that its queries emit. Every child of a gate of is a gate of a proper subpattern of , except that the child of a difference gate is a gate of itself and has children only among the gates of . Within a closure atom, every edge leads to a lower level, and every factor of the factored plan is built from earlier factors. The child relation is therefore acyclic.
LEMMA 4.8. Assume that distinct names have distinct IRIs. Let be a query of , let be a union, a projection or a difference in , and let be a mapping whose domain consists of variables in scope at . In the circuit of over , the gate named after and denotes . If , the gate named after and denotes .
The root of a mapping is the gate named after and , so Lemma 4.8 yields Equation (7), and Lemma 4.5 carries Equation (7) over to the factored plan.
THEOREM 4.9. Assume that distinct names have distinct IRIs. For every query of , the plan is sound and complete, and so is the factored plan when is a basic graph pattern.
The theorem and the computation of extend to a triple with several identifiers (Appendix B).
Finally, compiles every root into an OBDD with CUDD [53] or into a d-DNNF with d4 [41] and computes the weighted model count of the result (Appendix H).
5 Evaluation
In this section, we measure the overhead of circuit construction (Section 5.1), the growth of the endpoint time and of the provenance size with the number of derivations per answer (Section 5.2) and the end-to-end time of PQE (Section 5.3).
Data. WatDiv [1] generates graphs of 10.9 and 109 million triples and queries from 20 templates of basic graph patterns, to which we add five OPTIONAL and five MINUS templates. We report the WatDiv times under RDF-star annotations. gMark [7] generates chain queries with triple patterns and branching factor , the number of choices at every step, over graphs of 500,000 triples. On the 1.78 billion statements of Wikidata [62], each identified by its statement node, we run the 136 WDBench queries [3] that NPCS publishes and 45 property-path queries from WDBench. All probabilities are drawn uniformly from (0, 1).
Engines. GraphDB 10.7.6 [44], Fuseki 5.4.0 with TDB2 [56] and Oxigraph 0.5.9 [45] run locally without extensions and receive SPARQL 1.1 requests and, for RDF-star, SPARQL-star requests.
Baselines. The plain query (Base) runs on , and the reified query (Reification) runs on without provenance. We compare with NPCS [5], the state-of-the-art SPARQL provenance rewriting. For PQE, we merge the identical subexpressions of all answers into one DAG and compile it with CUDD 3.0.0. We run our reimplementation of the rewriting rules of NPCS, since its published JAR deviates from these rules beyond basic graph patterns (Appendix C).
Protocol. The endpoint time of a method ends when the response or the circuit is stored, and the end-to-end time ends when all probabilities are written. We report the median of five runs after a warm-up run, medians over sets of queries and medians of paired ratios. The time budget is the same for every method and ranges from 600 to 5000 s (Appendix J).
5.1 Overhead of circuit construction
Following the evaluation of NPCS [5], we measure the overhead of provenance on WatDiv relative to the plain query and the reified query. With 10.9 million triples on GraphDB, the reified query takes 8.7 times as long as the plain query, NPCS 1.9 times as long as the reified query and the flat plan 2.6 times as long as NPCS (Figure 5), or 0.87 s against 0.46 s end to end. The factored plan takes 4.3 times as long as NPCS. On the templates with MINUS, the flat plan takes 3.4 to 7.8 times as long as NPCS across the engines and sizes and exceeds the budget more often. Appendix J.1 gives all 30 templates on all three engines, sizes and encodings.

Figure 5: Endpoint time on WatDiv (GraphDB, 10.9M triples).
One circuit saves time only when the answers share subexpressions. On WatDiv, merging the identical subexpressions of NPCS does not reduce the median size of its provenance, so the flat plan pays only the overhead of a CONSTRUCT query per operator and of storing the returned triples, whereas NPCS sends one SELECT query. Most of this overhead is fixed per query, because with ten times as many triples, the plain query takes 3.9 times as long and the flat plan 1.5 times as long. The factored plan also writes every factor and runs the eliminations in sequence, and for MINUS, the subtrahend query evaluates the join of both operands.
5.2 Scalability with the number of derivations
We control the number of derivations per answer through the chain length and the branching factor of gMark and compare the endpoint time and the output size of NPCS and the factored plan (Figure 6). At , the response of NPCS grows about fivefold per triple pattern, and the circuit grows linearly. At , the response reaches 15.9 GiB, 101 times the size of the circuit. NPCS is faster for at and for at , and the factored plan
Table 1: End-to-end comparison on Wikidata.
| Derivations | GraphDB | Oxigraph | ||||
|---|---|---|---|---|---|---|
| Flat | NPCS | Ratio | Flat | NPCS | Ratio | |
| Fewer than | 0 | 17 | 1.20 | 0 | 17 | 1.11 |
| to | 12 | 21 | 1.06 | 18 | 14 | 0.99 |
| At least | 28 | 4 | 0.57 | 23 | 2 | 0.58 |
| All | 40 | 42 | 1.01 | 41 | 33 | 0.98 |
is faster for larger values, by a factor of about three at . At and at , NPCS exceeds the budget of 5000 s, whereas the factored plan completes.

Figure 6: Endpoint time and output size on gMark (GraphDB).
NPCS lists every derivation of an answer, so its response grows with the number of derivations. The factored plan shares the common parts of the derivations, so its circuit grows only with the number of triple patterns. To share gates, the factored plan writes a factor from all matches of every triple pattern to the endpoint and takes 313 to 418 s in total at . This time hardly depends on , because with a fixed number of triples, a larger yields fewer nodes, and each elimination creates at most one sum gate per node.
5.3 End-to-end PQE on Wikidata
We measure the end-to-end time of PQE on the WDBench queries and the property-path queries of Wikidata. We report the flat plan, which completes more queries than the factored plan (Appendix J.3). On the WDBench queries, the flat plan is faster than NPCS on 40 of the 82 queries that both methods complete on GraphDB and on 41 of 74 on Oxigraph, depending on the total number of derivations of the answers of a query. For each range of this number, Table 1 gives the number of faster queries per method and the median ratio of the time of the flat plan to that of NPCS. NPCS is faster on every query with fewer than 100 derivations, and the flat plan is faster on most queries with at least 10,000 derivations, where it takes 0.57 times as long as NPCS at the median. NPCS does not support transitive closures, whereas SPARQL completes 35 of the 45 property-path queries on both engines, in a median of 3.4 s on GraphDB. The largest of these circuits has 1.2 million gates for 38,757 answers.
The advantage of the flat plan on queries with many derivations stems from the preprocessing that NPCS requires before compilation. NPCS parses its expressions, which grow with the number of derivations, and merges them into one DAG. On the queries with at least 10,000 derivations, this takes about five times as long as reading the circuit of the flat plan.
6 Related Work
Probabilistic relational databases. Exact PQE has PTIME versus #P-hard dichotomies for unions of conjunctive queries [15] and for two classes of queries with negation [27], where even a difference of tractable queries can be #P-hard [39]. On a standard database system, Gatterbauer and Suciu compute exact probabilities or upper bounds for conjunctive queries without self-joins with SQL queries that obtain products through sums of logarithms [29]. SPARQL 1.1 offers no logarithm, exponential or product aggregate [34], so SPARQL compiles the circuit that the endpoint returns. SPROUT approximates, in a PostgreSQL extension, the probability of the lineage that rewritten SQL queries compute [26], and ProvSQL builds provenance circuits as a PostgreSQL extension [52]. Unlike ProvSQL, SPARQL computes gate names in SPARQL 1.1 queries. Probabilistic RDF. Earlier systems attach distributions to object values [60] or to node labels [42] and test triples or matches against a probability threshold. Huang and Liu compile the lineage of each answer of a conjunctive SPARQL query into a binary decision diagram and approximate the probability of transitive properties on acyclic graphs [37]. HAPPI computes the probability of each answer of a conjunctive query from a symbolic provenance expression [30]. These systems use dedicated processors and treat every answer separately. SPARQL builds one circuit for all answers with SPARQL 1.1 queries and computes exact probabilities also for non-monotone queries and transitive closures on cyclic graphs.
Provenance for SPARQL. Semiring provenance [33] with monus [31] captures OPTIONAL and MINUS [16], and spm-semirings in addition preserve the equivalences of SPARQL queries [32]. Dividino et al. annotate every SPARQL answer with a Boolean formula that also covers OPTIONAL and difference through an extended SPARQL syntax [20], and TripleProv computes provenance in a dedicated engine [63]. Ganepola et al. compute the why-provenance of monotone Core-GQL queries by rewriting [28]. SPARQLprov and NPCS return one provenance expression per answer [5, 6, 36], whereas SPARQL returns one circuit for all answers, and the gate names agree across queries and engines.
Provenance under recursion. Deutch et al. build one layered Datalog provenance circuit for all derived tuples [19]. Bellman–Ford-style circuits [23] and algorithms [47] compute single-source provenance. ProvSQL 1.10 compiles recursive reachability queries into deterministic decomposable circuits [51]. There is a regular path query whose provenance has no d-DNNF or OBDD of size polynomial in the graph [2]. The circuit of a closure atom has polynomial size, but computing the probability of its root is #P-hard [61]. SPARQL builds a Bellman–Ford-style circuit level by level with SPARQL 1.1 requests and stops at the first empty level.
7 Conclusion
We presented SPARQL, a rewriting method for exact PQE on SPARQL 1.1 endpoints. The plans name every gate by its content, so independent CONSTRUCT queries build one provenance circuit for all answers. The plans are sound and complete for joins, unions, projection, filters, OPTIONAL, difference and transitive closures. The ratio of the end-to-end time of PQE with one circuit to that with per-answer provenance expressions decreases with the number of derivations. Future work includes federated provenance circuits.
Acknowledgments
The project was funded by the Deutsche Forschungsgemeinschaft (DFG, German Research Foundation) - SFB 1574 - Project number 471687386 ("Circular Factory"). The authors thank the International Max Planck Research School for Intelligent Systems (IMPRS-IS) for supporting Jingcheng Wu.
References
[1] Güneş Aluc, Olaf Hartig, M. Tamer Özsu, and Khuzaima Daudjee. 2014. Diversified Stress Testing of RDF Data Management Systems. In The Semantic Web – ISWC 2014 (LNCS, Vol. 8796). Springer, Cham, 197–212. doi:10.1007/978-3-319-11964-9_13
[2] Antoine Amarilli, Timothy van Bremen, Octave Gaspard, and Kuldeep S. Meel. 2025. Approximating Queries on Probabilistic Graphs. Logical Methods in Computer Science 21, 4 (2025), 30:1–30:31. doi:10.46298/LMCS-21(4:30)2025
[3] Renzo Angles, Carlos Buil Aranda, Aidan Hogan, Carlos Rojas, and Domagoj Vrgoč. 2022. WBDenb: A Wikidata Graph Query Benchmark. In The Semantic Web – ISWC 2022 (LNCS, Vol. 13489). Springer, Cham, 714–731. doi:10.1007/978-3-031-19433-7_41
[4] Renzo Angles and Claudio Gutierrez. 2016. The Multiset Semantics of SPARQL Patterns. In The Semantic Web – ISWC 2016 (LNCS, Vol. 9981). Springer, Cham, 20–36. doi:10.1007/978-3-319-46523-4_2
[5] Zubaria Asma, Daniel Hernández, Luis Galarraga, Giorgos Flouris, Irini Fundulaki, and Katja Hose. 2024. NPCs: Native Provenance Computation for SPARQL. In Proceedings of the ACM Web Conference 2024 (WWW). ACM, New York, NY, USA, 2085–2093. doi:10.1145/3589334.3645557
[6] Zubaria Asma, Daniel Hernández, Luis Galarraga, Giorgos Flouris, Irini Fundulaki, and Katja Hose. 2026. Native Provenance Computation for Federated and Non-Federated SPARQL Queries. Transactions on Graph Data and Knowledge (TGDK) 4, 1 (2026), 4:1–4:43. doi:10.4230/TGDK.4.1.4
[7] Guillaume Bagan, Angela Bonifati, Radu Ciucanu, George H. L. Fletcher, Aurélien Lemay, and Nicky Advokaat. 2017. gMark: Schema-Driven Generation of Graphs and Queries. IEEE Transactions on Knowledge and Data Engineering 29, 4 (2017), 856–869. doi:10.1109/TKDE.2016.2633993
[8] Mihir Bellare and Phillip Rogaway. 1993. Random Oracles Are Practical: A Paradigm for Designing Efficient Protocols. In Proceedings of the 1st ACM Conference on Computer and Communications Security (CCS). ACM, New York, NY, USA, 62–73. doi:10.1145/168588.168596
[9] Dan Brickley and R. V. Guha. 2014. RDF Schema 1.1. W3C Recommendation. https://www.w3.org/TR/rdf-schema/.
[10] Andrew Carlson, Justin Betteridge, Richard C. Wang, Estevam R. Hruschka, and Tom M. Mitchell. 2010. Coupled Semi-Supervised Learning for Information Extraction. In Proceedings of the 3rd ACM International Conference on Web Search and Data Mining (WSDM). ACM, New York, NY, USA, 101–110. doi:10.1145/1718487.1718501
[11] Jeremy J. Carroll, Christian Bizer, Pat Hayes, and Patrick Stickler. 2005. Named Graphs, Provenance and Trust. In Proceedings of the 14th International Conference on World Wide Web (WWW). ACM, New York, NY, USA, 613–622. doi:10.1145/1060745.1060835
[12] Ismail Ilkan Ceylan, Adnan Darwiche, and Guy Van den Broeck. 2021. Open-World Probabilistic Databases: Semantics, Algorithms, Complexity. Artificial Intelligence 295 (2021), 103474. doi:10.1016/j.artint.2021.103474
[13] Xuelu Chen, Muhao Chen, Weijia Shi, Yizhou Sun, and Carlo Zaniolo. 2019. Embedding Uncertain Knowledge Graphs. Proceedings of the AAAI Conference on Artificial Intelligence 33, 1 (2019), 3363–3370. doi:10.1609/aaai.v33i01.33013363
[14] Richard Cyganiak, David Wood, and Markus Lanthaler. 2014. RDF 1.1 Concepts and Abstract Syntax. W3C Recommendation. https://www.w3.org/TR/rdf11-concepts/.
[15] Nilesh N. Dalvi and Dan Suciu. 2012. The Dichotomy of Probabilistic Inference for Unions of Conjunctive Queries. Journal of the ACM 59, 6 (2012), 30:1–30:87. doi:10.1145/2395116.2395119
[16] Carlos Viegas Damásio, Anastasia Analyti, and Grigoris Antoniou. 2012. Provenance for SPARQL Queries. In The Semantic Web – ISWC 2012 (LNCS, Vol. 7649). Springer, Berlin, Heidelberg, 625–640. doi:10.1007/978-3-642-35176-1_39
[17] Adnan Darwiche and Pierre Marquis. 2002. A Knowledge Compilation Map. Journal of Artificial Intelligence Research 17 (2002), 229–264. doi:10.1613/jair.989
[18] Rina Dechter. 1999. Bucket Elimination: A Unifying Framework for Reasoning. Artificial Intelligence 113, 1–2 (1999), 41–85. doi:10.1016/S0004-3702(99)00059-4
[19] Daniel Deutch, Tova Milo, Sudeepa Roy, and Val Tannen. 2014. Circuits for Datalog Provenance. In Proceedings of the 17th International Conference on Database Theory (ICDT). OpenProceedings.org, Konstanz, Germany, 201–212. doi:10.5441/002/icdt.2014.22
[20] Renata Dividino, Sergej Sizov, Steffen Staab, and Bernhard Schueler. 2009. Querying for Provenance, Trust, Uncertainty and Other Meta Knowledge in RDF. Journal of Web Semantics 7, 3 (2009), 204–219. doi:10.1016/j.websem.2009.07.004
[21] Xin Dong, Evgeniy Gabrilovich, Geremy Heitz, Wilko Horn, Ni Lao, Kevin Murphy, Thomas Strohmann, Shaohua Sun, and Wei Zhang. 2014. Knowledge Vault: A Web-Scale Approach to Probabilistic Knowledge Fusion. In Proceedings of the 20th ACM SIGKDD International Conference on Knowledge Discovery and Data Mining (KDD). ACM, New York, NY, USA, 601–610. doi:10.1145/2623330.2623623
[22] Oren Etzioni, Michael Cafarella, Doug Downey, Stanley Kok, Ana-Maria Popescu, Tal Shaked, Stephen Soderland, Daniel S. Weld, and Alexander Yates. 2004. Web-Scale Information Extraction in KnowItAll (Preliminary Results). In Proceedings of the 13th International Conference on World Wide Web (WWW). ACM, New York, NY, USA, 100–110. doi:10.1145/988672.988687
[23] Austen Z. Fan, Paraschos Koutris, and Sudeepa Roy. 2025. Circuits and Formulas for Datalog over Semirings. Proceedings of the ACM on Management of Data 3, 2 (2025), 93:1–93:22. doi:10.1145/3725230
[24] Daan Fierens, Guy Van den Broeck, Joris Renkens, Dimitar Shterionov, Bernd Gutmann, Ingo Thon, Gerda Janssens, and Lue De Raedt. 2015. Inference and Learning in Probabilistic Logic Programs Using Weighted Boolean Formulas. Theory and Practice of Logic Programming 15, 3 (2015), 358–401. doi:10.1017/S1471068414000076
[25] Jean-Christophe Filliâtre and Sylvain Conchon. 2006. Type-Safe Modular Hash-Consing. In Proceedings of the 2006 Workshop on ML. ACM, New York, NY, USA, 12–19. doi:10.1145/1159876.1159880
[26] Robert Fink, Jiewen Huang, and Dan Olteanu. 2013. Anytime Approximation in Probabilistic Databases. The VLDB Journal 22, 6 (2013), 823–848. doi:10.1007/s00778-013-0310-5
[27] Robert Fink and Dan Olteanu. 2016. Dichotomies for Queries with Negation in Probabilistic Databases. ACM Transactions on Database Systems 41, 1 (2016), 4:1–4:47. doi:10.1145/2877203
[28] Koumadi Ganepola, Maxime Jakubowski, and Katja Hose. 2026. Computing Why-Provenance for Property Graph Queries. Proceedings of the VLDB Endowment 19, 11 (2026), 3552–3564. doi:10.14778/3836663.3836708
[29] Wolfgang Gatterbauer and Dan Suciu. 2017. Dissociation and Propagation for Approximate Lifed Inference with Standard Relational Database Management Systems. The VLDB 26, 1 (2017), 5–30. doi:10.1007/s00778-016-0434-5
[30] Garima Gaur, Abhishek Dang, Arnab Bhattacharya, and Srikanta Bedathur. 2021. Computing and Maintaining Provenance of Query Result Probabilities in Uncertain Knowledge Graphs. In Proceedings of the 30th ACM International Conference on Information and Knowledge Management (CIKM). ACM, New York, NY, USA, 545–554. doi:10.1145/3459637.3482330
[31] Floris Geerts and Antonella Poggi. 2010. On Database Query Languages for K-relations. Journal of Applied Logic 8, 2 (2010), 173–185. doi:10.1016/j.jal.2009.09.001
[32] Floris Geerts, Thomas Unger, Grigoris Karvounarakis, Irini Fundulaki, and Vassilis Christophides. 2016. Algebraic Structures for Capturing the Provenance of SPARQL Queries. Journal of the ACM 63, 1 (2016), 7:1–7:63. doi:10.1145/2810037
[33] Todd J. Green, Gregory Karvounarakis, and Val Tannen. 2007. Provenance Semirings. In Proceedings of the Twenty-Sixth ACM SIGMOD-SIGACT-SIGART Symposium on Principles of Database Systems (PODS). ACM, New York, NY, USA, 31–40. doi:10.1145/1265530.1265535
[34] Steve Harris and Andy Seaborne. 2013. SPARQL 1.1 Query Language. W3C Recommendation. https://www.w3.org/TR/sparql11-query/.
[35] Olaf Hartig, Pierre-Antoine Champin, Gregg Kellogg, and Andy Seaborne. 2021. RDF-star and SPARQL-star. W3C Final Community Group Report. https://www.w3.org/2021/12/rdf-star.html
[36] Daniel Hernández, Luis Galarraga, and Katja Hose. 2021. Computing How-Provenance for SPARQL Queries via Query Rewriting. Proceedings of the VLDB Endowment 14, 13 (2021), 3389–3401. doi:10.14778/3484224.3484235
[37] Hai Huang and Chengfei Liu. 2009. Query Evaluation on Probabilistic RDF Databases. In Web Information Systems Engineering – WISE 2009 (LNCS, Vol. 5802). Springer, Berlin, Heidelberg, 307–320. doi:10.1007/978-3-642-04409-0_32
[38] Gregg Kellogg, Olaf Hartig, Pierre-Antoine Champin, and Andy Seaborne. 2026. RDF 1.2 Concepts and Abstract Data Model. W3C Candidate Recommendation Snapshot. https://www.w3.org/TR/rdf12-concepts/.
[39] Sanjeev Khanna, Sudeepa Roy, and Val Tannen. 2011. Queries with Difference on Probabilistic Databases. Proceedings of the VLDB Endowment 4, 11 (2011), 1051–1062. doi:10.14778/3402707.3402741
[40] Roman Kontchakov and Egor V. Kostylev. 2016. On Expressibility of Non-Monotone Operators in SPARQL. In Proceedings of the 15th International Conference on Principles of Knowledge Representation and Reasoning (KR). AAAI Press, Palo Alto, CA, USA, 369–378.
[41] Jean-Marie Lagniez and Pierre Marquis. 2017. An Improved Decision-DNNF Compiler. In Proceedings of the Twenty-Sixth International Joint Conference on Artificial Intelligence (IJCAI). International Joint Conferences on Artificial Intelligence Organization, California, 667–673. doi:10.24963/ijcai.2017/93
[42] Xiang Lian and Lei Chen. 2011. Efficient Query Answering in Probabilistic RDF Graphs. In Proceedings of the 2011 ACM SIGMOD International Conference on Management of Data (SIGMOD). ACM, New York, NY, USA, 157–168. doi:10.1145/1989323.1989341
[43] Stanislav Malyshev, Markus Krötzsch, Larry González, Julius Gonsior, and Adrian Bielefeld. 2018. Finding the Most Out of Wikidata: Semantic Technology Usage in Wikipedia's Knowledge Graph. In The Semantic Web – ISWC 2018 (LNCS, Vol. 11137). Springer, Cham, 376–394. doi:10.1007/978-3-030-00668-6_23
[44] Ontotext. 2024. GraphDB. https://graphdb.ontotext.com/. Version 10.7.6.
[45] Thomas Pellissier Tanon. 2026. Oxigraph 0.5.9. doi:10.5281/zenodo.7408022
[46] Jorge Pérez, Marcelo Arenas, and Claudio Gutierrez. 2009. Semantics and Complexity of SPARQL. ACM Transactions on Database Systems 34, 3 (2009), 16:1–16:45. doi:10.1145/1567274.1567278
[47] Yann Ramusat, Silviu Maniu, and Pierre Senellart. 2021. Provenance-Based Algorithms for Rich Queries over Graph Databases. In Proceedings of the 24th International Conference on Extending Database Technology (EDBT). OpenProceedings, Konstanz, Germany, 73–84. doi:10.5441/002/edbt.2021.08
[48] Christopher Ré, Nilesh Dalvi, and Dan Suciu. 2007. Efficient Top-k Query Evaluation on Probabilistic Data. In Proceedings of the 23rd International Conference on Data Engineering (ICDE). IEEE, Piscataway, NJ, USA, 886–895. doi:10.1109/ICDE.2007.367934
[49] Tian Sang, Paul Beame, and Henry Kautz. 2005. Performing Bayesian Inference by Weighted Model Counting. In Proceedings of the Twentieth National Conference on Artificial Intelligence (AAAI). AAAI Press, Menlo Park, CA, USA, 475–481.
[50] Aryak Sen, Silviu Maniu, and Pierre Senellart. 2026. ProvSQL: A General System for Keeping Track of the Provenance and Probability of Data. In Proceedings of the 42nd International Conference on Data Engineering (ICDE). IEEE, Piscataway, NJ, USA, 1252–1265. doi:10.1109/ICDE65706.2026.00098
[51] Pierre Senellart et al. 2026. ProvSQL: Semiring Provenance and Probability Management for PostgreSQL, Versions 1.7.0 to 1.12.0. doi:10.5281/zenodo.19512786
[52] Pierre Senellart, Louis Jachiet, Silviu Maniu, and Yann Ramusat. 2018. ProvSQL: Provenance and Probability Management in PostgreSQL. Proceedings of the VLDB Endowment 11, 12 (2018), 2034–2037. doi:10.14778/3229863.3236253
[53] Fabio Somenzi. 2015. CUDD: CU Decision Diagram Package Release 3.0.0. University of Colorado at Boulder.
[54] Dan Suciu, Dan Olteanu, Christopher Ré, and Christoph Koch. 2011. Probabilistic Databases. Morgan & Claypool, San Rafael, CA, USA. doi:10.2200/S00362ED1V01Y201105DTM016
[55] Nicholas P. Tatonetti, Patrick P. Ye, Roxana Daneshjou, and Russ B. Altman. 2012. Data-Driven Prediction of Drug Effects and Interactions. Science Translational Medicine 4, 125 (2012), 125ra31. doi:10.1126/scitranslmed.3003377
[56] The Apache Software Foundation. 2025. Apache Jena Fuseki. https://jena.apache.org/documentation/fuseki2/. Version 5.4.0.
[57] The Eclipse Foundation. 2026. Eclipse RDF4j. https://rdf4j.org/. Versions 4.2.1 and 5.3.2.
[58] Transaction Processing Performance Council. 2022. TPC-H: A Decision Support Benchmark (Standard Specification). https://www.tpc.org/tpch/. Revision 3.0.1.
[59] G. S. Tseitin. 1983. On the Complexity of Derivation in Propositional Calculus. In Automation of Reasoning: 2. Classical Papers on Computational Logic 1967–1970, Jörg H. Siekmann and Graham Wrightson (Eds.). Springer, Berlin, Heidelberg, 466–483. doi:10.1007/978-3-642-81955-1_28
[60] Octavian Udrea, V. S. Subrahmanian, and Zoran Majkić. 2006. Probabilistic RDF. In Proceedings of the IEEE International Conference on Information Reuse and Integration (IRI). IEEE, Piscataway, NJ, USA, 172–177. doi:10.1109/IRI.2006.252408
[61] Leslie G. Valiant. 1979. The Complexity of Enumeration and Reliability Problems. SIAM Journal on Computing 8, 3 (1979), 410–421. doi:10.1137/0208032
[62] Denny Vrandečić and Markus Krötzsch. 2014. Wikidata: A Free Collaborative Knowledgebase. Communications of the ACM 57, 10 (2014), 78–85. doi:10.1145/2629489
[63] Marcin Wylot, Philippe Cudré-Mauroux, and Paul Groth. 2014. TripleProv: Efficient Processing of Lineage Queries in a Native RDF Store. In Proceedings of the 23rd International Conference on World Wide Web (WWW). ACM, New York, NY, USA, 455–466. doi:10.1145/2566486.2568014
A Proofs
A.1 Factored basic graph patterns
PROOF OF LEMMA 4.5. Let be the variables of , let contain the terms that occur in , and let be the elimination order. We identify a factor with the map that sends every mapping of the scope to the Boolean function of the gate of the factor at the mapping, and to where the factor has no gate. The base factor thus maps to when and to
otherwise. For a mapping with , the root of in the flat plan denotes
Let be the factors after eliminating . For a binding of the remaining variables, let
We prove that the conjunction of the factors in at equals . For , Equation (9) contains the unique empty assignment and equals the original factor conjunction. Assume the claim for , let , and let for . The scopes of the factors outside do not contain . The claim for and distributivity therefore give
The second equality holds because the terms of the values are , and the disjunction of the other terms is the function of the gate of Definition 4.4, or when is empty. The result is the conjunction after replacing by . At , restriction to yields Equation (8), so the roots of in both plans denote the same Boolean function.
A.2 Transitive closures
PROOF OF THEOREM 4.6. The gates form an acyclic circuit and satisfy the equivalence of Section 4.4 (Appendix G). For an e-walk in , we write and , and let
We prove by induction on that
For i = 1, Equation (4) is the disjunction over all one-edge e-walks from s to v. Assume Equation (10) for i. Equation (5) gives
Appending to every walk of length i ending at u gives exactly the walks of length ending at v.
If , a shortest positive e-walk from s to v contains no repeated node and has length at most n - 1, because removing the segment between equal nodes yields a shorter walk. If , the same deletion argument makes a shortest positive closed walk a simple cycle of length at most . The construction runs levels, and Equation (6) gives
If the construction stopped because level is empty, no walk exceeds , since every longer walk has a prefix of length . Otherwise . The closure gate is therefore true in whenever , because a shortest such walk has length at most . Conversely, every satisfied term denotes an -walk in , so for every
Let . For , , and returns on exactly when . For and , as well, and the same equivalence holds because a walk from to has positive length. For and , is the zero-length gate of . For a constant source, the zero-length gate is , and returns on every . For a variable source, the zero-length gate is , which is true in exactly when is the subject or object of a triple of . The atom returns on under the same condition, because the first -step of a closed walk at uses a triple of whose subject or object is . In every case, exactly when returns on , which holds exactly when by the definition of in Section 2. The two Boolean functions therefore agree under every valuation of .
Each of the at most levels has at most sum gates and product gates, so the levels have gates. One further sum gate per target forms . Level references only the gates and level- gates, so the level order is topological.
A.3 Correctness of the plans
PROOF OF LEMMA 4.8. Under the assumption, two gates have the same IRI exactly when they have the same name, and we use three facts. (1) Two product gates have the same IRI if and only if their lists of children are equal up to order, because the name is the same for two lists of children exactly when the lists are equal up to order. (2) Two sum gates, or two difference gates, have the same IRI if and only if they have the same letter, the same mapping and subpatterns equal up to the identities of Definition 4.1. The name lists the values of the variables in scope at under the mapping, with = unbound for an unbound variable, determines up to these identities, which preserve Boolean provenance, and is injective. (3) The IRI of a gate depends only on the row, because a key expression applies only functions whose values SPARQL 1.1 fixes on IRIs and literals (Appendix E), and contains no blank nodes.
For a pattern and a mapping , let be the tuple of the variables in scope at in lexicographic order, as in Definition 4.2, let be the gates bound by the rows of that restrict to on , and let
We then prove by structural induction on , for every subpattern that is not a closure atom with a variable source and for every mapping . The base cases are triple patterns and closure atoms. For a compound pattern, the induction hypothesis is the claim for each of its direct subpatterns and every mapping. For a closure atom we prove the claim at the mappings whose source lies in , and the join and difference cases use the source-bound condition to apply it.
Triple pattern. For a matching triple , and . For every other mapping, both sides are .
Closure atom. Let . Every row of restricts on to a mapping with and a returned target , and all rows for one pair bind the gate of Section 4.4. For , Theorem 4.6 gives . If the construction does not return , then for every , so and both sides are . Thus
For a constant source, , so Equation (13) holds for every .
Filter. Let . If satisfies , then and the induction hypothesis gives . If does not satisfy , item (5) keeps FILTER() in the rewritten pattern, so and , and by the filter case of Section 2.
Join. Let . The gates of are the product gates of the compatible decompositions and choices . Fix a compatible decomposition and a world . We show that satisfies exactly when satisfies . For an operand that is not a closure atom with a variable source, the induction hypothesis gives . Let be a closure atom with a variable source. If satisfies every , then has a row at , so the source of lies in and Equation (13) applies. If satisfies every , induction on shows that satisfies for every . Every such then has a row at , so belongs to . The source-bound condition makes bind the source, and compatibility gives . The source of therefore lies in , and Equation (13) applies. Distributivity over the choices of the gates and the equivalence just shown give
with both disjunctions over the compatible decompositions of .
Union. Let . By fact (2), all rows for bind the same gate , with child set . Thus, . If every child set is empty, and both sides are .
Projection. Let . For a mapping with , the child set of is . Hence, .
Difference. Let and let be the gates of Definition 4.2. For every with , , and . In the subtrahend query, the group of binds before the join with . The name therefore depends on the mapping of alone, also when binds a variable that the mapping of leaves unbound. If , then and implies . Otherwise belongs to when is a closure atom with a variable source. If leaves the source unbound, the source-bound condition and Equation (1) give , and both sides are . Otherwise every with a source takes the source . The source-bound condition places in , so Equation (13) gives for every . For any other , the induction hypothesis gives the same equation. Therefore,
An OPT without a filter is UNION(JOIN , DIFF ) (Section 2), so the cases above cover it. A MINUS follows from the reduction to DIFF below.
By fact (2), for a union, projection or difference , so denotes , and for by the difference case, denotes .
PROOF OF THEOREM 4.9. Lemma 4.8 proves Equation (7) for the root of every mapping , so the plan is sound. If , the plan produces no root for , and Equation (12) gives , which equals by the induction in the proof of Lemma 4.8. By Equation (1), is then not an answer, so the plan is complete. The circuit is acyclic by Section 4.5 and the proof of Theorem 4.6, because subpatterns that share a gate have the same height when filters are not counted. Every answer also has a root in the factored plan, because every factor is defined at the restriction of a match that extends . Conversely, by Equation (9), the remaining factors are all defined at only when a match extends , so Lemma 4.5 applies to every root of the factored plan.
Coverage beyond the grammar. W3C MINUS removes a mapping of exactly when a compatible mapping of shares a variable with it [34]. The following facts reduce MINUS to DIFF for all patterns and once their unions are moved to the top, and each fact follows from the definitions of the operators. The operator MINUS distributes over a union in its first operand, and MINUS . All mappings of a union-free pattern bind the same set of variables. For union-free and , MINUS is if the mappings of and the mappings of bind disjoint sets of variables, and DIFF otherwise. Before it moves any union, SPARQL_circ applies two further facts. The pattern MINUS is DIFF when, on every graph, every mapping of and every mapping of bind a common variable, and when every mapping of and every mapping of bind disjoint sets of variables. A filter FILTER_ mentions only variables that every mapping of binds, so OPTIONAL equals OPT [34]. A path pattern with a constant target equals the closure atom when is a variable, because W3C evaluates a constant target as the constant source of the inverse path [34], and PROJ_ (FILTER_sameTerm( )) (( )) for a fresh variable when is a constant.
B Gate Names, Blank Nodes and Identifiers
The hash expression of Definition 4.1 applies SHA256 to the encoded arguments of the name and forms the gate IRI from urn:g; and the first 128 bits of the digest, and encodes the kind of a value with the digests of its lexical form, datatype and lower-cased language tag (Appendix E). SPARQL 1.1 only recommends lowercase digits for SHA256 [34], so every digest passes through LCASE, and every engine names a gate identically. Since SPARQL 1.1 cannot sort the values of a row, the plan sorts the digests of the children of a product gate with compare-exchange steps, each a pair of IF expressions. The digests have fixed widths, so distinct names have distinct encodings whenever the hashed parts have distinct digests.
The proofs assume that distinct names have distinct IRIs. A leaf keeps the identifier of the triple as its IRI, and every identifier of lies outside the namespace urn:g: of the other gates. Two distinct names of a circuit with gates receive the same IRI only when the 128-bit prefixes of the digests of two distinct encodings agree or two distinct hashed strings have equal digests. Computing one name hashes fewer than strings, so in the random-oracle model [8] the probability is below for .
Skolem IRIs. A key expression applies STR to every bound term, STR raises an error on a blank node, and a BIND expression that raises an error leaves its variable unbound [34], so a key over a blank node drops its gate. The reified graph therefore uses fresh Skolem IRIs from a namespace that G and Q do not use. The filter conditions of S use the built-ins STR, LANG, DATATYPE, isIRI, isLiteral, isBlank, isNumeric, sameTerm, langMatches, REGEX, IN, STRDT, CONCAT, CONTAINS and YEAR [34]. In the filter conditions of Q, the rewriting replaces isBlank, isIRI, STR and STRDT by expressions that return on a Skolem IRI what SPARQL returns on a blank node, and the key expressions keep the SPARQL 1.1 built-ins. The other built-ins compare terms or treat an IRI and a blank node alike. A filter therefore keeps a mapping on exactly when the filter keeps the corresponding mapping on G.
Identifier-level annotations. Let be the identifiers in , let be the nonempty set of identifiers of and let the for be independent Boolean variables with the probabilities of the identifiers. The substitution maps to . For an identifier world , let , and let make true exactly when . Since substitution preserves conjunction, disjunction and negation, every Boolean function over satisfies
The rows of a matching triple bind the leaves for , whose disjunction is , and the inductions in the proofs of Theorem 4.6 and Lemma 4.8 carry over under , so the root of denotes . By Equations (14) and (1), the root is true at exactly when , so its weighted model count is the marginal probability of over the worlds .
C Tests and the Reimplementation of NPCs
Tests compare the probabilities of SPARQL with an enumeration of the possible worlds on query shapes that cover S. For the comparison with NPCs, we reimplemented the rewriting rules of NPCs. The published NPCs rewriter is a compiled JAR that returns no provenance or provenance without triples for queries with OPTIONAL, UNION, DISTINCT or FILTER and evaluates MINUS as OPTIONAL. On the 138 basic graph pattern queries of the WatDiv workload of NPCS, our reimplementation returns the same rewritten queries as the JAR up to variable names and operand order.
D Proofs in Detail
D.1 Factored basic graph patterns
Appendix A.1 proves Lemma 4.5 for the base factors of Definition 4.4. When a triple pattern of has a constant subject or object, the factored plan computes all base factors with one query that matches the whole basic graph pattern. Every base factor is therefore defined only at restrictions of these matches.
The restriction of the base factors drops a mapping only when no match of the basic graph pattern extends the mapping. Every total binding that extends a dropped mapping then has for some , and therefore and the conjunction in Equation (8) is at . The dropped mappings contribute only to Equation (8), so the restriction leaves the equation unchanged.
For the bound of Section 4.3, the induced width gives for every eliminated z. Each factor is defined at most at mappings, while its product gates range over at most assignments to . Since and there are base factors and elimination steps, the elimination steps create gates, which is for fixed w. The roots add one product gate and one sum gate per answer.
D.2 Gate names in the proof of Lemma 4.8
The proof of Lemma 4.8 in Appendix A uses three facts about the names, which we prove here: (1) two product gates have the same IRI if and only if their lists of children are equal up to order, (2) two sum gates, or two difference gates, have the same IRI if and only if they have the same letter, the same mapping and subpatterns equal up to the identities of Definition 4.1, and (3) the IRI of a gate depends only on the values that the row binds. Under the assumption, two gates have the same IRI exactly when they have the same name. (1) The name of a product gate is for the IRIs of its children. Two product gates with the same IRI have the same name by the assumption, so their lists of children are equal up to order. Conversely, two such lists have the same hashes in ascending order, and the IRI depends only on these hashes. (2) The name of a sum gate is for its letter L, its subpattern P and the values of the variables in scope at P under its mapping , with when leaves unbound. Since determines P up to the identities of Definition 4.1, which preserve Boolean provenance, and is injective, two names are equal exactly when the letters, the mappings and the subpatterns up to these identities are equal. Difference gates have the letter M and the same argument. (3) A key expression applies only the functions of Section E to the values of a row, SPARQL 1.1 fixes their values on IRIs and literals, and contains no blank nodes. The IRI of a gate therefore depends only on the values that the row binds.
E Gate Names, Collisions and Identifiers in Detail
The hash expression h of Definition 4.1 is
\begin{aligned}h(\mathrm{T},d_{1},\ldots,d_{n})&=\mathrm{CONCAT}(\mathrm{“urn:g:t:”},\\&\delta_{128}(\mathrm{CONCAT}(\mathrm{“T|”},d_{1},\mathrm{“}|”,\ldots,\mathrm{“}|”},d_{n})),\\h(L,\theta,a_{1},\ldots,a_{k})&=\mathrm{CONCAT}(\mathrm{“urn:g:”},\mathrm{LCASE}(L),\mathrm{”}:\\&\delta_{128}(\mathrm{CONCAT}(L,\mathrm{”@”},\delta(\theta),\eta_{1},\ldots,\eta_{k}))),\end{aligned}where is one of the letters U, P, A, S and M, is LCASE(SHA256(·)) and is SUBSTR(, 1, 32) for a string expression, and is for the name of . The children enter as their digests in ascending order, and encodes of the value of ?x:
The letter t marks a quoted triple of SPARQL-star [35]. On , every value is an IRI, a literal or a quoted triple, so the branch for blank nodes is never taken. SPARQL 1.1 only recommends lowercase digits for SHA256 [34], and therefore applies LCASE, so every engine names a gate identically. SPARQL 1.1 offers no function that sorts the values of a row, and the plan sorts the digests of the children of a product gate with compare-exchange steps of two IF expressions each. The digests have fixed widths, so names whose hashed parts have distinct digests have distinct encodings.
The proofs assume that distinct names have distinct IRIs. A leaf keeps the identifier of the triple as its IRI, and every identifier of lies outside the namespace urn: g: of the other gates. For a circuit with N gates, let M be the number of distinct strings that the plan hashes to compute the names. Two distinct names receive the same IRI only when the digests of two distinct encodings agree in the first 128 bits or two of the M strings have equal digests. In the random-oracle model [8], the probability of either event is at most . Computing one name hashes fewer than strings, so and the probability is below . For gates, .
Identifier-level annotations. Let be the identifiers in , let be the nonempty set of identifiers of , and let be a Boolean variable with the probability of the identifier for every . The variables are independent. In Section 2, the sets are disjoint singletons. Multiple Wikidata statements give several identifiers for one triple, whereas the RDF triples of a TPC-H row share its identifier. The substitution maps to . For an identifier world , let , and let the valuation make true exactly when . Since substitution preserves conjunction, disjunction and negation, every Boolean function over satisfies
For a matching triple , the encoded rows bind the leaves , whose disjunction is , and the inductions in the proofs of Theorem 4.6 and Lemma 4.8 carry over to the functions under . The root of therefore denotes . By Equations (15) and (1), the root is true at exactly when . The weighted model count of the root is the sum of over the sets at which the root is true, that is, the marginal probability of over the worlds . Shared identifiers correlate the RDF triples of a row, but the stay independent.
F The Factored Plan on a Hub
For , let contain the triples
The names , and also denote the leaves of their triples. Over , the running query returns , and , and every answer has the three derivations . The flat plan of Definition 4.2 creates one product gate per derivation, so the circuit in Figure 7(a) has nine product gates with three edges each below three roots. The factored plan of Definition 4.4 eliminates ?x first, and maps Metformin to . Eliminating ?y then yields the factor that maps to , so the three answers share in Figure 7(b).
For drugs between Aspirin and Metformin and drugs after Metformin, the flat circuit has gates other than leaves and edges. After the removal of non-root sum gates with one child, the factored circuit has gates and edges. For , the flat circuit has 12 gates and 36 edges, and the factored circuit 10 gates and 18 edges. SPARQL_{circ} emits these circuits on .
G Transitive Closures in Detail
Let contain the subjects and objects occurring in . For every closure-free expression and , we construct a gate by recursion on . A construction with no child uses . For an IRI ,
Inverse and alternative use
For sequence, let
Gate keys contain the syntax node of and the node pair. Inverse reuses the gate , so the gate keys mention only IRI, sequence and alternative nodes. These equations define the global closure-free circuit . The equations index a gate by every node pair, so Lemma G.1 counts the gates of over the whole graph. A plan materializes only the gates other than that a root reaches.
LEMMA G.1. For every closure-free and world ,
The circuit is acyclic and has gates.
PROOF OF LEMMA G.1. We use structural induction on . The base case is an IRI , and the induction hypothesis is the claim for the direct subexpressions of at all and all .
IRI. Let . The semantics of Section 2 gives
The empty child set yields on both sides.
Inverse. Let . By construction and induction,
Alternative. Let . Since , omitting does not change the disjunction. The two induction hypotheses yield
Sequence. Let . Equation (16), the semantics of Section 2 and the induction hypotheses give
If no midpoint satisfies the first line, the outer disjunction is empty and both sides are false. The cases above exhaust the grammar.
Let . Each IRI or alternative syntax node creates gates. Each sequence node creates at most one sum gate per node pair and one product gate per node triple , so the count per sequence node is . The syntax tree has nodes, so has gates. Every edge leads to a leaf, to a gate of a proper subexpression or from the sum gate of a sequence to one of its product gates. The children of a product gate of a sequence are gates of the two subexpressions. Ordering the gates by expression depth and placing the product gates of a sequence below its sum gates therefore gives a topological order.
Let contain the pairs with . The set of Section 4.4 contains and the nodes that reaches from , and . Only part of is ever needed. The levels of Section 4.4 use for alone, and expanding one such gate involves only for a subexpression of and a midpoint that a prefix of reaches from . SPARQL_{circ} therefore emits these gates only on the matches of that start in . Choosing one part at every alternative node turns into finitely many sequences, and for each sequence one constructs query matches it from the nodes of and emits the gates of the syntax nodes that the sequence passes through. For , these are the gates with . Lemma G.1 and the count of level gates in the proof of Theorem 4.6 give the global total . For , the total is .
SPARQL : Probabilistic Query Evaluation with Provenance Circuits

(a) flat plan: 12 gates, 36 edges
(b) factored plan: 10 gates, 18 edges
Figure 7: Circuits of the running query over . The gray edges in (a) lead to the leaves , and the three answers in (b) share the orange sum gate .
SPARQL first collects with SELECT queries that each follow one -step from the nodes found so far, and then emits the gates with together with level 1. SPARQL keeps one row per gate of level with the source and the target of the gate, and issues CONSTRUCT queries for the product and sum gates of level . Every level gate records the level with c:r1v1, the digest of with c:rpath, the source with c:rfrom and the target with c:rto. SPARQL derives the rows from the level, the source and the target. Gate keys contain , , and the target, so every edge points to a lower level and the two closures of one expression build separate circuits. The key of the closure gate contains , and alone. The base gates and the zero-length gate carry distinguished levels of their own, so no round composes the zero-length gate. A last CONSTRUCT query emits the closure gates together with the roots or the rows of the closure atom, which take the zero-length gate for the pair when . For a closure that forms the whole query, the level queries receive the rows of level in a VALUES clause and only read the endpoint. When the rows exceed the size of one request, SPARQL splits them over several queries and gives each query the base rows that start at the targets of its rows. The merged results equal those of one query.
For a closure atom inside a larger pattern, SPARQL inserts the rows into the private namespace under two predicates, and the level queries read the rows from the endpoint. The names of the two predicates contain the run, the digest of , the source and the level, and therefore keep the rows of different runs, closure atoms, sources and levels apart. The digest also separates from , so only the star construction reads the zero-length row that it inserts. A source variable from an enclosing pattern invokes the same construction for each source binding, and the query that emits matches the triples whose subject or object is the source. RDF4j parses a closure atom whose source is its target variable, (?x, e^\circ, ?x), as the atom (?x, e^\circ, ?t) with a fresh variable ?t under the filter sameTerm(?x, ?t). SPARQL passes the source binding through this filter and keeps the column of ?t in the relation, so the filter keeps the pairs .
The Bellman–Ford circuit of Fan et al. [23] carries into level , so one level accumulates every length. In the endpoint, the
carried gates republish a pair at every later level as a sum gate with one input. The level is also part of a key, so the products and have different children and are distinct gates. Both products cover the walks of length at most that end with the step . Exact-length levels hold each walk at one level and avoid both costs. The construction stops at the first empty level or after levels (Section 4.4). The bound and the emptiness of a level depend only on and , so SPARQL stops at the same and emits the same gates on every engine.
H Implementation Details
Gate names. SPARQL computes once for every subpattern , and the tag of the outer projection serializes the parsed query. The query fixes the number of children of a product gate, and the plan sorts their digests with the compare-exchange steps of a bubble-sort network. Each step is the pair IF (?a <= ?b, ?a, ?b) and IF (?a <= ?b, ?b, ?a).
Roots. The prefix c: stands for urn::circuit:. The query that emits a root also emits the triple c: answerRoot vs with a literal vs that lists the projected variables. For every projected variable ?y that the mapping of binds to a value , the query also emits the triple c:bind: . The suffix is the hexadecimal encoding of the UTF-8 bytes of the name of ?y, and vs consists of vars: followed by the comma-separated suffixes of all projected variables. The plan (3) writes z in place of its encoding 7a. SPARQL reads the mapping of every root from these triples.
Skolem IRIs. A key over a blank node drops its gate (Appendix B) because a template omits every triple with an unbound variable. The label of a blank node is scoped to one query result [34], so two queries can return different labels for one blank node. In the filter conditions of , the expressions that replace isBlank, isIRI, STR and STRDT test whether an IRI is a Skolem IRI. On a Skolem IRI, isBlank then returns true and isIRI false, and STR and STRDT raise the error that SPARQL raises for a blank node. Every Skolem IRI in an answer is mapped back to its blank node.
The implemented plan. SPARQL builds the queries of Definition 4.2 with two changes. The query of the operator above a join emits the product gates of the join, which has no query of its own. The query contains the WHERE clause of the join, and its template emits the product gate of every row of the join with the edges to the children of the gate. Every product gate that a root reaches is therefore in the circuit. The pattern of a union ends with the BIND of . On RDF4J 4.2.1 and 5.3.2 [57], we observed that a join of two groups is evaluated as a hash join on the shared variables when one group contains a BIND. The hash join drops every row that leaves a shared variable unbound. SPARQL makes the row compatible with every row that agrees on the bound variables of the row. Over the triples :s :p0 :a, :s :p0 :b, :s :p1 :c and :s :p2 :d, the pattern
returns 0 rows on both versions, and the correct result has 2 rows. Before applying Definition 4.2, SPARQL therefore rewrites a join or a difference whose operand has a union with a branch that leaves unbound a variable of the other operand. Join and the left operand of a difference distribute over union, and . The rewritten query therefore has the answers and the Boolean provenance of the original query. For the RDF-star annotation, standard reification and named graphs, SPARQL matches a triple pattern together with its encoding. The matches remain those of Definition 4.2, because contains the triples of G with Skolem IRIs in place of blank nodes. SPARQL also adds DISTINCT to the subquery of a projection. The keyword removes duplicate solutions and leaves the rows and the circuit unchanged.
Factored basic graph patterns. Every row of a factor is an RDF node in the private namespace that stores the mapping and the gate of the row. The sum gates of a factor carry the prefix urn: g : s : and hash a tag together with the bindings of the scope. The tag of a base factor combines a digest of the basic graph pattern with the index of its triple pattern, and the tag of any other factor combines the digest with the eliminated variable and the step. The subtrahend sum gates of Definition 4.1 carry the same prefix, and only their hashed strings begin with S@. A base factor maps a row to the sum gate over the identifiers of its triple. One INSERT makes the rows of a factor available to the next query. At every step, SPARQL eliminates a variable z with the smallest and breaks ties by the name of the variable. The factored plan multiplies the factors of two at a time. Pairwise multiplication changes the nesting of the product gates and preserves their Boolean functions and the bound of Section 4.3. SPARQL uses the flat plan in three cases. In the first case, the basic graph pattern has at most one triple pattern, so every derivation consists of at most one triple. The other two cases concern a basic graph pattern whose subjects and objects are variables, and every base factor then contains every match of its triple pattern in G. In the second case, the query projects every variable, so every answer has one derivation. In the third case, a triple pattern has a variable predicate, and its base factor contains every triple of G.
Compilation. Before compilation, SPARQL replaces every sum gate that has one child and is not a root by its child. For d4,
SPARQL compiles the Tseitin encoding [59] of the circuit below the root, a CNF with one auxiliary variable per gate. Weight 1 on both literals of each auxiliary variable keeps the WMC [24, 49].
I Builder Independence
Definition 4.1 derives every gate name from the operator, the pattern tag and either the bindings of the row or the IRIs of the children, all of which Q and determine. Every engine that follows the SPARQL 1.1 semantics and evaluates the plan over therefore returns the same circuit.
For a subpattern , let be the SELECT queries obtained from each CONSTRUCT query of Definition 4.2 by replacing its template with the projection of and the child gate variables of that case. A union therefore has one such query per branch and a difference two, and is for a difference. The witness query of projects , which the group of binds before the join with , in place of , because a variable unbound in the row of can take a value of . We call their results the witness relations of .
Applying the templates of Definition 4.2 to the witness relations of every subpattern of Q yields the circuit of the plan with the same gate names, kinds and child sets. The plan and the witness relations give the key expressions the same arguments: the pattern tag and the binding tuple for - and -gates, and the child gates for -gates. A witness relation returns the binding tuple verbatim, the gate of a subtrahend query, and the child gates as its gate columns. In both cases, the children of one name are those of the rows that bind the name.
Emitting the gates inside the engine and building them from the witness relations differ in cost. Let be the number of rows that a plan enumerates, the number of distinct gates and the number of edges of its circuit. Emission inside the engine materializes triples, because set semantics merges a gate the moment it is emitted a second time. A witness relation instead returns terms for patterns. The two coincide only when is . The flat plan of a basic graph pattern gives every row a product gate with at most children and one edge from the root, so , and is when distinct rows match distinct sets of triples. The factored plan makes small even when the flat plan enumerates many rows, and the gain holds only while its intermediate factors stay in the endpoint that evaluates the joins.
J Additional Experiments
This section gives the results of Section 5 for all engines and the results that Section 5 leaves out. On WatDiv, the endpoint and the remaining steps each have 600 s with 10.9 million triples and 3000 s with 109 million triples. On gMark, the endpoint has 5000 s. On Wikidata, a run has 600 s from the rewriting of the query to the probabilities. On TPC-H, a run has 3000 s from the rewriting of the query to the probabilities.
J.1 WatDiv
NPCS reports an overhead of 20 to 30% over the original queries on GraphDB with a cold cache [5]. Our runs follow a warm-up run, the plain query runs on G and NPCS on , and with 10.9 million triples on GraphDB, NPCS takes 1.9 times as long as the reified query, which takes 8.7 times as long as the plain query (Section 5.1).
SPARQLcirc : Probabilistic Query Evaluation with Provenance Circuits
Table 2: End-to-end time (s) on WatDiv (RDF-star).
| GraphDB | Fuseki | Oxigraph | ||||
|---|---|---|---|---|---|---|
| Triples | 10.9M | 109M | 10.9M | 109M | 10.9M | 109M |
| NPCS | 0.46 | 0.80 | 0.49 | 0.87 | 0.69 | 11.89 |
| Flat plan | 0.87 | 1.11 | 0.82 | 1.43 | 1.09 | 12.88 |
| Factored plan | 1.34 | 2.20 | 1.15 | 3.29 | 1.15 | 1.53 |
Table 2 gives the end-to-end time over the queries that NPCS and both plans complete. At the endpoint, the flat plan costs 2.5 to 2.6 times NPCS on GraphDB and the factored plan 4.3 to 5.1 times. Fuseki and Oxigraph follow GraphDB, except on Oxigraph with 109 million triples. There, the reified query already takes 9.1 times as long as the plain query. The factored plan builds every factor in a separate query and takes 0.2 times as long as NPCS at the endpoint on the 19 templates of basic graph patterns that it completes. End to end, the factored plan returns all probabilities in 1.53 s against 11.89 s for NPCS.
The encoding changes the times by factors that depend on the engine. Standard reification stores four statements per triple instead of two and matches a triple with its identifier by three triple patterns instead of one. Over the queries that all three encodings complete, standard reification is slower than RDF-star for every engine, method and size, by median factors from 1.02 to 3.94. Relative to RDF-star, named graphs take 0.74 to 0.93 times as long on Oxigraph for NPCS and the flat plan, 0.87 to 1.15 times on GraphDB and 1.06 to 1.74 times on Fuseki.
Figure 8 repeats Figure 5 with 109 million triples.

Figure 8: Endpoint time per WatDiv class (109M triples).
Figures 9 to 14 give the endpoint time of every template, where Base is the plain query and Reification the reified query. The two property-path templates P+ and P* run only the plain query and the plan of Section 4.4.
J.2 gMark
At k = 6, GraphDB runs with a heap of 128 GiB instead of 48 GiB, and SPARQLcirc with 96 GiB instead of 64 GiB. Outside the endpoint, NPCS keeps about 0.1 GiB, since it only stores the response, whereas the factored plan reaches 2 to 25 GiB while it builds the circuit.
J.3 Wikidata
The graph holds the statements of the full dump of 29 September 2026 without qualifiers and references in 8.87 billion triples.
At the endpoint, NPCS completes on GraphDB 42 queries with one triple pattern, 32 with several and 13 with OPTIONAL, the flat plan 42, 30 and 15, and the factored plan 41, 25 and 14. On Oxigraph, NPCS completes 82 queries, the flat plan 77 and the factored plan 71, and the flat plan completes 5 of the queries with OPTIONAL against 10 for NPCS. At the median, the flat plan takes 2.5 times as long as NPCS on GraphDB and 1.7 times on Oxigraph (Figure 15), and the factored plan 2.8 and 2.2 times. Figure 15 gives the endpoint time of every query, which ends before NPCS parses and merges its provenance expressions. NPCS is therefore faster at the endpoint on almost every query, and the flat plan overtakes it only end to end on queries with many derivations (Table 1). End to end with CUDD, the flat plan returns all probabilities for 87 queries on GraphDB and 77 on Oxigraph, and NPCS for 82 and 80. If NPCS compiles the expression of every answer separately instead of merging them, it completes 66 and 64 queries, and the flat plan is faster on 49 of the 62 queries that both complete on GraphDB, by 2.7 times at the median. With d4, compilation and weighted model counting take 54 to 68% of the end-to-end time of the flat plan, against about a fifth with CUDD (Figure 16), and the flat plan and NPCS take about the same time end to end.
On GraphDB, the flat plan is more than ten times faster than NPCS on seven queries with OPTIONAL, with 2.1 s against 67 s at the median, although five of them have fewer than 500 derivations. On Oxigraph, the flat plan is at most twice as fast with OPTIONAL and exceeds the budget on four of these queries that NPCS completes.
J.4 TPC-H
TPC-H [58] at nine scale factors from 0.01 to 1 becomes 1.2 to 123 million triples under the mapping of SPARQLprov [36], in which the IRI of a row identifies its triples (Section E). ProvSQL 1.11.0-dev [52] in PostgreSQL 18.4 runs on a relational copy.
The time of SPARQLcirc grows about linearly with the size of TPC-H, as does that of ProvSQL. The flat plan completes every scale factor on six of the twelve templates on GraphDB and on seven on Oxigraph, and ProvSQL on eleven. On these templates, the time of the flat plan grows with the scale factor at a median exponent of 0.78 on GraphDB and 0.95 on Oxigraph, against 0.93 and 0.90 for ProvSQL. ProvSQL is faster in absolute terms, by 20 times at the median for the flat plan on GraphDB, because the direct mapping turns every attribute of a row into a triple, so a template joins more triple patterns than ProvSQL joins tables.
Figure 17 gives the end-to-end time on every template. On GraphDB, ProvSQL is faster than the flat plan on every template, by 5.7 to 288 times at the median of a template, and the factored plan takes 121 times as long as ProvSQL at the median.

Figure 9: Endpoint time per WatDiv template with 10.9 million triples and RDF-star annotations.

Figure 10: Endpoint time per WatDiv template with 10.9 million triples and standard reification.
SPARQLcirc : Probabilistic Query Evaluation with Provenance Circuits

Figure 11: Endpoint time per WatDiv template with 10.9 million triples and named graphs.

Figure 12: Endpoint time per WatDiv template with 109 million triples and RDF-star annotations.

Figure 13: Endpoint time per WatDiv template with 109 million triples and standard reification.

Figure 14: Endpoint time per WatDiv template with 109 million triples and named graphs.

Derivations across all answers
Figure 15: Endpoint time of every Wikidata query against its number of derivations, on GraphDB (top) and Oxigraph (bottom).
circuit construction circuit parsing compilation and WMC

query class and plan
circuit construction circuit parsing compilation and WMC

query class and plan
Figure 16: Share of the stages in the end-to-end time of SPARQL on Wikidata, on GraphDB (top) and Oxigraph (bottom).
engine
GraphDB 10.7.6
Oxigraph 0.5.9
PostgreSQL 18.4
mode -- ProvSQL — SPARQLcirc (flat) … SPARQLcirc (factored)

Figure 17: Exact PQE end to end on TPC-H, one panel per template. A line stops short where the budget was exhausted.
K Notation
Table 3: Notation.
| Symbol | Meaning |
|---|---|
| I, B, L, V, T | IRIs, blank nodes, literals, variables, RDF terms |
| S | SPARQL fragment (Section 2) |
| G | RDF graph underlying the probabilistic model |
| t, tp, P, Q | triple, triple pattern, pattern, query |
| W, | possible world , variable of |
| solution mappings and compatibility | |
| [[P]]_G, supp | multiset evaluation and its support |
| Y | projected variables of a query |
| mapping of closure atom C for s and v | |
| val_W | valuation that makes true exactly when |
| X | variables |
| BProv_P( ) | Boolean provenance of for pattern P |
| Pr( ), Pr( ), WMC | probability of t, marginal probability of , weighted model count |
| reified graph that the endpoint stores | |
| sum, product and difference gates | |
| ch, pos, neg | children, minuends and subtrahend of a gate |
| root( ) | root of the mapping |
| [[g]] | Boolean function of gate g (Section 2) |
| childless gates for and | |
| term encoding, serialization of P | |
| scope and projection tuples in lexicographic order | |
| lower-cased SHA-256 digest, its first 128 bits | |
| KEY_*, h, sort, , L | key expressions, their parts and the letter of a sum or difference gate (Definition 4.1) |
| plan of CONSTRUCT queries and gate variable of P | |
| queries of P (Definition 4.2) | |
| reif( ) | reification of tp with identifier variable ?t |
| rewritten pattern of P that binds gp | |
| gates bound by the rows of for , disjunction of their functions | |
| sp | subtrahend gate of a difference P |
| m, Z, | number of triple patterns, variables of Q outside Y, base factor of |
| factors whose scopes contain z, the factor that replaces them | |
| values of z at which every factor of is defined, terms of G | |
| scope of , induced width | |
| input relation and sources of a closure atom C | |
| gate of | |
| closure-free expression, closure ( ), source, target | |
| subjects and objects of G, closure-free circuit of e (Section G) | |
| relation of e on G and its transitive closure | |
| zero-length pairs of a closure (Section 2) | |
| closure atom with source and target variable ?y | |
| gate that is true in W exactly when | |
| nodes and e-steps reachable from s, | |
| gate for length-i walks, closure gate of v, last level | |
| zero-length gate: sum of the leaves of the triples with subject or object s | |
| identifiers, identifiers of t, variable of identifier i (Appendix B) | |
| substitution of by , world of the identifiers |