crates/kleene-plan/src/plan.rs
use crate::rules::{Agg, Aggregate, Part, Plan, RelId, RelKind, Rule, RuleId, Term};
use crate::{PlanError, Result};
/// Which way a recursive rule walks its edge relation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Way {
/// `r(Y) :- r(X), e(X, Y)`: along the edges.
Forward,
/// `r(Y) :- r(X), e(Y, X)`: against them.
Backward,
}
pub use kleene_graph::Side;
/// How one stratum (a set of mutually recursive derived relations) is computed.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Stratum {
/// A one-column relation grown along a two-column one: seeds from its other rules,
/// then a breadth-first search on kleene-graph.
Reach {
/// The relation.
rel: RelId,
/// Its non-recursive rules (the seeds).
seeds: Vec<RuleId>,
/// The recursive rule.
step: RuleId,
/// The edge relation.
edge: RelId,
/// Along or against the edges.
way: Way,
},
/// A two-column relation closed over a two-column one: semi-naive products on
/// kleene-sparse, each round masked by what is already known.
Closure {
/// The relation.
rel: RelId,
/// Its non-recursive rules (the base pairs).
base: Vec<RuleId>,
/// The recursive rule.
step: RuleId,
/// The edge relation.
edge: RelId,
/// Right or left linear.
side: Side,
},
/// A two-column relation of (entry, vertex) grown along a labelled edge relation,
/// where an edge counts for an entry only when its label holds the entry:
/// `r(E, T) :- r(E, S), edge(S, T, L), has(L, E)` (any column order of `edge` and
/// `has`, `E` first or second in `r`). Seeds from its other rules, then one walk of
/// entry bitmasks on kleene-graph ([`kleene_graph::label_reach`]), 64 entries a word.
LabelReach {
/// The relation.
rel: RelId,
/// Its non-recursive rules (the seed pairs).
seeds: Vec<RuleId>,
/// The recursive rule.
step: RuleId,
/// The labelled edge relation.
edge: RelId,
/// The relation of (label, entry) pairs.
has: RelId,
/// The column of `rel` that holds the entry (the other holds the vertex).
entry: usize,
/// The columns of `edge` that hold the source, the target and the label.
edge_cols: [usize; 3],
/// The columns of `has` that hold the label and the entry.
has_cols: [usize; 2],
},
/// A relation given by [`Plan::walk`]: the ends (or (start, end) pairs) of the walks
/// of bounded length from `from` along `edge`, as frontier steps on kleene-graph.
Walk {
/// The relation.
rel: RelId,
/// The starts.
from: RelId,
/// The edge relation.
edge: RelId,
/// Along or against the edges.
way: Way,
/// How many edges.
hops: crate::Hops,
/// `Some`: shortest paths as vertex lists ([`crate::Plan::shortest`]).
shortest: Option<crate::Shortest>,
},
/// A relation given by [`crate::Plan::procedure`]: a kleene-graph kernel's answer.
Procedure {
/// The relation.
rel: RelId,
/// The edge relation.
edge: RelId,
/// The algorithm.
procedure: crate::Procedure,
},
/// Everything else: semi-naive rounds of column-kernel joins (hash joins on packed
/// keys, range joins, anti-joins, distinct rows, sorted groups).
Joins {
/// The relations.
rels: Vec<RelId>,
/// Their rules.
rules: Vec<RuleId>,
},
/// Numbered heads ([`crate::Aggregate::set_number`]) and their tables of sets
/// ([`Plan::sets`]), read by none of their rules: the heads' other rules run once, then
/// every numbering rule's groups, the new sets numbered in one moment.
Sets {
/// The relations: the heads and the tables.
rels: Vec<RelId>,
/// Their rules.
rules: Vec<RuleId>,
},
/// A group of [`Plan::rounds`]: inflationary rounds, each computing the parts in order
/// (each one a fixed point of column-kernel joins over this round's facts of the parts
/// before it and the round before's of the rest), until a round changes no part.
Rounds {
/// The parts, in order.
parts: Vec<(RelId, Part)>,
/// Their rules.
rules: Vec<RuleId>,
},
}
impl Stratum {
/// The relations the stratum derives.
pub fn relations(&self) -> Vec<RelId> {
match self {
Stratum::Reach { rel, .. }
| Stratum::Closure { rel, .. }
| Stratum::LabelReach { rel, .. }
| Stratum::Walk { rel, .. }
| Stratum::Procedure { rel, .. } => vec![*rel],
Stratum::Joins { rels, .. } | Stratum::Sets { rels, .. } => rels.clone(),
Stratum::Rounds { parts, .. } => parts.iter().map(|p| p.0).collect(),
}
}
/// Whether the stratum runs split over the parts of its graph in local-first rounds
/// (kleene-graph's `reach_rounds`, `closure_rounds`, `components_rounds`,
/// `sssp_rounds`): a reach, a closure (Datalog recursion with no negation inside the
/// loop), weak components and shortest paths from one source, where a value only
/// improves, so the order of the work cannot change the answer. A stratum of joins splits
/// when it does not recurse (its rules read none of its own relations: it runs where its
/// inputs are); recursion over joins, rounds, labelled reach, walks and the other
/// procedures do not split and run on one machine, and so does a stratum of joins whose
/// rules make strings (`concat`, `substr`) and one of set numbers (one table numbers
/// every set).
pub fn splittable(&self, p: &crate::Plan) -> bool {
match self {
Stratum::Reach { .. } | Stratum::Closure { .. } => true,
Stratum::Procedure { procedure, .. } => matches!(
procedure,
crate::Procedure::WeakComponents | crate::Procedure::Sssp { .. }
),
// (a rule that makes strings adds to the run's one dictionary: one machine)
Stratum::Joins { rels, rules } => rules.iter().all(|&r| {
let rule = p.rule_at(r);
!rule
.body
.iter()
.chain(&rule.negated)
.any(|a| rels.contains(&a.rel))
&& !rule.computes.iter().any(|c| c.expr.makes_string())
}),
Stratum::LabelReach { .. }
| Stratum::Walk { .. }
| Stratum::Rounds { .. }
| Stratum::Sets { .. } => false,
}
}
/// A short name of the plan.
pub fn kind(&self) -> &'static str {
match self {
Stratum::Reach { .. } => "reach (kleene-graph BFS)",
Stratum::Closure { .. } => "closure (kleene-sparse mxm)",
Stratum::LabelReach { .. } => "labelled reach (kleene-graph mask walk)",
Stratum::Walk {
shortest: Some(_), ..
} => "shortest paths (kleene-graph BFS per start)",
Stratum::Walk { .. } => "bounded walk (kleene-graph frontier steps)",
Stratum::Procedure { .. } => "graph procedure (a kleene-graph kernel)",
Stratum::Joins { .. } => "joins (column kernels)",
Stratum::Rounds { .. } => "inflationary rounds (column kernels)",
Stratum::Sets { .. } => "set numbers (column kernels)",
}
}
}
/// The strata of a plan, dependencies first: the derived relations' dependency
/// graph (negated atoms included) cut into strongly connected parts (Tarjan), each given a
/// plan. A part whose rules negate one of its own relations, or aggregate over one,
/// cannot be stratified and is refused, unless it is a group of [`Plan::rounds`]: the
/// group is one part (its recursion must not take in other relations), and only a rule
/// that negates or aggregates over its own head relation is refused there.
pub fn plan(p: &Plan) -> Result<Vec<Stratum>> {
let n = p.relations().len();
let mut deps: Vec<Vec<usize>> = vec![Vec::new(); n];
for r in p.rules() {
for a in r.body.iter().chain(&r.negated) {
deps[r.head.rel.index()].push(a.rel.index());
}
}
for w in p.walks() {
deps[w.rel.index()].extend([w.from.index(), w.edge.index()]);
}
for c in p.calls() {
deps[c.rel.index()].push(c.edge.index());
if let Some(w) = c.procedure.weights() {
deps[c.rel.index()].push(w.index());
}
}
// A table of sets and the heads numbered into it are computed together: a ring each.
for r in p.rules() {
if let Some(t) = numbers_into(r) {
deps[t.index()].push(r.head.rel.index());
deps[r.head.rel.index()].push(t.index());
}
}
// A group of rounds is one part: its relations in a ring.
for g in p.round_groups() {
for (i, &(r, _)) in g.iter().enumerate() {
deps[r.index()].push(g[(i + 1) % g.len()].0.index());
}
}
let derived: Vec<bool> = p
.relations()
.iter()
.map(|r| r.kind == RelKind::Derived)
.collect();
let sccs = tarjan(&deps, &derived);
let mut out = Vec::with_capacity(sccs.len());
for scc in sccs {
let rels: Vec<RelId> = scc.iter().map(|&i| RelId(i as u32)).collect();
let rules: Vec<RuleId> = p
.rules()
.iter()
.enumerate()
.filter(|(_, r)| rels.contains(&r.head.rel))
.map(|(i, _)| RuleId(i as u32))
.collect();
// a string made by concat inside a recursion can grow for ever
if let Some(&r) = rules.iter().find(|&&r| {
let rule = p.rule_at(r);
rule.computes.iter().any(|c| c.expr.concats())
&& rule.body.iter().any(|a| rels.contains(&a.rel))
}) {
return Err(PlanError::Program(format!(
"a string made by concat inside a recursion does not end; make it outside the cycle: {}",
p.show_rule(r)
)));
}
let tables: Vec<RelId> = rels
.iter()
.copied()
.filter(|&r| p.set_limit(r).is_some())
.collect();
if !tables.is_empty() && rels.iter().all(|&r| p.round_of(r).is_none()) {
// Plain use: no rule of the part reads a relation of it. Else the recursion
// runs through the table: a group of rounds, which names the line it needs.
if rules
.iter()
.any(|&r| p.rule_at(r).body.iter().any(|a| rels.contains(&a.rel)))
{
let line: Vec<String> = rels
.iter()
.filter(|r| !tables.contains(r))
.chain(&tables)
.map(|&r| format!("{}: keep", p.relation_info(r).name))
.collect();
let names: Vec<String> = tables
.iter()
.map(|&t| format!("`{}`", p.relation_info(t).name))
.collect();
return Err(PlanError::Program(format!(
"the recursion through the table of sets {} runs as a group of rounds (Plan::rounds); \
it needs the line: rounds {}.",
names.join(", "),
line.join(", ")
)));
}
out.push(Stratum::Sets { rels, rules });
continue;
}
if let Some((g, _)) = rels.iter().find_map(|&r| p.round_of(r)) {
let parts = &p.round_groups()[g];
if let Some(&o) = rels.iter().find(|&&r| !parts.iter().any(|q| q.0 == r)) {
return Err(PlanError::Program(format!(
"`{}` is in the recursion of a group of rounds without being a part of it",
p.relation_info(o).name
)));
}
for &r in &rules {
let rule = p.rule_at(r);
let own = |a: &crate::rules::Atom| a.rel == rule.head.rel;
if rule.negated.iter().any(own) || (rule.groups() && rule.body.iter().any(own)) {
return Err(PlanError::Program(format!(
"a part of rounds negates or aggregates over itself: {}",
p.show_rule(r)
)));
}
}
out.push(Stratum::Rounds {
parts: parts.clone(),
rules,
});
continue;
}
if let Some(c) = rels.iter().find_map(|&r| p.call_of(r)) {
if rels.len() > 1 {
return Err(PlanError::Program(format!(
"`{}` is given by a procedure inside a recursion",
p.relation_info(c.rel).name
)));
}
out.push(Stratum::Procedure {
rel: c.rel,
edge: c.edge,
procedure: c.procedure,
});
continue;
}
if let Some(w) = rels.iter().find_map(|&r| p.walk_of(r)) {
if rels.len() > 1 || [w.from, w.edge].contains(&w.rel) {
return Err(PlanError::Program(format!(
"`{}` is given by a walk inside a recursion",
p.relation_info(w.rel).name
)));
}
out.push(Stratum::Walk {
rel: w.rel,
from: w.from,
edge: w.edge,
way: w.way,
hops: w.hops,
shortest: w.shortest,
});
continue;
}
for &r in &rules {
let rule = p.rule_at(r);
if let Some(a) = rule.negated.iter().find(|a| rels.contains(&a.rel)) {
return Err(PlanError::Program(format!(
"not stratifiable: `{}` negates `{}` inside its own recursion ({})",
p.relation_info(rule.head.rel).name,
p.relation_info(a.rel).name,
p.show_rule(r)
)));
}
if rule.groups()
&& let Some(a) = rule.body.iter().find(|a| rels.contains(&a.rel))
{
return Err(PlanError::Program(format!(
"not stratifiable: `{}` aggregates over `{}` inside its own recursion ({})",
p.relation_info(rule.head.rel).name,
p.relation_info(a.rel).name,
p.show_rule(r)
)));
}
}
out.push(special(p, &rels, &rules).unwrap_or(Stratum::Joins { rels, rules }));
}
Ok(out)
}
/// Strongly connected parts of the derived relations, each after the parts it depends on.
fn tarjan(deps: &[Vec<usize>], keep: &[bool]) -> Vec<Vec<usize>> {
struct T<'a> {
deps: &'a [Vec<usize>],
keep: &'a [bool],
index: Vec<Option<usize>>,
low: Vec<usize>,
on: Vec<bool>,
stack: Vec<usize>,
next: usize,
out: Vec<Vec<usize>>,
}
impl T<'_> {
fn visit(&mut self, v: usize) {
self.index[v] = Some(self.next);
self.low[v] = self.next;
self.next += 1;
self.stack.push(v);
self.on[v] = true;
for k in 0..self.deps[v].len() {
let w = self.deps[v][k];
if !self.keep[w] {
continue;
}
match self.index[w] {
None => {
self.visit(w);
self.low[v] = self.low[v].min(self.low[w]);
}
Some(iw) if self.on[w] => self.low[v] = self.low[v].min(iw),
Some(_) => {}
}
}
if Some(self.low[v]) == self.index[v] {
let mut scc = Vec::new();
while let Some(w) = self.stack.pop() {
self.on[w] = false;
scc.push(w);
if w == v {
break;
}
}
scc.sort_unstable();
self.out.push(scc);
}
}
}
let n = deps.len();
let mut t = T {
deps,
keep,
index: vec![None; n],
low: vec![0; n],
on: vec![false; n],
stack: Vec::new(),
next: 0,
out: Vec::new(),
};
for (v, &k) in keep.iter().enumerate() {
if k && t.index[v].is_none() {
t.visit(v);
}
}
t.out
}
/// A reach, closure or labelled reach plan, when the stratum has that shape.
fn special(p: &Plan, rels: &[RelId], rules: &[RuleId]) -> Option<Stratum> {
let [rel] = rels else { return None };
let rel = *rel;
let mentions = |id: RuleId| p.rule_at(id).body.iter().any(|a| a.rel == rel);
let rec: Vec<RuleId> = rules.iter().copied().filter(|&r| mentions(r)).collect();
let others: Vec<RuleId> = rules.iter().copied().filter(|&r| !mentions(r)).collect();
let [step] = rec[..] else { return None };
if others.is_empty() {
return None;
}
let rule = p.rule_at(step);
if !rule.negated.is_empty()
|| !rule.conds.is_empty()
|| !rule.computes.is_empty()
|| rule.groups()
{
return None;
}
// graph strata hold u64 vertex ids: typed relations are joined
if p.is_typed(rel) || rule.body.iter().any(|a| p.is_typed(a.rel)) {
return None;
}
if rule.body.len() == 3 {
return label_reach(p, rel, others, step);
}
let [a, b] = &rule.body[..] else { return None };
let (own, edge) = if a.rel == rel { (a, b) } else { (b, a) };
// An external edge relation may answer lookups only: it is joined, never a matrix.
if edge.rel == rel
|| p.relation_info(edge.rel).arity != 2
|| p.relation_info(edge.rel).kind == RelKind::External
{
return None;
}
let vars = |terms: &[Term]| -> Option<Vec<crate::rules::Var>> {
terms
.iter()
.map(|t| match t {
Term::Var(v) => Some(*v),
Term::Const(_) => None,
})
.collect()
};
let h = vars(&rule.head.terms)?;
let o = vars(&own.terms)?;
let e = vars(&edge.terms)?;
match p.relation_info(rel).arity {
1 => {
let (y, x) = (h[0], o[0]);
if x == y {
return None;
}
let way = if e == [x, y] {
Way::Forward
} else if e == [y, x] {
Way::Backward
} else {
return None;
};
Some(Stratum::Reach {
rel,
seeds: others,
step,
edge: edge.rel,
way,
})
}
2 => {
// Right: t(X,Z) :- t(X,Y), e(Y,Z). Left: t(X,Z) :- e(X,Y), t(Y,Z).
let (x, z) = (h[0], h[1]);
let distinct3 = |p: crate::rules::Var, q, r| p != q && q != r && p != r;
if o[0] == x && e[1] == z && o[1] == e[0] && distinct3(x, o[1], z) {
return Some(Stratum::Closure {
rel,
base: others,
step,
edge: edge.rel,
side: Side::Right,
});
}
if e[0] == x && o[1] == z && e[1] == o[0] && distinct3(x, e[1], z) {
return Some(Stratum::Closure {
rel,
base: others,
step,
edge: edge.rel,
side: Side::Left,
});
}
None
}
_ => None,
}
}
/// The labelled reach plan of `step` (three positive atoms, all variables), when it has
/// the shape `r(E, T) :- r(E, S), edge(S, T, L), has(L, E)`.
fn label_reach(p: &Plan, rel: RelId, seeds: Vec<RuleId>, step: RuleId) -> Option<Stratum> {
let rule = p.rule_at(step);
if p.relation_info(rel).arity != 2 {
return None;
}
let own = rule.body.iter().find(|a| a.rel == rel)?;
let edge = rule.body.iter().find(|a| a.terms.len() == 3)?;
let has = rule
.body
.iter()
.find(|a| a.terms.len() == 2 && a.rel != rel)?;
// External relations may answer lookups only: they are joined, never listed here.
let plain = |r: RelId| r != rel && p.relation_info(r).kind != RelKind::External;
if !plain(edge.rel) || !plain(has.rel) || rule.body.iter().filter(|a| a.rel == rel).count() != 1
{
return None;
}
let vars = |terms: &[Term]| -> Option<Vec<crate::rules::Var>> {
terms
.iter()
.map(|t| match t {
Term::Var(v) => Some(*v),
Term::Const(_) => None,
})
.collect()
};
let (h, o, e, l) = (
vars(&rule.head.terms)?,
vars(&own.terms)?,
vars(&edge.terms)?,
vars(&has.terms)?,
);
// the entry is the column the head and the recursive atom share
let entry = (0..2).find(|&i| h[i] == o[i])?;
let (ev, tv, sv) = (h[entry], h[1 - entry], o[1 - entry]);
let pos = |list: &[crate::rules::Var], v| list.iter().position(|&x| x == v);
let lv = *e.iter().find(|&&x| x != sv && x != tv)?;
let all = [ev, sv, tv, lv];
if (0..4).any(|i| (i + 1..4).any(|j| all[i] == all[j])) {
return None;
}
let edge_cols = [pos(&e, sv)?, pos(&e, tv)?, pos(&e, lv)?];
let has_cols = [pos(&l, lv)?, pos(&l, ev)?];
Some(Stratum::LabelReach {
rel,
seeds,
step,
edge: edge.rel,
has: has.rel,
entry,
edge_cols,
has_cols,
})
}
/// The table of sets rule `r` numbers into, when it is a set number rule.
pub(crate) fn numbers_into(r: &Rule) -> Option<RelId> {
match &r.agg {
Some(Aggregate {
agg: Agg::SetNumber { table, .. },
..
}) => Some(*table),
_ => None,
}
}