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

nordisk/kleene

crates/kleene-datalog/tests/aggregates.rs

//! E3 (aggregates: count, min / max by a key tuple, exactly one; stratified like
//! negation) and E6 (a deterministic "first refusal": the least key tuple, the same answer
//! at any thread count), each against a plain reference computed here.

use std::collections::{BTreeMap, BTreeSet, HashMap};

use datafusion::prelude::{SessionConfig, SessionContext};
use kleene_datalog::{
    Aggregate, DatalogError, Engine, Facts, How, Inputs, Output, Program, Proof, RelId, RelKind,
    Stratum, instantiate, lt, ne, plan,
};
use kleene_sparse::{CpuBackend, CpuDevice};

type E = Engine<CpuBackend>;

fn engine() -> E {
    Engine::new(CpuDevice::new(2)).explain(true)
}

fn rows(f: &Facts) -> BTreeSet<Vec<u64>> {
    f.rows().collect()
}

struct Lcg(u64);

impl Lcg {
    fn next(&mut self) -> u64 {
        self.0 = self
            .0
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);
        self.0 >> 11
    }
}

fn random_rows<const N: usize>(seed: u64, n: usize, range: [u64; N]) -> Vec<[u64; N]> {
    let mut r = Lcg(seed);
    (0..n)
        .map(|_| std::array::from_fn(|i| r.next() % range[i]))
        .collect()
}

fn facts<const N: usize>(rs: &[[u64; N]]) -> Facts {
    Facts::from_rows(N, rs.iter()).unwrap()
}

/// Every proof of every fact of `rels` checks: rule nodes instantiate their rule, aggregate
/// members agree with the head's group and prove their bodies, conditions hold, leaves are
/// inputs, absent facts are absent.
fn check_all(
    p: &Program,
    out: &Output,
    rels: &[RelId],
    inputs: &HashMap<RelId, BTreeSet<Vec<u64>>>,
) {
    let derived: HashMap<RelId, BTreeSet<Vec<u64>>> = rels
        .iter()
        .map(|&r| (r, out.get_id(r).map(rows).unwrap_or_default()))
        .collect();
    let holds = |rel: RelId, t: &Vec<u64>| match p.relation_info(rel).kind {
        RelKind::Derived => derived.get(&rel).is_some_and(|s| s.contains(t)),
        _ => inputs.get(&rel).is_some_and(|s| s.contains(t)),
    };
    fn body(
        p: &Program,
        rule: kleene_datalog::RuleId,
        binding: &[(kleene_datalog::Var, u64)],
        premises: &[Proof],
        absent: &[(RelId, Vec<u64>)],
        holds: &dyn Fn(RelId, &Vec<u64>) -> bool,
    ) {
        let r = p.rule_at(rule);
        assert!(r.conds_hold(binding));
        assert_eq!(premises.len(), r.body.len());
        for (a, q) in r.body.iter().zip(premises) {
            assert_eq!((a.rel, instantiate(a, binding)), (q.rel, q.tuple.clone()));
            check(p, q, holds);
        }
        for (a, (rel, t)) in r.negated.iter().zip(absent) {
            assert_eq!((a.rel, instantiate(a, binding)), (*rel, t.clone()));
            assert!(!holds(*rel, t));
        }
    }
    fn check(p: &Program, q: &Proof, holds: &dyn Fn(RelId, &Vec<u64>) -> bool) {
        assert!(holds(q.rel, &q.tuple), "{}", q.render(p));
        match &q.how {
            How::Input | How::External => {
                assert_ne!(p.relation_info(q.rel).kind, RelKind::Derived)
            }
            How::Rule {
                rule,
                binding,
                premises,
                absent,
            } => {
                assert_eq!(instantiate(&p.rule_at(*rule).head, binding), q.tuple);
                body(p, *rule, binding, premises, absent, holds);
            }
            How::Aggregate {
                rule,
                binding,
                members,
                size,
            } => {
                let r = p.rule_at(*rule);
                assert_eq!(instantiate(&r.head, binding), q.tuple);
                let a = r.agg.as_ref().expect("an aggregate rule");
                assert!(*size >= members.len());
                for m in members {
                    for g in &a.group {
                        let want = binding.iter().find(|(v, _)| v == g).unwrap().1;
                        let got = m.binding.iter().find(|(v, _)| v == g).unwrap().1;
                        assert_eq!(want, got, "a member outside its group");
                    }
                    body(p, *rule, &m.binding, &m.premises, &m.absent, holds);
                }
            }
            other => panic!("a proof the check does not know: {other:?}"),
        }
    }
    for (&rel, fs) in &derived {
        for t in fs {
            let q = out
                .why_id(p, rel, t)
                .unwrap_or_else(|| panic!("no proof of {} {t:?}", p.relation_info(rel).name));
            check(p, &q, &holds);
        }
    }
}

#[tokio::test]
async fn counts_per_group_like_a_loop() {
    let calls = random_rows(3, 400, [30, 40]);
    let mut p = Program::new();
    let e = p.input::<2>("calls");
    let skip = p.input::<1>("skip");
    let fan = p.derived::<2>("fan");
    let pairs = p.derived::<1>("pairs");
    let fan_up = p.derived::<2>("fan_up");
    let (f, g, n) = (p.var("F"), p.var("G"), p.var("N"));
    let rid = p
        .aggregate(
            fan.at([f, n]),
            Aggregate::count([f], [g], n),
            [e.at([f, g])],
        )
        .unwrap();
    assert_eq!(
        p.show_rule(rid),
        "fan(F, N) :- N = count (G) by (F): calls(F, G)."
    );
    // no grouping variable: one fact, the number of distinct pairs
    p.aggregate(
        pairs.at([n]),
        Aggregate::count([], [f, g], n),
        [e.at([f, g])],
    )
    .unwrap();
    // with a condition and a negation in the body
    p.aggregate(
        fan_up.at([f, n]),
        Aggregate::count([f], [g], n),
        [e.at([f, g]).into(), lt(f, g), !skip.at([g])],
    )
    .unwrap();
    let skips: Vec<[u64; 1]> = (0..40).filter(|g| g % 3 == 0).map(|g| [g]).collect();
    let mut inputs = Inputs::new();
    inputs.facts(&e, facts(&calls)).unwrap();
    inputs.facts(&skip, facts(&skips)).unwrap();
    let out = engine().run(&p, &inputs).await.unwrap();
    let set: BTreeSet<(u64, u64)> = calls.iter().map(|r| (r[0], r[1])).collect();
    let mut by: BTreeMap<u64, BTreeSet<u64>> = BTreeMap::new();
    let mut up: BTreeMap<u64, BTreeSet<u64>> = BTreeMap::new();
    for &(a, b) in &set {
        by.entry(a).or_default().insert(b);
        if a < b && b % 3 != 0 {
            up.entry(a).or_default().insert(b);
        }
    }
    let want: BTreeSet<Vec<u64>> = by.iter().map(|(&a, s)| vec![a, s.len() as u64]).collect();
    assert_eq!(rows(out.get(&fan).unwrap()), want);
    assert_eq!(
        rows(out.get(&pairs).unwrap()),
        BTreeSet::from([vec![set.len() as u64]])
    );
    let want_up: BTreeSet<Vec<u64>> = up.iter().map(|(&a, s)| vec![a, s.len() as u64]).collect();
    assert_eq!(rows(out.get(&fan_up).unwrap()), want_up);
    let given = HashMap::from([
        (e.id(), set.iter().map(|&(a, b)| vec![a, b]).collect()),
        (skip.id(), skips.iter().map(|r| r.to_vec()).collect()),
    ]);
    check_all(&p, &out, &[fan.id(), pairs.id(), fan_up.id()], &given);
    // A count's proof proves one binding per counted value.
    let (&a, s) = by.iter().next().unwrap();
    let q = out.why(&p, &fan, [a, s.len() as u64]).unwrap();
    let How::Aggregate { members, size, .. } = &q.how else {
        panic!("an aggregate proof")
    };
    assert_eq!((members.len(), *size), (s.len(), s.len()));
    assert!(q.render(&p).contains("in the group"), "{}", q.render(&p));
}

#[tokio::test]
async fn a_count_over_nothing_is_zero_only_without_groups() {
    let mut p = Program::new();
    let e = p.input::<2>("e");
    let total = p.derived::<1>("total");
    let fan = p.derived::<2>("fan");
    let (f, g, n) = (p.var("F"), p.var("G"), p.var("N"));
    p.aggregate(total.at([n]), Aggregate::count([], [f], n), [e.at([f, g])])
        .unwrap();
    p.aggregate(
        fan.at([f, n]),
        Aggregate::count([f], [g], n),
        [e.at([f, g])],
    )
    .unwrap();
    let mut inputs = Inputs::new();
    inputs.facts(&e, Facts::empty(2)).unwrap();
    let out = engine().run(&p, &inputs).await.unwrap();
    assert_eq!(rows(out.get(&total).unwrap()), BTreeSet::from([vec![0]]));
    assert!(out.get(&fan).unwrap().is_empty());
}

#[tokio::test]
async fn min_and_max_by_key_tuples_break_ties_by_the_head() {
    // weighted calls (F, G, W) with many equal weights
    let calls = random_rows(9, 500, [20, 50, 6]);
    let mut p = Program::new();
    let e = p.input::<3>("wcalls");
    let lightest = p.derived::<3>("lightest");
    let heaviest = p.derived::<3>("heaviest");
    let first_callee = p.derived::<2>("first_callee");
    let least_pair = p.derived::<2>("least_pair");
    let (f, g, w) = (p.var("F"), p.var("G"), p.var("W"));
    // lightest(F, G, W): least W per F; equal W: least (F, G, W)
    let rid = p
        .aggregate(
            lightest.at([f, g, w]),
            Aggregate::min_by([f], [w]),
            [e.at([f, g, w])],
        )
        .unwrap();
    assert_eq!(
        p.show_rule(rid),
        "lightest(F, G, W) :- min (W) by (F): wcalls(F, G, W)."
    );
    p.aggregate(
        heaviest.at([f, g, w]),
        Aggregate::max_by([f], [w]),
        [e.at([f, g, w])],
    )
    .unwrap();
    // a plain min of a value
    p.aggregate(
        first_callee.at([f, g]),
        Aggregate::min_by([f], [g]),
        [e.at([f, g, w])],
    )
    .unwrap();
    // no group: the single least (F, G) of all, a key tuple
    p.aggregate(
        least_pair.at([f, g]),
        Aggregate::min_by([], [w, g, f]),
        [e.at([f, g, w])],
    )
    .unwrap();
    let mut inputs = Inputs::new();
    inputs.facts(&e, facts(&calls)).unwrap();
    let out = engine().run(&p, &inputs).await.unwrap();
    let set: BTreeSet<[u64; 3]> = calls.iter().copied().collect();
    let mut light: BTreeMap<u64, [u64; 3]> = BTreeMap::new();
    let mut heavy: BTreeMap<u64, [u64; 3]> = BTreeMap::new();
    let mut first: BTreeMap<u64, u64> = BTreeMap::new();
    for &r in &set {
        let [a, b, c] = r;
        light
            .entry(a)
            .and_modify(|m| {
                if (c, [a, b, c]) < (m[2], *m) {
                    *m = r;
                }
            })
            .or_insert(r);
        heavy
            .entry(a)
            .and_modify(|m| {
                if c > m[2] || (c == m[2] && r < *m) {
                    *m = r;
                }
            })
            .or_insert(r);
        first.entry(a).and_modify(|m| *m = (*m).min(b)).or_insert(b);
    }
    let least = set.iter().min_by_key(|r| (r[2], r[1], r[0])).unwrap();
    assert_eq!(
        rows(out.get(&lightest).unwrap()),
        light.values().map(|r| r.to_vec()).collect()
    );
    assert_eq!(
        rows(out.get(&heaviest).unwrap()),
        heavy.values().map(|r| r.to_vec()).collect()
    );
    assert_eq!(
        rows(out.get(&first_callee).unwrap()),
        first.iter().map(|(&a, &b)| vec![a, b]).collect()
    );
    assert_eq!(
        rows(out.get(&least_pair).unwrap()),
        BTreeSet::from([vec![least[0], least[1]]])
    );
    // one fact per group, in group order
    let l = out.get(&lightest).unwrap();
    let firsts: Vec<u64> = l.column(0).iter().collect();
    assert!(firsts.windows(2).all(|w| w[0] < w[1]));
    let given = HashMap::from([(e.id(), set.iter().map(|r| r.to_vec()).collect())]);
    check_all(
        &p,
        &out,
        &[
            lightest.id(),
            heaviest.id(),
            first_callee.id(),
            least_pair.id(),
        ],
        &given,
    );
}

#[tokio::test]
async fn exactly_one_holds_only_for_single_valued_groups() {
    let at = random_rows(21, 120, [60, 3]);
    let mut p = Program::new();
    let e = p.input::<2>("at");
    let only = p.derived::<2>("only");
    let only_big = p.derived::<2>("only_big");
    let (s, x) = (p.var("S"), p.var("X"));
    let rid = p
        .aggregate(
            only.at([s, x]),
            Aggregate::exactly_one([s], [x]),
            [e.at([s, x])],
        )
        .unwrap();
    assert_eq!(
        p.show_rule(rid),
        "only(S, X) :- exactly one (X) by (S): at(S, X)."
    );
    p.aggregate(
        only_big.at([s, x]),
        Aggregate::exactly_one([s], [x]),
        [e.at([s, x]).into(), ne(x, 0u64)],
    )
    .unwrap();
    let mut inputs = Inputs::new();
    inputs.facts(&e, facts(&at)).unwrap();
    let out = engine().run(&p, &inputs).await.unwrap();
    let mut by: BTreeMap<u64, BTreeSet<u64>> = BTreeMap::new();
    for r in &at {
        by.entry(r[0]).or_default().insert(r[1]);
    }
    let want: BTreeSet<Vec<u64>> = by
        .iter()
        .filter(|(_, v)| v.len() == 1)
        .map(|(&k, v)| vec![k, *v.first().unwrap()])
        .collect();
    let want_big: BTreeSet<Vec<u64>> = by
        .iter()
        .filter_map(|(&k, v)| {
            let nz: Vec<u64> = v.iter().copied().filter(|&x| x != 0).collect();
            (nz.len() == 1).then(|| vec![k, nz[0]])
        })
        .collect();
    assert!(!want.is_empty() && want.len() < by.len());
    assert_eq!(rows(out.get(&only).unwrap()), want);
    assert_eq!(rows(out.get(&only_big).unwrap()), want_big);
    let given = HashMap::from([(e.id(), at.iter().map(|r| r.to_vec()).collect())]);
    check_all(&p, &out, &[only.id(), only_big.id()], &given);
}

#[tokio::test]
async fn aggregates_over_lower_strata_and_never_over_their_own_recursion() {
    // reach then count it: allowed (the reach is complete first)
    let mut p = Program::new();
    let entry = p.input::<1>("entry");
    let calls = p.input::<2>("calls");
    let reach = p.derived::<1>("reach");
    let size = p.derived::<1>("size");
    let (f, g, n) = (p.var("F"), p.var("G"), p.var("N"));
    p.rule(reach.at([f]), [entry.at([f])]).unwrap();
    p.rule(reach.at([g]), [reach.at([f]), calls.at([f, g])])
        .unwrap();
    p.aggregate(size.at([n]), Aggregate::count([], [f], n), [reach.at([f])])
        .unwrap();
    assert!(matches!(
        plan(&p).unwrap()[..],
        [Stratum::Reach { .. }, Stratum::Joins { .. }]
    ));
    let es = [[0u64, 1], [1, 2], [2, 0], [2, 3], [5, 6]];
    let mut inputs = Inputs::new();
    inputs.facts(&entry, facts(&[[0u64]])).unwrap();
    inputs.facts(&calls, facts(&es)).unwrap();
    let out = engine().run(&p, &inputs).await.unwrap();
    assert_eq!(rows(out.get(&size).unwrap()), BTreeSet::from([vec![4]]));
    // a count feeding its own relation: refused
    let mut q = Program::new();
    let e = q.input::<2>("e");
    let a = q.derived::<2>("a");
    let (x, y, c) = (q.var("X"), q.var("Y"), q.var("C"));
    q.rule(a.at([x, y]), [e.at([x, y])]).unwrap();
    q.aggregate(a.at([x, c]), Aggregate::count([x], [y], c), [a.at([x, y])])
        .unwrap();
    assert!(matches!(plan(&q), Err(DatalogError::Program(_))));
    let mut inputs = Inputs::new();
    inputs.facts(&e, facts(&es)).unwrap();
    assert!(engine().run(&q, &inputs).await.is_err());
}

#[test]
fn malformed_aggregates_are_refused() {
    let mut p = Program::new();
    let e = p.input::<2>("e");
    let r2 = p.derived::<2>("r2");
    let r1 = p.derived::<1>("r1");
    let (x, y, n, z) = (p.var("X"), p.var("Y"), p.var("N"), p.var("Z"));
    let bad = |p: &mut Program, head, agg| {
        matches!(
            p.aggregate(head, agg, [e.at([x, y])]),
            Err(DatalogError::Program(_))
        )
    };
    // the count bound by the body
    assert!(bad(&mut p, r2.at([x, y]), Aggregate::count([x], [y], y)));
    // a head variable the count does not give
    assert!(bad(&mut p, r2.at([x, y]), Aggregate::count([x], [y], n)));
    // a grouping variable not in the head
    assert!(bad(&mut p, r1.at([n]), Aggregate::count([x], [y], n)));
    // an unbound key, an empty key, an unbound counted variable
    assert!(bad(&mut p, r1.at([x]), Aggregate::min_by([x], [z])));
    assert!(bad(&mut p, r1.at([x]), Aggregate::min_by([x], [])));
    assert!(bad(&mut p, r2.at([x, n]), Aggregate::count([x], [z], n)));
    // exactly one: the head may hold only grouped and single-valued variables
    assert!(bad(&mut p, r1.at([y]), Aggregate::exactly_one([x], [z])));
    assert!(bad(&mut p, r2.at([x, n]), Aggregate::exactly_one([x], [y])));
    assert!(!bad(
        &mut p,
        r2.at([x, y]),
        Aggregate::exactly_one([x], [y])
    ));
}

/// The first refusal of each entry: candidate refusals (entry, a, b, code) come from a
/// join; the least (a, b, code) per entry is the one reported. Everything that could
/// differ between runs (engine threads, DataFusion partitions, the order facts are given
/// in) is varied, and every run must give the same facts in the same order.
#[tokio::test]
async fn the_first_refusal_is_the_same_at_any_thread_count() {
    let pairs = random_rows(77, 3000, [8, 300, 300]); // (entry, a, b)
    let codes = random_rows(78, 900, [300, 5]); // (b, code)
    let mut p = Program::new();
    let pair = p.input::<3>("pair");
    let refuse = p.input::<2>("refuse");
    let cand = p.derived::<4>("cand");
    let first = p.derived::<4>("first");
    let first_all = p.derived::<4>("first_all");
    let (e, a, b, c) = (p.var("E"), p.var("A"), p.var("B"), p.var("C"));
    p.rule(
        cand.at([e, a, b, c]),
        [
            pair.at([e, a, b]).into(),
            refuse.at([b, c]).into(),
            ne(a, b),
        ],
    )
    .unwrap();
    p.aggregate(
        first.at([e, a, b, c]),
        Aggregate::min_by([e], [a, b, c]),
        [cand.at([e, a, b, c])],
    )
    .unwrap();
    // the first refusal of all, by (code, entry, a, b)
    p.aggregate(
        first_all.at([e, a, b, c]),
        Aggregate::min_by([], [c, e, a, b]),
        [
            pair.at([e, a, b]).into(),
            refuse.at([b, c]).into(),
            ne(a, b),
        ],
    )
    .unwrap();
    // reference
    let mut want: BTreeMap<u64, [u64; 4]> = BTreeMap::new();
    let mut all_min: Option<[u64; 4]> = None;
    for &[en, x, y] in &pairs {
        for &[z, code] in &codes {
            if z == y && x != y {
                let k = [en, x, y, code];
                want.entry(en)
                    .and_modify(|m| {
                        if k[1..] < m[1..] {
                            *m = k;
                        }
                    })
                    .or_insert(k);
                let key = |r: &[u64; 4]| (r[3], r[0], r[1], r[2]);
                if all_min.is_none_or(|m| key(&k) < key(&m)) {
                    all_min = Some(k);
                }
            }
        }
    }
    let want: Vec<Vec<u64>> = want.values().map(|r| r.to_vec()).collect();
    assert!(want.len() == 8);
    type Rows = Vec<Vec<u64>>;
    let mut runs: Vec<(Rows, Rows)> = Vec::new();
    for (threads, parts, reversed) in [(1, 1, false), (2, 4, true), (8, 8, false), (16, 3, true)] {
        let ctx =
            SessionContext::new_with_config(SessionConfig::new().with_target_partitions(parts));
        let eng: E = Engine::with_context(CpuDevice::new(threads), ctx);
        let (mut pr, mut cr) = (pairs.clone(), codes.clone());
        if reversed {
            pr.reverse();
            cr.reverse();
        }
        let mut inputs = Inputs::new();
        inputs.facts(&pair, facts(&pr)).unwrap();
        inputs.facts(&refuse, facts(&cr)).unwrap();
        let out = eng.run(&p, &inputs).await.unwrap();
        let in_order = |f: &Facts| f.rows().collect::<Vec<_>>();
        runs.push((
            in_order(out.get(&first).unwrap()),
            in_order(out.get(&first_all).unwrap()),
        ));
    }
    for r in &runs {
        assert_eq!(r.0, want, "per entry, in entry order");
        assert_eq!(r.1, vec![all_min.unwrap().to_vec()]);
    }
}

/// A count of derivations in a rule head ([`Program::count_rule`]): the paths of two
/// edges per pair of ends, a counted input's counts (parallel edges) multiplied, against a
/// plain loop over the edge list with its repeats; the bag expanded at the output.
#[tokio::test]
async fn count_of_derivations_in_a_rule_head() {
    // parallel edges 0->1 (twice), a self loop 2->2, a two-cycle 3<->4
    let list: [(u64, u64); 8] = [
        (0, 1),
        (0, 1),
        (1, 2),
        (2, 2),
        (2, 3),
        (3, 4),
        (4, 3),
        (1, 3),
    ];
    let mut counted: BTreeMap<(u64, u64), u64> = BTreeMap::new();
    for &e in &list {
        *counted.entry(e).or_default() += 1;
    }
    let mut p = Program::new();
    let e = p.input_counted::<3>("e");
    let two = p.derived_counted::<3>("two");
    let (a, b, c, x, y, n) = (
        p.var("A"),
        p.var("B"),
        p.var("C"),
        p.var("X"),
        p.var("Y"),
        p.var("N"),
    );
    p.count_rule(two.at([a, c, n]), [e.at([a, b, x]), e.at([b, c, y])])
        .unwrap();
    let mut inp = Inputs::new();
    inp.facts(
        &e,
        Facts::from_rows(3, counted.iter().map(|(&(s, t), &k)| [s, t, k])).unwrap(),
    )
    .unwrap();
    let out = engine().run(&p, &inp).await.unwrap();
    let mut want: BTreeMap<Vec<u64>, u64> = BTreeMap::new();
    for &(s, m) in &list {
        for &(m2, t) in &list {
            if m == m2 {
                *want.entry(vec![s, t]).or_default() += 1;
            }
        }
    }
    let got: BTreeMap<Vec<u64>, u64> = out
        .get(&two)
        .unwrap()
        .rows()
        .map(|r| (r[..2].to_vec(), r[2]))
        .collect();
    assert_eq!(got, want);
    let bag = out.expand(&p, &two, None).unwrap();
    assert_eq!(bag.len() as u64, want.values().sum::<u64>());
}

/// The proof of a counted relation's row ([`How::Counted`]): one part per counting rule
/// that gave the row, each the row with that rule's count, its members the rule's distinct
/// bindings, each weighing the product of its counted premises' counts; the parts' counts
/// add up to the row's. A counted premise of a derived counted relation is itself proven
/// as counted. Against plain loops over the edge list with its repeats, the proofs the same
/// at one and at four threads.
/// Per counting rule (by number), its distinct bindings (the premises' values) and their
/// weights.
type ByRule = BTreeMap<usize, BTreeMap<Vec<u64>, u64>>;

#[tokio::test]
async fn a_counted_row_has_a_proof_of_its_count() {
    // parallel edges 0->1 (twice), 2->3 (twice), a self loop 2->2, a two-cycle 3<->4
    let list: [(u64, u64); 9] = [
        (0, 1),
        (0, 1),
        (1, 2),
        (2, 2),
        (2, 3),
        (2, 3),
        (3, 4),
        (4, 3),
        (1, 3),
    ];
    let mut counted: BTreeMap<(u64, u64), u64> = BTreeMap::new();
    for &e in &list {
        *counted.entry(e).or_default() += 1;
    }
    let mut p = Program::new();
    let e = p.input_counted::<3>("e");
    let two = p.derived_counted::<3>("two");
    let three = p.derived_counted::<2>("three");
    let (a, b, c, d, x, y, m, n) = (
        p.var("A"),
        p.var("B"),
        p.var("C"),
        p.var("D"),
        p.var("X"),
        p.var("Y"),
        p.var("M"),
        p.var("N"),
    );
    // the walks of two edges and those of one, into one counted relation
    let r_two = p
        .count_rule(two.at([a, c, n]), [e.at([a, b, x]), e.at([b, c, y])])
        .unwrap();
    let r_one = p.count_rule(two.at([a, b, n]), [e.at([a, b, x])]).unwrap();
    // a counted derived relation read by a counting rule
    let r_three = p
        .count_rule(three.at([a, n]), [two.at([a, c, m]), e.at([c, d, y])])
        .unwrap();
    let mut inp = Inputs::new();
    inp.facts(
        &e,
        Facts::from_rows(3, counted.iter().map(|(&(s, t), &k)| [s, t, k])).unwrap(),
    )
    .unwrap();
    // the reference: per row of `two`, per rule, its distinct bindings and their weights
    let mut want: BTreeMap<(u64, u64), ByRule> = BTreeMap::new();
    for (&(s, t), &k1) in &counted {
        for (&(t2, u), &k2) in &counted {
            if t == t2 {
                *want
                    .entry((s, u))
                    .or_default()
                    .entry(r_two.index())
                    .or_default()
                    .entry(vec![s, t, k1, u, k2])
                    .or_default() += k1 * k2;
            }
        }
        *want
            .entry((s, t))
            .or_default()
            .entry(r_one.index())
            .or_default()
            .entry(vec![s, t, k1])
            .or_default() += k1;
    }
    let total = |rules: &ByRule| -> u64 { rules.values().flat_map(|b| b.values()).sum() };
    let mut proofs: Vec<Vec<Proof>> = Vec::new();
    for threads in [1, 4] {
        let out = E::new(CpuDevice::new(threads))
            .explain(true)
            .run(&p, &inp)
            .await
            .unwrap();
        let got: BTreeMap<(u64, u64), u64> = out
            .get(&two)
            .unwrap()
            .rows()
            .map(|r| ((r[0], r[1]), r[2]))
            .collect();
        let want_counts: BTreeMap<(u64, u64), u64> =
            want.iter().map(|(&k, r)| (k, total(r))).collect();
        assert_eq!(got, want_counts);
        let mut all = Vec::new();
        for (&(s, u), rules) in &want {
            let k = total(rules);
            let q = out
                .why(&p, &two, [s, u, k])
                .unwrap_or_else(|| panic!("a proof of two({s}, {u}, {k})"));
            assert_eq!((q.rel, q.tuple.clone()), (two.id(), vec![s, u, k]));
            let How::Counted { parts } = &q.how else {
                panic!("a counted proof: {:?}", q.how)
            };
            assert_eq!(parts.len(), rules.len());
            let mut sum = 0;
            for (part, (&rule, bindings)) in parts.iter().zip(rules) {
                let part_count: u64 = bindings.values().sum();
                sum += part_count;
                assert_eq!(part.tuple, vec![s, u, part_count]);
                let How::Aggregate {
                    rule: r,
                    members,
                    size,
                    ..
                } = &part.how
                else {
                    panic!("an aggregate part: {:?}", part.how)
                };
                assert_eq!((r.index(), *size), (rule, bindings.len()));
                let mut seen: BTreeMap<Vec<u64>, u64> = BTreeMap::new();
                for mem in members {
                    // each premise an input fact with its count; the weight their product
                    let mut key = Vec::new();
                    let mut w = 1;
                    for (i, pr) in mem.premises.iter().enumerate() {
                        assert_eq!((pr.rel, &pr.how), (e.id(), &How::Input));
                        assert_eq!(counted[&(pr.tuple[0], pr.tuple[1])], pr.tuple[2]);
                        if i == 0 {
                            key.push(pr.tuple[0]);
                        }
                        key.extend([pr.tuple[1], pr.tuple[2]]);
                        w *= pr.tuple[2];
                    }
                    assert!(seen.insert(key, w).is_none(), "a member twice");
                }
                assert_eq!(&seen, bindings);
            }
            assert_eq!(sum, k);
            assert!(q.render(&p).contains("counting rule"), "{}", q.render(&p));
            // a wrong count and the row without its count have none
            assert!(out.why(&p, &two, [s, u, k + 1]).is_none());
            assert!(out.why_id(&p, two.id(), &[s, u]).is_none());
            all.push(q);
        }
        // a row of `three`: its premises of `two` proven as counted rows
        let (&s3, _) = want.iter().next().unwrap();
        let mut k3 = 0;
        for (&(s, c), rules) in &want {
            if s == s3.0 {
                k3 += total(rules)
                    * counted
                        .iter()
                        .filter(|(t, _)| t.0 == c)
                        .map(|(_, &k)| k)
                        .sum::<u64>();
            }
        }
        let q = out.why(&p, &three, [s3.0, k3]).unwrap();
        let How::Counted { parts } = &q.how else {
            panic!("a counted proof")
        };
        let How::Aggregate { rule, members, .. } = &parts[0].how else {
            panic!("an aggregate part")
        };
        assert_eq!(*rule, r_three);
        assert!(
            members
                .iter()
                .all(|mem| matches!(mem.premises[0].how, How::Counted { .. })),
            "{}",
            q.render(&p)
        );
        all.push(q);
        proofs.push(all);
    }
    assert_eq!(proofs[0], proofs[1]);
}