crates/kleene-plan/tests/rounds.rs
//! Count and negation inside recursion: a stratum of inflationary rounds. Its relations are
//! parts in an order, each kept from round to round (it only grows) or made afresh every
//! round; a round computes the parts in order, each from this round's facts of the parts
//! before it and the round before's facts of the rest, and adds all it finds at once; the
//! rounds stop when one changes nothing. Checked against the driver's tree pass
//! (`tie_by_tree`, copied here as it is) on random trees whose macro repetitions give nodes
//! several fragment candidates; the why of a fact names the round that made it.
use std::collections::{BTreeSet, HashMap};
use kleene_plan::{
Aggregate, Atom, Cmp, Cond, Engine, Facts, How, Inputs, Literal, Part, Plan, PlanError, RelId,
Stratum, Term, Value, Var, plan,
};
use kleene_sparse::{CpuBackend, CpuDevice};
const NONE: u32 = u32::MAX;
/// The driver's node row, as much of it as the tree pass reads.
#[derive(Clone, Copy, Debug)]
struct NodeRow {
parent: u32,
frag: u32,
}
/// The driver's tree pass (nornir mimir-driver `hir::tie_by_tree`, lane to, 2026-11-27), as
/// it is: of a node's candidates it keeps those holding the fragment node of each tied
/// descendant and those inside the fragment node of its nearest tied ancestor; one left is
/// its tie; repeated until no tie is added.
fn tie_by_tree(
nodes: &mut [NodeRow],
owner_lo: &[u32],
owner_parent: &[u32],
many: Vec<(u32, Vec<u32>)>,
end: &[u32],
) -> u64 {
let n = nodes.len();
// each node's parent, an owner's root its owner's parent node
let up: Vec<u32> = {
let mut up: Vec<u32> = nodes.iter().map(|r| r.parent).collect();
for (&lo, &p) in owner_lo.iter().zip(owner_parent) {
if let Some(u) = up.get_mut(lo as usize)
&& *u == NONE
{
*u = p;
}
}
up
};
let end_of = |f: u32| end.get(f as usize).copied().unwrap_or(f.saturating_add(1));
let holds = |c: u32, f: u32| c <= f && f < end_of(c);
let mut cands: HashMap<u32, Vec<u32>> = many
.into_iter()
.filter(|(r, c)| (*r as usize) < n && !c.is_empty())
.collect();
let mut added = 0u64;
// a walk up from `r`: the nodes over it until the first tied one (that one too)
let above = |nodes: &[NodeRow], r: u32| -> Vec<u32> {
let mut out = Vec::new();
let mut p = up[r as usize];
let mut steps = 0;
while p != NONE && (p as usize) < n && steps < n {
out.push(p);
if nodes[p as usize].frag != NONE {
break;
}
p = up[p as usize];
steps += 1;
}
out
};
loop {
// each tied node: every candidate node over it, up to the first tied, holds its fragment
for t in 0..n as u32 {
let d = nodes[t as usize].frag;
if d == NONE {
continue;
}
for p in above(nodes, t) {
if let Some(c) = cands.get_mut(&p) {
c.retain(|&c| holds(c, d));
}
}
}
// each candidate node: inside its nearest tied ancestor's fragment node
for (&r, c) in cands.iter_mut() {
if let Some(&a) = above(nodes, r).last() {
let af = nodes[a as usize].frag;
if af != NONE {
c.retain(|&c| holds(af, c));
}
}
}
let one: Vec<(u32, u32)> = cands
.iter()
.filter(|(_, c)| c.len() == 1)
.map(|(&r, c)| (r, c[0]))
.collect();
cands.retain(|_, c| c.len() > 1);
if one.is_empty() {
return added;
}
for (r, f) in one {
nodes[r as usize].frag = f;
added += 1;
}
}
}
struct Lcg(u64);
impl Lcg {
fn next(&mut self) -> u64 {
self.0 = self
.0
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
self.0 >> 33
}
fn below(&mut self, n: u64) -> u64 {
self.next() % n
}
}
/// A unit like the driver sees one: a HIR tree (some subtrees owners whose root's parent
/// is left out and given by the owner), the fragment tree of its macro output in preorder
/// with each node's subtree end, where a repeated subtree is written twice (the copies a
/// span cannot tell apart). Nodes outside repetitions are tied by their span; inside one a
/// few are, the rest have both copies (and now and then a stray fragment node) as
/// candidates.
struct Unit {
nodes: Vec<NodeRow>,
owner_lo: Vec<u32>,
owner_parent: Vec<u32>,
many: Vec<(u32, Vec<u32>)>,
end: Vec<u32>,
}
fn unit(g: &mut Lcg, n: usize) -> Unit {
// HIR tree: node i's parent is an earlier node (preorder-like), a few roots.
let mut parent = vec![NONE; n];
for (i, p) in parent.iter_mut().enumerate().skip(1) {
if g.below(40) != 0 {
*p = (i as u64 - 1 - g.below((i as u64).min(4))) as u32;
}
}
let mut kids: Vec<Vec<u32>> = vec![Vec::new(); n];
for (i, &p) in parent.iter().enumerate() {
if p != NONE {
kids[p as usize].push(i as u32);
}
}
// Fragment tree in preorder: each HIR node one fragment node (copy 0); a repeated
// subtree a second copy right after the first.
struct Frags {
end: Vec<u32>,
copy: Vec<[u32; 2]>,
inside: Vec<bool>,
}
impl Frags {
fn emit(&mut self, v: u32, c: usize, kids: &[Vec<u32>], rep: bool, g: &mut Lcg) {
let me = self.end.len();
self.end.push(0);
self.copy[v as usize][c] = me as u32;
self.inside[v as usize] |= rep;
for &k in &kids[v as usize] {
if !rep && c == 0 && g.below(6) == 0 {
self.emit(k, 0, kids, true, g);
self.emit(k, 1, kids, true, g);
} else {
self.emit(k, c, kids, rep, g);
}
}
self.end[me] = self.end.len() as u32;
}
}
let mut fr = Frags {
end: Vec::new(),
copy: vec![[NONE, NONE]; n],
inside: vec![false; n],
};
for r in 0..n as u32 {
if parent[r as usize] == NONE {
fr.emit(r, 0, &kids, false, g);
}
}
let Frags { end, copy, inside } = fr;
let frags = end.len() as u64;
let mut nodes: Vec<NodeRow> = parent
.iter()
.map(|&p| NodeRow {
parent: p,
frag: NONE,
})
.collect();
let mut many = Vec::new();
for v in 0..n {
let [a, b] = copy[v];
if !inside[v] || b == NONE {
if g.below(10) != 0 {
nodes[v].frag = a;
}
} else if g.below(8) == 0 {
nodes[v].frag = if g.below(2) == 0 { a } else { b };
} else {
let mut c = vec![a, b];
if g.below(5) == 0 {
c.push(g.below(frags) as u32);
}
c.sort_unstable();
c.dedup();
many.push((v as u32, c));
}
}
// Owners: some non-roots lose their parent, which their owner gives back.
let (mut owner_lo, mut owner_parent) = (Vec::new(), Vec::new());
for (v, node) in nodes.iter_mut().enumerate().skip(1) {
if node.parent != NONE && g.below(15) == 0 {
owner_lo.push(v as u32);
owner_parent.push(node.parent);
node.parent = NONE;
}
}
Unit {
nodes,
owner_lo,
owner_parent,
many,
end,
}
}
fn v(x: Var) -> Term {
Term::Var(x)
}
fn at(rel: RelId, terms: &[Term]) -> Atom {
Atom {
rel,
terms: terms.to_vec(),
}
}
fn pos(rel: RelId, terms: &[Term]) -> Literal {
Literal::Pos(at(rel, terms))
}
fn neg(rel: RelId, terms: &[Term]) -> Literal {
Literal::Neg(at(rel, terms))
}
fn cmp(a: Var, op: Cmp, b: Var) -> Literal {
Literal::Cond(Cond::Cmp {
left: v(a),
op,
right: v(b),
})
}
/// The tree pass as rules.
struct TreeRules {
p: Plan,
up: RelId,
end: RelId,
cand: RelId,
seed: RelId,
tied: RelId,
gone: RelId,
}
fn tree_rules() -> TreeRules {
let mut p = Plan::new();
let up = p.input("up", 2); // up(child, parent)
let end = p.input("end", 2); // end(frag, first row past its subtree)
let cand = p.input("cand", 2); // cand(node, frag): a node's candidates
let seed = p.input("seed", 2); // seed(node, frag): tied by the span
let cnode = p.derived("cnode", 1);
let istied = p.derived("istied", 1);
let abv = p.derived("abv", 2);
let anc = p.derived("anc", 2);
let gone = p.derived("gone", 2);
let left = p.derived("left", 2);
let tied = p.derived("tied", 2);
let [r, c, x, q, t, d, a, af, e, f] =
["R", "C", "X", "Q", "T", "D", "A", "AF", "E", "F"].map(|s| p.var(s));
p.rule(at(cnode, &[v(r)]), [pos(cand, &[v(r), v(c)])])
.unwrap();
// istied(N): tied (as of this round's ties, made from the round before's `left`).
p.rule(at(istied, &[v(r)]), [pos(tied, &[v(r), v(f)])])
.unwrap();
// abv(T, P): untied P over tied node T, none tied between them (the driver walks up
// from each tied node to the first tied one; only the untied nodes on the way matter).
p.rule(
at(abv, &[v(t), v(x)]),
[
pos(istied, &[v(t)]),
pos(up, &[v(t), v(x)]),
neg(istied, &[v(x)]),
],
)
.unwrap();
p.rule(
at(abv, &[v(t), v(x)]),
[
pos(abv, &[v(t), v(q)]),
pos(up, &[v(q), v(x)]),
neg(istied, &[v(x)]),
],
)
.unwrap();
// anc(R, A): A over untied candidate node R, up to the first tied one.
p.rule(
at(anc, &[v(r), v(x)]),
[
pos(cnode, &[v(r)]),
neg(istied, &[v(r)]),
pos(up, &[v(r), v(x)]),
],
)
.unwrap();
p.rule(
at(anc, &[v(r), v(x)]),
[
pos(anc, &[v(r), v(q)]),
neg(istied, &[v(q)]),
pos(up, &[v(q), v(x)]),
],
)
.unwrap();
// gone(P, C): a candidate that does not hold a tied descendant's fragment ...
p.rule(
at(gone, &[v(r), v(c)]),
[
pos(cand, &[v(r), v(c)]),
pos(abv, &[v(t), v(r)]),
pos(tied, &[v(t), v(d)]),
cmp(d, Cmp::Lt, c),
],
)
.unwrap();
p.rule(
at(gone, &[v(r), v(c)]),
[
pos(cand, &[v(r), v(c)]),
pos(abv, &[v(t), v(r)]),
pos(tied, &[v(t), v(d)]),
pos(end, &[v(c), v(e)]),
cmp(d, Cmp::Ge, e),
],
)
.unwrap();
// ... or is not inside the nearest tied ancestor's fragment.
p.rule(
at(gone, &[v(r), v(c)]),
[
pos(cand, &[v(r), v(c)]),
pos(anc, &[v(r), v(a)]),
pos(tied, &[v(a), v(af)]),
cmp(c, Cmp::Lt, af),
],
)
.unwrap();
p.rule(
at(gone, &[v(r), v(c)]),
[
pos(cand, &[v(r), v(c)]),
pos(anc, &[v(r), v(a)]),
pos(tied, &[v(a), v(af)]),
pos(end, &[v(af), v(e)]),
cmp(c, Cmp::Ge, e),
],
)
.unwrap();
// left(R, C): the candidates still in, of nodes not yet tied.
p.rule(
at(left, &[v(r), v(c)]),
[
pos(cand, &[v(r), v(c)]),
neg(gone, &[v(r), v(c)]),
neg(istied, &[v(r)]),
],
)
.unwrap();
// tied: the span's ties, and each node with exactly one candidate left.
p.rule(at(tied, &[v(r), v(f)]), [pos(seed, &[v(r), v(f)])])
.unwrap();
p.aggregate(
at(tied, &[v(r), v(c)]),
Aggregate::exactly_one([r], [c]),
[pos(left, &[v(r), v(c)])],
)
.unwrap();
// tied first: round 1 holds the span's ties, and each later round adds the nodes the
// round before left one candidate (the driver's tree pass, one of its loops a round).
p.rounds([
(tied, Part::Keep),
(istied, Part::Fresh),
(abv, Part::Fresh),
(anc, Part::Fresh),
(gone, Part::Keep),
(left, Part::Fresh),
])
.unwrap();
TreeRules {
p,
up,
end,
cand,
seed,
tied,
gone,
}
}
fn pairs(rows: impl IntoIterator<Item = (u32, u32)>) -> Facts {
let (a, b): (Vec<u32>, Vec<u32>) = rows.into_iter().unzip();
Facts::from_columns(vec![a, b]).unwrap()
}
fn inputs(rules: &TreeRules, u: &Unit) -> Inputs {
let mut up: Vec<(u32, u32)> = u
.nodes
.iter()
.enumerate()
.filter(|(_, r)| r.parent != NONE)
.map(|(i, r)| (i as u32, r.parent))
.collect();
let mut given = vec![false; u.nodes.len()];
for (&lo, &p) in u.owner_lo.iter().zip(&u.owner_parent) {
if u.nodes[lo as usize].parent == NONE && !given[lo as usize] && p != NONE {
given[lo as usize] = true;
up.push((lo, p));
}
}
let end = u.end.iter().enumerate().map(|(f, &e)| (f as u32, e));
let cand = u
.many
.iter()
.flat_map(|(r, c)| c.iter().map(move |&f| (*r, f)));
let seed = u
.nodes
.iter()
.enumerate()
.filter(|(_, r)| r.frag != NONE)
.map(|(i, r)| (i as u32, r.frag));
let mut inp = Inputs::new();
inp.facts(rules.up, pairs(up))
.facts(rules.end, pairs(end))
.facts(rules.cand, pairs(cand))
.facts(rules.seed, pairs(seed));
inp
}
#[tokio::test]
async fn the_tree_pass_as_rounds_equals_the_driver_s() {
let rules = tree_rules();
let strata = plan(&rules.p).unwrap();
let rounds = strata
.iter()
.find(|s| matches!(s, Stratum::Rounds { .. }))
.expect("a stratum of rounds");
assert_eq!(rounds.kind(), "inflationary rounds (column kernels)");
let mut late_rounds = 0;
for seed in [3u64, 11, 29, 101] {
let mut g = Lcg(seed);
let u = unit(&mut g, 3000);
let mut want_nodes = u.nodes.clone();
let added = tie_by_tree(
&mut want_nodes,
&u.owner_lo,
&u.owner_parent,
u.many.clone(),
&u.end,
);
assert!(added > 50, "seed {seed}: the pass ties something ({added})");
let want: BTreeSet<Vec<Value>> = want_nodes
.iter()
.enumerate()
.filter(|(_, r)| r.frag != NONE)
.map(|(i, r)| vec![i as Value, r.frag as Value])
.collect();
for threads in [1, 6] {
let engine: Engine<CpuBackend> = Engine::new(CpuDevice::new(threads)).explain(true);
let out = engine.run(&rules.p, &inputs(&rules, &u)).await.unwrap();
let got: BTreeSet<Vec<Value>> = out.get(rules.tied).unwrap().rows().collect();
assert_eq!(got.len(), want.len(), "seed {seed}");
assert_eq!(got, want, "seed {seed}");
let report = out
.report
.strata
.iter()
.find(|s| s.kind == "inflationary rounds (column kernels)")
.unwrap();
assert!(report.rounds >= 3, "seed {seed}: {} rounds", report.rounds);
// The why of each tie the tree made: the exactly-one over the candidates the
// round before left, proven as of that round.
for t in want.iter().filter(|t| u.nodes[t[0] as usize].frag == NONE) {
let proof = out.why(&rules.p, rules.tied, t).unwrap();
let round = proof.round.expect("a fact of a round names it");
assert!(round >= 2 && round <= report.rounds, "{round}");
late_rounds += usize::from(round > 2);
let How::Aggregate { members, size, .. } = &proof.how else {
panic!("{}", proof.render(&rules.p));
};
assert_eq!((*size, members.len()), (1, 1));
let left = &members[0].premises[0];
assert_eq!(left.round, Some(round - 1), "{}", proof.render(&rules.p));
assert!(proof.render(&rules.p).contains(&format!("round {round}")));
}
// A candidate dropped: proven in its round from facts of that round or before.
let gone = out.get(rules.gone).unwrap();
if !gone.is_empty() {
let row = gone.row(gone.len() / 2);
let proof = out.why(&rules.p, rules.gone, &row).unwrap();
assert!(proof.round.is_some());
assert!(matches!(proof.how, How::Rule { .. }));
}
}
}
assert!(
late_rounds > 0,
"some ties need more than one round of the tree"
);
}
#[test]
fn rounds_are_checked() {
let mut p = Plan::new();
let e = p.input("e", 2);
let a = p.derived("a", 1);
let b = p.derived("b", 1);
let o = p.derived("o", 1);
let (x, y) = (p.var("X"), p.var("Y"));
p.rule(at(a, &[v(x)]), [pos(e, &[v(x), v(y)]), neg(b, &[v(y)])])
.unwrap();
p.rule(at(b, &[v(y)]), [pos(e, &[v(x), v(y)]), neg(a, &[v(x)])])
.unwrap();
// Without rounds the two negate each other inside one recursion.
assert!(matches!(plan(&p), Err(PlanError::Program(_))));
// Not derived, twice, or in two groups: refused when declared.
assert!(p.rounds([(e, Part::Keep)]).is_err());
assert!(p.rounds([(a, Part::Keep), (a, Part::Fresh)]).is_err());
assert!(p.rounds([]).is_err());
let mut q = p.clone();
q.rounds([(a, Part::Keep), (b, Part::Keep)]).unwrap();
assert!(q.rounds([(a, Part::Fresh)]).is_err());
assert!(plan(&q).is_ok());
// A relation outside the group in its recursion is refused.
p.rule(at(o, &[v(x)]), [pos(a, &[v(x)])]).unwrap();
p.rule(at(a, &[v(x)]), [pos(o, &[v(x)])]).unwrap();
let mut r = p.clone();
r.rounds([(a, Part::Keep), (b, Part::Keep)]).unwrap();
assert!(matches!(plan(&r), Err(PlanError::Program(_))));
// A part may not negate itself.
let mut s = Plan::new();
let e = s.input("e", 1);
let a = s.derived("a", 1);
let x = s.var("X");
s.rule(at(a, &[v(x)]), [pos(e, &[v(x)]), neg(a, &[v(x)])])
.unwrap();
s.rounds([(a, Part::Keep)]).unwrap();
assert!(matches!(plan(&s), Err(PlanError::Program(_))));
}
#[tokio::test]
async fn a_round_reads_the_parts_before_it_now_and_the_rest_as_they_were() {
// odd(X) and even(X) along a chain, each from the other with negation:
// [even keep, odd keep]: round 1 even = {0} (odd empty: everything not odd ... with e),
// a small program whose answer depends on the order.
let mut p = Plan::new();
let s = p.input("s", 1); // s(0)
let e = p.input("e", 2); // e(i, i+1)
let ev = p.derived("ev", 1);
let od = p.derived("od", 1);
let (x, y) = (p.var("X"), p.var("Y"));
p.rule(at(ev, &[v(x)]), [pos(s, &[v(x)])]).unwrap();
// od(Y) :- ev(X), e(X, Y), !ev(Y). ev(Y) :- od(X), e(X, Y), !od(Y).
p.rule(
at(od, &[v(y)]),
[pos(ev, &[v(x)]), pos(e, &[v(x), v(y)]), neg(ev, &[v(y)])],
)
.unwrap();
p.rule(
at(ev, &[v(y)]),
[pos(od, &[v(x)]), pos(e, &[v(x), v(y)]), neg(od, &[v(y)])],
)
.unwrap();
p.rounds([(ev, Part::Keep), (od, Part::Keep)]).unwrap();
let n = 9u32;
let mut inp = Inputs::new();
inp.facts(s, Facts::from_rows(1, [[0u32]]).unwrap())
.facts(e, pairs((0..n).map(|i| (i, i + 1))));
let engine: Engine<CpuBackend> = Engine::new(CpuDevice::new(2)).explain(true);
let out = engine.run(&p, &inp).await.unwrap();
let ev_got: Vec<Value> = out.get(ev).unwrap().column(0).iter().collect();
let od_got: Vec<Value> = out.get(od).unwrap().column(0).iter().collect();
assert_eq!(ev_got, (0..=n as Value).step_by(2).collect::<Vec<_>>());
assert_eq!(od_got, (1..=n as Value).step_by(2).collect::<Vec<_>>());
// ev(2k) comes in round k+1 (od of round k is read from its round, before ev), od(2k+1)
// in the same round as ev(2k).
for k in 0..=(n as Value) / 2 {
let pr = out.why(&p, ev, &[2 * k]).unwrap();
assert_eq!(pr.round, Some(k as u32 + 1), "{}", pr.render(&p));
if 2 * k < n as Value {
let pr = out.why(&p, od, &[2 * k + 1]).unwrap();
assert_eq!(pr.round, Some(k as u32 + 1), "{}", pr.render(&p));
}
}
}
#[tokio::test]
async fn rounds_that_go_in_a_circle_are_refused() {
// [b fresh, a fresh]: b is a as the round before left it, a is s without b; a flips
// between s and nothing and never settles.
let mut p = Plan::new();
let s = p.input("s", 1);
let a = p.derived("a", 1);
let b = p.derived("b", 1);
let x = p.var("X");
p.rule(at(b, &[v(x)]), [pos(a, &[v(x)])]).unwrap();
p.rule(at(a, &[v(x)]), [pos(s, &[v(x)]), neg(b, &[v(x)])])
.unwrap();
p.rounds([(b, Part::Fresh), (a, Part::Fresh)]).unwrap();
let mut inp = Inputs::new();
inp.facts(s, Facts::from_rows(1, [[1u32], [2]]).unwrap());
let engine: Engine<CpuBackend> = Engine::new(CpuDevice::new(1));
let err = engine.run(&p, &inp).await.unwrap_err();
assert!(err.to_string().contains("circle"), "{err}");
}