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/eval/cont.rs

//! A run continued from an earlier run of the same plan ([`Engine::continue_from`]): the
//! inputs read again, each stratum then kept as it was (nothing it reads changed),
//! continued from the rows its inputs gained (the engine's own semi-naive rounds started
//! from those rows, a reach search from its new frontier, counts added), deleted and derived
//! again (joins and recursions of joins reading a relation that lost rows: what derives
//! from a lost row is deleted, what still has a derivation found again, the rounds go on
//! from there; counts take off the counts of the bindings lost), or computed again (it
//! negates or aggregates over a relation that changed, or is a reach or a closure reading
//! one that lost rows). Its facts equal a run from scratch on the same inputs.

use std::collections::hash_map::Entry;

use kleene_sparse::Mask;

use super::*;

/// How a relation stands against the run continued from.
#[derive(Clone, Debug)]
enum Status {
    /// As it was.
    Same,
    /// Its old facts and these, none of them old.
    Grew(Facts),
    /// Its old facts without `lost` (some, all of them old) and with `gained` (none of them
    /// old).
    Lost { gained: Facts, lost: Facts },
    /// Anything else (a count changed, an external replaced, another arity).
    Changed,
}

impl Status {
    /// Whether a stratum reading it can only be computed again.
    fn changed(&self) -> bool {
        matches!(self, Status::Changed)
    }

    /// Whether it lost rows.
    fn lost(&self) -> bool {
        matches!(self, Status::Lost { .. })
    }

    /// The rows it gained (`None`: as it was, or changed).
    fn gained(&self) -> Option<&Facts> {
        match self {
            Status::Grew(d) | Status::Lost { gained: d, .. } => Some(d),
            _ => None,
        }
    }

    /// The status of facts `now` against `old`, `fresh` the rows of `now` found again or
    /// anew and `gone` those of `old` deleted for a while (`now` holds `old` without
    /// `gone`, and `fresh`).
    fn of(par: &Par, gone: &Facts, fresh: &Facts, now: &Facts) -> Status {
        let gained = new_rows(par, gone, fresh);
        let lost = new_rows(par, now, gone);
        match (gained.is_empty(), lost.is_empty()) {
            (true, true) => Status::Same,
            (_, true) => Status::Grew(gained),
            _ => Status::Lost { gained, lost },
        }
    }
}

/// The relations stratum `s` reads, its own left out.
fn reads(p: &Plan, s: &Stratum) -> Vec<RelId> {
    let of_rules = |rules: &[RuleId]| -> Vec<RelId> {
        rules
            .iter()
            .flat_map(|&r| {
                let rule = p.rule_at(r);
                rule.body.iter().chain(&rule.negated).map(|a| a.rel)
            })
            .collect()
    };
    let mut out = match s {
        Stratum::Reach {
            seeds, step, edge, ..
        } => {
            let mut v = of_rules(seeds);
            v.extend(of_rules(&[*step]));
            v.push(*edge);
            v
        }
        Stratum::Closure {
            base, step, edge, ..
        } => {
            let mut v = of_rules(base);
            v.extend(of_rules(&[*step]));
            v.push(*edge);
            v
        }
        Stratum::LabelReach {
            seeds,
            step,
            edge,
            has,
            ..
        } => {
            let mut v = of_rules(seeds);
            v.extend(of_rules(&[*step]));
            v.extend([*edge, *has]);
            v
        }
        Stratum::Walk { from, edge, .. } => vec![*from, *edge],
        Stratum::Procedure {
            edge, procedure, ..
        } => [Some(*edge), procedure.weights()]
            .into_iter()
            .flatten()
            .collect(),
        Stratum::Joins { rules, .. }
        | Stratum::Rounds { rules, .. }
        | Stratum::Sets { rules, .. } => of_rules(rules),
    };
    let own = s.relations();
    out.retain(|r| !own.contains(r));
    out.sort_unstable();
    out.dedup();
    out
}

/// The facts of a source given as added rows (`None`: a kind that is not rows).
fn added_facts(src: &Source) -> Result<Option<Facts>> {
    Ok(Some(match src {
        Source::Facts(f) => f.clone(),
        Source::Columns(cols) => Facts::from_columns(crate::facts::columns_of(cols)?)?,
        Source::ColumnsAt { columns, bases } => Facts::from_columns(crate::facts::columns_of(
            &crate::facts::columns_at(columns, bases)?,
        )?)?,
        Source::Graph { out, .. } => csr_pairs(out),
        Source::GraphAt { out, bases, .. } => csr_pairs_at(out, *bases),
        Source::Table { .. } | Source::External(_) => return Ok(None),
    }))
}

/// Whether two graphs hold the same edges at the same ids.
fn same_graph(a: &GraphAt, b: &GraphAt) -> bool {
    let (x, y) = (&a.0, &b.0);
    a.2 == b.2
        && x.nrows() == y.nrows()
        && x.ncols() == y.ncols()
        && x.pattern().offsets()[..] == y.pattern().offsets()[..]
        && x.pattern().indices()[..] == y.pattern().indices()[..]
}

/// The rows of counted facts (each tuple, then its count) of `parts` with the counts of
/// equal tuples added.
fn add_counts(arity: usize, parts: &[Facts]) -> Result<Facts> {
    let mut sum: std::collections::BTreeMap<Vec<Value>, Value> = Default::default();
    for f in parts {
        for mut r in f.rows() {
            let n = r.pop().expect("a count column");
            let c = sum.entry(r).or_insert(0);
            *c = c
                .checked_add(n)
                .ok_or_else(|| PlanError::Program("a count past u64".into()))?;
        }
    }
    let mut cols: Vec<Vec<Value>> = vec![Vec::with_capacity(sum.len()); arity];
    for (r, n) in sum {
        for (c, x) in cols.iter_mut().zip(r.into_iter().chain([n])) {
            c.push(x);
        }
    }
    Facts::from_columns(cols)
}

/// The pairs of graph `out` (its ids from `bases` on) at the rows whose source values
/// `allowed` names for the atom's first term (`None`: the first term is not such a
/// variable).
fn graph_rows(
    out: &Csr<u8>,
    bases: (Value, Value),
    terms: &[Term],
    allowed: &HashMap<Var, HashSet<Value>>,
) -> Option<Facts> {
    let xs = allowed.get(&var_of(terms.first()?)?)?;
    let mut rows: Vec<Value> = xs
        .iter()
        .filter_map(|&x| x.checked_sub(bases.0))
        .filter(|&i| i < out.nrows() as Value)
        .collect();
    rows.sort_unstable();
    let (mut src, mut dst) = (Vec::new(), Vec::new());
    for i in rows {
        for &y in out.row(i as usize) {
            src.push(bases.0 + i);
            dst.push(bases.1 + Value::from(y));
        }
    }
    Facts::from_columns(vec![src, dst]).ok()
}

/// The rows of `f` (an atom's facts, `terms` its terms) whose values at a variable `allowed`
/// names are among those allowed (a variable it does not name: any value).
fn narrowed(f: &Facts, terms: &[Term], allowed: &HashMap<Var, HashSet<Value>>) -> Result<Facts> {
    let on: Vec<(usize, &HashSet<Value>)> = terms
        .iter()
        .enumerate()
        .filter_map(|(c, t)| Some((c, allowed.get(&var_of(t)?)?)))
        .collect();
    if on.is_empty() {
        return Ok(f.clone());
    }
    let keep: Vec<usize> = (0..f.len())
        .filter(|&i| on.iter().all(|(c, vals)| vals.contains(&f.value(*c, i))))
        .collect();
    if keep.len() == f.len() {
        return Ok(f.clone());
    }
    let cols: Vec<Vec<Value>> = (0..f.arity())
        .map(|c| keep.iter().map(|&i| f.value(c, i)).collect())
        .collect();
    Facts::from_columns(cols)
}

/// Counted facts `have` with the counts of `minus` taken off (each tuple, then its count): a
/// tuple whose count reaches 0 is gone; one taken below 0, or not there, is refused.
fn take_counts(arity: usize, have: &Facts, minus: &[Facts]) -> Result<Facts> {
    if minus.iter().all(Facts::is_empty) {
        return Ok(have.clone());
    }
    let mut sum: std::collections::BTreeMap<Vec<Value>, Value> = Default::default();
    for mut r in have.rows() {
        let n = r.pop().expect("a count column");
        sum.insert(r, n);
    }
    for f in minus {
        for mut r in f.rows() {
            let n = r.pop().expect("a count column");
            let c = sum
                .get_mut(&r)
                .filter(|c| **c >= n)
                .ok_or_else(|| PlanError::Program("a count taken below 0".into()))?;
            *c -= n;
        }
    }
    sum.retain(|_, c| *c > 0);
    let mut cols: Vec<Vec<Value>> = vec![Vec::with_capacity(sum.len()); arity];
    for (r, n) in sum {
        for (c, x) in cols.iter_mut().zip(r.into_iter().chain([n])) {
            c.push(x);
        }
    }
    Facts::from_columns(cols)
}

impl<B: GraphBackend> Engine<B> {
    /// Run `p` on `inputs`, continuing from `prev`, an output of `p` run by this engine on
    /// earlier inputs: `added` holds, for any input that gained rows, exactly the rows it
    /// gained (none of them old; `inputs` holds the old rows and these). An input `added`
    /// does not name is checked against the one `prev` read (as it was, grown, or
    /// changed). Each stratum is then kept as it was when nothing it reads changed,
    /// continued from the gained rows when it can be (joins and recursion through the
    /// engine's semi-naive rounds started from the new rows, counts added, a reach
    /// searched on from its new frontier, a closure grown by rounds), and computed again
    /// when it negates or aggregates over a relation that changed, reads a relation that
    /// lost rows, or is of another kind (a walk, a procedure, a labelled reach, rounds).
    /// The facts equal a run from scratch ([`Engine::run`]) on `inputs`; so do proofs
    /// ([`Output::why`]), those of facts kept from `prev` asked there. A run that cannot
    /// continue (another plan, strings that are not the same, no proofs kept while this
    /// engine explains) runs from scratch. [`StratumReport::continued`] says which strata
    /// did not run again from scratch.
    pub async fn continue_from(
        &self,
        p: &Plan,
        prev: &Output,
        inputs: &Inputs,
        added: &Inputs,
    ) -> Result<Output> {
        self.continue_with_traced(p, prev, inputs, added, &Inputs::new(), &mut NoTrace)
            .await
    }

    /// [`Engine::continue_from`], telling `trace` as it goes.
    pub async fn continue_traced(
        &self,
        p: &Plan,
        prev: &Output,
        inputs: &Inputs,
        added: &Inputs,
        trace: &mut dyn Trace,
    ) -> Result<Output> {
        self.continue_with_traced(p, prev, inputs, added, &Inputs::new(), trace)
            .await
    }

    /// [`Engine::continue_from`] on inputs that also lost rows: `removed` holds, for any
    /// input that lost rows, exactly the rows it lost (all of them old; `inputs` holds the
    /// old rows without these and with those of `added`). An input neither names is
    /// compared with the one `prev` read. A stratum of joins reading a relation that lost
    /// rows deletes what derives from them and derives again what still has a proof; a
    /// count takes off the counts of the bindings lost; a reach or a closure reading one
    /// is computed again. The facts and proofs equal a run from scratch on `inputs`.
    pub async fn continue_with(
        &self,
        p: &Plan,
        prev: &Output,
        inputs: &Inputs,
        added: &Inputs,
        removed: &Inputs,
    ) -> Result<Output> {
        self.continue_with_traced(p, prev, inputs, added, removed, &mut NoTrace)
            .await
    }

    /// [`Engine::continue_with`], telling `trace` as it goes.
    pub async fn continue_with_traced(
        &self,
        p: &Plan,
        prev: &Output,
        inputs: &Inputs,
        added: &Inputs,
        removed: &Inputs,
        trace: &mut dyn Trace,
    ) -> Result<Output> {
        let change = (added, removed);
        if self.index_choice
            && let Some((q, ins, _)) = crate::index::choose_indexes(p, inputs)?
        {
            let mut out = self
                .continue_as(&q, prev, &ins, change, trace, true)
                .await?;
            out.written = Some(Arc::new(p.clone()));
            return Ok(out);
        }
        self.continue_as(p, prev, inputs, change, trace, false)
            .await
    }

    async fn continue_as(
        &self,
        p: &Plan,
        prev: &Output,
        inputs: &Inputs,
        change: (&Inputs, &Inputs),
        trace: &mut dyn Trace,
        chosen: bool,
    ) -> Result<Output> {
        let kept = match &prev.kept {
            Some(k) if k.chosen == chosen && (!self.explain || prev.why.is_some()) => k.clone(),
            _ => return self.run_as(p, inputs, trace, chosen).await,
        };
        let Loaded {
            mut st,
            strata,
            dict,
            resolved,
            load,
            t0,
        } = self.load(p, inputs, chosen).await?;
        let ran: &Plan = resolved.as_deref().unwrap_or(p);
        let mut report = Report {
            load,
            ..Report::default()
        };
        let prev_rules = prev
            .resolved
            .as_deref()
            .map_or(p.rules().len(), |q| q.rules().len());
        if dict.as_deref() != prev.dict.as_deref() || prev_rules != ran.rules().len() {
            // (string codes are the run's: facts of another dictionary are not comparable)
            for (k, stratum) in strata.iter().enumerate() {
                let r = self.stratum(ran, &mut st, k, stratum, trace)?;
                report.strata.push(Self::reported(ran, &mut st, stratum, r));
            }
            report.total = t0.elapsed();
            return Ok(Self::output(st, dict, resolved, report, chosen));
        }
        let mut status = self.input_status(ran, &st, &kept, change)?;
        let mut asked_before: HashSet<RelId> = HashSet::new();
        for (k, stratum) in strata.iter().enumerate() {
            let own = stratum.relations();
            let read = reads(ran, stratum);
            let stat = |r: &RelId| status.get(r).cloned().unwrap_or(Status::Same);
            let r = if read.iter().all(|r| matches!(stat(r), Status::Same))
                && own.iter().all(|r| prev.facts.contains_key(r))
            {
                self.keep_stratum(&mut st, prev, &own, &mut status, &mut asked_before)
            } else if let Some(r) = self.continue_stratum(
                ran,
                &mut st,
                k,
                stratum,
                prev,
                &kept,
                &mut status,
                &mut asked_before,
                trace,
            )? {
                r
            } else {
                let r = self.stratum(ran, &mut st, k, stratum, trace)?;
                for rel in own {
                    let s = self.diff(prev.facts.get(&rel), &st.derived[&rel]);
                    status.insert(rel, s);
                }
                r
            };
            report.strata.push(Self::reported(ran, &mut st, stratum, r));
        }
        if let (Some(why), Some(pw)) = (st.why.as_mut(), &prev.why) {
            why.prev = Some((pw.clone(), asked_before));
        }
        report.total = t0.elapsed();
        Ok(Self::output(st, dict, resolved, report, chosen))
    }

    /// How each input of the run in `st` stands against the run that read `kept`.
    fn input_status(
        &self,
        p: &Plan,
        st: &State,
        kept: &Kept,
        (added, removed): (&Inputs, &Inputs),
    ) -> Result<HashMap<RelId, Status>> {
        let mut out = HashMap::new();
        for (&rel, ext) in &st.externals {
            let same = kept
                .externals
                .get(&rel)
                .is_some_and(|o| std::ptr::addr_eq(Arc::as_ptr(o), Arc::as_ptr(ext)));
            out.insert(rel, if same { Status::Same } else { Status::Changed });
        }
        let given = |from: &Inputs, rel: RelId| -> Result<Option<Facts>> {
            if p.is_typed(rel) {
                // (a typed input's rows are codes of this run: found by comparing below)
                return Ok(None);
            }
            match from.source(rel) {
                Some(src) => added_facts(src),
                None => Ok(None),
            }
        };
        // the rows given as gained and lost, when they account for the new count
        let moved = |rel: RelId, old: usize, new: usize, arity: usize| -> Result<Option<Status>> {
            let (d, l) = (given(added, rel)?, given(removed, rel)?);
            let fits = |f: &Option<Facts>| f.as_ref().is_none_or(|f| f.arity() == arity);
            if !fits(&d) || !fits(&l) {
                return Ok(None);
            }
            let (dn, ln) = (
                d.as_ref().map_or(0, Facts::len),
                l.as_ref().map_or(0, Facts::len),
            );
            if dn + ln == 0 || new + ln != old + dn {
                return Ok(None);
            }
            Ok(Some(match l {
                Some(lost) if ln > 0 => Status::Lost {
                    gained: d.unwrap_or_else(|| Facts::empty(arity)),
                    lost,
                },
                _ => Status::Grew(d.expect("rows gained")),
            }))
        };
        for (&rel, g) in &st.graphs {
            let s = match kept.graphs.get(&rel) {
                Some(old) if same_graph(old, g) => Status::Same,
                Some(old) => match moved(rel, old.0.nnz(), g.0.nnz(), 2)? {
                    Some(s) if g.2 == old.2 => s,
                    _ => self.diff(Some(&csr_pairs_at(&old.0, old.2)), &csr_pairs_at(&g.0, g.2)),
                },
                None => Status::Changed,
            };
            out.insert(rel, s);
        }
        for (&rel, f) in &st.inputs {
            let s = match kept.inputs.get(&rel) {
                Some(old) if old == f => Status::Same,
                Some(old) => match moved(rel, old.len(), f.len(), f.arity())? {
                    Some(s) => s,
                    None => self.diff(Some(old), f),
                },
                None => Status::Changed,
            };
            out.insert(rel, s);
        }
        Ok(out)
    }

    /// `new` against `old`: as it was, grown by the rows `old` lacks, with rows lost too,
    /// or changed (another arity, nothing before).
    fn diff(&self, old: Option<&Facts>, new: &Facts) -> Status {
        let Some(old) = old else {
            return Status::Changed;
        };
        if old == new {
            return Status::Same;
        }
        if old.arity() != new.arity() {
            return Status::Changed;
        }
        let (gained, lost) = (new_rows(&self.par, old, new), new_rows(&self.par, new, old));
        if lost.is_empty() {
            Status::Grew(gained)
        } else {
            Status::Lost { gained, lost }
        }
    }

    /// A stratum nothing of whose reads changed: its facts as `prev` derived them.
    fn keep_stratum(
        &self,
        st: &mut State,
        prev: &Output,
        own: &[RelId],
        status: &mut HashMap<RelId, Status>,
        asked_before: &mut HashSet<RelId>,
    ) -> StratumReport {
        let mut n = 0;
        for &rel in own {
            let f = prev.facts[&rel].clone();
            n += f.len();
            st.derived.insert(rel, f);
            status.insert(rel, Status::Same);
            asked_before.insert(rel);
            if let (Some(why), Some(pw)) = (st.why.as_mut(), &prev.why) {
                // (a table of sets is proven by its first facts)
                if let Some(first) = pw.sets.get(&rel) {
                    why.sets.insert(rel, first.clone());
                }
                // (a fresh part of rounds is proven by round)
                if let Some(&at) = pw.parts.get(&rel) {
                    why.parts.insert(rel, at);
                    for (key, pv) in pw.rounds.iter().filter(|(key, _)| key.0 == rel) {
                        why.rounds.insert(*key, pv.clone());
                    }
                }
            }
        }
        StratumReport {
            kind: "",
            relations: Vec::new(),
            rounds: 0,
            facts: n,
            prepare: Duration::ZERO,
            compute: Duration::ZERO,
            renumbered: false,
            continued: true,
            peak_rows: 0,
            proof_rows: 0,
            indexed_rows: 0,
            range_joins: 0,
            next_rows: 0,
        }
    }

    /// Stratum `k` continued from the rows its reads gained, when it can be (`None`: it
    /// is computed again).
    #[allow(clippy::too_many_arguments)]
    fn continue_stratum(
        &self,
        p: &Plan,
        st: &mut State,
        k: usize,
        stratum: &Stratum,
        prev: &Output,
        kept: &Kept,
        status: &mut HashMap<RelId, Status>,
        asked_before: &mut HashSet<RelId>,
        trace: &mut dyn Trace,
    ) -> Result<Option<StratumReport>> {
        let own = stratum.relations();
        if own.iter().any(|r| !prev.facts.contains_key(r)) {
            return Ok(None);
        }
        let stat = |r: RelId| status.get(&r).cloned().unwrap_or(Status::Same);
        // A rule continues when what it negates is as it was, and what it reads (outside
        // its stratum) only grew; a rule that groups only when nothing it reads changed,
        // except a count into a counted relation (its counts add).
        let rule_ok = |r: RuleId| {
            let rule = p.rule_at(r);
            let outside = |a: &&Atom| !own.contains(&a.rel);
            if rule
                .negated
                .iter()
                .filter(outside)
                .any(|a| !matches!(stat(a.rel), Status::Same))
            {
                return false;
            }
            let counting = rule.fold.as_ref().is_some_and(|f| {
                f.op == crate::rules::FoldOp::Count && p.is_counted(rule.head.rel)
            });
            if rule.groups() && !counting {
                return rule
                    .body
                    .iter()
                    .filter(outside)
                    .all(|a| matches!(stat(a.rel), Status::Same));
            }
            !rule
                .body
                .iter()
                .filter(outside)
                .any(|a| stat(a.rel).changed())
        };
        // a relation it reads lost rows: joins delete and derive again, counts subtract, the
        // rest is computed again
        let lost_read = reads(p, stratum).iter().any(|&r| stat(r).lost());
        let t0 = Instant::now();
        let r = match stratum {
            Stratum::Joins { rels, rules } => {
                if !rules.iter().all(|&r| rule_ok(r)) {
                    return Ok(None);
                }
                if rels.iter().any(|&r| p.is_counted(r)) {
                    // (explained, counted rows run again: their proofs keep each counting
                    // rule's rows, which adding counts does not)
                    if self.explain {
                        return Ok(None);
                    }
                    let recursive = rules
                        .iter()
                        .any(|&r| p.rule_at(r).body.iter().any(|a| rels.contains(&a.rel)));
                    if recursive {
                        return Ok(None);
                    }
                    self.continue_counts(p, st, rels, rules, prev, kept, status)?
                } else if lost_read {
                    if rules.iter().any(|&r| p.rule_at(r).groups()) {
                        return Ok(None);
                    }
                    self.again_joins(
                        p,
                        st,
                        k,
                        rels,
                        rules,
                        prev,
                        kept,
                        status,
                        asked_before,
                        trace,
                    )?
                } else {
                    self.continue_joins(p, st, k, rels, rules, prev, status, asked_before, trace)?
                }
            }
            Stratum::Closure {
                rel,
                base,
                step,
                edge,
                side,
            } => {
                let rules: Vec<RuleId> = base.iter().copied().chain([*step]).collect();
                if lost_read || !rules.iter().all(|&r| rule_ok(r)) || stat(*edge).changed() {
                    return Ok(None);
                }
                let r = self.continue_joins(
                    p,
                    st,
                    k,
                    &[*rel],
                    &rules,
                    prev,
                    status,
                    asked_before,
                    trace,
                )?;
                if st.why.is_some() {
                    // proven as a closure's facts are: the base facts by their rules, the
                    // rest by walks over the base and the edges as they now are
                    asked_before.remove(rel);
                    self.closure_why(p, st, *rel, base, *step, *edge, *side)?;
                }
                r
            }
            Stratum::Reach {
                rel,
                seeds,
                step,
                edge,
                way,
            } => {
                let ok = !lost_read && seeds.iter().all(|&r| rule_ok(r)) && !stat(*edge).changed();
                let edge_rows = match stat(*edge) {
                    Status::Grew(d) => d,
                    _ => Facts::empty(2),
                };
                match ok {
                    true => match self.continue_reach(
                        p, st, k, *rel, seeds, *step, *edge, *way, &edge_rows, prev, status, trace,
                    )? {
                        Some(r) => r,
                        None => return Ok(None),
                    },
                    false => return Ok(None),
                }
            }
            _ => return Ok(None),
        };
        Ok(Some(StratumReport {
            compute: t0.elapsed(),
            continued: true,
            peak_rows: 0,
            proof_rows: 0,
            indexed_rows: 0,
            range_joins: 0,
            next_rows: 0,
            ..r
        }))
    }

    /// A stratum of joins continued: its relations start from their old facts, and the
    /// semi-naive rounds ([`Engine::fixpoint`]) from the rows their reads gained; the
    /// proofs of the new facts kept here, those of the old ones asked of the run before.
    #[allow(clippy::too_many_arguments)]
    fn continue_joins(
        &self,
        p: &Plan,
        st: &mut State,
        k: usize,
        rels: &[RelId],
        rules: &[RuleId],
        prev: &Output,
        status: &mut HashMap<RelId, Status>,
        asked_before: &mut HashSet<RelId>,
        trace: &mut dyn Trace,
    ) -> Result<StratumReport> {
        let mut total: HashMap<RelId, RowSet> = HashMap::new();
        let mut marks: HashMap<RelId, usize> = HashMap::new();
        for &r in rels {
            let mut set = RowSet::new(p.relation_info(r).arity);
            for row in prev.facts[&r].rows() {
                set.insert(&row);
            }
            marks.insert(r, set.len());
            total.insert(r, set);
        }
        let mut prov: HashMap<RelId, ProvBuilder> = if self.explain {
            rels.iter().map(|&r| (r, ProvBuilder::default())).collect()
        } else {
            HashMap::new()
        };
        let gained: HashMap<RelId, Facts> = rules
            .iter()
            .flat_map(|&r| p.rule_at(r).body.iter().map(|a| a.rel))
            .filter(|r| !rels.contains(r))
            .filter_map(|r| match status.get(&r) {
                Some(Status::Grew(d)) if !d.is_empty() => Some((r, d.clone())),
                _ => None,
            })
            .collect();
        let mut ix = Indexes::new();
        let mut on_round = |n, new| trace.round(k, n, new);
        let rounds = self.fixpoint(
            p,
            st,
            rules,
            &mut total,
            &mut prov,
            0,
            &mut ix,
            Some(&gained),
            &mut on_round,
        )?;
        let mut n = 0;
        for (r, set) in total {
            let m = marks[&r];
            let fresh = rows_from(&set.facts(), m);
            let (facts, _) = set.finish(&self.par, false);
            n += facts.len();
            if let (Some(pv), Some(why)) = (prov.remove(&r), st.why.as_mut()) {
                let mut only = RowSet::new(fresh.arity());
                for row in fresh.rows() {
                    only.insert(&row);
                }
                let (sorted, order) = only.finish(&self.par, true);
                why.derived.insert(r, pv.finish(sorted, order));
            }
            asked_before.insert(r);
            status.insert(
                r,
                if fresh.is_empty() {
                    Status::Same
                } else {
                    Status::Grew(fresh)
                },
            );
            st.derived.insert(r, facts);
        }
        Ok(StratumReport {
            kind: "",
            relations: Vec::new(),
            rounds,
            facts: n,
            prepare: Duration::ZERO,
            compute: Duration::ZERO,
            renumbered: false,
            continued: true,
            peak_rows: 0,
            proof_rows: 0,
            indexed_rows: 0,
            range_joins: 0,
            next_rows: 0,
        })
    }

    /// A stratum of joins whose reads lost rows, deleted and derived again: (1) every fact
    /// of the run before with a derivation through a lost row is deleted (the rules run on
    /// the lost rows, everything else as it was, and again on the facts so deleted, until
    /// none is new); (2) of those, each with a derivation from what is left and the inputs
    /// as they now are is found again (each rule run once, its atoms narrowed to the
    /// deleted facts' values first); (3) the semi-naive rounds go on from the facts found
    /// again and the rows the reads gained. The facts kept are proven as the run before
    /// proved them (no proof of theirs goes through a deleted fact), those found here by
    /// their rules here.
    #[allow(clippy::too_many_arguments)]
    fn again_joins(
        &self,
        p: &Plan,
        st: &mut State,
        k: usize,
        rels: &[RelId],
        rules: &[RuleId],
        prev: &Output,
        kept: &Kept,
        status: &mut HashMap<RelId, Status>,
        asked_before: &mut HashSet<RelId>,
        trace: &mut dyn Trace,
    ) -> Result<StratumReport> {
        let arity = |r: RelId| p.relation_info(r).arity;
        // (an index is kept per relation, not per facts: the phases that read the facts of a
        // relation as they were, or narrowed, build their indexes per join)
        // (1) deleted: what derives from a lost row, through the old facts
        let mut gone: HashMap<RelId, RowSet> =
            rels.iter().map(|&r| (r, RowSet::new(arity(r)))).collect();
        let mut delta: HashMap<RelId, Facts> = HashMap::new();
        for &r in rules {
            for a in &p.rule_at(r).body {
                if rels.contains(&a.rel) {
                    continue;
                }
                if let Some(Status::Lost { lost, .. }) = status.get(&a.rel)
                    && !lost.is_empty()
                {
                    delta.insert(a.rel, lost.clone());
                }
            }
        }
        let mut olds: HashMap<RelId, Facts> = HashMap::new();
        let mut rounds = 0u32;
        while !delta.is_empty() {
            rounds += 1;
            let marks: HashMap<RelId, usize> = gone.iter().map(|(&r, s)| (r, s.len())).collect();
            for &r in rules {
                let rule = p.rule_at(r);
                if rule.groups() {
                    continue;
                }
                for (pos, a) in rule.body.iter().enumerate() {
                    let Some(d) = delta.get(&a.rel) else {
                        continue;
                    };
                    let mut ins = Vec::with_capacity(rule.body.len());
                    for (j, b) in rule.body.iter().enumerate() {
                        ins.push(if st.is_external(p, b.rel) {
                            In::External
                        } else if j == pos {
                            In::Facts(d.clone())
                        } else {
                            let f = match olds.entry(b.rel) {
                                Entry::Occupied(o) => o.get().clone(),
                                Entry::Vacant(v) => v
                                    .insert(match prev.facts.get(&b.rel) {
                                        Some(f) if rels.contains(&b.rel) => f.clone(),
                                        _ => self.old_facts(p, st, b.rel, prev, kept, status)?,
                                    })
                                    .clone(),
                            };
                            In::Facts(f)
                        });
                    }
                    let t = self.bindings(p, st, r, &ins, Some(pos), &mut Indexes::new())?;
                    let set = gone.get_mut(&rule.head.rel).expect("own relation");
                    self.heads(p, r, t, set, None, 0)?;
                }
            }
            delta = gone
                .iter()
                .filter(|(r, s)| s.len() > marks[*r])
                .map(|(&r, s)| (r, rows_from(&s.facts(), marks[&r])))
                .collect();
            trace.round(k, rounds, delta.values().map(Facts::len).sum());
        }
        let gone: HashMap<RelId, Facts> = gone
            .into_iter()
            .map(|(r, s)| (r, s.finish(&self.par, false).0))
            .collect();
        // what is left of each relation
        let mut total: HashMap<RelId, RowSet> = HashMap::new();
        let mut marks: HashMap<RelId, usize> = HashMap::new();
        let mut left: HashMap<RelId, Facts> = HashMap::new();
        for &r in rels {
            let rest = new_rows(&self.par, &gone[&r], &prev.facts[&r]);
            let mut set = RowSet::new(arity(r));
            for row in rest.rows() {
                set.insert(&row);
            }
            marks.insert(r, set.len());
            total.insert(r, set);
            left.insert(r, rest);
        }
        let mut prov: HashMap<RelId, ProvBuilder> = if self.explain {
            rels.iter().map(|&r| (r, ProvBuilder::default())).collect()
        } else {
            HashMap::new()
        };
        // (2) found again: each rule once on what is left and the inputs now, its atoms
        // narrowed to the values the deleted facts of its head hold
        for &r in rules {
            let rule = p.rule_at(r);
            let head = rule.head.rel;
            let cand = &gone[&head];
            if rule.groups() || cand.is_empty() {
                continue;
            }
            let mut allowed: HashMap<Var, HashSet<Value>> = HashMap::new();
            for (c, t) in rule.head.terms.iter().enumerate() {
                if let Some(v) = var_of(t) {
                    allowed
                        .entry(v)
                        .or_insert_with(|| (0..cand.len()).map(|i| cand.value(c, i)).collect());
                }
            }
            let mut ins = Vec::with_capacity(rule.body.len());
            for a in &rule.body {
                ins.push(if st.is_external(p, a.rel) {
                    In::External
                } else {
                    // a graph input is read only at the rows the values allow
                    let by_rows = match (left.get(&a.rel), st.graphs.get(&a.rel)) {
                        (None, Some((out, _, bases))) => {
                            graph_rows(out, *bases, &a.terms, &allowed)
                        }
                        _ => None,
                    };
                    let f = match (by_rows, left.get(&a.rel)) {
                        (Some(f), _) => f,
                        (None, Some(f)) => f.clone(),
                        (None, None) => st.facts(p, a.rel)?,
                    };
                    In::Facts(narrowed(&f, &a.terms, &allowed)?)
                });
            }
            let t = self.bindings(p, st, r, &ins, None, &mut Indexes::new())?;
            let set = total.get_mut(&head).expect("own relation");
            st.proof_rows += self.heads(p, r, t, set, prov.get_mut(&head), 0)?;
        }
        // (3) on from those and from the rows the reads gained
        let gained: HashMap<RelId, Facts> = rules
            .iter()
            .flat_map(|&r| p.rule_at(r).body.iter().map(|a| a.rel))
            .filter(|r| !rels.contains(r))
            .filter_map(|r| {
                let d = status.get(&r)?.gained()?;
                (!d.is_empty()).then(|| (r, d.clone()))
            })
            .collect();
        let mut ix = Indexes::new();
        let mut on_round = |n, new| trace.round(k, rounds + n, new);
        rounds += self.fixpoint_from(
            p,
            st,
            rules,
            &mut total,
            &mut prov,
            0,
            &mut ix,
            Some(&gained),
            Some(&marks),
            &mut on_round,
        )?;
        let mut n = 0;
        for (r, set) in total {
            let fresh = rows_from(&set.facts(), marks[&r]);
            let (facts, _) = set.finish(&self.par, false);
            n += facts.len();
            if let (Some(pv), Some(why)) = (prov.remove(&r), st.why.as_mut()) {
                let mut only = RowSet::new(fresh.arity());
                for row in fresh.rows() {
                    only.insert(&row);
                }
                let (sorted, order) = only.finish(&self.par, true);
                why.derived.insert(r, pv.finish(sorted, order));
            }
            asked_before.insert(r);
            status.insert(r, Status::of(&self.par, &gone[&r], &fresh, &facts));
            st.derived.insert(r, facts);
        }
        Ok(StratumReport {
            kind: "",
            relations: Vec::new(),
            rounds,
            facts: n,
            prepare: Duration::ZERO,
            compute: Duration::ZERO,
            renumbered: false,
            continued: true,
            peak_rows: 0,
            proof_rows: 0,
            indexed_rows: 0,
            range_joins: 0,
            next_rows: 0,
        })
    }

    /// The facts of `rel` the run before read or derived: its input as read then, a lower
    /// stratum's facts as derived then.
    fn old_facts(
        &self,
        p: &Plan,
        st: &mut State,
        rel: RelId,
        prev: &Output,
        kept: &Kept,
        status: &HashMap<RelId, Status>,
    ) -> Result<Facts> {
        if matches!(status.get(&rel), None | Some(Status::Same)) {
            return st.facts(p, rel);
        }
        if p.relation_info(rel).kind == RelKind::Derived {
            return prev
                .facts
                .get(&rel)
                .cloned()
                .ok_or_else(|| PlanError::Program("no facts of the run before".into()));
        }
        if let Some((out, _, bases)) = kept.graphs.get(&rel) {
            return Ok(csr_pairs_at(out, *bases));
        }
        kept.inputs
            .get(&rel)
            .cloned()
            .ok_or_else(|| PlanError::Program("no input of the run before".into()))
    }

    /// A stratum of counting rules continued: each rule's new bindings counted (a body atom
    /// that grew read on its gained rows, the atoms before it as they now are, those after
    /// it as they were: every new binding once), the counts added to the old ones.
    #[allow(clippy::too_many_arguments)]
    fn continue_counts(
        &self,
        p: &Plan,
        st: &mut State,
        rels: &[RelId],
        rules: &[RuleId],
        prev: &Output,
        kept: &Kept,
        status: &mut HashMap<RelId, Status>,
    ) -> Result<StratumReport> {
        let mut n = 0;
        let mut rounds = 0;
        for &rel in rels {
            let arity = p.relation_info(rel).arity;
            let mut parts = vec![prev.facts[&rel].clone()];
            let mut minus = Vec::new();
            for &r in rules.iter().filter(|&&r| p.rule_at(r).head.rel == rel) {
                let rule = p.rule_at(r);
                for (pos, a) in rule.body.iter().enumerate() {
                    // the bindings the atom's change makes and unmakes: the atoms before it
                    // as they now are, those after it as they were (every binding once)
                    let (d, l) = match status.get(&a.rel).cloned() {
                        Some(Status::Grew(d)) => (d, None),
                        Some(Status::Lost { gained, lost }) => (gained, Some(lost)),
                        _ => continue,
                    };
                    for (rows, plus) in [(Some(d), true), (l, false)] {
                        let Some(rows) = rows.filter(|f| !f.is_empty()) else {
                            continue;
                        };
                        let mut ins = Vec::with_capacity(rule.body.len());
                        for (j, b) in rule.body.iter().enumerate() {
                            ins.push(if st.is_external(p, b.rel) {
                                In::External
                            } else if j == pos {
                                In::Facts(rows.clone())
                            } else if j < pos {
                                In::Facts(st.facts(p, b.rel)?)
                            } else {
                                In::Facts(self.old_facts(p, st, b.rel, prev, kept, status)?)
                            });
                        }
                        // the same relation read as it is and as it was: no index kept
                        let t = self.bindings(p, st, r, &ins, Some(pos), &mut Indexes::new())?;
                        let mut set = RowSet::new(arity + 1);
                        self.heads(p, r, t, &mut set, None, 0)?;
                        let (f, _) = set.finish(&self.par, false);
                        if plus {
                            parts.push(summed(f)?);
                        } else {
                            minus.push(summed(f)?);
                        }
                        rounds += 1;
                    }
                }
            }
            let facts = take_counts(arity, &add_counts(arity, &parts)?, &minus)?;
            n += facts.len();
            let s = self.diff(prev.facts.get(&rel), &facts);
            status.insert(rel, s);
            st.derived.insert(rel, facts);
        }
        Ok(StratumReport {
            kind: "",
            relations: Vec::new(),
            rounds,
            facts: n,
            prepare: Duration::ZERO,
            compute: Duration::ZERO,
            renumbered: false,
            continued: true,
            peak_rows: 0,
            proof_rows: 0,
            indexed_rows: 0,
            range_joins: 0,
            next_rows: 0,
        })
    }

    /// What a closure stratum keeps to explain its facts, as [`Engine::closure`] keeps it:
    /// the base facts' derivations, the base and the edges as matrices.
    #[allow(clippy::too_many_arguments)]
    fn closure_why(
        &self,
        p: &Plan,
        st: &mut State,
        rel: RelId,
        base: &[RuleId],
        step: RuleId,
        edge: RelId,
        side: Side,
    ) -> Result<()> {
        let b = self.union_of(p, st, base)?;
        let (e, _, ids) = self.edge_matrix(p, st, edge, &[b.column(0), b.column(1)])?;
        let (b0, b1) = (ids.vertices(b.column(0))?, ids.vertices(b.column(1))?);
        let n = e.nrows();
        let bm = Csr::from_edges(n, n, &b0, &b1, None, BoolOrAnd)?;
        let rule = p.rule_at(step);
        let x = rule.head.terms.first().and_then(var_of);
        let z = rule.head.terms.get(1).and_then(var_of);
        if let (Some(x), Some(z), Some(why)) = (x, z, st.why.as_mut())
            && let Some(&y) = rule.vars().iter().find(|&&v| v != x && v != z)
        {
            why.closure
                .insert(rel, ClosureWhy::new(step, side, [x, y, z], bm, e, ids));
        }
        Ok(())
    }

    /// A reach continued: the search goes on from the vertices it newly reaches (new
    /// seeds, and the far ends of new edges from vertices reached before), never into a
    /// vertex reached before; the levels of the new vertices numbered past the old ones,
    /// so a proof walks back to a vertex of a lower level as before. `None`: the run
    /// before kept no levels while this one explains.
    #[allow(clippy::too_many_arguments)]
    fn continue_reach(
        &self,
        p: &Plan,
        st: &mut State,
        k: usize,
        rel: RelId,
        seeds: &[RuleId],
        step: RuleId,
        edge: RelId,
        way: Way,
        edge_rows: &Facts,
        prev: &Output,
        status: &mut HashMap<RelId, Status>,
        trace: &mut dyn Trace,
    ) -> Result<Option<StratumReport>> {
        let t0 = Instant::now();
        let old = prev.facts[&rel].clone();
        let before = match &prev.why {
            Some(w) => w.reach.get(&rel),
            None => None,
        };
        if st.why.is_some() && before.is_none() {
            return Ok(None);
        }
        let seed_facts = self.union_of(p, st, seeds)?;
        let (out, inn, ids) =
            self.edge_matrix(p, st, edge, &[seed_facts.column(0), old.column(0)])?;
        let n = ids.n();
        let old_v: Vec<u32> = ids.vertices(old.column(0))?.into_owned();
        let mut was = vec![false; n];
        for &v in &old_v {
            was[v as usize] = true;
        }
        let mut queued = was.clone();
        let mut frontier: Vec<u32> = Vec::new();
        for &v in ids.vertices(seed_facts.column(0))?.iter() {
            if !queued[v as usize] {
                queued[v as usize] = true;
                frontier.push(v);
            }
        }
        for i in 0..edge_rows.len() {
            let (a, b) = (edge_rows.value(0, i), edge_rows.value(1, i));
            let (x, y) = match way {
                Way::Forward => (a, b),
                Way::Backward => (b, a),
            };
            if let (Some(vx), Some(vy)) = (ids.vertex(x), ids.vertex(y))
                && was[vx as usize]
                && !queued[vy as usize]
            {
                queued[vy as usize] = true;
                frontier.push(vy);
            }
        }
        let (fwd, back) = match way {
            Way::Forward => (out, inn),
            Way::Backward => match inn {
                Some(t) => (t, Some(out)),
                None => (out.transpose(), Some(out)),
            },
        };
        let back_host = st.why.is_some().then(|| match &back {
            Some(t) => t.clone(),
            None => fwd.transpose(),
        });
        let prepare = t0.elapsed();
        let t1 = Instant::now();
        let mut new_v: Vec<(u32, u32)> = Vec::new();
        let mut rounds = 0;
        if !frontier.is_empty() {
            let g: Graph<B> = match back {
                Some(t) => Graph::with_transpose(fwd, t, &self.device)?,
                None => Graph::new(fwd, &self.device)?,
            };
            let opts = BfsOptions {
                allowed: Some(Mask::from_indices(n, &old_v).complement()),
                ..BfsOptions::default()
            };
            let mut search = self.search.lock().unwrap_or_else(|e| e.into_inner());
            let state = search.get_or_insert_with(|| BfsState::new(g.vertices(), &self.device));
            bfs_with(&g, &frontier, &opts, &self.device, state)?;
            for (i, s) in state.steps().iter().enumerate() {
                trace.round(k, i as u32 + 1, s.reached);
            }
            rounds = state.steps().len() as u32;
            new_v = B::vector_to_host(state.levels()).iter().collect();
        }
        let compute = t1.elapsed();
        let mut all: Vec<u32> = old_v.clone();
        all.extend(new_v.iter().map(|x| x.0));
        all.sort_unstable();
        let mut fresh: Vec<u32> = new_v.iter().map(|x| x.0).collect();
        fresh.sort_unstable();
        if let (Some(why), Some(back), Some(before)) = (st.why.as_mut(), back_host, before) {
            let mut levels = vec![u32::MAX; n];
            let mut top = 0;
            for id in old.column(0).iter() {
                let l = before
                    .ids
                    .vertex(id)
                    .and_then(|v| before.levels.get(v as usize).copied())
                    .unwrap_or(0);
                if let Some(v) = ids.vertex(id) {
                    levels[v as usize] = l;
                }
                top = top.max(l);
            }
            for &(v, l) in &new_v {
                levels[v as usize] = top + 1 + l;
            }
            why.reach.insert(
                rel,
                ReachWhy {
                    step,
                    from: before.from,
                    to: before.to,
                    levels,
                    back,
                    ids: ids.clone(),
                },
            );
        }
        let facts = Facts::from_columns(vec![ids.column(all)])?;
        let fresh = Facts::from_columns(vec![ids.column(fresh)])?;
        let count = facts.len();
        st.derived.insert(rel, facts);
        status.insert(
            rel,
            if fresh.is_empty() {
                Status::Same
            } else {
                Status::Grew(fresh)
            },
        );
        Ok(Some(StratumReport {
            kind: "",
            relations: Vec::new(),
            rounds,
            facts: count,
            prepare,
            compute,
            renumbered: ids.ranked(),
            continued: true,
            peak_rows: 0,
            proof_rows: 0,
            indexed_rows: 0,
            range_joins: 0,
            next_rows: 0,
        }))
    }
}