Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-plan/src/why.rs

use std::collections::{HashMap, VecDeque};
use std::sync::OnceLock;

use kleene_graph::Side;
use kleene_sparse::Csr;

use crate::facts::Facts;
use crate::ids::Ids;
use crate::rules::{Cond, Part, Plan, RelId, RelKind, RuleId, Term, Value, Var, instantiate};
use crate::typed::Dict;

/// Why a fact holds: the rule and the facts it was derived from, down to input facts.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Proof {
    /// The relation.
    pub rel: RelId,
    /// The fact.
    pub tuple: Vec<Value>,
    /// How it holds.
    pub how: How,
    /// For a fact of a stratum of rounds ([`crate::Plan::rounds`]): the round that derived
    /// it (from 1); its premises are proven as of the rounds that round read.
    pub round: Option<u32>,
}

/// How a fact holds.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum How {
    /// It is an input fact.
    Input,
    /// An external relation (an index or a producer) answered it.
    External,
    /// A rule derived it.
    Rule {
        /// The rule.
        rule: RuleId,
        /// The rule's variables and the values they took (the rule's conditions hold
        /// under them).
        binding: Vec<(Var, Value)>,
        /// The positive body atoms, as proven facts.
        premises: Vec<Proof>,
        /// The negated body atoms, as facts that do not hold (their relations are
        /// complete when the rule runs; a part of rounds as of the round it was read at).
        absent: Vec<(RelId, Vec<Value>)>,
    },
    /// An aggregate rule reduced a group of its body's bindings to this fact.
    Aggregate {
        /// The rule.
        rule: RuleId,
        /// The values the head took: the grouping variables and the result (a count's
        /// variable, the chosen binding of a min or max, the single value of exactly-one,
        /// a rank's binding and its position).
        binding: Vec<(Var, Value)>,
        /// The bindings the result rests on, each proven: every distinct counted tuple of
        /// a count (one binding each), the chosen binding of a min or max, the single one
        /// of exactly-one, the fact's own (first) binding of a rank.
        members: Vec<Member>,
        /// Distinct bindings the reduction looked at: the count, 1 for exactly-one, the
        /// candidates of a min or max; for a rank, its group's number of distinct keys (the
        /// position is under it).
        size: usize,
    },
    /// A fact of a counted relation ([`crate::Plan::derived_counted`]): the rows its
    /// counting rules ([`crate::Plan::count_rule`]) gave the tuple, added up.
    Counted {
        /// One per counting rule that gave the tuple, in rule order: each a proof of
        /// [`How::Aggregate`] whose tuple is the fact's with that rule's count (its members
        /// the rule's distinct bindings, each weighing the product of the counts of its
        /// counted premises). The parts' counts add up to the fact's.
        parts: Vec<Proof>,
    },
    /// A set number rule ([`crate::Aggregate::set_number`]) gave this fact: its group's
    /// bindings make a set, and the set has `number` in the table of sets `table`.
    Numbered {
        /// The rule.
        rule: RuleId,
        /// The values the head took: the grouping variables and the set's number.
        binding: Vec<(Var, Value)>,
        /// The group's member rows: each distinct binding of the group, proven.
        members: Vec<Member>,
        /// The table of sets.
        table: RelId,
        /// The set's number in it.
        number: Value,
    },
    /// A fact `(n, element..)` of a table of sets ([`crate::Plan::sets`]): set `n` was
    /// first given by the numbered fact `first` (the least of those that numbered it at
    /// that moment, in row order), whose set holds the element.
    Set {
        /// The set's number.
        number: Value,
        /// The proof of the numbered fact that first gave the set.
        first: Box<Proof>,
    },
}

/// One binding of an aggregate rule's body, proven.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Member {
    /// The rule's variables and their values (the rule's conditions hold under them).
    pub binding: Vec<(Var, Value)>,
    /// The positive body atoms, as proven facts.
    pub premises: Vec<Proof>,
    /// The negated body atoms, as facts that do not hold.
    pub absent: Vec<(RelId, Vec<Value>)>,
}

impl Proof {
    /// The number of rule steps in the proof.
    pub fn steps(&self) -> usize {
        match &self.how {
            How::Input | How::External => 0,
            How::Rule { premises, .. } => 1 + premises.iter().map(Proof::steps).sum::<usize>(),
            How::Aggregate { members, .. } | How::Numbered { members, .. } => {
                1 + members
                    .iter()
                    .flat_map(|m| &m.premises)
                    .map(Proof::steps)
                    .sum::<usize>()
            }
            How::Counted { parts } => parts.iter().map(Proof::steps).sum(),
            How::Set { first, .. } => first.steps(),
        }
    }

    /// The longest chain of rule steps down to an input.
    pub fn depth(&self) -> usize {
        match &self.how {
            How::Input | How::External => 0,
            How::Rule { premises, .. } => 1 + premises.iter().map(Proof::depth).max().unwrap_or(0),
            How::Aggregate { members, .. } | How::Numbered { members, .. } => {
                1 + members
                    .iter()
                    .flat_map(|m| &m.premises)
                    .map(Proof::depth)
                    .max()
                    .unwrap_or(0)
            }
            How::Counted { parts } => parts.iter().map(Proof::depth).max().unwrap_or(0),
            How::Set { first, .. } => first.depth(),
        }
    }

    /// This proof of a run of the plan the index choice made from `written`
    /// ([`crate::Engine::index_choice`]), as a proof of `written`: each step of one of its
    /// rules has the premises of the rule's body atoms as written (a premise the run proved
    /// for the atom kept, an input or external atom the choice replaced by its lookup an
    /// input or external fact), so no relation the choice put in shows.
    pub(crate) fn into_written(self, written: &Plan) -> Proof {
        let n = written.rules().len();
        let premises_of = |rule: RuleId, binding: &[(Var, Value)], ran: Vec<Proof>| {
            let mut ran: Vec<Proof> = ran.into_iter().map(|q| q.into_written(written)).collect();
            written
                .rule_at(rule)
                .body
                .iter()
                .map(|a| {
                    let tuple: Option<Vec<Value>> =
                        a.terms.iter().map(|t| t.value(binding)).collect();
                    let tuple = tuple.expect("a body atom's variables are bound");
                    match ran.iter().position(|q| q.rel == a.rel && q.tuple == tuple) {
                        Some(i) => ran.remove(i),
                        None => Proof {
                            rel: a.rel,
                            how: match written.relation_info(a.rel).kind {
                                RelKind::External => How::External,
                                _ => How::Input,
                            },
                            tuple,
                            round: None,
                        },
                    }
                })
                .collect::<Vec<Proof>>()
        };
        let how = match self.how {
            How::Rule {
                rule,
                binding,
                premises,
                absent,
            } if rule.index() < n => How::Rule {
                premises: premises_of(rule, &binding, premises),
                rule,
                binding,
                absent,
            },
            How::Aggregate {
                rule,
                binding,
                members,
                size,
            } if rule.index() < n => How::Aggregate {
                members: members
                    .into_iter()
                    .map(|m| Member {
                        premises: premises_of(rule, &m.binding, m.premises),
                        binding: m.binding,
                        absent: m.absent,
                    })
                    .collect(),
                rule,
                binding,
                size,
            },
            How::Numbered {
                rule,
                binding,
                members,
                table,
                number,
            } if rule.index() < n => How::Numbered {
                members: members
                    .into_iter()
                    .map(|m| Member {
                        premises: premises_of(rule, &m.binding, m.premises),
                        binding: m.binding,
                        absent: m.absent,
                    })
                    .collect(),
                rule,
                binding,
                table,
                number,
            },
            How::Counted { parts } => How::Counted {
                parts: parts.into_iter().map(|q| q.into_written(written)).collect(),
            },
            How::Set { number, first } => How::Set {
                number,
                first: Box::new(first.into_written(written)),
            },
            how => how,
        };
        Proof { how, ..self }
    }

    /// The proof as an indented tree, one fact per line. Values print by their column's
    /// type; a string prints as its id (`#id`) here, as text through
    /// [`crate::Output::render`].
    pub fn render(&self, p: &Plan) -> String {
        self.render_with(p, None)
    }

    /// [`Proof::render`] with the run's strings.
    pub(crate) fn render_with(&self, p: &Plan, dict: Option<&Dict>) -> String {
        let mut out = String::new();
        self.render_into(p, dict, 0, &mut out);
        out
    }

    fn render_into(&self, p: &Plan, dict: Option<&Dict>, indent: usize, out: &mut String) {
        let fact = |rel: RelId, t: &[Value]| {
            let args: Vec<String> = t
                .iter()
                .enumerate()
                .map(|(i, &v)| p.col_type(rel, i).decode(v, dict).to_string())
                .collect();
            format!("{}({})", p.relation_info(rel).name, args.join(", "))
        };
        let pad = "  ".repeat(indent);
        let round = self
            .round
            .map_or(String::new(), |n| format!("  [round {n}]"));
        match &self.how {
            How::Input => out.push_str(&format!("{pad}{}  [input]\n", fact(self.rel, &self.tuple))),
            How::External => out.push_str(&format!(
                "{pad}{}  [external]\n",
                fact(self.rel, &self.tuple)
            )),
            How::Rule {
                rule,
                binding,
                premises,
                absent,
            } => {
                out.push_str(&format!(
                    "{pad}{}  [{}]{round}\n",
                    fact(self.rel, &self.tuple),
                    p.show_rule(*rule)
                ));
                for q in premises {
                    q.render_into(p, dict, indent + 1, out);
                }
                for (rel, t) in absent {
                    out.push_str(&format!("{pad}  !{}  [absent]\n", fact(*rel, t)));
                }
                render_computes(p, dict, *rule, binding, &pad, out);
                render_conds(p, dict, *rule, binding, &pad, out);
            }
            How::Aggregate { rule, members, .. } | How::Numbered { rule, members, .. } => {
                let note = match &self.how {
                    How::Aggregate { size, .. } => format!("{size} in the group"),
                    How::Numbered { table, number, .. } => format!(
                        "set {number} of `{}`, {} member{}",
                        p.relation_info(*table).name,
                        members.len(),
                        if members.len() == 1 { "" } else { "s" }
                    ),
                    _ => unreachable!("an aggregate"),
                };
                out.push_str(&format!(
                    "{pad}{}  [{}]  ({note}){round}\n",
                    fact(self.rel, &self.tuple),
                    p.show_rule(*rule)
                ));
                for m in members {
                    let vals: Vec<String> = m
                        .binding
                        .iter()
                        .map(|&(v, x)| {
                            format!("{}={}", p.var_name(v), p.var_type(*rule, v).decode(x, dict))
                        })
                        .collect();
                    out.push_str(&format!("{pad}  - {}\n", vals.join(" ")));
                    for q in &m.premises {
                        q.render_into(p, dict, indent + 2, out);
                    }
                    for (rel, t) in &m.absent {
                        out.push_str(&format!("{pad}    !{}  [absent]\n", fact(*rel, t)));
                    }
                    render_computes(p, dict, *rule, &m.binding, &format!("{pad}  "), out);
                    render_conds(p, dict, *rule, &m.binding, &format!("{pad}  "), out);
                }
            }
            How::Set { number, first } => {
                out.push_str(&format!(
                    "{pad}{}  [set {number}, first given by]\n",
                    fact(self.rel, &self.tuple)
                ));
                first.render_into(p, dict, indent + 1, out);
            }
            How::Counted { parts } => {
                out.push_str(&format!(
                    "{pad}{}  [the counts of {} counting rule{}]{round}\n",
                    fact(self.rel, &self.tuple),
                    parts.len(),
                    if parts.len() == 1 { "" } else { "s" }
                ));
                for q in parts {
                    q.render_into(p, dict, indent + 1, out);
                }
            }
        }
    }
}

/// Rule `rule`'s computed values under `binding`, one line each with its operands' values
/// in place and its value (`O = LO + I = 3 + 4 = 7`, `F & 4 = 5 & 4 = 4`).
fn render_computes(
    p: &Plan,
    dict: Option<&Dict>,
    rule: RuleId,
    binding: &[(Var, Value)],
    pad: &str,
    out: &mut String,
) {
    for c in &p.rule_at(rule).computes {
        let ty = p.var_type(rule, c.out);
        let value = |v: Var| match Term::Var(v).value(binding) {
            Some(x) => p.var_type(rule, v).decode(x, dict).to_string(),
            None => p.var_name(v).to_string(),
        };
        let with_values = c.expr.show_with(
            &|t| match t {
                Term::Var(v) => value(v),
                Term::Const(k) if ty == crate::typed::Type::F64 => {
                    p.show_const(k, crate::typed::Type::F64)
                }
                Term::Const(k) => k.to_string(),
            },
            &|t| match t {
                Term::Var(v) => value(v),
                Term::Const(k) => p.show_const(k, crate::typed::Type::Str),
            },
        );
        let text = p.show_expr(rule, c);
        let lead = if c.of_test() {
            text
        } else {
            format!("{} = {text}", p.var_name(c.out))
        };
        out.push_str(&format!(
            "{pad}  {lead} = {with_values} = {}  [computed]\n",
            value(c.out)
        ));
    }
}

/// Rule `rule`'s conditions under `binding`, one line each with the values in place (each
/// printed by its type).
fn render_conds(
    p: &Plan,
    dict: Option<&Dict>,
    rule: RuleId,
    binding: &[(Var, Value)],
    pad: &str,
    out: &mut String,
) {
    for c in &p.rule_at(rule).conds {
        let ty = c
            .terms()
            .iter()
            .find_map(|t| match t {
                Term::Var(v) => Some(p.var_type(rule, *v)),
                Term::Const(_) => None,
            })
            .unwrap_or_default();
        let term = |t: Term| match t {
            Term::Var(v) => match t.value(binding) {
                Some(x) => p.var_type(rule, v).decode(x, dict).to_string(),
                None => p.var_name(v).to_string(),
            },
            Term::Const(k) => p.show_const(k, ty),
        };
        let text = match *c {
            Cond::Cmp { left, op, right } => {
                format!("{} {} {}", term(left), op.symbol(), term(right))
            }
            Cond::Within { x, lo, hi } => format!("{} in [{}, {})", term(x), term(lo), term(hi)),
            Cond::IsNull { x, null } => {
                format!("{} is {}null", term(x), if null { "" } else { "not " })
            }
            Cond::Text { x, op, pat } => {
                // the pattern is a string constant of the plan
                let pat = match pat {
                    Term::Const(k) => p.show_const(k, crate::typed::Type::Str),
                    Term::Var(_) => term(pat),
                };
                format!("{} {} {pat}", term(x), op.words())
            }
            Cond::OneOf { x, list, not } => format!(
                "{} {}in {}",
                term(x),
                if not { "not " } else { "" },
                p.show_list(list)
            ),
        };
        out.push_str(&format!("{pad}  {text}  [holds]\n"));
    }
}

/// A rule and the values its variables took: one derivation of a fact.
#[derive(Clone, Debug)]
pub(crate) struct Derivation {
    pub rule: RuleId,
    /// The round of a stratum of rounds that derived it (0: not a round).
    pub round: u32,
    pub binding: Vec<(Var, Value)>,
    /// For an aggregate rule, the bindings the result rests on.
    pub agg: Option<AggWhy>,
}

/// What an aggregate fact rests on.
#[derive(Clone, Debug)]
pub(crate) struct AggWhy {
    pub members: Vec<Vec<(Var, Value)>>,
    pub size: usize,
}

/// What a reach stratum keeps to explain its facts afterwards.
#[derive(Clone, Debug)]
pub(crate) struct ReachWhy {
    pub step: RuleId,
    /// The recursive atom's variable (`X` in `r(Y) :- r(X), e(X, Y)`).
    pub from: Var,
    /// The head's variable (`Y`).
    pub to: Var,
    /// BFS level per vertex (`u32::MAX` when not reached).
    pub levels: Vec<u32>,
    /// Row `v`: the vertices with a step to `v`.
    pub back: Csr<u8>,
    /// The vertices' ids.
    pub ids: Ids,
}

/// What a closure stratum keeps to explain its facts afterwards.
#[derive(Clone, Debug)]
pub(crate) struct ClosureWhy {
    pub step: RuleId,
    pub side: Side,
    /// `x`, `y`, `z` of `t(X,Z) :- t(X,Y), e(Y,Z)` (right) or `t(X,Z) :- e(X,Y), t(Y,Z)`.
    pub vars: [Var; 3],
    pub base: Csr<u8>,
    pub edges: Csr<u8>,
    /// `base` and `edges` transposed: built once, by the first proof that walks against them.
    pub base_t: OnceLock<Csr<u8>>,
    pub edges_t: OnceLock<Csr<u8>>,
    /// The vertices' ids.
    pub ids: Ids,
}

impl ClosureWhy {
    /// What a closure stratum keeps; the transposes are built when a proof first needs them.
    pub fn new(
        step: RuleId,
        side: Side,
        vars: [Var; 3],
        base: Csr<u8>,
        edges: Csr<u8>,
        ids: Ids,
    ) -> Self {
        ClosureWhy {
            step,
            side,
            vars,
            base,
            edges,
            base_t: OnceLock::new(),
            edges_t: OnceLock::new(),
            ids,
        }
    }
}

/// What a labelled reach stratum keeps to explain its facts afterwards: the graph it
/// walked, which entries each edge passed, the labels behind that, and the seeds.
#[derive(Clone, Debug)]
pub(crate) struct LabelWhy {
    pub step: RuleId,
    /// `E`, `S`, `T`, `L` of `r(E, T) :- r(E, S), edge(S, T, L), has(L, E)`.
    pub vars: [Var; 4],
    /// The column of the relation that holds the entry.
    pub entry: usize,
    /// The entries, rising; entry `k` is bit `k`.
    pub entries: Vec<Value>,
    /// The walked graph (one slot per distinct source and target).
    pub graph: Csr<u8>,
    /// The set of each slot, and the sets' words (`words` per set).
    pub slot_set: Vec<u32>,
    pub set_words: Vec<u64>,
    pub words: usize,
    /// Slot `j`'s labels are `labels[label_off[j]..label_off[j + 1]]`, as label ids; label
    /// id `i` is the value `label_values[i]` and passes set `i`.
    pub label_off: Vec<u32>,
    pub labels: Vec<u32>,
    pub label_values: Vec<Value>,
    /// The seed vertices of each entry.
    pub seeds: Vec<Vec<u32>>,
    /// The vertices' ids.
    pub ids: Ids,
}

impl LabelWhy {
    fn passes(&self, set: u32, k: usize) -> bool {
        self.set_words[set as usize * self.words + k / 64] >> (k % 64) & 1 == 1
    }

    /// The parent of every vertex on a fewest-steps walk of entry `k` from its seeds (a
    /// seed is its own parent; `u32::MAX`: not reached).
    fn parents(&self, k: usize) -> Vec<u32> {
        let mut parent = vec![u32::MAX; self.graph.nrows()];
        let mut q = VecDeque::new();
        for &s in &self.seeds[k] {
            if parent[s as usize] == u32::MAX {
                parent[s as usize] = s;
                q.push_back(s);
            }
        }
        let (off, adj) = (
            self.graph.pattern().offsets(),
            self.graph.pattern().indices(),
        );
        while let Some(v) = q.pop_front() {
            for j in off[v as usize] as usize..off[v as usize + 1] as usize {
                let w = adj[j];
                if parent[w as usize] == u32::MAX && self.passes(self.slot_set[j], k) {
                    parent[w as usize] = v;
                    q.push_back(w);
                }
            }
        }
        parent
    }
}

/// The derivations of one relation's joined facts, as columns: per fact (in the sorted
/// order of `facts`) its arrival number, which names a chunk (a batch of derivations of one
/// rule's slot, appended whole) and a row in it; an aggregate fact's members beside, by
/// arrival number.
#[derive(Clone, Debug)]
pub(crate) struct Provenance {
    facts: Facts,
    arrival: Vec<u32>,
    slots: Vec<Slot>,
    chunks: Vec<Chunk>,
    /// The arrival number of each chunk's first row, rising.
    starts: Vec<u32>,
    agg: HashMap<u32, AggWhy>,
}

/// Where a variable's value of a derivation is kept.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Place {
    /// In the fact, at this column (a head variable: not stored again).
    Head(usize),
    /// In this stored column of the chunk.
    Col(usize),
}

/// One rule's derivations' variables in a [`Provenance`]: those the head does not hold are
/// stored, a column each, in the chunks of the slot.
#[derive(Clone, Debug)]
pub(crate) struct Slot {
    rule: RuleId,
    vars: Vec<Var>,
    places: Vec<Place>,
    /// The places in `vars` of the stored variables, in column order.
    stored: Vec<usize>,
}

/// A batch of derivations of one slot: each stored column exactly as long as the batch.
#[derive(Clone, Debug)]
struct Chunk {
    slot: u32,
    round: u32,
    cols: Vec<Vec<Value>>,
}

/// A [`Provenance`] being written as facts arrive: one chunk per batch of new facts, its
/// columns handed over whole (moved when they are the bindings' own), never grown.
#[derive(Clone, Debug, Default)]
pub(crate) struct ProvBuilder {
    slots: Vec<Slot>,
    chunks: Vec<Chunk>,
    starts: Vec<u32>,
    /// Derivations written.
    len: u32,
    agg: HashMap<u32, AggWhy>,
}

/// Derivations of one slot gathered row by row (an aggregate's facts), appended as one
/// chunk ([`ProvBuilder::append_rows`]).
#[derive(Debug)]
pub(crate) struct Rows {
    slot: usize,
    stored: Vec<usize>,
    cols: Vec<Vec<Value>>,
    n: usize,
    agg: Vec<(u32, AggWhy)>,
}

impl Rows {
    /// The next derivation: the values of all the slot's variables (and, for an aggregate,
    /// what it rests on).
    pub(crate) fn push(&mut self, values: &[Value], agg: Option<AggWhy>) {
        for (c, &j) in self.cols.iter_mut().zip(&self.stored) {
            c.push(values[j]);
        }
        if let Some(a) = agg {
            self.agg.push((self.n as u32, a));
        }
        self.n += 1;
    }

    /// The derivations gathered.
    pub(crate) fn len(&self) -> usize {
        self.n
    }
}

impl ProvBuilder {
    /// The slot of rule `r` whose bindings hold `vars` (made the first time); `head` is the
    /// head the facts are made by (the variables it holds are read from the fact).
    pub(crate) fn slot(&mut self, r: RuleId, vars: &[Var], head: &[Term]) -> usize {
        if let Some(i) = self
            .slots
            .iter()
            .position(|s| s.rule == r && s.vars == vars)
        {
            return i;
        }
        let mut stored = Vec::new();
        let places = vars
            .iter()
            .enumerate()
            .map(
                |(j, v)| match head.iter().position(|t| *t == Term::Var(*v)) {
                    Some(c) => Place::Head(c),
                    None => {
                        stored.push(j);
                        Place::Col(stored.len() - 1)
                    }
                },
            )
            .collect();
        self.slots.push(Slot {
            rule: r,
            vars: vars.to_vec(),
            places,
            stored,
        });
        self.slots.len() - 1
    }

    /// The places in the slot's variables of the columns a chunk of it stores, in order.
    pub(crate) fn stored(&self, slot: usize) -> &[usize] {
        &self.slots[slot].stored
    }

    /// The derivations of the next `n` facts to arrive, all of `slot` in `round`: `cols`
    /// holds the stored columns ([`ProvBuilder::stored`]), each exactly `n` long, kept as
    /// they are.
    pub(crate) fn append(&mut self, slot: usize, round: u32, cols: Vec<Vec<Value>>, n: usize) {
        debug_assert!(cols.len() == self.slots[slot].stored.len());
        debug_assert!(cols.iter().all(|c| c.len() == n));
        if n == 0 {
            return;
        }
        self.starts.push(self.len);
        self.chunks.push(Chunk {
            slot: slot as u32,
            round,
            cols,
        });
        self.len += n as u32;
    }

    /// Derivations of `slot` to gather row by row.
    pub(crate) fn rows(&self, slot: usize) -> Rows {
        let stored = self.slots[slot].stored.clone();
        Rows {
            slot,
            cols: vec![Vec::new(); stored.len()],
            stored,
            n: 0,
            agg: Vec::new(),
        }
    }

    /// The derivations gathered in `rows`, of the next facts to arrive, in `round`: one
    /// chunk, its columns cut to their length.
    pub(crate) fn append_rows(&mut self, rows: Rows, round: u32) {
        let at = self.len;
        for (k, a) in rows.agg {
            self.agg.insert(at + k, a);
        }
        let cols = rows
            .cols
            .into_iter()
            .map(|mut c| {
                c.shrink_to_fit();
                c
            })
            .collect();
        self.append(rows.slot, round, cols, rows.n);
    }

    /// The provenance of `facts` (sorted), whose `i`-th row arrived `order[i]`-th.
    pub(crate) fn finish(self, facts: Facts, order: Vec<u32>) -> Provenance {
        Provenance {
            facts,
            arrival: order,
            slots: self.slots,
            chunks: self.chunks,
            starts: self.starts,
            agg: self.agg,
        }
    }
}

impl Provenance {
    /// The derivation of `tuple`, when it is one of the facts.
    fn derivation(&self, tuple: &[Value]) -> Option<Derivation> {
        let k = crate::cols::find_row(&self.facts, tuple)?;
        Some(self.derivation_at(k, tuple))
    }

    /// The facts whose first columns are `prefix` (rows `lo..hi` of the sorted facts).
    fn rows_from(&self, prefix: &[Value]) -> std::ops::Range<usize> {
        let cmp = |k: usize| {
            prefix
                .iter()
                .enumerate()
                .map(|(i, &x)| self.facts.value(i, k).cmp(&x))
                .find(|o| o.is_ne())
                .unwrap_or(std::cmp::Ordering::Equal)
        };
        let n = self.facts.len();
        let lo = partition(n, |k| cmp(k).is_lt());
        let hi = partition(n, |k| cmp(k).is_le());
        lo..hi
    }

    /// The derivation of fact `k`, which is `tuple`.
    fn derivation_at(&self, k: usize, tuple: &[Value]) -> Derivation {
        let a = self.arrival[k];
        let c = self.starts.partition_point(|&s| s <= a) - 1;
        let chunk = &self.chunks[c];
        let row = (a - self.starts[c]) as usize;
        let s = &self.slots[chunk.slot as usize];
        Derivation {
            rule: s.rule,
            round: chunk.round,
            binding: s
                .vars
                .iter()
                .zip(&s.places)
                .map(|(&v, p)| {
                    (
                        v,
                        match *p {
                            Place::Head(j) => tuple[j],
                            Place::Col(j) => chunk.cols[j][row],
                        },
                    )
                })
                .collect(),
            agg: self.agg.get(&a).cloned(),
        }
    }
}

/// The first of `0..n` for which `before` is false (`before` true on a prefix of it).
fn partition(n: usize, before: impl Fn(usize) -> bool) -> usize {
    let (mut lo, mut hi) = (0, n);
    while lo < hi {
        let mid = (lo + hi) / 2;
        if before(mid) {
            lo = mid + 1;
        } else {
            hi = mid;
        }
    }
    lo
}

/// Everything a run keeps to answer "why".
#[derive(Clone, Debug, Default)]
pub(crate) struct WhyStore {
    pub derived: HashMap<RelId, Provenance>,
    /// The derivations of each counted relation's rows as its counting rules gave them,
    /// before they were added up: per row its columns, that rule's count and the rule's
    /// number ([`How::Counted`]).
    pub counted: HashMap<RelId, Provenance>,
    /// The derivations of each fresh part of a stratum of rounds, by round.
    pub rounds: HashMap<(RelId, u32), Provenance>,
    /// Each part of a stratum of rounds: its group, its place in the order, and its kind.
    pub parts: HashMap<RelId, (usize, usize, Part)>,
    pub reach: HashMap<RelId, ReachWhy>,
    pub closure: HashMap<RelId, ClosureWhy>,
    pub label: HashMap<RelId, LabelWhy>,
    /// Per table of sets, per number: the numbered fact that first gave the set (its
    /// relation and tuple) and the round of rounds it came in (0: none).
    pub sets: HashMap<RelId, Vec<(RelId, Vec<Value>, u32)>>,
    /// The proofs of the run this one continued from ([`crate::Engine::continue_from`]),
    /// and the relations whose facts of that run are asked there: a relation continued
    /// keeps here the derivations of its new facts only.
    pub prev: Option<(std::sync::Arc<WhyStore>, std::collections::HashSet<RelId>)>,
}

/// BFS levels from `starts` along the rows of `a`.
fn levels_from(a: &Csr<u8>, starts: &[u32]) -> Vec<u32> {
    let mut level = vec![u32::MAX; a.nrows()];
    let mut q = VecDeque::new();
    for &s in starts {
        if level[s as usize] == u32::MAX {
            level[s as usize] = 0;
            q.push_back(s);
        }
    }
    while let Some(v) = q.pop_front() {
        for &w in a.row(v as usize) {
            if level[w as usize] == u32::MAX {
                level[w as usize] = level[v as usize] + 1;
                q.push_back(w);
            }
        }
    }
    level
}

impl WhyStore {
    /// One derivation of `rel(tuple)`, or `None` when the run did not derive it.
    fn derivation(
        &self,
        rel: RelId,
        tuple: &[Value],
        cache: &mut HashMap<(RelId, u32), Vec<u32>>,
    ) -> Option<Derivation> {
        if let Some(d) = self.derived.get(&rel).and_then(|m| m.derivation(tuple)) {
            return Some(d);
        }
        if let Some(r) = self.reach.get(&rel) {
            let v = r.ids.vertex(*tuple.first()?)?;
            let l = *r.levels.get(v as usize)?;
            if l == 0 || l == u32::MAX {
                return None;
            }
            // (a predecessor of any lower level: in one search that is the level before; a
            // continued search numbers its levels past the old ones)
            let u = r
                .back
                .row(v as usize)
                .iter()
                .copied()
                .find(|&u| r.levels[u as usize] < l)?;
            return Some(Derivation {
                round: 0,
                rule: r.step,
                binding: vec![(r.from, r.ids.id(u)), (r.to, r.ids.id(v))],
                agg: None,
            });
        }
        if let Some(c) = self.closure.get(&rel) {
            let x = c.ids.vertex(*tuple.first()?)?;
            let z = c.ids.vertex(*tuple.get(1)?)?;
            let [vx, vy, vz] = c.vars;
            return match c.side {
                Side::Right => {
                    // Levels from x: base successors at 0, then along the edges.
                    let level = cache
                        .entry((rel, x))
                        .or_insert_with(|| levels_from(&c.edges, c.base.row(x as usize)));
                    let l = level[z as usize];
                    if l == 0 || l == u32::MAX {
                        return None;
                    }
                    let et = c.edges_t.get_or_init(|| c.edges.transpose());
                    let y = et
                        .row(z as usize)
                        .iter()
                        .copied()
                        .find(|&y| level[y as usize] == l - 1)?;
                    Some(Derivation {
                        round: 0,
                        rule: c.step,
                        binding: vec![(vx, c.ids.id(x)), (vy, c.ids.id(y)), (vz, c.ids.id(z))],
                        agg: None,
                    })
                }
                Side::Left => {
                    // Levels back from z: base predecessors at 0, then against the edges.
                    let level = cache.entry((rel, z)).or_insert_with(|| {
                        let bt = c.base_t.get_or_init(|| c.base.transpose());
                        let et = c.edges_t.get_or_init(|| c.edges.transpose());
                        levels_from(et, bt.row(z as usize))
                    });
                    let l = level[x as usize];
                    if l == 0 || l == u32::MAX {
                        return None;
                    }
                    let y = c
                        .edges
                        .row(x as usize)
                        .iter()
                        .copied()
                        .find(|&y| level[y as usize] == l - 1)?;
                    Some(Derivation {
                        round: 0,
                        rule: c.step,
                        binding: vec![(vx, c.ids.id(x)), (vy, c.ids.id(y)), (vz, c.ids.id(z))],
                        agg: None,
                    })
                }
            };
        }
        if let Some(w) = self.label.get(&rel) {
            return self.label_derivation(w, rel, tuple, cache);
        }
        match &self.prev {
            Some((prev, kept)) if kept.contains(&rel) => prev.derivation(rel, tuple, cache),
            _ => None,
        }
    }

    /// One derivation of `rel(tuple)` by the labelled reach `w`.
    fn label_derivation(
        &self,
        w: &LabelWhy,
        rel: RelId,
        tuple: &[Value],
        cache: &mut HashMap<(RelId, u32), Vec<u32>>,
    ) -> Option<Derivation> {
        let e = *tuple.get(w.entry)?;
        let t = w.ids.vertex(*tuple.get(1 - w.entry)?)?;
        let k = w.entries.binary_search(&e).ok()?;
        let parent = cache.entry((rel, k as u32)).or_insert_with(|| w.parents(k));
        let s = *parent.get(t as usize)?;
        if s == u32::MAX || s == t {
            return None;
        }
        let row = w.graph.row(s as usize);
        let j = w.graph.pattern().offsets()[s as usize] as usize + row.binary_search(&t).ok()?;
        let ids = &w.labels[w.label_off[j] as usize..w.label_off[j + 1] as usize];
        let l = ids.iter().find(|&&i| w.passes(i, k))?;
        let [ve, vs, vt, vl] = w.vars;
        Some(Derivation {
            round: 0,
            rule: w.step,
            binding: vec![
                (ve, e),
                (vs, w.ids.id(s)),
                (vt, w.ids.id(t)),
                (vl, w.label_values[*l as usize]),
            ],
            agg: None,
        })
    }

    /// The proof of `rel(tuple)`: input facts are leaves (taken as given); a derived fact
    /// the run did not derive has none.
    pub(crate) fn proof(&self, p: &Plan, rel: RelId, tuple: &[Value]) -> Option<Proof> {
        let mut cache = HashMap::new();
        self.proof_with(p, rel, tuple, None, &mut cache)
    }

    /// The round a premise of relation `of` is read at by a derivation of `head` in round
    /// `round`: a part before it (or itself) as of that round, a part after it as of the
    /// round before; `None` outside a group of rounds.
    fn read_round(&self, head: RelId, of: RelId, round: u32) -> Option<u32> {
        let (g, i, _) = *self.parts.get(&head)?;
        let (h, j, _) = *self.parts.get(&of)?;
        (g == h).then_some(if j > i { round - 1 } else { round })
    }

    /// The proof of `rel(tuple)`, a fresh part's as of round `at`.
    fn proof_with(
        &self,
        p: &Plan,
        rel: RelId,
        tuple: &[Value],
        at: Option<u32>,
        cache: &mut HashMap<(RelId, u32), Vec<u32>>,
    ) -> Option<Proof> {
        let given = |how| {
            Some(Proof {
                rel,
                tuple: tuple.to_vec(),
                how,
                round: None,
            })
        };
        match p.relation_info(rel).kind {
            RelKind::Input => return given(How::Input),
            RelKind::External => return given(How::External),
            RelKind::Derived => {}
        }
        if let Some(pv) = self.counted_of(rel) {
            return self.counted_proof(p, rel, tuple, pv, cache);
        }
        if let Some(first) = self.sets_of(rel) {
            return self.set_proof(p, rel, tuple, first, cache);
        }
        let d = match self.parts.get(&rel) {
            Some(&(_, _, Part::Fresh)) => {
                // as of the round asked; the final facts when asked from outside
                let n = at.unwrap_or_else(|| {
                    self.rounds
                        .keys()
                        .filter(|k| k.0 == rel)
                        .map(|k| k.1)
                        .max()
                        .unwrap_or(0)
                });
                self.rounds.get(&(rel, n))?.derivation(tuple)?
            }
            _ => self.derivation(rel, tuple, cache)?,
        };
        self.proof_of(p, rel, tuple, d, cache)
    }

    /// The counted rows' derivations of `rel`: this run's, or those of the run it
    /// continued from when it kept the relation.
    fn counted_of(&self, rel: RelId) -> Option<&Provenance> {
        if let Some(pv) = self.counted.get(&rel) {
            return Some(pv);
        }
        match &self.prev {
            Some((prev, kept)) if kept.contains(&rel) => prev.counted_of(rel),
            _ => None,
        }
    }

    /// The first facts of table of sets `rel`: this run's, or those of the run it
    /// continued from when it kept the table.
    fn sets_of(&self, rel: RelId) -> Option<&[(RelId, Vec<Value>, u32)]> {
        if let Some(f) = self.sets.get(&rel) {
            return Some(f);
        }
        match &self.prev {
            Some((prev, kept)) if kept.contains(&rel) => prev.sets_of(rel),
            _ => None,
        }
    }

    /// The proof of a table of sets' row `(n, element..)`: the numbered fact that first
    /// gave set `n`, as of the round it came in, when that set holds the element.
    fn set_proof(
        &self,
        p: &Plan,
        rel: RelId,
        tuple: &[Value],
        first: &[(RelId, Vec<Value>, u32)],
        cache: &mut HashMap<(RelId, u32), Vec<u32>>,
    ) -> Option<Proof> {
        let (head, fact, round) = first.get(usize::try_from(*tuple.first()?).ok()?)?;
        let proof = self.proof_with(p, *head, fact, (*round > 0).then_some(*round), cache)?;
        let How::Numbered { rule, members, .. } = &proof.how else {
            return None;
        };
        // the element is one of the set's
        let of = match &p.rule_at(*rule).agg {
            Some(crate::rules::Aggregate {
                agg: crate::rules::Agg::SetNumber { of, .. },
                ..
            }) => of,
            _ => return None,
        };
        let holds = members.iter().any(|m| {
            of.iter()
                .zip(&tuple[1..])
                .all(|(&v, &x)| Term::Var(v).value(&m.binding) == Some(x))
        });
        if !holds {
            return None;
        }
        Some(Proof {
            rel,
            tuple: tuple.to_vec(),
            how: How::Set {
                number: tuple[0],
                first: Box::new(proof),
            },
            round: None,
        })
    }

    /// The proof of counted `rel(tuple)` (its row, then its count): a part per counting
    /// rule that gave the row, those rules' counts adding up to the tuple's.
    fn counted_proof(
        &self,
        p: &Plan,
        rel: RelId,
        tuple: &[Value],
        pv: &Provenance,
        cache: &mut HashMap<(RelId, u32), Vec<u32>>,
    ) -> Option<Proof> {
        let (&n, row) = tuple.split_last()?;
        if row.len() + 2 != pv.facts.arity() {
            return None;
        }
        let mut parts: Vec<(RuleId, Proof)> = Vec::new();
        let mut sum: u64 = 0;
        for k in pv.rows_from(row) {
            // the row with this rule's count, then the rule's number
            let mut part = pv.facts.row(k);
            part.pop();
            sum = sum.checked_add(*part.last()?)?;
            let d = pv.derivation_at(k, &part);
            parts.push((d.rule, self.proof_of(p, rel, &part, d, cache)?));
        }
        if parts.is_empty() || sum != n {
            return None;
        }
        parts.sort_by_key(|q| q.0);
        Some(Proof {
            rel,
            tuple: tuple.to_vec(),
            how: How::Counted {
                parts: parts.into_iter().map(|q| q.1).collect(),
            },
            round: None,
        })
    }

    /// The proof of `rel(tuple)` by derivation `d`.
    fn proof_of(
        &self,
        p: &Plan,
        rel: RelId,
        tuple: &[Value],
        d: Derivation,
        cache: &mut HashMap<(RelId, u32), Vec<u32>>,
    ) -> Option<Proof> {
        let round = (d.round > 0).then_some(d.round);
        let rule = p.rule_at(d.rule);
        let premise = |a: &crate::rules::Atom,
                       b: &[(Var, Value)],
                       cache: &mut HashMap<(RelId, u32), Vec<u32>>| {
            let at = round.and_then(|n| self.read_round(rule.head.rel, a.rel, n));
            self.proof_with(p, a.rel, &instantiate(a, b), at, cache)
        };
        if let Some(aw) = d.agg {
            let numbered = match &rule.agg {
                Some(crate::rules::Aggregate {
                    agg: crate::rules::Agg::SetNumber { out, table, .. },
                    ..
                }) => Some((*table, Term::Var(*out).value(&d.binding)?)),
                _ => None,
            };
            let mut members = Vec::with_capacity(aw.members.len());
            for m in aw.members {
                let mut premises = Vec::with_capacity(rule.body.len());
                for a in &rule.body {
                    premises.push(premise(a, &m, cache)?);
                }
                let absent = rule
                    .negated
                    .iter()
                    .map(|a| (a.rel, instantiate(a, &m)))
                    .collect();
                members.push(Member {
                    binding: m,
                    premises,
                    absent,
                });
            }
            let how = match numbered {
                Some((table, number)) => How::Numbered {
                    rule: d.rule,
                    binding: d.binding,
                    members,
                    table,
                    number,
                },
                None => How::Aggregate {
                    rule: d.rule,
                    binding: d.binding,
                    members,
                    size: aw.size,
                },
            };
            return Some(Proof {
                rel,
                tuple: tuple.to_vec(),
                how,
                round,
            });
        }
        let mut premises = Vec::with_capacity(rule.body.len());
        for a in &rule.body {
            premises.push(premise(a, &d.binding, cache)?);
        }
        let absent = rule
            .negated
            .iter()
            .map(|a| (a.rel, instantiate(a, &d.binding)))
            .collect();
        Some(Proof {
            rel,
            tuple: tuple.to_vec(),
            how: How::Rule {
                rule: d.rule,
                binding: d.binding,
                premises,
                absent,
            },
            round,
        })
    }
}