crates/kleene-plan/src/side.rs
//! Columns side by side read in one scan: in a rule body, positive atoms over input
//! relations that are two columns each over ONE id column (`Source::Columns` sharing the id
//! array, as a catalog's properties of one vertex type are) and that share the variable of
//! that id run as one atom over those columns side by side, `(id, v1, .., vk)`
//! ([`crate::Catalog::columns`]'s shape), instead of one join per column.
//!
//! The engine applies it to every plan before the index choice ([`crate::Engine::side_by_side`],
//! on by default). Rules keep their numbers, and the run keeps the plan as written, so a
//! proof shows each atom as written, by its own name ([`crate::Proof`]'s premises), as a run
//! without the pass does. Anything else stays a join: an atom with an index, a counted input,
//! another source, a pair over another id array, a value variable two of the atoms read, a
//! relation read twice, an unsigned column with nulls (its relation leaves such a row out,
//! the scan would not).
use std::collections::HashMap;
use arrow_array::{Array, ArrayRef};
use crate::rules::{Atom, Plan, RelId, RelKind, Term, Var};
use crate::{Inputs, Result, Source, Type};
/// The plan with its side-by-side atoms merged, its inputs (each merged relation given its
/// columns), and how many atoms the rules read in merged scans; `None` when no
/// rule has two such atoms.
pub(crate) fn merge(p: &Plan, inputs: &Inputs) -> Result<Option<(Plan, Inputs, usize)>> {
let mut q: Option<(Plan, Inputs)> = None;
let mut made: HashMap<Vec<RelId>, RelId> = HashMap::new();
let mut merged = 0;
for (r, rule) in p.rules().iter().enumerate() {
// the atoms that may join a scan, by (id array, id variable)
let mut groups: Vec<((usize, Var), Vec<usize>)> = Vec::new();
for (i, a) in rule.body.iter().enumerate() {
let Some((ids, v)) = side_atom(p, inputs, a) else {
continue;
};
let key = (ids, v);
match groups.iter_mut().find(|g| g.0 == key) {
Some(g) => g.1.push(i),
None => groups.push((key, vec![i])),
}
}
let mut body: Vec<Option<Atom>> = rule.body.iter().cloned().map(Some).collect();
let mut any = false;
for (_, at) in groups {
let at = distinct(&rule.body, at);
if at.len() < 2 {
continue;
}
let rels: Vec<RelId> = at.iter().map(|&i| rule.body[i].rel).collect();
let (q, ins) = q.get_or_insert_with(|| (p.clone(), inputs.clone()));
let rel = match made.get(&rels) {
Some(&rel) => rel,
None => {
let rel = side_relation(p, inputs, q, ins, &rels);
made.insert(rels.clone(), rel);
rel
}
};
let mut terms = vec![rule.body[at[0]].terms[0]];
terms.extend(at.iter().map(|&i| rule.body[i].terms[1]));
body[at[0]] = Some(Atom { rel, terms });
for &i in &at[1..] {
body[i] = None;
}
merged += at.len();
any = true;
}
if any {
let (q, _) = q.as_mut().expect("made with the first merge");
q.rule_mut(crate::RuleId(r as u32)).body = body.into_iter().flatten().collect();
}
}
Ok(q.map(|(q, ins)| (q, ins, merged)))
}
/// The id array (by address) and the id variable of `a`, when `a` may be read in a scan of
/// columns side by side: a positive atom `rel(I, x)` of an input of two columns over
/// [`Source::Columns`], uncounted, with no index, its second column no unsigned column
/// with nulls.
fn side_atom(p: &Plan, inputs: &Inputs, a: &Atom) -> Option<(usize, Var)> {
let info = p.relation_info(a.rel);
if info.kind != RelKind::Input
|| info.arity != 2
|| p.is_counted(a.rel)
|| inputs.index_of(a.rel).is_some()
{
return None;
}
let Some(Source::Columns(cols)) = inputs.source(a.rel) else {
return None;
};
let [ids, values] = &cols[..] else {
return None;
};
if p.types(a.rel)[1] == Type::U64 && values.null_count() > 0 {
return None;
}
if ids.null_count() > 0 {
return None;
}
let Term::Var(v) = a.terms[0] else {
return None;
};
if a.terms[1] == Term::Var(v) {
return None;
}
Some((address(ids), v))
}
/// Of the atoms `at` of `body` (one group), those a scan may read together: each relation
/// once, and no value variable read by two of them (a later one that would stays a join).
fn distinct(body: &[Atom], at: Vec<usize>) -> Vec<usize> {
let mut keep: Vec<usize> = Vec::with_capacity(at.len());
for i in at {
let a = &body[i];
let clash = keep.iter().any(|&j| {
let b = &body[j];
b.rel == a.rel || (matches!(a.terms[1], Term::Var(_)) && b.terms[1] == a.terms[1])
});
if !clash {
keep.push(i);
}
}
keep
}
/// The input relation of `rels`' columns side by side, `(id, v1, .., vk)`, declared in `q`
/// and given its columns in `ins`.
fn side_relation(
p: &Plan,
inputs: &Inputs,
q: &mut Plan,
ins: &mut Inputs,
rels: &[RelId],
) -> RelId {
let mut columns: Vec<ArrayRef> = Vec::with_capacity(rels.len() + 1);
let mut types = vec![p.types(rels[0])[0]];
let mut names: Vec<&str> = Vec::with_capacity(rels.len());
for &r in rels {
let Some(Source::Columns(cols)) = inputs.source(r) else {
unreachable!("checked by side_atom");
};
if columns.is_empty() {
columns.push(cols[0].clone());
}
columns.push(cols[1].clone());
types.push(p.types(r)[1]);
names.push(&p.relation_info(r).name);
}
let name = format!("{} side by side", names.join(" + "));
let rel = if types.iter().all(|&t| t == Type::U64) {
q.input(&name, types.len())
} else {
q.input_typed(&name, &types)
};
ins.set(rel, Source::Columns(columns));
rel
}
/// The address of an Arrow array's data, to tell one id column from another.
fn address(a: &ArrayRef) -> usize {
std::sync::Arc::as_ptr(a) as *const () as usize
}