crates/kleene-plan/src/index.rs
//! Index choice: a condition on an input with an index becomes a lookup of the index.
//!
//! An input relation may have an [`Index`] ([`Inputs::index`]; [`Inputs::bind`] gives each
//! input the catalog names its index too): a range index of an (id, value) property, a name
//! index of an (id, string) property, or the id blocks of a one-column label. For one
//! variable, a [`Lookup`] holds what bounds it: its properties (each with the index of every
//! relation holding it), the id blocks it lies in, its comparisons with constants and its
//! ORs of equalities. [`Lookup::choose`] picks one index (an id range of blocks first, then
//! a name lookup, then a range lookup, an equality preferred, then one range lookup per value
//! of an OR of equalities) and [`Choice::build`] makes the relation of the ids it finds (a
//! derived relation of one column, read from the index's lookups alone, so it leads the
//! joins). The choice never changes an answer: the found ids are a superset of the ids the
//! comparisons keep, and the comparisons stay where they are.
//!
//! The engine applies it to every rule of a plan whose inputs have indexes
//! ([`crate::Engine::index_choice`], on by default): for each variable of a rule's body that
//! an indexed input's atom binds, a chosen index's relation joins the body, and the label
//! atom the index's ids lie within (or the blocks' label, for an id range) is dropped. An
//! external atom whose other terms are all constants (a lookup written by hand,
//! `idx(10, 49, N)`) is asked once in a relation of its own, the same plan. kleene-gql
//! builds a [`Lookup`] per node of a pattern and uses the same choice.
use std::collections::HashMap;
use std::sync::Arc;
use crate::rules::{Atom, Cmp, Cond, Literal, Plan, RelId, RelKind, Term, Var};
use crate::{IdRanges, Inputs, NULL, NameHits, NameIndex, Result, Source, Type, Value};
/// An index of an input relation, for the index choice.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum Index {
/// Of an (id, value) property of an unsigned, signed or float type: `lookup` holds
/// (lo, hi, id) for each id whose value (its order-keeping code) lies in `lo..=hi`,
/// answered with `lo` and `hi` bound (an external relation, such as kleene's
/// `RangeRel`). `within`: the name of the one-column label relation every such id is in.
Range {
/// The lookup relation's source.
lookup: Source,
/// The label holding every id the index finds.
within: Option<String>,
},
/// Of an (id, string) property: the ids of a string.
Names {
/// The index.
index: Arc<dyn NameIndex>,
/// The label holding every id the index finds.
within: Option<String>,
},
/// Of a one-column label relation: its ids are exactly the `(base, count)` blocks (a
/// vertex type of one id space).
Blocks(Vec<(Value, Value)>),
}
/// What a comparison of a [`Lookup`] is on.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum On {
/// The variable itself (its id).
Id,
/// Property `i` of [`Lookup::props`].
Prop(usize),
}
/// A comparison with a constant: `on op value` (a typed value by its code, a string by its
/// number in the plan, [`Plan::str`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Bound {
/// What is compared.
pub on: On,
/// The comparison.
pub op: Cmp,
/// The constant.
pub value: Value,
}
/// A property of a [`Lookup`]'s variable: its type and, for each relation holding it (a
/// label, or every label holding it for a node of no label), that relation's index of it.
#[derive(Clone, Debug)]
pub struct Key {
/// The values' type.
pub ty: Type,
/// Per holder, its index (`None`: that holder has none, so no index finds every id).
pub indexes: Vec<Option<Index>>,
}
/// What bounds one variable, for [`Lookup::choose`].
#[derive(Clone, Debug, Default)]
pub struct Lookup {
/// Its properties.
pub props: Vec<Key>,
/// The id blocks its ids lie in exactly (every relation it may come from a label with
/// [`Index::Blocks`]), if so.
pub blocks: Option<Vec<(Value, Value)>>,
/// Comparisons that all hold (a conjunction).
pub bounds: Vec<Bound>,
/// ORs of comparisons, each a disjunction that holds.
pub ors: Vec<Vec<Bound>>,
}
/// The index [`Lookup::choose`] picked.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Choice {
/// The ids of the blocks in the closed intervals `wanted`, listed from the numbers
/// ([`IdRanges`]), no label read.
Ids {
/// The intervals.
wanted: Vec<(Value, Value)>,
},
/// One lookup of the name index of property `prop` per string.
Names {
/// The property.
prop: usize,
/// The strings.
names: Vec<String>,
},
/// One lookup of the range index of property `prop` (codes `lo..=hi`; `lo > hi` finds
/// nothing).
Range {
/// The property.
prop: usize,
/// The least code.
lo: Value,
/// The greatest code.
hi: Value,
/// Whether an equality gave it.
eq: bool,
},
/// One lookup of the range index of property `prop` per value (an OR of equalities).
At {
/// The property.
prop: usize,
/// The values.
values: Vec<Value>,
},
}
fn flipped(op: Cmp) -> Cmp {
match op {
Cmp::Lt => Cmp::Gt,
Cmp::Le => Cmp::Ge,
Cmp::Gt => Cmp::Lt,
Cmp::Ge => Cmp::Le,
o => o,
}
}
/// The closed range `(lo, hi, an equality)` the comparisons on `on` give within `0..=top`,
/// when any but `<>` does.
fn range(bounds: &[Bound], on: On, top: Value) -> Option<(Value, Value, bool)> {
let (mut lo, mut hi, mut eq, mut any) = (0, top, false, false);
for b in bounds.iter().filter(|b| b.on == on) {
let c = b.value;
any |= b.op != Cmp::Ne;
// An empty range: lo above hi.
match b.op {
Cmp::Eq => {
lo = lo.max(c);
hi = hi.min(c);
eq = true;
}
Cmp::Lt => match c.checked_sub(1) {
Some(x) => hi = hi.min(x),
None => (lo, hi) = (1, 0),
},
Cmp::Le => hi = hi.min(c),
Cmp::Gt => match c.checked_add(1) {
Some(x) => lo = lo.max(x),
None => (lo, hi) = (1, 0),
},
Cmp::Ge => lo = lo.max(c),
Cmp::Ne => {}
}
}
any.then_some((lo, hi, eq))
}
impl Key {
fn ranged(&self) -> bool {
matches!(self.ty, Type::U64 | Type::I64 | Type::F64)
&& !self.indexes.is_empty()
&& self
.indexes
.iter()
.all(|i| matches!(i, Some(Index::Range { .. })))
}
fn named(&self) -> bool {
self.ty == Type::Str
&& !self.indexes.is_empty()
&& self
.indexes
.iter()
.all(|i| matches!(i, Some(Index::Names { .. })))
}
}
impl Lookup {
/// The index to find the variable by, if one fits: an id range when its ids are blocks
/// and comparisons (or an OR of equalities) bound its id; else a name lookup of a string
/// property every holder has a name index of, for an equality or an OR of equalities
/// (the first such in the bounds, then the ORs); else a range lookup of a numeric
/// property every holder has a range index of, for its comparisons (an equality
/// preferred over bounds; the null code, the largest of a typed property, never in the
/// range); else one range lookup per value of an OR of equalities of one such property.
/// `strings` are the plan's string constants ([`Plan::strings`]).
pub fn choose(&self, strings: &[String]) -> Option<Choice> {
if self.blocks.as_ref().is_some_and(|b| !b.is_empty()) {
if let Some((lo, hi, _)) = range(&self.bounds, On::Id, Value::MAX) {
return Some(Choice::Ids {
wanted: vec![(lo, hi)],
});
}
let eqs = |or: &Vec<Bound>| -> Option<Vec<(Value, Value)>> {
or.iter()
.map(|b| (b.on == On::Id && b.op == Cmp::Eq).then_some((b.value, b.value)))
.collect()
};
if let Some(wanted) = self.ors.iter().find_map(eqs) {
return Some(Choice::Ids { wanted });
}
}
// the values a property must equal, from an equality or an OR of equalities
let eq_of = |b: &Bound| match b.on {
On::Prop(s) if b.op == Cmp::Eq => Some((s, vec![b.value])),
_ => None,
};
let or_of = |or: &Vec<Bound>| -> Option<(usize, Vec<Value>)> {
let all: Vec<(usize, Vec<Value>)> = or.iter().map(eq_of).collect::<Option<_>>()?;
let s = all.first()?.0;
all.iter()
.all(|x| x.0 == s)
.then(|| (s, all.into_iter().flat_map(|x| x.1).collect()))
};
let named = self
.bounds
.iter()
.filter_map(eq_of)
.chain(self.ors.iter().filter_map(or_of))
.find(|(s, _)| self.props.get(*s).is_some_and(Key::named));
if let Some((prop, codes)) = named {
let names = codes
.iter()
.map(|&c| strings.get(c as usize).cloned())
.collect::<Option<Vec<String>>>()?;
return Some(Choice::Names { prop, names });
}
let mut best: Option<Choice> = None;
for (s, k) in self.props.iter().enumerate() {
if !k.ranged() {
continue;
}
// Typed values are order-keeping codes; the null code (the largest) is no value.
let top = if k.ty == Type::U64 {
Value::MAX
} else {
NULL - 1
};
let Some((lo, hi, eq)) = range(&self.bounds, On::Prop(s), top) else {
continue;
};
let better = match &best {
None => true,
Some(Choice::Range { eq: was, .. }) => eq && !was,
Some(_) => false,
};
if better {
best = Some(Choice::Range {
prop: s,
lo,
hi,
eq,
});
}
}
if best.is_some() {
return best;
}
self.ors
.iter()
.filter_map(or_of)
.find(|(s, _)| self.props.get(*s).is_some_and(Key::ranged))
.map(|(prop, values)| Choice::At { prop, values })
}
}
impl Choice {
/// The relation of the ids the choice finds for `lookup`'s variable: a derived relation
/// of one column named `name`, each holder's lookups a rule (asked with constants only,
/// so the relation leads every join it is in); its external relations given in
/// `inputs`.
pub fn build(
&self,
lookup: &Lookup,
plan: &mut Plan,
inputs: &mut Inputs,
name: &str,
) -> Result<RelId> {
let hit = plan.derived(name, 1);
let v = plan.var("I");
let one = |plan: &mut Plan, ext: RelId, terms: Vec<Term>| -> Result<()> {
plan.rule(
Atom {
rel: hit,
terms: vec![Term::Var(v)],
},
[Literal::Pos(Atom { rel: ext, terms })],
)?;
Ok(())
};
match self {
Choice::Ids { wanted } => {
let blocks = lookup.blocks.clone().unwrap_or_default();
let ext = plan.external(&format!("{name}: ids"), 1);
inputs.external(ext, Arc::new(IdRanges::new(blocks, wanted.clone())));
one(plan, ext, vec![Term::Var(v)])?;
}
Choice::Names { prop, names } => {
for (i, ix) in lookup.props[*prop].indexes.iter().enumerate() {
let Some(Index::Names { index, .. }) = ix else {
continue;
};
let ext = plan.external(&format!("{name}: names {i}"), 1);
inputs.external(ext, Arc::new(NameHits::new(index.clone(), names.clone())));
one(plan, ext, vec![Term::Var(v)])?;
}
}
Choice::Range { prop, lo, hi, .. } => {
for (i, ix) in lookup.props[*prop].indexes.iter().enumerate() {
let Some(Index::Range { lookup: src, .. }) = ix else {
continue;
};
let ext = plan.external(&format!("{name}: range {i}"), 3);
inputs.set(ext, src.clone());
one(
plan,
ext,
vec![Term::Const(*lo), Term::Const(*hi), Term::Var(v)],
)?;
}
}
Choice::At { prop, values } => {
for (i, ix) in lookup.props[*prop].indexes.iter().enumerate() {
let Some(Index::Range { lookup: src, .. }) = ix else {
continue;
};
let ext = plan.external(&format!("{name}: range {i}"), 3);
inputs.set(ext, src.clone());
for &x in values {
one(
plan,
ext,
vec![Term::Const(x), Term::Const(x), Term::Var(v)],
)?;
}
}
}
}
Ok(hit)
}
}
/// What the index choice did to one rule: the variable, the relation that now finds it and
/// the choice (for an external atom of constants asked once, `None`).
#[derive(Clone, Debug)]
pub struct Chosen {
/// The rule (of the plan as given).
pub rule: crate::RuleId,
/// The variable.
pub var: Var,
/// The relation of the ids found.
pub found: RelId,
/// The index chosen.
pub choice: Option<Choice>,
}
/// `p` with the index choice applied to every rule (see the module), and its inputs with
/// the lookups' relations; `None` when nothing changes (no input has an index and no
/// external atom is asked with constants only beside other atoms).
pub fn choose_indexes(p: &Plan, inputs: &Inputs) -> Result<Option<(Plan, Inputs, Vec<Chosen>)>> {
let hoistable = |p: &Plan, a: &Atom| -> bool {
p.relation_info(a.rel).kind == RelKind::External
&& a.terms.iter().any(|t| matches!(t, Term::Const(_)))
&& matches!(inputs.source(a.rel), Some(Source::External(e))
if e.can(const_mask(a)))
};
let any = p.rules().iter().any(|r| {
r.body.iter().any(|a| inputs.index_of(a.rel).is_some())
|| (r.body.len() > 1 && r.body.iter().any(|a| hoistable(p, a)))
});
if !any {
return Ok(None);
}
let mut q = p.clone();
let mut ins = inputs.clone();
let mut chosen: Vec<Chosen> = Vec::new();
for r in 0..p.rules().len() {
let rid = crate::RuleId(r as u32);
let rule = p.rule_at(rid).clone();
if rule.body.len() < 2 && !rule.body.iter().any(|a| ins.index_of(a.rel).is_some()) {
continue;
}
let head = p.relation_info(rule.head.rel).name.clone();
let mut body = rule.body.clone();
// A lookup written by hand: asked once with its constants, in a relation of its own.
let mut found_by: Vec<Var> = Vec::new();
if body.len() > 1 {
for a in body.iter_mut() {
if !hoistable(p, a) {
continue;
}
let vars: Vec<Var> = a.vars().collect();
let mut seen: Vec<Var> = Vec::new();
for v in &vars {
if !seen.contains(v) {
seen.push(*v);
}
}
let types: Vec<Type> = seen.iter().map(|&v| p.var_type(rid, v)).collect();
let h = if types.iter().all(|&t| t == Type::U64) {
q.derived(
&format!("{head}: {} asked once", p.relation_info(a.rel).name),
seen.len(),
)
} else {
q.derived_typed(
&format!("{head}: {} asked once", p.relation_info(a.rel).name),
&types,
)
};
let terms: Vec<Term> = seen.iter().map(|&v| Term::Var(v)).collect();
q.rule(
Atom {
rel: h,
terms: terms.clone(),
},
[Literal::Pos(a.clone())],
)?;
for &v in &seen {
found_by.push(v);
chosen.push(Chosen {
rule: rid,
var: v,
found: h,
choice: None,
});
}
*a = Atom { rel: h, terms };
}
}
// The variables an indexed input's atom binds, in order.
let mut vars: Vec<Var> = Vec::new();
for a in &body {
if ins.index_of(a.rel).is_some()
&& let Some(Term::Var(v)) = a.terms.first()
&& !vars.contains(v)
&& !found_by.contains(v)
{
vars.push(*v);
}
}
for n in vars {
// ids are unsigned
if p.has_types() && p.var_type(rid, n) != Type::U64 {
continue;
}
let mut lk = Lookup::default();
let mut block_atom: Option<usize> = None;
for (i, a) in body.iter().enumerate() {
if a.terms.first() != Some(&Term::Var(n)) {
continue;
}
match ins.index_of(a.rel) {
Some(Index::Blocks(b)) if a.terms.len() == 1 && block_atom.is_none() => {
lk.blocks = Some(b.clone());
block_atom = Some(i);
}
Some(ix @ (Index::Range { .. } | Index::Names { .. }))
if a.terms.len() == 2 =>
{
let s = lk.props.len();
lk.props.push(Key {
ty: p.col_type(a.rel, 1),
indexes: vec![Some(ix.clone())],
});
match a.terms[1] {
Term::Const(c) => lk.bounds.push(Bound {
on: On::Prop(s),
op: Cmp::Eq,
value: c,
}),
Term::Var(x) => bounds_on(
p,
&rule.conds,
x,
On::Prop(s),
&mut lk.bounds,
&mut lk.ors,
),
}
}
_ => {}
}
}
bounds_on(p, &rule.conds, n, On::Id, &mut lk.bounds, &mut lk.ors);
let Some(choice) = lk.choose(p.strings()) else {
continue;
};
let name = format!("{head}: {} found", p.var_name(n));
let hit = choice.build(&lk, &mut q, &mut ins, &name)?;
// the label the found ids lie within: dropped, the found relation in its place
let within: Option<usize> = match &choice {
Choice::Ids { .. } => block_atom,
Choice::Names { prop, .. }
| Choice::Range { prop, .. }
| Choice::At { prop, .. } => {
let label = match &lk.props[*prop].indexes[0] {
Some(Index::Range { within, .. } | Index::Names { within, .. }) => {
within.clone()
}
_ => None,
};
label.and_then(|l| {
body.iter().position(|a| {
a.terms == [Term::Var(n)]
&& p.relation_info(a.rel).kind == RelKind::Input
&& p.relation_info(a.rel).name == l
})
})
}
};
let found = Atom {
rel: hit,
terms: vec![Term::Var(n)],
};
match within {
Some(i) => body[i] = found,
None => body.push(found),
}
chosen.push(Chosen {
rule: rid,
var: n,
found: hit,
choice: Some(choice),
});
}
if body != rule.body {
q.rule_mut(rid).body = body;
}
}
if chosen.is_empty() {
return Ok(None);
}
Ok(Some((q, ins, chosen)))
}
/// The mask of an atom's constant terms.
fn const_mask(a: &Atom) -> u64 {
a.terms
.iter()
.enumerate()
.filter(|(_, t)| matches!(t, Term::Const(_)))
.fold(0u64, |m, (j, _)| m | 1 << j)
}
/// The comparisons of `x` with constants among `conds`, as bounds on `on`; each list test
/// of `x` (not negated, not empty) an OR of equalities in `ors`, one lookup per member.
fn bounds_on(
p: &Plan,
conds: &[Cond],
x: Var,
on: On,
out: &mut Vec<Bound>,
ors: &mut Vec<Vec<Bound>>,
) {
for c in conds {
match *c {
Cond::OneOf {
x: Term::Var(v),
list,
not: false,
} if v == x && !p.list_of(list).members.is_empty() => {
let l = p.list_of(list);
let mut vals = l.members.clone();
vals.sort_unstable();
vals.dedup();
ors.push(
vals.into_iter()
.map(|value| Bound {
on,
op: Cmp::Eq,
value,
})
.collect(),
);
}
Cond::Cmp {
left: Term::Var(v),
op,
right: Term::Const(k),
} if v == x => out.push(Bound { on, op, value: k }),
Cond::Cmp {
left: Term::Const(k),
op,
right: Term::Var(v),
} if v == x => out.push(Bound {
on,
op: flipped(op),
value: k,
}),
Cond::Within {
x: Term::Var(v),
lo: Term::Const(lo),
hi: Term::Const(hi),
} if v == x => {
out.push(Bound {
on,
op: Cmp::Ge,
value: lo,
});
out.push(Bound {
on,
op: Cmp::Lt,
value: hi,
});
}
_ => {}
}
}
}
/// The indexes of an [`Inputs`], by relation.
pub(crate) type Indexes = HashMap<RelId, Index>;