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/next.rs

//! The next row by a key: an aggregate rule that takes, per row of one atom, the least value
//! of another atom past one of its values (`next(A, B) :- min(B) by (A): bound(A), bound(B),
//! A < B.`), or the greatest before it (`max` with `>`), more equal keys beside it or not. Run
//! as written it is a cross product cut by the comparison, reduced per group; here the atom
//! of the reduced value is sorted by (key, value) and each row of the other finds its value
//! by one binary search, so the bindings the reduction reads are each row's winners alone
//! (n log n). The facts and the proofs are the reduction's over every binding.
//!
//! A run also rewrites its plan ([`rewrite`], with no proof kept) so that more rules take
//! this shape: an aggregate over a relation its client marked internal ([`Plan::internal`])
//! and derived by one rule (GQL's matches) reads that rule's body itself, and a side of
//! several atoms (a label and a property) becomes a relation of its own.

use std::cmp::Ordering;

use crate::Result;
use crate::cols::{Par, Rows, Table, select};
use crate::rules::{
    Agg, Aggregate, Atom, Cmp, Cond, Literal, Plan, ReduceOp, RelKind, Rule, RuleId, Term, Value,
    Var,
};
use crate::typed::Type;

/// The variable of the hidden column that carries each row's count of bindings (on the first
/// winner of each row; 0 on the others): the size of a group, as the proof names it.
pub(crate) const WEIGHT: Var = Var(u32::MAX - 8192);

/// The shape of a rule run as the next row ([`shape`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Next {
    /// The atom of the bound value `a` (one search per row) and the atom of the reduced `b`.
    pub(crate) left: usize,
    pub(crate) right: usize,
    pub(crate) a: Var,
    pub(crate) b: Var,
    /// The greatest `b` before `a` (a `max`); else the least past it.
    pub(crate) desc: bool,
    /// `b` strictly past (or before) `a`.
    pub(crate) strict: bool,
}

/// The reduced variable of `agg` and whether it takes the greatest: a `min` or `max` of one
/// variable ([`Agg::Min`], [`Agg::Max`] of one key), or with `many` an [`Agg::Many`] of one
/// least or greatest value (no flags, no counts, no `has`).
fn reduced(agg: &Aggregate, many: bool) -> Option<(Var, bool)> {
    match &agg.agg {
        Agg::Min { key } if key.len() == 1 => Some((key[0], false)),
        Agg::Max { key } if key.len() == 1 => Some((key[0], true)),
        Agg::Many { reduces, times } if many && times.is_empty() && reduces.len() == 1 => {
            let r = &reduces[0];
            let desc = match r.op {
                ReduceOp::Min => false,
                ReduceOp::Max => true,
                _ => return None,
            };
            (r.of.len() == 1 && r.when.is_empty() && r.has.is_none()).then_some((r.of[0], desc))
        }
        _ => None,
    }
}

/// `b op a` of a comparison between `b` and another variable: the other and the operator
/// as seen from `b`.
fn from_b(c: &Cond, b: Var) -> Option<(Var, Cmp)> {
    let Cond::Cmp {
        left: Term::Var(l),
        op,
        right: Term::Var(r),
    } = *c
    else {
        return None;
    };
    let flip = |o: Cmp| match o {
        Cmp::Lt => Cmp::Gt,
        Cmp::Le => Cmp::Ge,
        Cmp::Gt => Cmp::Lt,
        Cmp::Ge => Cmp::Le,
        o => o,
    };
    if l == b && r != b {
        Some((r, op))
    } else if r == b && l != b {
        Some((l, flip(op)))
    } else {
        None
    }
}

/// Whether `op` (from `b`) bounds `b` the way the reduction needs: past `a` for a least
/// value, before it for a greatest; with its strictness.
fn bounds(op: Cmp, desc: bool) -> Option<bool> {
    match (op, desc) {
        (Cmp::Gt, false) | (Cmp::Lt, true) => Some(true),
        (Cmp::Ge, false) | (Cmp::Le, true) => Some(false),
        _ => None,
    }
}

/// The rule as the next row: two positive atoms, no negation, one comparison of the
/// reduced variable `b` (bound by one atom alone) with a variable `a` of the other atom alone
/// (`b` past `a` for a least, before it for a greatest); the variables the atoms share are
/// equal keys. A [`Agg::Many`] only when no proof is kept (its proof lists every member).
pub(crate) fn shape(rule: &Rule, explain: bool) -> Option<Next> {
    let agg = rule.agg.as_ref()?;
    if rule.fold.is_some()
        || !rule.negated.is_empty()
        || !rule.computes.is_empty()
        || rule.body.len() != 2
    {
        return None;
    }
    let [cond] = rule.conds.as_slice() else {
        return None;
    };
    let (b, desc) = reduced(agg, !explain)?;
    if agg.group.contains(&b) {
        return None;
    }
    let holds = |i: usize, v: Var| rule.body[i].vars().any(|w| w == v);
    let right = (0..2).find(|&i| holds(i, b))?;
    let left = 1 - right;
    if holds(left, b) {
        return None;
    }
    let (a, op) = from_b(cond, b)?;
    if !holds(left, a) || holds(right, a) {
        return None;
    }
    let strict = bounds(op, desc)?;
    Some(Next {
        left,
        right,
        a,
        b,
        desc,
        strict,
    })
}

/// The first place of `lo..hi` where `before` no longer holds (it holds on a first stretch).
fn first(lo: usize, hi: usize, before: impl Fn(usize) -> bool) -> usize {
    let (mut lo, mut hi) = (lo, hi);
    while lo < hi {
        let mid = lo + (hi - lo) / 2;
        if before(mid) {
            lo = mid + 1;
        } else {
            hi = mid;
        }
    }
    lo
}

/// The distinct variables of `a` in term order, each with its first column.
fn vars_of(a: &Atom) -> Vec<(Var, usize)> {
    let mut out: Vec<(Var, usize)> = Vec::new();
    for (j, t) in a.terms.iter().enumerate() {
        if let Term::Var(v) = *t
            && !out.iter().any(|x| x.0 == v)
        {
            out.push((v, j));
        }
    }
    out
}

/// The selected rows of `a` over `r`, one per distinct binding of its variables, sorted by
/// the columns `order` (then the rest of its variables).
fn distinct_rows(par: &Par, a: &Atom, r: &Rows, order: &[usize]) -> Vec<u32> {
    let vars = vars_of(a);
    let mut cols: Vec<usize> = order.to_vec();
    cols.extend(vars.iter().map(|x| x.1).filter(|c| !order.contains(c)));
    let sel = select(par, &a.terms, r, &[]);
    let mut rows: Vec<u32> = (0..sel.len()).map(|i| sel.at(i)).collect();
    let cmp = |x: u32, y: u32| {
        cols.iter()
            .map(|&c| r.get(c, x as usize).cmp(&r.get(c, y as usize)))
            .find(|o| o.is_ne())
            .unwrap_or(Ordering::Equal)
    };
    par.sort_by(&mut rows, |&x, &y| cmp(x, y).then(x.cmp(&y)));
    rows.dedup_by(|y, x| cmp(*x, *y).is_eq());
    rows
}

/// The bindings rule `rule` of shape `n` reduces, from its atoms' rows `rl` (the left atom)
/// and `rr` (the right): per distinct binding of the left atom, the right atom's distinct
/// bindings of equal keys whose `b` is the least past `a` (the greatest before it), all of
/// them when several hold that value; none where no `b` is past. With `weights`, a hidden
/// column [`WEIGHT`]: on each left binding's first winner, the number of the right atom's
/// bindings past `a` (the bindings today's join gives that left binding), 0 on the others.
/// The variables in the rule's order.
pub(crate) fn run(par: &Par, rule: &Rule, n: Next, rl: &Rows, rr: &Rows, weights: bool) -> Table {
    let (la, ra) = (&rule.body[n.left], &rule.body[n.right]);
    let (lv, rv) = (vars_of(la), vars_of(ra));
    let col = |vs: &[(Var, usize)], v: Var| vs.iter().find(|x| x.0 == v).map(|x| x.1);
    // the keys, as (left column, right column)
    let keys: Vec<(usize, usize)> = lv
        .iter()
        .filter_map(|&(v, c)| col(&rv, v).map(|d| (c, d)))
        .collect();
    let (ac, bc) = (
        col(&lv, n.a).expect("a on the left"),
        col(&rv, n.b).expect("b on the right"),
    );
    let lrows = distinct_rows(par, la, rl, &[]);
    let rorder: Vec<usize> = keys.iter().map(|k| k.1).chain([bc]).collect();
    let rrows = distinct_rows(par, ra, rr, &rorder);
    let bv = |i: usize| rr.get(bc, rrows[i] as usize);
    // per left binding: its winners' places in `rrows` and its count
    let found: Vec<(Vec<u32>, Vec<u32>, Vec<Value>)> = par.split(lrows.len(), |lo, hi| {
        let (mut left, mut right, mut count) = (Vec::new(), Vec::new(), Vec::new());
        for (i, &l) in lrows.iter().enumerate().take(hi).skip(lo) {
            let l = l as usize;
            let key = |k: u32| {
                keys.iter()
                    .map(|&(lc, rc)| rr.get(rc, k as usize).cmp(&rl.get(lc, l)))
                    .find(|o| o.is_ne())
                    .unwrap_or(Ordering::Equal)
            };
            let k0 = rrows.partition_point(|&k| key(k).is_lt());
            let k1 = k0 + rrows[k0..].partition_point(|&k| key(k).is_eq());
            let a = rl.get(ac, l);
            // the first place past `a` (with `b == a` inside when not strict)
            let p = first(k0, k1, |q| {
                let b = bv(q);
                if n.desc != n.strict { b <= a } else { b < a }
            });
            let (s, e, size) = if n.desc {
                // the greatest before `a`: places k0..p hold the bindings
                if p == k0 {
                    continue;
                }
                let m = bv(p - 1);
                (first(k0, p, |q| bv(q) < m), p, p - k0)
            } else {
                if p == k1 {
                    continue;
                }
                let m = bv(p);
                (p, first(p, k1, |q| bv(q) <= m), k1 - p)
            };
            for q in s..e {
                left.push(i as u32);
                right.push(q as u32);
                count.push(if q == s { size as Value } else { 0 });
            }
        }
        (left, right, count)
    });
    let li: Vec<u32> = found.iter().flat_map(|x| x.0.iter().copied()).collect();
    let ri: Vec<u32> = found.iter().flat_map(|x| x.1.iter().copied()).collect();
    let len = li.len();
    let mut vars: Vec<Var> = Vec::new();
    let mut cols: Vec<Vec<Value>> = Vec::new();
    for v in rule.vars() {
        let c = match (col(&lv, v), col(&rv, v)) {
            (Some(c), _) => par.fill(len, |i| rl.get(c, lrows[li[i] as usize] as usize)),
            (None, Some(c)) => par.fill(len, |i| rr.get(c, rrows[ri[i] as usize] as usize)),
            (None, None) => continue,
        };
        vars.push(v);
        cols.push(c);
    }
    if weights {
        vars.push(WEIGHT);
        cols.push(found.into_iter().flat_map(|x| x.2).collect());
    }
    Table {
        vars,
        cols,
        len,
        distinct: false,
        perm: None,
    }
}

/// `p` rewritten so that more aggregate rules take the next row's shape, or `None` when
/// nothing changes; for a run that keeps no proof (the rules that run are not the rules
/// written). First the counted matches go ([`counted`]); then two steps, each as long as it
/// applies:
/// 1. An aggregate of one reduced variable whose body is one atom of a relation `m` with
///    distinct variables, `m` internal ([`Plan::internal`]), derived by one rule of distinct
///    head variables and read by no other rule: the aggregate reads that rule's body (its
///    variables through `m`'s head), and `m`'s rule goes (`m` stays empty).
/// 2. An aggregate whose reduced variable `b` has one comparison with a variable `a` of
///    other atoms: the atoms tied to `b`'s through variables other than the groups and `a`
///    are its side, the rest the other; a side of more than one atom becomes a relation of
///    its own (the variables the head, the groups, the keys and the comparison read), with
///    the conditions and negated atoms that read that side alone.
pub(crate) fn rewrite(p: &Plan) -> Result<Option<Plan>> {
    if !p.rules().iter().any(|r| r.agg.is_some()) {
        return Ok(None);
    }
    let mut q = p.clone();
    let mut changed = counted(&mut q)?;
    while let Some((r, m)) = fusable(&q) {
        fuse(&mut q, r, m)?;
        changed = true;
    }
    let mut r = 0;
    while r < q.rules().len() {
        if split(&mut q, RuleId(r as u32))? {
            changed = true;
        }
        r += 1;
    }
    Ok(changed.then_some(q))
}

/// The first aggregate rule and the rule of the relation it reads that [`rewrite`]'s step 1
/// takes.
fn fusable(q: &Plan) -> Option<(RuleId, RuleId)> {
    let rules = q.rules();
    let reads = |rel| {
        rules
            .iter()
            .filter(|r| r.body.iter().chain(&r.negated).any(|a| a.rel == rel))
            .count()
    };
    let distinct = |a: &Atom| {
        a.terms.iter().enumerate().all(|(j, t)| match t {
            Term::Var(_) => !a.terms[..j].contains(t),
            Term::Const(_) => false,
        })
    };
    for (i, r) in rules.iter().enumerate() {
        let Some(agg) = &r.agg else { continue };
        if r.fold.is_some() || reduced(agg, true).is_none() {
            continue;
        }
        let [a] = r.body.as_slice() else { continue };
        if !r.negated.is_empty() || !r.conds.is_empty() || !r.computes.is_empty() || !distinct(a) {
            continue;
        }
        let m = a.rel;
        if !q.is_internal(m)
            || q.relation_info(m).kind != RelKind::Derived
            || q.is_counted(m)
            || reads(m) != 1
        {
            continue;
        }
        let mut of_m = rules.iter().enumerate().filter(|x| x.1.head.rel == m);
        let (Some((j, mr)), None) = (of_m.next(), of_m.next()) else {
            continue;
        };
        // (a computed value stays in its own rule)
        if mr.groups() || !mr.computes.is_empty() || !distinct(&mr.head) {
            continue;
        }
        return Some((RuleId(i as u32), RuleId(j as u32)));
    }
    None
}

/// [`rewrite`]'s step 1 on aggregate `r` reading the relation of rule `m`.
fn fuse(q: &mut Plan, r: RuleId, m: RuleId) -> Result<()> {
    let (rule, mr) = (q.rule_at(r).clone(), q.rule_at(m).clone());
    // a variable of the aggregate's atom to the head variable of `m`'s rule at its place
    let map: Vec<(Var, Var)> = rule.body[0].vars().zip(mr.head.vars()).collect();
    let to = |v: Var| map.iter().find(|x| x.0 == v).map_or(v, |x| x.1);
    let term = |t: Term| match t {
        Term::Var(v) => Term::Var(to(v)),
        c => c,
    };
    let mut agg = rule.agg.clone().expect("an aggregate");
    agg.group = agg.group.iter().map(|&v| to(v)).collect();
    match &mut agg.agg {
        Agg::Min { key } | Agg::Max { key } => *key = key.iter().map(|&v| to(v)).collect(),
        Agg::Many { reduces, .. } => {
            for x in reduces {
                x.of = x.of.iter().map(|&v| to(v)).collect();
            }
        }
        _ => unreachable!("a reduction of one variable"),
    }
    let fused = Rule {
        head: Atom {
            rel: rule.head.rel,
            terms: rule.head.terms.iter().map(|&t| term(t)).collect(),
        },
        body: mr.body,
        negated: mr.negated,
        conds: mr.conds,
        agg: Some(agg),
        fold: None,
        computes: Vec::new(),
    };
    q.set_rule(r, fused)?;
    q.remove_rule(m);
    Ok(())
}

/// The counted matches gone from `q` ([`rewrite`]'s first step); whether it changed. Two
/// steps, each as long as it applies:
/// 1. An aggregate of several reductions ([`Aggregate::many`]) whose body is one atom of a
///    counted relation `m` with distinct variables, weighed by that atom's count alone, `m`
///    derived by one counting rule ([`Plan::count_rule`]) of distinct head variables and no
///    computed value: the aggregate reads that rule's body (its variables through `m`'s
///    head), weighed by the counts of its counted atoms. A count of `m`'s rows weighed by
///    their counts is the number of the body's distinct bindings weighed so, a group's sum
///    the same weighed values, its distinct values and least and greatest the same values:
///    the answers do not change. (A sum or mean of f64 values stays as written: its order of
///    adding would.) When `m` is internal ([`Plan::internal`]) and read by no other rule,
///    its rule goes.
/// 2. An internal relation read by no rule, walk or call: its rules go (a client reads none
///    of its facts, so none is derived; GQL's match relation of a grouped query).
pub(crate) fn counted(q: &mut Plan) -> Result<bool> {
    let mut changed = false;
    while let Some((r, m)) = counted_fusable(q) {
        let (rule, mr) = (q.rule_at(r).clone(), q.rule_at(m).clone());
        let fold = mr.fold.clone().expect("a counting rule");
        // the aggregate's variables of `m`'s columns to the counting rule's head variables
        let n = rule.body[0].terms.len();
        let map: Vec<(Var, Var)> = rule.body[0].terms[..n - 1]
            .iter()
            .zip(&mr.head.terms[..n - 1])
            .filter_map(|(a, b)| match (a, b) {
                (Term::Var(a), Term::Var(b)) => Some((*a, *b)),
                _ => None,
            })
            .collect();
        let to = |v: Var| map.iter().find(|x| x.0 == v).map_or(v, |x| x.1);
        let term = |t: Term| match t {
            Term::Var(v) => Term::Var(to(v)),
            c => c,
        };
        let mut agg = rule.agg.clone().expect("an aggregate");
        agg.group = agg.group.iter().map(|&v| to(v)).collect();
        let Agg::Many { reduces, times } = &mut agg.agg else {
            unreachable!("several reductions")
        };
        for x in reduces.iter_mut() {
            x.of = x.of.iter().map(|&v| to(v)).collect();
            x.when = x.when.iter().map(|&v| to(v)).collect();
        }
        *times = fold.times.clone();
        let fused = Rule {
            head: Atom {
                rel: rule.head.rel,
                terms: rule.head.terms.iter().map(|&t| term(t)).collect(),
            },
            body: mr.body,
            negated: mr.negated,
            conds: mr.conds,
            agg: Some(agg),
            fold: None,
            computes: Vec::new(),
        };
        q.set_rule(r, fused)?;
        let rel = mr.head.rel;
        if q.is_internal(rel) && reads(q, rel) == 0 {
            q.remove_rule(m);
        }
        changed = true;
    }
    // 2: the internal relations nothing reads, as long as one goes
    loop {
        let dead: Vec<usize> = (0..q.rules().len())
            .filter(|&i| {
                let rel = q.rules()[i].head.rel;
                q.is_internal(rel) && reads(q, rel) == 0 && !read_elsewhere(q, rel)
            })
            .collect();
        if dead.is_empty() {
            break;
        }
        for &i in dead.iter().rev() {
            q.remove_rule(RuleId(i as u32));
        }
        changed = true;
    }
    Ok(changed)
}

/// The number of rules whose body reads `rel` (positive or negated).
fn reads(q: &Plan, rel: crate::rules::RelId) -> usize {
    q.rules()
        .iter()
        .filter(|r| r.body.iter().chain(&r.negated).any(|a| a.rel == rel))
        .count()
}

/// Whether a walk, a call, a group of rounds or a table of sets names `rel`.
fn read_elsewhere(q: &Plan, rel: crate::rules::RelId) -> bool {
    q.walks()
        .iter()
        .any(|w| w.from == rel || w.edge == rel || w.rel == rel)
        || q.calls().iter().any(|c| c.edge == rel || c.rel == rel)
        || q.round_of(rel).is_some()
        || q.set_limit(rel).is_some()
}

/// The first aggregate rule and the counting rule of the counted relation it reads that
/// [`counted`]'s step 1 takes.
fn counted_fusable(q: &Plan) -> Option<(RuleId, RuleId)> {
    let rules = q.rules();
    let distinct = |a: &Atom| {
        a.terms.iter().enumerate().all(|(j, t)| match t {
            Term::Var(_) => !a.terms[..j].contains(t),
            Term::Const(_) => false,
        })
    };
    for (i, r) in rules.iter().enumerate() {
        let Some(agg) = &r.agg else { continue };
        let Agg::Many { reduces, times } = &agg.agg else {
            continue;
        };
        let [a] = r.body.as_slice() else { continue };
        if r.fold.is_some()
            || !r.negated.is_empty()
            || !r.conds.is_empty()
            || !r.computes.is_empty()
            || !distinct(a)
        {
            continue;
        }
        let m = a.rel;
        if !q.is_counted(m) || q.relation_info(m).kind != RelKind::Derived {
            continue;
        }
        // weighed by the atom's count alone, which nothing else reads
        let Some(&Term::Var(count)) = a.terms.last() else {
            continue;
        };
        let reads_count = |v: &Var| *v == count;
        if times.as_slice() != [count]
            || agg.group.iter().any(reads_count)
            || reduces.iter().any(|x| {
                x.of.iter().chain(&x.when).any(reads_count)
                    || (matches!(x.op, ReduceOp::Sum | ReduceOp::Avg)
                        && x.of
                            .iter()
                            .any(|&v| q.var_type(RuleId(i as u32), v) == Type::F64))
            })
        {
            continue;
        }
        let mut of_m = rules.iter().enumerate().filter(|x| x.1.head.rel == m);
        let (Some((j, mr)), None) = (of_m.next(), of_m.next()) else {
            continue;
        };
        let counting = mr
            .fold
            .as_ref()
            .is_some_and(|f| f.op == crate::rules::FoldOp::Count);
        if !counting || mr.agg.is_some() || !mr.computes.is_empty() || !distinct(&mr.head) {
            continue;
        }
        // (a result variable of the aggregate is no variable of that body)
        let outs: Vec<Var> = reduces
            .iter()
            .flat_map(|x| [Some(x.out), x.has])
            .flatten()
            .collect();
        if mr
            .body
            .iter()
            .chain(&mr.negated)
            .flat_map(|b| b.vars())
            .chain(mr.conds.iter().flat_map(|c| c.vars()))
            .any(|v| outs.contains(&v))
        {
            continue;
        }
        return Some((RuleId(i as u32), RuleId(j as u32)));
    }
    None
}

/// [`rewrite`]'s step 2 on rule `r`; whether it changed.
fn split(q: &mut Plan, r: RuleId) -> Result<bool> {
    let rule = q.rule_at(r).clone();
    let Some(agg) = &rule.agg else {
        return Ok(false);
    };
    if rule.fold.is_some() || !rule.computes.is_empty() || rule.body.len() < 3 {
        return Ok(false);
    }
    let Some((b, desc)) = reduced(agg, true) else {
        return Ok(false);
    };
    // the one comparison of `b`, the right way
    let tied: Vec<usize> = (0..rule.conds.len())
        .filter(|&i| rule.conds[i].vars().any(|v| v == b))
        .collect();
    let [ci] = tied.as_slice() else {
        return Ok(false);
    };
    let Some((a, op)) = from_b(&rule.conds[*ci], b) else {
        return Ok(false);
    };
    if bounds(op, desc).is_none() || agg.group.contains(&b) {
        return Ok(false);
    }
    // `b`'s side: the atoms reached from `b`'s through variables other than the groups and `a`
    let n = rule.body.len();
    let mut right = vec![false; n];
    let mut todo: Vec<Var> = vec![b];
    while let Some(v) = todo.pop() {
        for (i, at) in rule.body.iter().enumerate() {
            if !right[i] && at.vars().any(|w| w == v) {
                right[i] = true;
                todo.extend(
                    at.vars()
                        .filter(|&w| w != a && w != b && !agg.group.contains(&w)),
                );
            }
        }
    }
    let side_vars = |s: bool| -> Vec<Var> {
        let mut out: Vec<Var> = Vec::new();
        for (i, at) in rule.body.iter().enumerate() {
            if right[i] == s {
                for v in at.vars() {
                    if !out.contains(&v) {
                        out.push(v);
                    }
                }
            }
        }
        out
    };
    let (lv, rv) = (side_vars(false), side_vars(true));
    if lv.is_empty() || !lv.contains(&a) || rv.contains(&a) || lv.contains(&b) {
        return Ok(false);
    }
    // every other condition and negated atom reads one side alone
    let on = |vs: &[Var], mut it: Box<dyn Iterator<Item = Var> + '_>| it.all(|v| vs.contains(&v));
    let cond_side = |i: usize| -> Option<bool> {
        let c = &rule.conds[i];
        if on(&rv, Box::new(c.vars())) {
            Some(true)
        } else if on(&lv, Box::new(c.vars())) {
            Some(false)
        } else {
            None
        }
    };
    let neg_side = |at: &Atom| -> Option<bool> {
        if on(&rv, Box::new(at.vars())) {
            Some(true)
        } else if on(&lv, Box::new(at.vars())) {
            Some(false)
        } else {
            None
        }
    };
    if (0..rule.conds.len()).any(|i| i != *ci && cond_side(i).is_none())
        || rule.negated.iter().any(|at| neg_side(at).is_none())
    {
        return Ok(false);
    }
    let atoms = |s: bool| (0..n).filter(|&i| right[i] == s).count();
    if atoms(false) < 2 && atoms(true) < 2 {
        return Ok(false);
    }
    // the variables a side hands on: the head's, the groups, the keys, `a` and `b`
    let needed = |v: Var| {
        rule.head.vars().any(|w| w == v)
            || agg.group.contains(&v)
            || v == a
            || v == b
            || (lv.contains(&v) && rv.contains(&v))
    };
    let head_name = q.relation_info(rule.head.rel).name.clone();
    let mut body: Vec<Atom> = Vec::new();
    for s in [false, true] {
        let idx: Vec<usize> = (0..n).filter(|&i| right[i] == s).collect();
        if idx.len() == 1 {
            body.push(rule.body[idx[0]].clone());
            continue;
        }
        let vs: Vec<Var> = if s { &rv } else { &lv }
            .iter()
            .copied()
            .filter(|&v| needed(v))
            .collect();
        let types: Vec<Type> = vs.iter().map(|&v| q.var_type(r, v)).collect();
        let name = format!(
            "{head_name}.next{}.{}",
            r.index(),
            if s { "b" } else { "a" }
        );
        let rel = q.derived_typed(&name, &types);
        let head = Atom {
            rel,
            terms: vs.iter().map(|&v| Term::Var(v)).collect(),
        };
        let lits: Vec<Literal> = idx
            .iter()
            .map(|&i| Literal::Pos(rule.body[i].clone()))
            .chain(
                (0..rule.conds.len())
                    .filter(|&i| i != *ci && cond_side(i) == Some(s))
                    .map(|i| Literal::Cond(rule.conds[i])),
            )
            .chain(
                rule.negated
                    .iter()
                    .filter(|at| neg_side(at) == Some(s))
                    .map(|at| Literal::Neg(at.clone())),
            )
            .collect();
        q.rule(head.clone(), lits)?;
        body.push(head);
    }
    // the conditions and negations of a side of one atom stay in the aggregate
    let one = |s: bool| atoms(s) == 1;
    let conds: Vec<Cond> = (0..rule.conds.len())
        .filter(|&i| i == *ci || cond_side(i).is_some_and(one))
        .map(|i| rule.conds[i])
        .collect();
    let negated: Vec<Atom> = rule
        .negated
        .iter()
        .filter(|at| neg_side(at).is_some_and(one))
        .cloned()
        .collect();
    let new = Rule {
        head: rule.head.clone(),
        body,
        negated,
        conds,
        agg: rule.agg.clone(),
        fold: None,
        computes: Vec::new(),
    };
    q.set_rule(r, new)?;
    Ok(true)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn at(rel: crate::RelId, vs: &[Var]) -> Atom {
        Atom {
            rel,
            terms: vs.iter().map(|&v| Term::Var(v)).collect(),
        }
    }

    fn cmp(l: Var, op: Cmp, r: Var) -> Literal {
        Literal::Cond(Cond::Cmp {
            left: Term::Var(l),
            op,
            right: Term::Var(r),
        })
    }

    #[test]
    fn the_shape_is_a_least_past_or_a_greatest_before_with_keys_beside() {
        let mut p = Plan::new();
        let bound = p.input("bound", 2);
        let next = p.derived("next", 3);
        let [s, a, b, x] = ["S", "A", "B", "X"].map(|n| p.var(n));
        let rule = |p: &mut Plan, agg: Aggregate, c: Literal| {
            let r = p
                .aggregate(
                    at(next, &[s, a, b]),
                    agg,
                    [
                        Literal::Pos(at(bound, &[s, a])),
                        Literal::Pos(at(bound, &[s, b])),
                        c,
                    ],
                )
                .unwrap();
            shape(p.rule_at(r), true)
        };
        let n = rule(&mut p, Aggregate::min_by([s, a], [b]), cmp(a, Cmp::Lt, b)).unwrap();
        assert_eq!(
            (n.left, n.right, n.a, n.b, n.desc, n.strict),
            (0, 1, a, b, false, true)
        );
        let n = rule(&mut p, Aggregate::max_by([s, a], [b]), cmp(a, Cmp::Ge, b)).unwrap();
        assert_eq!((n.desc, n.strict), (true, false));
        // the wrong way: a least before `a` is no next row
        assert!(rule(&mut p, Aggregate::min_by([s, a], [b]), cmp(b, Cmp::Lt, a)).is_none());
        // a comparison of `b` with a constant, or with a key
        assert!(rule(&mut p, Aggregate::min_by([s, a], [b]), cmp(s, Cmp::Lt, b)).is_none());
        let _ = x;
    }
}