Algorithm Search⌘K

Algorithmadvanced

Holistic twig join

Also called TwigStack.

Match a tree pattern of an XML query over sorted element streams with one stack per query node. With only ancestor-descendant edges, no intermediate result is wasted.

Time
O(k (n + l z)) worst
Space
O(k d + k l z) extra
Where
d = the depth of the document; k = the number of query nodes; l = the number of leaves of the twig; n = the number of elements in all streams; z = the number of matches
Properties
deterministicexactexternalnot in placeofflinerecursive
Origin
Nicolas Bruno, Nick Koudas, Divesh Srivastava, 2002

A holistic twig join finds all matches of a small tree pattern, a twig, in an XML document. It reads one sorted stream of elements for each node of the twig, and it keeps one stack per node, so that it handles the whole pattern at once. TwigStack, the algorithm of Bruno, Koudas and Srivastava, outputs a partial match for each root-to-leaf path of the twig and then joins these. When every edge of the twig is an ancestor-descendant edge, every partial match is part of a final match. A plan of binary structural joins can build large intermediate results that the final answer does not use. This is a multiway join on containment of intervals, not on equal values as in generic join, and it is not the tree pattern matching of term rewriting, which matches children in a fixed order.

In plain words

A book has chapters, sections and figures, nested inside each other. You want every chapter that holds both a figure and a table somewhere inside it.

In one walk through the book, give each part two numbers: where it begins and where it ends. Then one part is inside another exactly when its numbers lie between the numbers of the other.

Now keep a list of all chapters, all figures and all tables, each in order of where it begins. Read the three lists together from the front. Keep a pile of the chapters that are still open. When you read a figure, pair it with each open chapter, and do the same for a table. At the end, join the figure pairs and the table pairs on their chapter. The algorithm opens a chapter only when it already sees a figure and a table ahead inside it.

The problem

Data model. An XML document is an ordered tree of elements, and each element has a tag, such as book or figure. Text and attributes do not matter here. One depth-first walk gives each element a region code (start,end,level)(\mathit{start}, \mathit{end}, \mathit{level}): a counter value when the walk enters the element, a counter value when it leaves, and the depth. This is the Euler tour numbering of the tree. Then uu is an ancestor of vv if and only if u.start<v.startu.\mathit{start} < v.\mathit{start} and v.end<u.endv.\mathit{end} < u.\mathit{end}, and uu is the parent of vv if also v.level=u.level+1v.\mathit{level} = u.\mathit{level} + 1.

Query. A twig is a tree of query nodes. Each node has a tag, and each edge has an axis: // (ancestor-descendant) or / (parent-child). In XPath, a[.//b]//c is the twig with root aa and two children bb and cc on // edges. A match maps each query node to an element with its tag so that every edge holds. Two query nodes may map to the same element if the edges allow it.

Input and output. For each query node qq the input is the stream TqT_q of all elements with the tag of qq, sorted by start, as an index on tags gives them. The output is the set of all matches. The cost is the number of elements read and the size of the intermediate results, in the word RAM.

The algorithm

Each query node qq has a stack SqS_q. Each entry of SqS_q holds an element and a pointer to the top entry of the parent stack at the time of its push. The entries of a stack are nested, the innermost on top, so the stack is a path in the document.

  1. TWIGSTACK(Q)
  2. 1while some leaf stream of Q is not exhausted do
  3. 2q ← GETNEXT(root)
  4. 3if q is not the root then pop from S_parent(q) every entry that ends before start(head(T_q))
  5. 4if q is the root or S_parent(q) is not empty then
  6. 5pop from S_q every entry that ends before start(head(T_q)); push (head(T_q), top of S_parent(q)) on S_q; advance T_q
  7. 6if q is a leaf then output the path solutions of the new entry, through the pointers; pop it
  8. else
  9. 7advance T_q ▷ this element has no ancestor that can be part of a match
  10. 8join the path solutions of all leaves on their common query nodes
  11. GETNEXT(q)
  12. 9if q is a leaf then return q
  13. 10for each child c of q whose leaf streams are not all exhausted do n ← GETNEXT(c); if n ≠ c then return n
  14. 11n_min ← that child with the smallest start of its head; far ← the largest start of a head among all children, ∞ for an exhausted child
  15. 12while end(head(T_q)) < far do advance T_q
  16. 13if start(head(T_q)) < start(head(T_{n_min})) then return q else return n_min

GETNEXT returns a query node whose head can be the start of a match below it: the heads of its children lie inside its head, and so on down to the leaves. Line L12 drops heads of TqT_q that end before the head of some child begins, because such an element cannot hold an element of that child stream. A path solution is the list of elements on one root-to-leaf path. Line L6 forms it by taking, in the parent stack, every entry at or below the pointer, and so on up to the root, and it keeps a combination only when each edge of the path holds. For a // edge the test always passes; for a / edge it compares levels.

The implementation does not call GETNEXT on a child whose leaf streams are all exhausted (line L10) and treats that child as being at infinity (line L11). Without this, GETNEXT can return a node whose stream is empty.

Example

Take the document a1(b1,a2(b2,c1),c2,a3(b3))a_1(b_1, a_2(b_2, c_1), c_2, a_3(b_3)) and the twig a[.//b]//c. The region codes are a1=(0,15,0)a_1 = (0, 15, 0), b1=(1,2,1)b_1 = (1, 2, 1), a2=(3,8,1)a_2 = (3, 8, 1), b2=(4,5,2)b_2 = (4, 5, 2), c1=(6,7,2)c_1 = (6, 7, 2), c2=(9,10,1)c_2 = (9, 10, 1), a3=(11,14,1)a_3 = (11, 14, 1) and b3=(12,13,2)b_3 = (12, 13, 2). The streams are Ta=a1,a2,a3T_a = a_1, a_2, a_3, Tb=b1,b2,b3T_b = b_1, b_2, b_3 and Tc=c1,c2T_c = c_1, c_2.

step GETNEXT returns action SaS_a after the step path solutions output
1 aa push a1a_1 a1a_1
2 bb push b1b_1, output, pop a1a_1 (a1,b1)(a_1, b_1)
3 aa push a2a_2 a1,a2a_1, a_2
4 bb push b2b_2, output, pop a1,a2a_1, a_2 (a1,b2)(a_1, b_2), (a2,b2)(a_2, b_2)
5 cc push c1c_1, output, pop a1,a2a_1, a_2 (a1,c1)(a_1, c_1), (a2,c1)(a_2, c_1)
6 cc pop a2a_2, which ends at 8, before 9; push c2c_2, output, pop a1a_1 (a1,c2)(a_1, c_2)
7 bb inside GETNEXT, TcT_c is exhausted, so line L12 drops a3a_3; then push b3b_3, output, pop a1a_1 (a1,b3)(a_1, b_3)

Line L8 joins the 4 path solutions of bb with the 3 path solutions of cc on aa. This gives 3⋅2=63 \cdot 2 = 6 matches with a1a_1 and 1 match (a2,b2,c1)(a_2, b_2, c_1), so 7 in all. Every path solution is used. The element a3a_3 is never pushed, because no cc lies inside it.

Correctness

The proof keeps an invariant for each match: an element of the match is never skipped or dropped, it is pushed after the element of its parent, it stays on its stack while a leaf below it still waits, and its pointer reaches the element of its parent. The key lemma is that the node that GETNEXT returns has a head that starts no later than any waiting element of a match in the relevant part of the twig. So a stack never loses an element that a later leaf still needs. When a leaf element of a match is pushed, its whole path is on the stacks, and its path solution is output. The join of line L8 then gives every match once. The full proof is in the proof page.

For twigs with only // edges, the same lemma gives more. When GETNEXT returns qq, the heads below qq form a match of the subtwig at qq. So each pushed element can be extended below, and every path solution is part of some match. This is the optimality of TwigStack. With a / edge the heads are nested but need not be parent and child, and the guarantee fails.

Proof: TwigStack outputs every match exactly once, and for ancestor-descendant twigs every path solution is part of a matchfull

We use the line numbers of the pseudocode. The document is a tree of elements with region codes (start,end,level)(\mathit{start}, \mathit{end}, \mathit{level}) from one depth-first walk, so all start and end values are distinct and the intervals [start,end][\mathit{start}, \mathit{end}] of two elements are either nested, when one element is an ancestor of the other, or disjoint. A match mm of the twig QQ maps each query node qq to an element m(q)m(q) with the tag of qq, so that for each edge from pp to qq the element m(q)m(q) is a descendant of m(p)m(p) (axis //) or a child of m(p)m(p) (axis /). For a query node qq, QqQ_q is the subtree of QQ rooted at qq.

For a query node qq, h(q)h(q) is the head of the stream TqT_q, L(q)L(q) is its start and R(q)R(q) its end, with L(q)=R(q)=∞L(q) = R(q) = \infty when TqT_q is exhausted. The node qq is ended when the streams of all leaves of QqQ_q are exhausted. An element is taken from TqT_q when the head moves past it: by a push (line L5), a skip (line L7) or a drop (line L12). For a match mm, the element m(q)m(q) is waiting while it is not yet taken from TqT_q; then L(q)≤m(q).startL(q) \le m(q).\mathit{start}, because the stream is sorted by start.

Invariant J. For every match mm and every query node qq:

  • (J1) if m(q)m(q) is taken, it was pushed, and if qq is not the root, m(parent(q))m(\mathit{parent}(q)) was pushed before it;
  • (J2) if m(q)m(q) is taken and m(l)m(l) is waiting for some leaf ll strictly below qq, then m(q)m(q) is in the stack SqS_q;
  • (J3) if qq is not the root and m(q)m(q) is in SqS_q, the pointer of its entry is at least the position of m(parent(q))m(\mathit{parent}(q)) in Sparent(q)S_{\mathit{parent}(q)}.

An entry keeps its position while it is in a stack, because stacks change only at the top. By J1, if m(q)m(q) is waiting, then m(y)m(y) is waiting for every yy in QqQ_q: the waiting nodes of a match are closed downward. In particular, no node of an ended subtree QcQ_c has a waiting element in any match, since a waiting m(y)m(y) would give a waiting leaf below yy whose stream is exhausted.

Lemma 1 (getNext). Suppose J holds when getNext(q)\mathrm{getNext}(q) is called on a node qq that is not ended, and let xx be the node it returns. Then:

  • (a) no drop at line L12 during the call takes an element m(y)m(y) of a match mm;
  • (b) L(x)<∞L(x) < \infty, and xx is a node of QqQ_q that is not ended;
  • (c) let P=QqP = Q_q if x=qx = q and P=Qparent(x)P = Q_{\mathit{parent}(x)} otherwise; for every match mm and every yy in PP with m(y)m(y) waiting, L(x)≤m(y).startL(x) \le m(y).\mathit{start};
  • (d) if every edge of QqQ_q has axis //, the heads h(y)h(y) for yy in QxQ_x form a match of QxQ_x.

Proof. By induction on the height of qq. If qq is a leaf, then x=qx = q (line L9) and there is no drop. TqT_q is not exhausted, since qq is not ended, and for y=qy = q a waiting m(q)m(q) has L(q)≤m(q).startL(q) \le m(q).\mathit{start}. Property (d) holds with one node.

Let qq be internal. At least one child is not ended, since qq is not ended. Line L10 calls getNext on each live child cc in turn. Drops in these calls take no match element by the induction hypothesis, so J still holds, and the waiting elements stay waiting. If a call returns n≠cn \ne c, then getNext(q)\mathrm{getNext}(q) returns nn, and (a) to (d) follow from the hypothesis for cc, because parent(n)\mathit{parent}(n) is in QcQ_c.

Otherwise every live child cc returned cc, so L(c)<∞L(c) < \infty and L(c)≤m(y).startL(c) \le m(y).\mathit{start} for each waiting m(y)m(y) with yy in QcQ_c. Later calls on other children change only heads of other subtrees, so these facts still hold. Line L11 chooses the live child nmin⁡n_{\min} with the smallest LL and sets far\mathit{far} to the largest L(c)L(c) over all children, with ∞\infty for an ended child.

(a) Suppose line L12 drops h(q)h(q), so R(q)<farR(q) < \mathit{far}, and h(q)=m(q)h(q) = m(q) for a match mm, so that m(q)m(q) is waiting. If some child cc is ended, then m(l)m(l) is taken for a leaf ll of QcQ_c, and by J1 so is m(q)m(q), which is false. If no child is ended, let cc be a child with L(c)=farL(c) = \mathit{far}. Then m(c)m(c) is waiting, and L(c)≤m(c).start<m(q).end=R(q)<far=L(c)L(c) \le m(c).\mathit{start} < m(q).\mathit{end} = R(q) < \mathit{far} = L(c), which is false. After a drop, J still holds, so the same argument applies to the next head.

(b) Line L13 returns qq only when L(q)<L(nmin⁡)<∞L(q) < L(n_{\min}) < \infty, and otherwise it returns nmin⁡n_{\min}, which is live with L(nmin⁡)<∞L(n_{\min}) < \infty.

(c) Let mm be a match and yy a node with m(y)m(y) waiting. There is no such yy in an ended subtree. If x=qx = q: for y=qy = q, L(q)≤m(q).startL(q) \le m(q).\mathit{start}, because by (a) the drops did not pass m(q)m(q); for yy in QcQ_c with cc live, L(q)<L(nmin⁡)≤L(c)≤m(y).startL(q) < L(n_{\min}) \le L(c) \le m(y).\mathit{start}. If x=nmin⁡x = n_{\min}, then parent(x)=q\mathit{parent}(x) = q and P=QqP = Q_q: for y=qy = q, L(nmin⁡)≤L(q)≤m(q).startL(n_{\min}) \le L(q) \le m(q).\mathit{start}, and for yy in QcQ_c, L(nmin⁡)≤L(c)≤m(y).startL(n_{\min}) \le L(c) \le m(y).\mathit{start}.

(d) If x=nmin⁡x = n_{\min}, use the hypothesis for nmin⁡n_{\min}. If x=qx = q, no child is ended, because then far=∞\mathit{far} = \infty, line L12 exhausts TqT_q, and qq is not returned. For each child cc, L(q)<L(c)L(q) < L(c), and R(q)≥far≥L(c)R(q) \ge \mathit{far} \ge L(c), with R(q)≠L(c)R(q) \ne L(c) because codes are distinct. So h(c)h(c) starts inside the interval of h(q)h(q), and since the intervals are nested or disjoint, h(c)h(c) is a descendant of h(q)h(q). With the matches of each QcQ_c formed by the heads, from the hypothesis, the heads form a match of QqQ_q. □\square

Theorem 1 (completeness). J holds during the whole run, and for every match mm and every leaf ll, the path solution of mm on the path from the root to ll is output.

Proof. At the start nothing is taken, so J holds. Consider one iteration, with x=getNext(root)x = \mathrm{getNext}(\mathit{root}) at line L2, s=L(x)<∞s = L(x) < \infty by Lemma 1(b), and p=parent(x)p = \mathit{parent}(x) when xx is not the root. Let PP be as in Lemma 1(c), so P=QpP = Q_p, or all of QQ when xx is the root.

Line L3. cleanStack pops from SpS_p only entries with end below ss. Suppose it pops m(p)m(p) while m(l)m(l) is waiting for a leaf ll below pp. Since ll is in PP, Lemma 1(c) gives s≤m(l).start<m(p).end<ss \le m(l).\mathit{start} < m(p).\mathit{end} < s, which is false. So J2 holds after line L3.

Lines L4 and L5. Suppose h(x)=m(x)h(x) = m(x) for a match mm. If xx is not the root, then m(p)m(p) is taken: otherwise it is waiting, and Lemma 1(c) gives s≤m(p).start<m(x).start=ss \le m(p).\mathit{start} < m(x).\mathit{start} = s. So m(p)m(p) was pushed by J1, and since m(x)m(x) and all leaves below xx are waiting, m(p)m(p) is in SpS_p by J2. So SpS_p is not empty and m(x)m(x) is pushed, not skipped. The cleanStack of SxS_x in line L5 keeps every m′(x)m'(x) that has a waiting leaf below it, by the argument of line L3, since that leaf is in PP. The new entry points to the top of SpS_p, at least the position of m(p)m(p), which gives J3. So J1, J2 and J3 hold after line L5.

Line L7. By the above, a skipped head is not m(x)m(x) for any match mm, so J1 holds. Drops keep J by Lemma 1(a).

Line L6. Let xx be a leaf with h(x)=m(x)h(x) = m(x). Before the push, m(x)m(x) is waiting, so by J1 and J2 every m(q)m(q) on the path from the root to xx, except m(x)m(x), is in its stack. By J3 the pointer of each entry on this path is at least the position of the element of the parent. The output step visits every entry of the parent stack at a position up to the pointer, keeps those that satisfy the edge, and continues from the pointer of each. So it visits m(p)m(p), then the element of the parent of pp, and so on up to the root, and it outputs the path solution of mm.

The loop ends when the root is ended, that is, when all leaf streams are exhausted. Then every m(l)m(l) is taken, so by J1 it was pushed, and its path solution was output at line L6. □\square

Theorem 2 (correctness and termination). TwigStack ends, and it outputs every match of QQ exactly once and nothing else.

Proof. Each iteration takes an element from a stream that is not exhausted (line L5 or L7), by Lemma 1(b), and each drop takes one, so the run ends after at most ∑q∣Tq∣\sum_q |T_q| iterations. Each output path solution takes its elements from the streams of the path, so the tags are right, and line L6 checks every edge of the path, so it is an embedding of the path. A stack holds distinct elements, and each leaf element is pushed once, so each path solution is output once. Line L8 joins the path solutions on the shared query nodes. The result is the set of maps whose restriction to every root-to-leaf path is an output path solution. Every edge of QQ lies on some root-to-leaf path, so each such map is a match, and by Theorem 1 every match is in the result, once. ■\blacksquare

Theorem 3 (no useless path solutions). If every edge of QQ has axis //, every path solution that TwigStack outputs is the restriction of a match to its path. So for each leaf the number of path solutions is at most the number of matches.

Proof. Let (e0,…,et)(e_0, \dots, e_t) be an output path solution on the path q0,…,qtq_0, \dots, q_t from the root to the leaf qtq_t. Each eie_i was pushed at a time when getNext returned qiq_i and ei=h(qi)e_i = h(q_i). By Lemma 1(d), at that time the heads of QqiQ_{q_i} formed a match μi\mu_i of QqiQ_{q_i} with μi(qi)=ei\mu_i(q_i) = e_i. Define m(qi)=eim(q_i) = e_i, and for each child cc of qiq_i that is not qi+1q_{i+1}, let mm agree with μi\mu_i on QcQ_c. Each node of QQ is on the path or in exactly one such QcQ_c. The edges of the path hold because line L6 checked them; an edge from qiq_i to cc holds because μi(c)\mu_i(c) is a descendant of μi(qi)=ei\mu_i(q_i) = e_i; and the edges inside QcQ_c hold because μi\mu_i is a match. So mm is a match whose restriction to the path is the path solution. Distinct path solutions of one leaf are restrictions of distinct matches. ■\blacksquare

With an edge of axis /, Lemma 1(d) fails: the heads are nested, but not necessarily parent and child. In the document a(b(c))a(b(c)) and the twig with root aa, a child bb on an edge //, and a child cc on an edge /, TwigStack pushes aa because cc lies inside it, outputs the path solution (a,b)(a, b), and finds no match, because cc is not a child of aa.

Complexity

  • Reads. Each element of each stream is read once, in order, so the streams can be scanned from disk. The main loop runs at most nn times, and each call of GETNEXT visits each query node at most once, which gives O(kn)O(k n) for the scan with the exhausted streams tracked by counters.
  • Path solutions. For twigs with only // edges, each leaf has at most zz path solutions, so there are at most lzl z of them, each of length at most kk. Bruno et al. prove that TwigStack then runs in time and I/O linear in the size of the input and the output, with the query size as a factor.
  • Space. Each stack is a chain of nested elements, so it holds at most dd entries. The path solutions are kept until line L8, or written to disk in sorted order and merged.
  • Parent-child edges. The bound in the front matter is for twigs with only // edges. With / edges, the number of path solutions is not bounded by the output. In the document a(b(c))a(b(c)), the twig a[.//b]/c gives the path solution (a,b)(a, b) and no match.

Properties

  • Holistic. The algorithm treats the twig as one unit. A plan of binary structural joins has to choose an order, and each intermediate result is a match of part of the twig that may not extend to the whole.
  • Streaming. Each stream is read once from the front, so the input needs only a sort by start, which an index on tags provides.
  • Output order. Path solutions of a leaf come out in order of the leaf element. The final join needs them sorted on the common prefix, or a hash table.
  • Non-injective matches. Two sibling query nodes with the same tag can match the same element, as in XPath.

Variants and improvements

  • PathStack. For a twig that is a single path, the same stacks give the matches directly, without the join of line L8. Bruno et al. give it in the same paper.
  • Skipping with an index. Bruno et al. also use a B-tree variant on each stream, so that line L12 and the advance of line L7 can skip many elements at once.
  • Look-ahead for parent-child edges. Lu, Chen and Ling (2004) look ahead in the streams before a push, to avoid many useless path solutions when the twig has / edges. Choi, Mahoui and Wood (2003) studied the limits of optimality for such twigs.
  • Binary structural joins. Al-Khalifa et al. (2002) join two streams at a time on ancestor-descendant or parent-child with a stack. A plan of such joins is simpler, but its intermediate results can be much larger than the output.

When to use it

Use a holistic twig join when XML or other tree-shaped data is stored with region codes and an index on tags, and queries are twigs of a few nodes, mainly with // edges. With many / edges a look-ahead variant is better, and with a selective index on values a navigation from the few candidate elements can be faster.

Pitfalls

  • Region codes from different walks. The ancestor test needs start and end values from one walk of one document. Codes of different documents need a document id in front.
  • An exhausted subtree. If GETNEXT goes into a child whose leaf streams are all exhausted, it can return a node with an empty stream, and the main loop then makes no progress. The implementation skips such children and treats them as infinitely far.
  • Parent-child edges. The level test removes wrong combinations, so the result is correct, but the path solutions are no longer bounded by the output.
  • Non-strict tests. The ancestor test must be strict on both sides. Since all codes of one walk are distinct, a test with ≤\le in place of << makes an element its own ancestor.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

dbrel.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the databases pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Naive relations, operators by definition, SQL three-valued logic and a page-counting disk.

This is the reference that the tests of the databases pages compare against.
Every operator here follows its definition directly, with nested loops and no
index, hash table or sort of the input. Do not use it as a fast engine.

Relations
    Relation(schema, rows, mode) holds a tuple of distinct attribute names and
    a collections.Counter from tuples to positive counts. mode is "bag" (the
    default, SQL semantics) or "set" (relational theory); in set mode every
    count is 1. rows may be an iterable of tuples (duplicates add up) or a
    mapping from tuples to counts. Two relations are equal when they have the
    same attributes (in any column order) and the same count for each tuple.
    The mode is not compared.

Operators (each returns a new Relation in the mode of its input)
    select(rel, pred)            keeps a row only when pred(row) is True
    where(rel, pred)             the same as select (the SQL WHERE filter)
    project(rel, attrs)          bag: counts add up; set: duplicates removed
    rename(rel, mapping)         mapping is {old: new}
    union(r, s)                  bag: UNION ALL (counts add); set: union
    difference(r, s)             bag: monus max(0, m - n); set: r - s
    intersection(r, s)           bag: min(m, n); set: intersection
    product(r, s)                attributes must be disjoint; counts multiply
    natural_join(r, s)           nested loops on the common attributes
    theta_join(r, s, pred)       select(product(r, s), pred)
    semijoin(r, s), antijoin(r, s)
    distinct(rel)                every count becomes 1
    aggregate(rel, group_attrs, aggs)
                                 aggs is a list of (func, attr, out) with func in
                                 count_star, count, count_distinct, sum, avg, min, max

A predicate receives the row as a dict from attribute name to value. It may
return True, False or None (UNKNOWN). Only True keeps the row.

Nulls
    NULL is None. Joins follow SQL: a common attribute that is None in either
    row never matches. aggregate follows SQL: GROUP BY puts all nulls of a
    column in one group, every aggregate except count_star skips nulls, and
    sum, avg, min and max of no non-null value give None while count gives 0.
    With no grouping attributes, aggregate returns one row even for an empty
    input, as SQL does.

Expressions
    evaluate(expr, db, mode) evaluates a tree of nested tuples:
        ("scan", name)
        ("select", pred, e)          ("project", attrs, e)
        ("rename", mapping, e)       ("distinct", e)
        ("union", e1, e2)            ("difference", e1, e2)
        ("intersection", e1, e2)     ("product", e1, e2)
        ("join", e1, e2)             ("theta_join", pred, e1, e2)
        ("semijoin", e1, e2)         ("antijoin", e1, e2)
        ("aggregate", group_attrs, aggs, e)
    db maps a name to a Relation. Each scanned relation is first put in mode.

Three-valued logic
    tv_and, tv_or and tv_not are the strong Kleene connectives on True, False
    and None. cmp3(op, x, y) compares with op in =, <>, !=, <, <=, >, >= and
    returns None when x or y is None.

Disk
    Disk counts page reads and writes. load(rows, per_page) puts an existing
    input on the disk without counting it. paginate(rows, per_page) splits a
    list of rows into pages.

Random data
    random_relation(rng, schema, n, domain, mode, null_rate) draws n rows.
"""

from collections import Counter
from collections.abc import Callable, Hashable, Iterable, Mapping, Sequence
from fractions import Fraction
from numbers import Number
import random

BAG = "bag"
SET = "set"
MODES = (BAG, SET)


# ---------------------------------------------------------------- ordering

def value_key(v: object) -> tuple:
    """A total order on the values of one column: None first, then numbers, then strings."""
    if v is None:
        return (0, 0)
    if isinstance(v, Number):
        return (1, v)
    if isinstance(v, str):
        return (2, v)
    if isinstance(v, tuple):
        return (3, tuple(value_key(x) for x in v))
    return (4, repr(v))


def row_key(t: Sequence) -> tuple:
    """A total order on tuples that tolerates None. Use it to sort rows in tests."""
    return tuple(value_key(v) for v in t)


# ---------------------------------------------------------------- relations

class Relation:
    """A relation: a schema (tuple of names), a Counter of tuples and a mode."""

    __slots__ = ("schema", "rows", "mode")

    def __init__(self, schema: Sequence[str], rows: Iterable | Mapping = (), mode: str = BAG) -> None:
        if mode not in MODES:
            raise ValueError("mode must be 'bag' or 'set'")
        schema = tuple(schema)
        if len(set(schema)) != len(schema):
            raise ValueError("duplicate attribute in schema %r" % (schema,))
        counts: Counter = Counter()
        items = rows.items() if isinstance(rows, Mapping) else ((t, 1) for t in rows)
        for t, c in items:
            t = tuple(t)
            if len(t) != len(schema):
                raise ValueError("tuple %r does not fit schema %r" % (t, schema))
            if c < 0:
                raise ValueError("negative count for %r" % (t,))
            if c:
                counts[t] += c
        if mode == SET:
            counts = Counter({t: 1 for t in counts})
        self.schema = schema
        self.rows = counts
        self.mode = mode

    def index(self, attr: str) -> int:
        return self.schema.index(attr)

    def reorder(self, schema: Sequence[str]) -> "Relation":
        """The same relation with its columns in the order of schema."""
        schema = tuple(schema)
        if sorted(schema) != sorted(self.schema):
            raise ValueError("schemas %r and %r differ" % (self.schema, schema))
        pos = [self.schema.index(a) for a in schema]
        return Relation(schema, {tuple(t[i] for i in pos): c for t, c in self.rows.items()}, self.mode)

    def with_mode(self, mode: str) -> "Relation":
        return Relation(self.schema, self.rows, mode)

    def as_dict(self, t: Sequence) -> dict:
        return dict(zip(self.schema, t))

    def sorted_rows(self) -> list:
        """Every tuple, repeated by its count, in row_key order."""
        out = []
        for t in sorted(self.rows, key=row_key):
            out.extend([t] * self.rows[t])
        return out

    def __iter__(self):
        return iter(self.sorted_rows())

    def __len__(self) -> int:
        return sum(self.rows.values())

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Relation):
            return NotImplemented
        if sorted(self.schema) != sorted(other.schema):
            return False
        return self.rows == other.reorder(self.schema).rows

    def __repr__(self) -> str:
        body = ", ".join("%r: %d" % (t, self.rows[t]) for t in sorted(self.rows, key=row_key))
        return "Relation(%r, {%s}, %r)" % (self.schema, body, self.mode)


def _mode2(r: Relation, s: Relation) -> str:
    if r.mode != s.mode:
        raise ValueError("operands have modes %r and %r" % (r.mode, s.mode))
    return r.mode


def _same_schema(r: Relation, s: Relation) -> Relation:
    """s with its columns in the order of r; the attribute sets must be equal."""
    if sorted(r.schema) != sorted(s.schema):
        raise ValueError("union-incompatible schemas %r and %r" % (r.schema, s.schema))
    return s.reorder(r.schema)


# ---------------------------------------------------------------- three-valued logic

def tv_and(a: bool | None, b: bool | None) -> bool | None:
    if a is False or b is False:
        return False
    if a is None or b is None:
        return None
    return True


def tv_or(a: bool | None, b: bool | None) -> bool | None:
    if a is True or b is True:
        return True
    if a is None or b is None:
        return None
    return False


def tv_not(a: bool | None) -> bool | None:
    return None if a is None else not a


_CMP = {
    "=": lambda x, y: x == y,
    "<>": lambda x, y: x != y,
    "!=": lambda x, y: x != y,
    "<": lambda x, y: x < y,
    "<=": lambda x, y: x <= y,
    ">": lambda x, y: x > y,
    ">=": lambda x, y: x >= y,
}


def cmp3(op: str, x: object, y: object) -> bool | None:
    """SQL comparison: None (UNKNOWN) if either side is NULL."""
    if op not in _CMP:
        raise ValueError("unknown comparison %r" % (op,))
    if x is None or y is None:
        return None
    return bool(_CMP[op](x, y))


def is_true(v: bool | None) -> bool:
    """The WHERE test: only True passes; False and None (UNKNOWN) do not."""
    return v is True


# ---------------------------------------------------------------- operators

def select(rel: Relation, pred: Callable[[dict], bool | None]) -> Relation:
    out = {t: c for t, c in rel.rows.items() if pred(rel.as_dict(t)) is True}
    return Relation(rel.schema, out, rel.mode)


where = select


def project(rel: Relation, attrs: Sequence[str]) -> Relation:
    attrs = tuple(attrs)
    pos = [rel.index(a) for a in attrs]
    out: Counter = Counter()
    for t, c in rel.rows.items():
        out[tuple(t[i] for i in pos)] += c
    return Relation(attrs, out, rel.mode)


def rename(rel: Relation, mapping: Mapping[str, str]) -> Relation:
    for a in mapping:
        if a not in rel.schema:
            raise ValueError("no attribute %r to rename" % (a,))
    return Relation(tuple(mapping.get(a, a) for a in rel.schema), rel.rows, rel.mode)


def union(r: Relation, s: Relation) -> Relation:
    mode = _mode2(r, s)
    s = _same_schema(r, s)
    out = Counter(r.rows)
    out.update(s.rows)
    return Relation(r.schema, out, mode)


def difference(r: Relation, s: Relation) -> Relation:
    mode = _mode2(r, s)
    s = _same_schema(r, s)
    out = {t: max(0, c - s.rows.get(t, 0)) for t, c in r.rows.items()}
    return Relation(r.schema, out, mode)


def intersection(r: Relation, s: Relation) -> Relation:
    mode = _mode2(r, s)
    s = _same_schema(r, s)
    out = {t: min(c, s.rows.get(t, 0)) for t, c in r.rows.items()}
    return Relation(r.schema, out, mode)


def product(r: Relation, s: Relation) -> Relation:
    mode = _mode2(r, s)
    common = [a for a in r.schema if a in s.schema]
    if common:
        raise ValueError("product needs disjoint schemas; common: %r" % (common,))
    out: Counter = Counter()
    for t, c in r.rows.items():
        for u, d in s.rows.items():
            out[t + u] += c * d
    return Relation(r.schema + s.schema, out, mode)


def _matches(r: Relation, s: Relation, t: tuple, u: tuple, common: Sequence[str]) -> bool:
    for a in common:
        x, y = t[r.index(a)], u[s.index(a)]
        if x is None or y is None or x != y:
            return False
    return True


def natural_join(r: Relation, s: Relation) -> Relation:
    """Nested loops over both inputs. With no common attribute it is the product."""
    mode = _mode2(r, s)
    common = [a for a in r.schema if a in s.schema]
    rest = [a for a in s.schema if a not in common]
    rest_pos = [s.index(a) for a in rest]
    out: Counter = Counter()
    for t, c in r.rows.items():
        for u, d in s.rows.items():
            if _matches(r, s, t, u, common):
                out[t + tuple(u[i] for i in rest_pos)] += c * d
    return Relation(r.schema + tuple(rest), out, mode)


def theta_join(r: Relation, s: Relation, pred: Callable[[dict], bool | None]) -> Relation:
    return select(product(r, s), pred)


def semijoin(r: Relation, s: Relation) -> Relation:
    """Rows of r (with their counts) that join with at least one row of s."""
    _mode2(r, s)
    common = [a for a in r.schema if a in s.schema]
    out = {t: c for t, c in r.rows.items() if any(_matches(r, s, t, u, common) for u in s.rows)}
    return Relation(r.schema, out, r.mode)


def antijoin(r: Relation, s: Relation) -> Relation:
    """Rows of r (with their counts) that join with no row of s."""
    _mode2(r, s)
    common = [a for a in r.schema if a in s.schema]
    out = {t: c for t, c in r.rows.items() if not any(_matches(r, s, t, u, common) for u in s.rows)}
    return Relation(r.schema, out, r.mode)


def distinct(rel: Relation) -> Relation:
    return Relation(rel.schema, {t: 1 for t in rel.rows}, rel.mode)


AGG_FUNCS = ("count_star", "count", "count_distinct", "sum", "avg", "min", "max")


def _avg(vals: list) -> object:
    total = sum(vals)
    if all(isinstance(v, (int, Fraction)) for v in vals):
        return Fraction(total, 1) / len(vals)
    return total / len(vals)


def agg_value(func: str, vals: list) -> object:
    """One SQL aggregate over a list of column values (with repeats). count_star counts all."""
    if func == "count_star":
        return len(vals)
    nn = [v for v in vals if v is not None]
    if func == "count":
        return len(nn)
    if func == "count_distinct":
        seen: list = []
        for v in nn:
            if v not in seen:
                seen.append(v)
        return len(seen)
    if not nn:
        return None
    if func == "sum":
        return sum(nn)
    if func == "avg":
        return _avg(nn)
    if func == "min":
        return min(nn)
    if func == "max":
        return max(nn)
    raise ValueError("unknown aggregate %r" % (func,))


def aggregate(rel: Relation, group_attrs: Sequence[str], aggs: Sequence[tuple]) -> Relation:
    """gamma_{G; f(A) -> B}(rel) by definition.

    aggs is a list of (func, attr, out); attr is ignored for count_star and may
    be None. For each distinct group key, in row_key order, the whole input is
    scanned. Each result row has count 1 in either mode.
    """
    group_attrs = tuple(group_attrs)
    gpos = [rel.index(a) for a in group_attrs]
    for func, attr, _ in aggs:
        if func not in AGG_FUNCS:
            raise ValueError("unknown aggregate %r" % (func,))
        if func != "count_star":
            rel.index(attr)
    keys: list = []
    for t in rel.rows:
        k = tuple(t[i] for i in gpos)
        if k not in keys:
            keys.append(k)
    if not group_attrs and not keys:
        keys = [()]
    out: Counter = Counter()
    for k in sorted(keys, key=row_key):
        row = list(k)
        for func, attr, _ in aggs:
            vals: list = []
            for t, c in rel.rows.items():
                if tuple(t[i] for i in gpos) == k:
                    vals.extend([None if func == "count_star" else t[rel.index(attr)]] * c)
            row.append(agg_value(func, vals))
        out[tuple(row)] = 1
    schema = group_attrs + tuple(o for _, _, o in aggs)
    return Relation(schema, out, rel.mode)


# ---------------------------------------------------------------- evaluation

def evaluate(expr: tuple, db: Mapping[str, Relation], mode: str = BAG) -> Relation:
    """Evaluate an expression tree of nested tuples over db, in mode."""
    if mode not in MODES:
        raise ValueError("mode must be 'bag' or 'set'")
    op = expr[0]
    ev = lambda e: evaluate(e, db, mode)
    if op == "scan":
        return db[expr[1]].with_mode(mode)
    if op == "select":
        return select(ev(expr[2]), expr[1])
    if op == "project":
        return project(ev(expr[2]), expr[1])
    if op == "rename":
        return rename(ev(expr[2]), expr[1])
    if op == "distinct":
        return distinct(ev(expr[1]))
    if op == "aggregate":
        return aggregate(ev(expr[3]), expr[1], expr[2])
    if op == "theta_join":
        return theta_join(ev(expr[2]), ev(expr[3]), expr[1])
    binary = {
        "union": union, "difference": difference, "intersection": intersection,
        "product": product, "join": natural_join, "semijoin": semijoin, "antijoin": antijoin,
    }
    if op in binary:
        return binary[op](ev(expr[1]), ev(expr[2]))
    raise ValueError("unknown operator %r" % (op,))


# ---------------------------------------------------------------- disk

def paginate(rows: Sequence, per_page: int) -> list:
    """Split rows into pages of per_page rows; the last page may be shorter."""
    if per_page < 1:
        raise ValueError("per_page must be at least 1")
    rows = list(rows)
    return [rows[i:i + per_page] for i in range(0, len(rows), per_page)]


class Disk:
    """Pages on a simulated disk. Each read_page and write_page call costs one I/O."""

    def __init__(self) -> None:
        self.pages: dict = {}
        self.reads = 0
        self.writes = 0
        self._next = 0

    def alloc(self) -> int:
        pid = self._next
        self._next += 1
        self.pages[pid] = ()
        return pid

    def write_page(self, pid: int, rows: Iterable) -> None:
        if pid not in self.pages:
            raise KeyError("page %r was not allocated" % (pid,))
        self.pages[pid] = tuple(rows)
        self.writes += 1

    def read_page(self, pid: int) -> list:
        self.reads += 1
        return list(self.pages[pid])

    def free(self, pid: int) -> None:
        del self.pages[pid]

    def load(self, rows: Sequence, per_page: int) -> list:
        """Store an input file without counting I/O; return its page ids in order."""
        ids = []
        for page in paginate(rows, per_page):
            pid = self.alloc()
            self.pages[pid] = tuple(page)
            ids.append(pid)
        return ids

    def io(self) -> int:
        return self.reads + self.writes

    def reset_counters(self) -> None:
        self.reads = 0
        self.writes = 0


# ---------------------------------------------------------------- random data

def random_relation(rng: random.Random, schema: Sequence[str], n: int,
                    domain: int | Sequence | Mapping = 4, mode: str = BAG,
                    null_rate: float = 0.0) -> Relation:
    """n rows drawn with rng. domain is a size k (values 0 to k - 1), a list of
    values, or a dict from attribute to either. Each value is None with
    probability null_rate. In set mode duplicates collapse, so there may be
    fewer than n rows."""
    schema = tuple(schema)

    def values(a: str) -> list:
        d = domain[a] if isinstance(domain, Mapping) else domain
        return list(range(d)) if isinstance(d, int) else list(d)

    doms = [values(a) for a in schema]
    rows = []
    for _ in range(n):
        t = []
        for d in doms:
            if null_rate and rng.random() < null_rate:
                t.append(None)
            else:
                t.append(rng.choice(d))
        rows.append(tuple(t))
    return Relation(schema, rows, mode)
holistic_twig_join.py 195 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/holistic-twig-join/. The authors are listed in prov/JKP2FG.jsonl.

"""TwigStack, the holistic twig join of Bruno, Koudas and Srivastava (2002).

A document is an ordered tree of elements. Each element has the region code
(start, end, level) from one depth-first walk: start is the counter on entry,
end the counter on exit and level the depth. Element u is an ancestor of v when
u.start < v.start and v.end < u.end, and the parent of v when it is also one
level higher.

A twig is a tree of query nodes. Node q has a tag and, if it is not the root,
an axis to its parent: "//" (ancestor-descendant) or "/" (parent-child). A
match maps every query node to an element with its tag so that each edge holds.
Two query nodes may map to the same element when that is allowed by the edges.

For every query node q, the stream T_q lists the elements with the tag of q in
order of start. TwigStack keeps one stack S_q per query node; the entries of a
stack form a chain of nested elements, and each entry points to the top of the
parent stack at the time of its push. It outputs the path solutions of every
root-to-leaf path and then joins them on the shared query nodes.
"""

from collections import namedtuple

Elem = namedtuple("Elem", "start end level tag")
INF = float("inf")


def encode(tags: list, parent: list) -> list:
    """Region codes for a document given by tags[i] and parent[i] (-1 for the root, children in order of i)."""
    kids = [[] for _ in tags]
    roots = []
    for i, p in enumerate(parent):
        (roots if p < 0 else kids[p]).append(i)
    out = [None] * len(tags)
    clock = 0
    stack = [(r, 0, False) for r in reversed(roots)]
    start = {}
    while stack:
        v, lev, done = stack.pop()
        if done:
            out[v] = Elem(start[v], clock, lev, tags[v])
            clock += 1
            continue
        start[v] = clock
        clock += 1
        stack.append((v, lev, True))
        stack.extend((c, lev + 1, False) for c in reversed(kids[v]))
    return out


def is_ancestor(u: Elem, v: Elem) -> bool:
    return u.start < v.start and v.end < u.end


def holds(axis: str, u: Elem, v: Elem) -> bool:
    """The edge test: v is a descendant ("//") or a child ("/") of u."""
    return is_ancestor(u, v) and (axis == "//" or v.level == u.level + 1)


class Twig:
    """Query nodes 0..k-1; node 0 is the root. nodes[q] = (tag, parent, axis)."""

    def __init__(self, nodes: list) -> None:
        self.tag = [t for t, _, _ in nodes]
        self.parent = [p for _, p, _ in nodes]
        self.axis = [a for _, _, a in nodes]
        self.kids = [[] for _ in nodes]
        for q, p in enumerate(self.parent):
            if q:
                assert 0 <= p < q, "list a parent before its children"
                self.kids[p].append(q)
        self.leaves = [q for q in range(len(nodes)) if not self.kids[q]]

    def path(self, q: int) -> list:
        out = [q]
        while self.parent[out[-1]] >= 0:
            out.append(self.parent[out[-1]])
        return out[::-1]

    def subtree_leaves(self, q: int) -> list:
        return [l for l in self.leaves if q in self.path(l)]


def twig_stack(twig: Twig, elems: list):
    """Return (matches, stats). A match is a tuple with one element per query node.

    stats holds "path_solutions" (a dict from leaf to its list of path
    solutions, each a tuple of elements along the root-to-leaf path) and "steps",
    one (query node, element, action) per element taken from a stream: "push"
    (line L5), "skip" (line L7) or "drop" (line L12, inside getNext).
    """
    k = len(twig.tag)
    stream = [sorted((e for e in elems if e.tag == twig.tag[q]), key=lambda e: e.start) for q in range(k)]
    pos = [0] * k
    stacks = [[] for _ in range(k)]  # entries (element, index of the top of the parent stack or -1)
    leaves_below = [twig.subtree_leaves(q) for q in range(k)]
    paths = {l: [] for l in twig.leaves}
    steps = []
    stats = {"path_solutions": paths, "steps": steps}

    eof = lambda q: pos[q] >= len(stream[q])
    next_l = lambda q: INF if eof(q) else stream[q][pos[q]].start
    next_r = lambda q: INF if eof(q) else stream[q][pos[q]].end
    ended = lambda q: all(eof(l) for l in leaves_below[q])

    def clean_stack(q: int, act_l) -> None:
        s = stacks[q]
        while s and s[-1][0].end < act_l:
            s.pop()

    def get_next(q: int) -> int:
        if not twig.kids[q]:
            return q  # @line L9
        live = [c for c in twig.kids[q] if not ended(c)]
        for c in live:
            n = get_next(c)
            if n != c:
                return n  # @line L10
        n_min = min(live, key=next_l)
        far = max(INF if ended(c) else next_l(c) for c in twig.kids[q])  # @line L11
        while next_r(q) < far:
            steps.append((q, stream[q][pos[q]], "drop"))
            pos[q] += 1  # @line L12
        return q if next_l(q) < next_l(n_min) else n_min  # @line L13

    def show_solutions(leaf: int) -> None:
        path = twig.path(leaf)
        out = paths[leaf]

        def up(i: int, top: int, suffix: tuple) -> None:
            q = path[i]
            for j in range(min(top, len(stacks[q]) - 1) + 1):
                e, ptr = stacks[q][j]
                child = suffix[0] if suffix else None
                if child is not None and not holds(twig.axis[path[i + 1]], e, child):
                    continue
                if i == 0:
                    out.append((e,) + suffix)
                else:
                    up(i - 1, ptr, (e,) + suffix)

        e, ptr = stacks[leaf][-1]
        if len(path) == 1:
            out.append((e,))
        else:
            up(len(path) - 2, ptr, (e,))

    root = 0
    while not ended(root):  # @line L1
        q = get_next(root)  # @line L2
        p = twig.parent[q]
        if q != root:
            clean_stack(p, next_l(q))  # @line L3
        if q == root or stacks[p]:  # @line L4
            clean_stack(q, next_l(q))
            stacks[q].append((stream[q][pos[q]], len(stacks[p]) - 1 if p >= 0 else -1))
            steps.append((q, stream[q][pos[q]], "push"))
            pos[q] += 1  # @line L5
            if not twig.kids[q]:
                show_solutions(q)
                stacks[q].pop()  # @line L6
        else:
            steps.append((q, stream[q][pos[q]], "skip"))
            pos[q] += 1  # @line L7
    return merge(twig, paths), stats  # @line L8


def merge(twig: Twig, paths: dict) -> list:
    """Join the path solutions of all leaves on their shared query nodes, one leaf at a time."""
    k = len(twig.tag)
    acc = None
    for leaf in twig.leaves:
        path = twig.path(leaf)
        rows = [dict(zip(path, sol)) for sol in paths[leaf]]
        if acc is None:
            acc = rows
            continue
        common = [q for q in path if q in acc[0]] if acc else []
        index = {}
        for r in rows:
            index.setdefault(tuple(r[q] for q in common), []).append(r)
        acc = [{**a, **r} for a in acc for r in index.get(tuple(a[q] for q in common), [])]
    return sorted(tuple(m[q] for q in range(k)) for m in (acc or []))


def useless(twig: Twig, paths: dict, matches: list) -> int:
    """The number of path solutions that are not part of any match."""
    count = 0
    for leaf in twig.leaves:
        path = twig.path(leaf)
        used = {tuple(m[q] for q in path) for m in matches}
        count += sum(1 for sol in paths[leaf] if sol not in used)
    return count
test_holistic_twig_join.py 124 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/holistic-twig-join/. The authors are listed in prov/JKP2FG.jsonl.

import random
from collections import Counter

import dbrel
from holistic_twig_join import Twig, encode, is_ancestor, twig_stack, useless

# The example of the page: a1(b1, a2(b2, c1), c2, a3(b3)).
NAMES = ["a1", "b1", "a2", "b2", "c1", "c2", "a3", "b3"]
PARENT = [-1, 0, 0, 2, 2, 0, 0, 6]


def oracle(twig: Twig, elems: list) -> Counter:
    """The twig as a chain of theta joins over one relation (start, end, level) per query node."""
    db = {}
    for q, tag in enumerate(twig.tag):
        db["E%d" % q] = dbrel.Relation(("s%d" % q, "e%d" % q, "l%d" % q),
                                       [(e.start, e.end, e.level) for e in elems if e.tag == tag])
    expr = ("scan", "E0")
    for q in range(1, len(twig.tag)):
        p, pc = twig.parent[q], twig.axis[q] == "/"

        def edge(r, p=p, q=q, pc=pc):
            inside = r["s%d" % p] < r["s%d" % q] and r["e%d" % q] < r["e%d" % p]
            return inside and (not pc or r["l%d" % q] == r["l%d" % p] + 1)

        expr = ("theta_join", edge, expr, ("scan", "E%d" % q))
    rel = dbrel.evaluate(expr, db)
    rel = dbrel.project(rel, ["s%d" % q for q in range(len(twig.tag))])
    return Counter(rel.rows)


def as_starts(matches: list) -> Counter:
    return Counter(tuple(e.start for e in m) for m in matches)


def random_doc(rng: random.Random, n: int) -> list:
    tags = [rng.choice("abc") for _ in range(n)]
    parent = [-1] + [rng.randrange(i) for i in range(1, n)]
    return encode(tags, parent[:n])


def random_twig(rng: random.Random, k: int, pc_rate: float) -> Twig:
    nodes = [(rng.choice("abc"), -1, None)]
    for q in range(1, k):
        nodes.append((rng.choice("abc"), rng.randrange(q), "/" if rng.random() < pc_rate else "//"))
    return Twig(nodes)


def test_region_encoding() -> None:
    elems = encode([n[0] for n in NAMES], PARENT)
    assert [(e.start, e.end, e.level) for e in elems[:3]] == [(0, 15, 0), (1, 2, 1), (3, 8, 1)]

    def anc(u, v):
        while PARENT[v] >= 0:
            v = PARENT[v]
            if v == u:
                return True
        return False

    for u in range(len(NAMES)):
        for v in range(len(NAMES)):
            assert is_ancestor(elems[u], elems[v]) == anc(u, v)


def test_example() -> None:
    elems = encode([n[0] for n in NAMES], PARENT)
    name = {e: NAMES[i] for i, e in enumerate(elems)}
    twig = Twig([("a", -1, None), ("b", 0, "//"), ("c", 0, "//")])
    matches, stats = twig_stack(twig, elems)
    steps = [(twig.tag[q], name[e], act) for q, e, act in stats["steps"]]
    assert steps == [("a", "a1", "push"), ("b", "b1", "push"), ("a", "a2", "push"), ("b", "b2", "push"),
                     ("c", "c1", "push"), ("c", "c2", "push"), ("a", "a3", "drop"), ("b", "b3", "push")]
    paths = {leaf: [tuple(name[e] for e in s) for s in sols] for leaf, sols in stats["path_solutions"].items()}
    assert paths == {1: [("a1", "b1"), ("a1", "b2"), ("a2", "b2"), ("a1", "b3")],
                     2: [("a1", "c1"), ("a2", "c1"), ("a1", "c2")]}
    assert len(matches) == 7 and ("a2", "b2", "c1") in [tuple(name[e] for e in m) for m in matches]
    assert useless(twig, stats["path_solutions"], matches) == 0


def test_random_against_dbrel() -> None:
    rng = random.Random(2)
    for trial in range(150):
        elems = random_doc(rng, rng.randrange(0, 31))
        twig = random_twig(rng, rng.randrange(1, 5), rng.choice([0.0, 0.5, 1.0]))
        matches, _ = twig_stack(twig, elems)
        assert as_starts(matches) == oracle(twig, elems)


def test_ancestor_descendant_twigs_have_no_useless_path_solutions() -> None:
    rng = random.Random(3)
    for trial in range(400):
        elems = random_doc(rng, rng.randrange(1, 60))
        twig = random_twig(rng, rng.randrange(1, 6), 0.0)
        matches, stats = twig_stack(twig, elems)
        assert useless(twig, stats["path_solutions"], matches) == 0
        used = {(q, m[q]) for m in matches for q in range(len(twig.tag))}
        taken = [(q, e) for q, e, act in stats["steps"]]
        assert all(act == "push" for q, e, act in stats["steps"] if (q, e) in used)
        assert used <= set(taken)


def test_parent_child_edge_gives_useless_path_solution() -> None:
    elems = encode(["a", "b", "c"], [-1, 0, 1])
    twig = Twig([("a", -1, None), ("b", 0, "//"), ("c", 0, "/")])
    matches, stats = twig_stack(twig, elems)
    assert matches == []
    assert [tuple(e.tag for e in s) for s in stats["path_solutions"][1]] == [("a", "b")]
    assert useless(twig, stats["path_solutions"], matches) == 1


def test_edges() -> None:
    one = Twig([("a", -1, None)])
    assert twig_stack(one, [])[0] == []
    elems = encode(["a", "a", "b"], [-1, 0, 1])
    assert [tuple(e.start for e in m) for m in twig_stack(one, elems)[0]] == [(0,), (1,)]
    assert twig_stack(Twig([("a", -1, None), ("c", 0, "//")]), elems)[0] == []
    # Two query nodes with the same tag on one path: a//a.
    assert as_starts(twig_stack(Twig([("a", -1, None), ("a", 0, "//")]), elems)[0]) == Counter({(0, 1): 1})
    # Two sibling query nodes may map to the same element.
    sib = Twig([("a", -1, None), ("b", 0, "//"), ("b", 0, "//")])
    assert as_starts(twig_stack(sib, elems)[0]) == Counter({(0, 2, 2): 1, (1, 2, 2): 1})

History

Zhang, Naughton, DeWitt, Luo and Lohman (2001) stored XML in relations with region codes and evaluated containment queries with joins. Al-Khalifa, Jagadish, Koudas, Patel, Srivastava and Wu (2002) gave stack-based binary structural joins. Bruno, Koudas and Srivastava (SIGMOD 2002) gave PathStack and TwigStack, which process the whole twig at once, and proved that TwigStack is optimal for twigs with only ancestor-descendant edges. Later work, such as that of Choi, Mahoui and Wood (2003) and of Lu, Chen and Ling (2004), studied twigs with parent-child edges.

References

  1. Nicolas Bruno, Nick Koudas and Divesh Srivastava, Holistic twig joins: optimal XML pattern matching, SIGMOD 2002, pages 310 to 321, the algorithms PathStack and TwigStack, getNext, the proof of correctness and the optimality for twigs with only ancestor-descendant edges
  2. Shurug Al-Khalifa, H. V. Jagadish, Nick Koudas, Jignesh M. Patel, Divesh Srivastava and Yuqing Wu, Structural joins: a primitive for efficient XML query pattern matching, ICDE 2002, pages 141 to 152, binary structural joins on region codes with stacks, which a plan of binary joins combines
  3. Chun Zhang, Jeffrey Naughton, David DeWitt, Qiong Luo and Guy Lohman, On supporting containment queries in relational database management systems, SIGMOD 2001, pages 425 to 436, the region encoding of elements and containment joins on it
  4. Byron Choi, Malika Mahoui and Derick Wood, On the optimality of holistic algorithms for twig queries, DEXA 2003, Lecture Notes in Computer Science, pages 28 to 37, the limits of optimality of holistic twig algorithms when the twig has parent-child edges
  5. Jiaheng Lu, Ting Chen and Tok Wang Ling, Efficient processing of XML twig patterns with parent child edges: a look-ahead approach, CIKM 2004, pages 533 to 542, a look-ahead variant of TwigStack for twigs with parent-child edges

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example