nordisk/kleene
crates/kleene-plan/src/eval.rs
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::{Duration, Instant};
use datafusion::prelude::SessionContext;
use kleene_graph::{
BfsOptions, BfsState, EdgeSets, Graph, GraphBackend, Split, SplitKey, bfs_with,
};
use kleene_sparse::{BoolOrAnd, Csr, SparseBackend};
use arrow_array::ArrayRef;
use crate::External;
use crate::cols::{
Band, Check, HeadCol, Index, Kinds, Pairs, Par, RowSet, Rows, Sel, Src, Table, band_join,
cross_join, extend_table, first_of_kind, first_of_kind_by, gather_sel, hash_join, hash_of,
kept_places, kinds_by, new_rows, range_join, rows_from, select, semi_join, semi_join_by,
};
use crate::compute::{Compiled, Got};
use crate::facts::{Column, Facts, FactsBuilder, Inputs, Source};
use crate::ids::Ids;
use crate::plan::{Side, Stratum, Way, plan};
use crate::rules::{
Agg, Aggregate, Atom, Cmp, Cond, Part, Plan, Reduce, ReduceOp, RelId, RelKind, Rule, RuleId,
Term, Value, Var,
};
use crate::typed::{Datum, Dict, NULL, Type};
use crate::why::{AggWhy, ClosureWhy, LabelWhy, Proof, ProvBuilder, ReachWhy, WhyStore};
use crate::{PlanError, Result};
mod cont;
#[cfg(test)]
mod same_why;
mod sets;
use crate::plan::numbers_into;
use sets::{Gathered, Tab};
/// What a run tells as it goes (new facts per round). Every method has a default that
/// does nothing. The why of each fact is kept by [`Engine::explain`] instead.
pub trait Trace {
/// Stratum `stratum` finished round `round` with `new_facts` new facts.
fn round(&mut self, stratum: usize, round: u32, new_facts: usize) {
let _ = (stratum, round, new_facts);
}
}
/// A trace that keeps nothing.
#[derive(Debug, Default, Clone, Copy)]
pub struct NoTrace;
impl Trace for NoTrace {}
/// How one stratum went.
#[derive(Clone, Debug)]
pub struct StratumReport {
/// The plan's name.
pub kind: &'static str,
/// The relations it derived.
pub relations: Vec<String>,
/// Rounds (BFS levels, products, or semi-naive rounds).
pub rounds: u32,
/// Facts derived.
pub facts: usize,
/// Time to get the stratum's operands ready (seed or base rules, graph or matrix).
pub prepare: Duration,
/// Time of the recursion itself (BFS, products, rounds of joins).
pub compute: Duration,
/// A graph stratum whose vertex ids were too far apart to index directly, numbered
/// densely for the run (its answers and proofs are in the original values).
pub renumbered: bool,
/// A stratum of a continued run ([`Engine::continue_from`]) that did not run again
/// from scratch: kept as it was, or continued from the rows its reads gained.
pub continued: bool,
/// The most rows a rule's bindings carried at once in this stratum (into its next
/// join step, its externals, or its head): the rows after each step, once the bindings
/// that differ only in variables no longer needed are made one.
pub peak_rows: usize,
/// The derivation rows the stratum's joined rules wrote for the why ([`Engine::explain`]):
/// one per new fact, none for a fact found again.
pub proof_rows: usize,
/// The rows the stratum's joined rules put in hash indexes, built or extended: an index
/// of facts in hand is built once, and one of a relation the stratum derives, read
/// whole, is extended by the rows each round added.
pub indexed_rows: usize,
/// The join steps of the stratum's rules run as a sort and a search on a range (a value
/// between two ends from the other side, beside equal keys or not), not as a cross
/// product or a hash join cut by the conditions.
pub range_joins: usize,
/// The aggregate rules of the stratum run as the next row by a key (a sort and one
/// search per row, [`Engine::next_rows`]), not as a cross product reduced per group.
pub next_rows: usize,
}
/// How a run went.
#[derive(Clone, Debug, Default)]
pub struct Report {
/// Time to read the inputs (tables through DataFusion; graphs are shared, not read).
pub load: Duration,
/// The strata, in the order they ran.
pub strata: Vec<StratumReport>,
/// The whole run.
pub total: Duration,
/// The body atoms the run read in scans of columns side by side
/// ([`Engine::side_by_side`]): each one a join fewer, less one per scan.
pub side_by_side: usize,
}
/// The facts a run derived, and how it went.
#[derive(Clone, Debug)]
pub struct Output {
facts: HashMap<RelId, Facts>,
why: Option<Arc<WhyStore>>,
/// The run's strings, when the plan has a string column or constant.
dict: Option<Arc<Dict>>,
/// The plan as it ran, for a typed plan (string constants as dictionary ids, the
/// implicit null checks added).
resolved: Option<Arc<Plan>>,
/// The plan as written, when the index choice rewrote it: a proof names its rules and
/// atoms, not the relations the choice put in.
written: Option<Arc<Plan>>,
/// How the run went.
pub report: Report,
/// What the run read, for a run that continues from it.
kept: Option<Arc<Kept>>,
}
impl Output {
/// The rows of a counted relation taken as `rows` says, without the count: the bag
/// ([`Output::expand`], refused past `limit` rows) or each distinct row once.
pub fn rows_as(
&self,
p: &Plan,
rel: RelId,
rows: crate::rules::Rows,
limit: Option<u64>,
) -> Result<Vec<Vec<Value>>> {
match rows {
crate::rules::Rows::Bag => self.expand(p, rel, limit),
crate::rules::Rows::Distinct => Ok(self.facts.get(&rel).map_or_else(Vec::new, |f| {
f.rows()
.map(|mut r| {
if p.is_counted(rel) {
r.pop();
}
r
})
.collect()
})),
}
}
/// The facts of a derived relation.
pub fn get(&self, rel: RelId) -> Option<&Facts> {
self.facts.get(&rel)
}
/// Whether derived relation `rel` holds a fact: for a relation of no column (a flag),
/// whether it holds.
pub fn holds(&self, rel: RelId) -> bool {
self.facts.get(&rel).is_some_and(|f| !f.is_empty())
}
/// The rows of a counted relation ([`Plan::derived_counted`]) as the bag they stand
/// for: each row without its count, repeated its count's times, rows in order. The
/// only place a count becomes rows; refused past `limit` rows in all (`None`: no
/// limit) or for a relation that is not counted.
pub fn expand(&self, p: &Plan, rel: RelId, limit: Option<u64>) -> Result<Vec<Vec<Value>>> {
if !p.is_counted(rel) {
return Err(PlanError::Program(format!(
"`{}` is not counted: its facts are its rows",
p.relation_info(rel).name
)));
}
let Some(f) = self.facts.get(&rel) else {
return Ok(Vec::new());
};
let mut all: u64 = 0;
for r in f.rows() {
all = all.saturating_add(*r.last().expect("a count column"));
}
if let Some(l) = limit
&& all > l
{
return Err(PlanError::Program(format!(
"`{}` stands for {all} rows, past the limit of {l}",
p.relation_info(rel).name
)));
}
let mut out: Vec<Vec<Value>> = Vec::new();
for r in f.rows() {
let (row, n) = r.split_at(r.len() - 1);
for _ in 0..n[0] {
out.push(row.to_vec());
}
}
Ok(out)
}
/// Why `rel(tuple)` holds: a proof down to input facts, when the run was explained
/// ([`Engine::explain`]) and derived it. `p` is the plan that ran.
pub fn why(&self, p: &Plan, rel: RelId, tuple: &[Value]) -> Option<Proof> {
let ran = self.resolved.as_deref().unwrap_or(p);
let proof = self.why.as_ref()?.proof(ran, rel, tuple)?;
Some(match &self.written {
Some(w) => proof.into_written(w),
None => proof,
})
}
/// The run's strings (dictionary ids are the codes of [`crate::Type::Str`] columns),
/// when the plan has a string column or constant.
pub fn dict(&self) -> Option<&Dict> {
self.dict.as_deref()
}
/// The facts of derived relation `rel` as Arrow arrays of its column types
/// ([`crate::Type::U64`] as stored, `Int64`, `Float64`, `Boolean`, `Utf8`, with nulls),
/// one per column, rows sorted by their codes (each type's own order). `p` is the plan
/// that ran.
pub fn arrow(&self, p: &Plan, rel: RelId) -> Option<Result<Vec<ArrayRef>>> {
let f = self.get(rel)?;
Some(
(0..f.arity())
.map(|i| crate::typed::to_arrow(p.col_type(rel, i), f.column(i), self.dict()))
.collect(),
)
}
/// The facts of derived relation `rel` as typed values, row by row (sorted as stored).
pub fn datums(&self, p: &Plan, rel: RelId) -> Option<Vec<Vec<Datum>>> {
let f = self.get(rel)?;
let types = p.types(rel);
Some(
(0..f.len())
.map(|k| {
(0..f.arity())
.map(|i| types[i].decode(f.value(i, k), self.dict()))
.collect()
})
.collect(),
)
}
/// Why `rel(tuple)` holds, the fact given as typed values (strings by text); `None`
/// when a value is not of its column's type, a string is not in the run, or the run
/// was not explained or did not derive it.
pub fn why_of(&self, p: &Plan, rel: RelId, tuple: &[Datum]) -> Option<Proof> {
let codes: Vec<Value> = tuple
.iter()
.enumerate()
.map(|(i, d)| p.col_type(rel, i).encode(d, self.dict()))
.collect::<Option<_>>()?;
self.why(p, rel, &codes)
}
/// `proof` as an indented tree ([`Proof::render`]) with every value printed by its
/// type: strings from the run's dictionary, signed and float values as such, nulls.
pub fn render(&self, p: &Plan, proof: &Proof) -> String {
proof.render_with(p, self.dict())
}
}
/// Runs plans: recursive two-column shapes on a sparse backend, the rest as column
/// kernels (joins on packed keys, anti-joins, ranges, dedupe, sorted groups). DataFusion
/// (in `ctx`) only reads table inputs.
pub struct Engine<B: SparseBackend> {
device: B::Device,
/// Where the column kernels run: the device's parked workers on a CPU backend, a CPU
/// device of the engine's own beside any other.
par: Par,
ctx: std::sync::OnceLock<SessionContext>,
explain: bool,
/// Whether the index choice runs on each plan ([`Engine::index_choice`]).
index_choice: bool,
/// Whether a join step runs a value between two ends as a sort and a search
/// ([`Engine::range_joins`]).
range_joins: bool,
/// Whether an aggregate of the next row by a key runs as a sort and a search
/// ([`Engine::next_rows`]).
next_rows: bool,
/// Whether atoms over columns side by side run as one scan ([`Engine::side_by_side`]).
side_by_side: bool,
/// The buffers of the last reach search, reused by the next (no allocation per run
/// once grown).
search: std::sync::Mutex<Option<BfsState<B>>>,
/// The key the graph strata split their graph by ([`Engine::split`]); `None`: one part.
split: Option<SplitKey>,
/// The tests' reference: rules run as before the bindings were made distinct and the
/// heads added by batch (row by row, a bag for each relation no rule of its stratum reads).
#[cfg(test)]
reference: bool,
}
impl<B: SparseBackend> std::fmt::Debug for Engine<B> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Engine")
.field("backend", &B::name())
.field("device", &self.device)
.field("explain", &self.explain)
.finish()
}
}
/// A run's inputs read and its strata planned ([`Engine::load`]).
struct Loaded {
st: State,
strata: Vec<Stratum>,
dict: Option<Arc<Dict>>,
resolved: Option<Arc<Plan>>,
load: Duration,
t0: Instant,
}
/// What a run read, kept in its output for a run that continues from it
/// ([`Engine::continue_from`]): the inputs as read, the graphs, the externals.
pub(crate) struct Kept {
pub(crate) inputs: HashMap<RelId, Facts>,
pub(crate) graphs: HashMap<RelId, GraphAt>,
pub(crate) externals: HashMap<RelId, Arc<dyn External>>,
/// Whether the plan that ran was the index choice's.
pub(crate) chosen: bool,
}
impl std::fmt::Debug for Kept {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Kept")
.field("inputs", &self.inputs.len())
.field("graphs", &self.graphs.len())
.field("externals", &self.externals.len())
.field("chosen", &self.chosen)
.finish()
}
}
/// Facts in hand during a run.
struct State {
inputs: HashMap<RelId, Facts>,
/// Graphs given whole, with the ids of their row 0 and column 0.
graphs: HashMap<RelId, GraphAt>,
derived: HashMap<RelId, Facts>,
/// Relations answered by Rust code.
externals: HashMap<RelId, Arc<dyn External>>,
why: Option<WhyStore>,
/// Whether the plan has typed relations (a negated atom then never matches on a null).
typed: bool,
/// The run's strings: those read and the plan's constants, then those rules make as
/// the run goes ([`Dict::sorted_len`]).
dict: Option<Arc<Dict>>,
/// The stratum running's counters ([`StratumReport::peak_rows`],
/// [`StratumReport::proof_rows`], [`StratumReport::indexed_rows`],
/// [`StratumReport::range_joins`], [`StratumReport::next_rows`]), taken into its report.
peak_rows: usize,
proof_rows: usize,
indexed_rows: usize,
range_joins: usize,
next_rows: usize,
}
/// [`csr_pairs`] in an id space: row `x` as `bases.0 + x`, column `y` as `bases.1 + y`.
/// A graph given whole: by source, by destination if stored, the ids of row 0 and column 0.
type GraphAt = (Csr<u8>, Option<Csr<u8>>, (Value, Value));
fn csr_pairs_at(a: &Csr<u8>, bases: (Value, Value)) -> Facts {
if bases == (0, 0) {
return csr_pairs(a);
}
let mut src = Vec::with_capacity(a.nnz());
for i in 0..a.nrows() {
src.extend(std::iter::repeat_n(bases.0 + i as Value, a.row(i).len()));
}
let dst: Vec<Value> = a
.pattern()
.indices()
.iter()
.map(|&y| bases.1 + Value::from(y))
.collect();
Facts::from_columns(vec![src, dst]).expect("equal lengths")
}
fn csr_pairs(a: &Csr<u8>) -> Facts {
let mut src = Vec::with_capacity(a.nnz());
for i in 0..a.nrows() {
src.extend(std::iter::repeat_n(i as u32, a.row(i).len()));
}
Facts::from_columns(vec![src, a.pattern().indices().to_vec()]).expect("equal lengths")
}
impl State {
/// The facts of `rel` in hand (shared, not copied): an input, a relation a lower
/// stratum derived, an external listed whole, a graph as pairs.
fn facts(&mut self, p: &Plan, rel: RelId) -> Result<Facts> {
if p.relation_info(rel).kind == RelKind::Derived {
return self.derived.get(&rel).cloned().ok_or_else(|| {
PlanError::Program(format!(
"`{}` is used before it is derived",
p.relation_info(rel).name
))
});
}
if !self.inputs.contains_key(&rel) {
let info = p.relation_info(rel);
let f = if let Some(ext) = self.externals.get(&rel) {
// Listed whole, once per run.
if !ext.can(0) {
return Err(PlanError::Input(format!(
"`{}` answers lookups only and cannot be listed whole here",
info.name
)));
}
let mut f = FactsBuilder::new(info.arity);
let none: Vec<&[Value]> = vec![&[]; info.arity];
ext.lookup(0, &none, 1, &mut |_, r| f.push(r))?;
f.finish()
} else {
let (out, _, bases) = self
.graphs
.get(&rel)
.ok_or_else(|| PlanError::Input(format!("no input for `{}`", info.name)))?;
csr_pairs_at(out, *bases)
};
self.inputs.insert(rel, f);
}
Ok(self.inputs[&rel].clone())
}
fn is_external(&self, p: &Plan, rel: RelId) -> bool {
p.relation_info(rel).kind == RelKind::External
}
}
fn var_of(t: &Term) -> Option<Var> {
match t {
Term::Var(v) => Some(*v),
Term::Const(_) => None,
}
}
/// The places of a labelled reach (see [`Stratum::LabelReach`]).
#[derive(Clone, Copy, Debug)]
struct LabelShape {
rel: RelId,
step: RuleId,
edge: RelId,
has: RelId,
entry: usize,
edge_cols: [usize; 3],
has_cols: [usize; 2],
}
/// What one positive body atom reads in one application of a rule.
enum In<'a> {
/// Facts in hand, the same every round of the stratum (their indexes are kept).
Facts(Facts),
/// Rows `lo..hi` of a relation the running stratum derives.
Own(&'a RowSet, usize, usize),
/// An external, asked when the rule runs.
External,
}
impl In<'_> {
fn rows(&self) -> Option<Rows<'_>> {
match self {
In::Facts(f) => Some(Rows::of(f)),
In::Own(s, lo, hi) => Some(Rows::range(s, *lo, *hi)),
In::External => None,
}
}
}
/// The indexes of one stratum's facts in hand (built once, probed every round), and, in a
/// fixed point whose relations only grow at their end (`grows`), those of the relations it
/// derives read whole (extended to the rows each round added).
#[derive(Default)]
struct Indexes {
map: HashMap<IxKey, Index>,
grows: bool,
/// Rows put in an index (built or extended) since the counter was last taken.
rows: usize,
}
impl Indexes {
fn new() -> Self {
Self::default()
}
/// For a fixed point whose relations only grow at their end.
fn growing() -> Self {
Indexes {
grows: true,
..Self::default()
}
}
/// Whether the index of atom `a` reading `input` is kept: facts in hand, or (in a
/// fixed point that only grows) a derived relation read whole by an atom that selects
/// no rows by itself (the rows a round adds are not selected).
fn keeps(&self, input: &In, a: &Atom) -> bool {
match input {
In::Facts(_) => true,
In::Own(s, lo, hi) => self.grows && *lo == 0 && *hi == s.len() && !filters(a),
In::External => false,
}
}
}
/// What an index is of: an atom that selects rows by itself (a constant or a repeated
/// variable), by rule, atom (negated atoms after the positive ones) and key columns; any
/// other atom by its relation and key columns, shared by every rule.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum IxKey {
Atom(RuleId, usize, Vec<usize>),
Rel(RelId, Vec<usize>),
/// A relation the fixed point derives, read whole as it grows.
Own(RelId, Vec<usize>),
}
impl IxKey {
fn of(r: RuleId, pos: usize, a: &Atom, key: &[usize], own: bool) -> Self {
if filters(a) {
IxKey::Atom(r, pos, key.to_vec())
} else if own {
IxKey::Own(a.rel, key.to_vec())
} else {
IxKey::Rel(a.rel, key.to_vec())
}
}
/// The relation the index is of.
fn rel(&self, p: &Plan) -> RelId {
match self {
IxKey::Atom(r, pos, _) => {
let rule = p.rule_at(*r);
rule.body
.get(*pos)
.unwrap_or_else(|| &rule.negated[*pos - rule.body.len()])
.rel
}
IxKey::Rel(rel, _) | IxKey::Own(rel, _) => *rel,
}
}
}
/// The index of `rows` (selected rows `sel`) by `key`: kept in `ix` under `at` when the
/// facts stay the same through the stratum, or only grow at their end (a kept part of
/// rounds, indexed whole: the index is extended to the new rows).
#[allow(clippy::too_many_arguments)]
fn index_of<'c>(
par: &Par,
ix: &'c mut Indexes,
keep: bool,
at: IxKey,
rows: &Rows,
sel: impl FnOnce() -> Sel,
key: &[usize],
scratch: &'c mut Option<Index>,
) -> &'c Index {
let counted = &mut ix.rows;
if keep {
let whole = matches!(at, IxKey::Rel(..) | IxKey::Own(..));
let index = ix.map.entry(at).or_insert_with(|| {
let index = Index::build(par, rows, sel(), key);
*counted += index.len();
index
});
if whole {
let before = index.len();
index.extend(par, rows);
*counted += index.len() - before;
}
index
} else {
let index = Index::build(par, rows, sel(), key);
*counted += index.len();
scratch.insert(index)
}
}
/// Whether an atom selects rows by itself: a constant or a repeated variable.
fn filters(a: &Atom) -> bool {
a.terms.iter().enumerate().any(|(j, t)| match t {
Term::Const(_) => true,
Term::Var(_) => a.terms[..j].contains(t),
})
}
impl<B: GraphBackend> Engine<B> {
/// An engine on `device`; its DataFusion session is made the first time a table input
/// needs it.
pub fn new(device: B::Device) -> Self {
Engine {
par: Par::new(B::host_device(&device).cloned().unwrap_or_default()),
device,
ctx: std::sync::OnceLock::new(),
explain: false,
index_choice: true,
range_joins: true,
next_rows: true,
side_by_side: true,
search: std::sync::Mutex::new(None),
split: None,
#[cfg(test)]
reference: false,
}
}
/// An engine on `device` that reads table inputs in `ctx`.
pub fn with_context(device: B::Device, ctx: SessionContext) -> Self {
Engine {
par: Par::new(B::host_device(&device).cloned().unwrap_or_default()),
device,
ctx: std::sync::OnceLock::from(ctx),
explain: false,
index_choice: true,
range_joins: true,
next_rows: true,
side_by_side: true,
search: std::sync::Mutex::new(None),
split: None,
#[cfg(test)]
reference: false,
}
}
/// Keep the why of every derived fact ([`Output::why`]): the first derivation of each
/// joined fact (as columns: the rule and the values of its variables), the BFS levels
/// of a reach, the operands of a closure (their proofs are walked back when asked).
pub fn explain(mut self, on: bool) -> Self {
self.explain = on;
self
}
/// Whether a run applies the index choice to its plan ([`crate::choose_indexes`]: a
/// rule's comparisons with constants on an input with an [`crate::Index`] become a
/// lookup of the index; an external atom of constants is asked once). On by default;
/// off, every plan runs as written (the answers are the same).
pub fn index_choice(mut self, on: bool) -> Self {
self.index_choice = on;
self
}
/// Whether a join step whose conditions hold a value of one side between two ends from
/// the other side (a range `A in LO..HI` beside equal keys, or a lower and an upper
/// comparison such as `LO <= A, A < HI`) runs as a sort and a search: the side that
/// holds the value sorted by (key, value), each row of the other side finding its
/// stretch by binary search ([`StratumReport::range_joins`] counts them). On by
/// default; off, such a step runs as a hash join or a cross product cut by the
/// conditions. The answers and the proofs are the same either way. A range with no
/// equal key beside it runs as a sort and a search always.
pub fn range_joins(mut self, on: bool) -> Self {
self.range_joins = on;
self
}
/// Whether an aggregate rule that takes, per row of one atom, the least value of
/// another atom past one of its values (`next(A, B) :- min(B) by (A): bound(A),
/// bound(B), A < B.`; `max` with `>` the greatest before it; more equal keys beside)
/// runs as a sort and a search: the reduced atom sorted by (key, value), one binary
/// search per row of the other, the reduction reading each row's winners alone
/// ([`StratumReport::next_rows`] counts them). With no proof kept, a run first rewrites
/// its plan so that more rules take that shape: an aggregate over an internal relation
/// ([`Plan::internal`], GQL's matches) derived by one rule reads that rule's body, and a
/// side of several atoms becomes a relation of its own; a reduction of several values
/// ([`Aggregate::many`]: its proof lists every member) takes the run only then. On by
/// default; off, such a rule runs as a cross product reduced per group. The answers are
/// the same either way, and so are the proofs of the rules that keep one.
pub fn next_rows(mut self, on: bool) -> Self {
self.next_rows = on;
self
}
/// Whether a run reads a rule's atoms over columns side by side in one scan: positive
/// atoms over input relations of two columns each over one and the same id column
/// ([`Source::Columns`] sharing the id array, as a catalog's properties of one vertex
/// type are) that share the id's variable become one atom over those columns, instead
/// of a join per column ([`Report::side_by_side`] counts them). The answers and proofs
/// are the same (each atom shows by its own name). On by default. A run that read such
/// a scan keeps nothing for [`Engine::continue_from`]: continuing from it runs from
/// scratch.
pub fn side_by_side(mut self, on: bool) -> Self {
self.side_by_side = on;
self
}
/// Run the graph strata over the parts of their graph cut by `key` (kleene-graph's
/// [`kleene_graph::Split`]: a property per vertex of the stratum's graph, blocks of
/// vertex numbers, a hash), in local-first rounds: each part runs the engine's kernel on
/// its own part until it finds nothing new, then the parts hand each other only their
/// new border nodes ([`kleene_graph::reach_rounds`], [`kleene_graph::closure_rounds`],
/// [`kleene_graph::components_rounds`], [`kleene_graph::sssp_rounds`]). The answers are
/// the one-part answers. A plan with a stratum that does not split
/// ([`Stratum::splittable`]) is refused ([`PlanError::NotSplittable`]), as is the why
/// of a split run; without a key (the default) every stratum runs as one part, the same
/// code with no border and no exchange.
pub fn split(mut self, key: SplitKey) -> Self {
self.split = Some(key);
self
}
/// Whether rules run as the tests' reference ([`Engine::reference`]'s field).
fn reference(&self) -> bool {
#[cfg(test)]
{
self.reference
}
#[cfg(not(test))]
{
false
}
}
/// The tests' reference engine: rules run row by row as before the batch.
#[cfg(test)]
pub(crate) fn with_reference(mut self) -> Self {
self.reference = true;
self
}
/// The rows of a relation of `arity` columns: a bag when `bag` (no rule of the stratum
/// reads it) and no why is kept (a bag's arrival order is not kept), else a set.
fn row_set(&self, arity: usize, bag: bool) -> RowSet {
if bag && (!self.explain || self.reference()) {
RowSet::bag(arity)
} else {
RowSet::new(arity)
}
}
/// [`add_heads`] (the reference's row by row in the tests' reference).
fn heads(
&self,
p: &Plan,
r: RuleId,
t: Table,
set: &mut RowSet,
prov: Option<&mut ProvBuilder>,
round: u32,
) -> Result<usize> {
#[cfg(test)]
if self.reference {
let mut t = t;
t.resolve(&self.par);
return add_heads_rows(&self.par, p, r, t, set, prov, round);
}
add_heads(&self.par, p, r, t, set, prov, round)
}
/// The DataFusion session.
pub fn context(&self) -> &SessionContext {
self.ctx.get_or_init(SessionContext::new)
}
/// Run `p` on `inputs`.
pub async fn run(&self, p: &Plan, inputs: &Inputs) -> Result<Output> {
self.run_traced(p, inputs, &mut NoTrace).await
}
/// Run `p` on `inputs`, telling `trace` as it goes.
pub async fn run_traced(
&self,
p: &Plan,
inputs: &Inputs,
trace: &mut dyn Trace,
) -> Result<Output> {
// with no proof kept, the plan rewritten for the next row by a key (first: it fuses
// and splits rules as written; the columns side by side then merge inside the
// rules it made too)
let next = if self.next_rows && !self.explain && !self.reference() {
crate::next::rewrite(p)?
} else {
None
};
let q0: &Plan = next.as_ref().unwrap_or(p);
let side = match self.side_by_side {
true => crate::side::merge(q0, inputs)?,
false => None,
};
let (sp, sins) = side.as_ref().map_or((q0, inputs), |(q, ins, _)| (q, ins));
let mut out = if self.index_choice
&& let Some((q, ins, _)) = crate::index::choose_indexes(sp, sins)?
{
self.run_as(&q, &ins, trace, true).await?
} else if next.is_some() || side.is_some() {
self.run_as(sp, sins, trace, true).await?
} else {
return self.run_as(p, inputs, trace, false).await;
};
out.written = Some(Arc::new(p.clone()));
if let Some((_, _, merged)) = side {
out.report.side_by_side = merged;
// (its relations are not the written plan's: a continued run starts afresh)
out.kept = None;
}
Ok(out)
}
/// Run `p` on `inputs`; `chosen`: `p` is the plan the index choice made, kept in the
/// output as the plan that ran.
async fn run_as(
&self,
p: &Plan,
inputs: &Inputs,
trace: &mut dyn Trace,
chosen: bool,
) -> Result<Output> {
let Loaded {
mut st,
strata,
dict,
resolved,
load,
t0,
} = self.load(p, inputs, chosen).await?;
let p: &Plan = resolved.as_deref().unwrap_or(p);
st.dict = dict;
let mut report = Report {
load,
..Report::default()
};
for (k, stratum) in strata.iter().enumerate() {
let r = self.stratum(p, &mut st, k, stratum, trace)?;
report.strata.push(Self::reported(p, &mut st, stratum, r));
}
self.par.drop_spare();
report.total = t0.elapsed();
let dict = st.dict.take();
Ok(Self::output(st, dict, resolved, report, chosen))
}
/// The report of `stratum` as it ran.
fn reported(p: &Plan, st: &mut State, stratum: &Stratum, r: StratumReport) -> StratumReport {
StratumReport {
peak_rows: std::mem::take(&mut st.peak_rows),
proof_rows: std::mem::take(&mut st.proof_rows),
indexed_rows: std::mem::take(&mut st.indexed_rows),
range_joins: std::mem::take(&mut st.range_joins),
next_rows: std::mem::take(&mut st.next_rows),
kind: stratum.kind(),
relations: stratum
.relations()
.iter()
.map(|r| p.relation_info(*r).name.clone())
.collect(),
..r
}
}
/// The output of a run that ended in `st`: its derived facts, its proofs, and what it
/// read (kept for [`Engine::continue_from`]).
fn output(
st: State,
dict: Option<Arc<Dict>>,
resolved: Option<Arc<Plan>>,
report: Report,
chosen: bool,
) -> Output {
Output {
facts: st.derived,
why: st.why.map(Arc::new),
dict,
resolved,
written: None,
report,
kept: Some(Arc::new(Kept {
inputs: st.inputs,
graphs: st.graphs,
externals: st.externals,
chosen,
})),
}
}
/// Stratum `k` of a run, computed from the facts in `st`.
fn stratum(
&self,
p: &Plan,
st: &mut State,
k: usize,
stratum: &Stratum,
trace: &mut dyn Trace,
) -> Result<StratumReport> {
Ok(match stratum {
Stratum::Reach {
rel,
seeds,
step,
edge,
way,
} => self.reach(p, st, k, *rel, seeds, *step, *edge, *way, trace)?,
Stratum::Closure {
rel,
base,
step,
edge,
side,
} => self.closure(p, st, k, *rel, base, *step, *edge, *side, trace)?,
Stratum::LabelReach {
rel,
seeds,
step,
edge,
has,
entry,
edge_cols,
has_cols,
} => {
let shape = LabelShape {
rel: *rel,
step: *step,
edge: *edge,
has: *has,
entry: *entry,
edge_cols: *edge_cols,
has_cols: *has_cols,
};
self.label_reach(p, st, k, seeds, shape, trace)?
}
Stratum::Walk {
rel,
from,
edge,
way,
hops,
shortest,
} => self.walk(
p,
st,
k,
*rel,
*from,
*edge,
*way,
(*hops, *shortest),
trace,
)?,
Stratum::Procedure {
rel,
edge,
procedure,
} => self.procedure(p, st, k, *rel, *edge, *procedure, trace)?,
Stratum::Joins { rels, rules } => self.joins(p, st, k, rels, rules, trace)?,
Stratum::Rounds { parts, rules } => self.rounds(p, st, k, parts, rules, trace)?,
Stratum::Sets { rels, rules } => self.sets_stratum(p, st, rels, rules)?,
})
}
/// The inputs of `p` read into a run's state, the strata planned (of the plan as it
/// runs: resolved for a typed plan); `chosen`: `p` is the plan the index choice made.
async fn load(&self, p: &Plan, inputs: &Inputs, chosen: bool) -> Result<Loaded> {
let t0 = Instant::now();
let mut st = State {
inputs: HashMap::new(),
graphs: HashMap::new(),
derived: HashMap::new(),
externals: HashMap::new(),
why: self.explain.then(WhyStore::default),
typed: false,
dict: None,
peak_rows: 0,
proof_rows: 0,
indexed_rows: 0,
range_joins: 0,
next_rows: 0,
};
let mut strata = plan(p)?;
if self.split.is_some() {
if self.explain {
return Err(PlanError::NotSplittable(
"the why of a run split over parts".to_string(),
));
}
if let Some(x) = strata.iter().find(|x| !x.splittable(p)) {
let names: Vec<&str> = x
.relations()
.iter()
.map(|&r| p.relation_info(r).name.as_str())
.collect();
return Err(PlanError::NotSplittable(format!(
"{} of {}: it runs on one machine",
x.kind(),
names.join(", ")
)));
}
}
// A typed plan: its typed inputs are read after the others (strings need the
// run's dictionary), and it runs as resolved for the run.
let typed = crate::resolve::needs_resolving(p);
let mut pending: Vec<(RelId, Vec<Vec<ArrayRef>>)> = Vec::new();
let used: HashSet<RelId> = p
.rules()
.iter()
.flat_map(|r| r.body.iter().chain(&r.negated).map(|a| a.rel))
.chain(p.walks().iter().flat_map(|w| [w.from, w.edge]))
.chain(
p.calls()
.iter()
.flat_map(|c| [Some(c.edge), c.procedure.weights()].into_iter().flatten()),
)
.filter(|r| p.relation_info(*r).kind != RelKind::Derived)
.collect();
for &rel in &used {
let info = p.relation_info(rel);
if p.is_typed(rel) {
if let Some(chunks) = self.typed_source(p, &mut st, rel, inputs).await? {
pending.push((rel, chunks));
}
continue;
}
// (columns in an id space: their bases added now, as the run reads them)
let shifted;
let source = match inputs.source(rel) {
Some(Source::ColumnsAt { columns, bases }) => {
shifted = Source::Columns(crate::facts::columns_at(columns, bases)?);
Some(&shifted)
}
s => s,
};
match source {
None => {
return Err(PlanError::Input(format!("no input for `{}`", info.name)));
}
Some(Source::Facts(f)) => {
if f.arity() != info.arity {
return Err(PlanError::Input(format!(
"{} columns of facts for `{}` of {}",
f.arity(),
info.name,
info.arity
)));
}
st.inputs.insert(rel, f.clone());
}
Some(Source::External(ext)) => {
if ext.arity() != info.arity {
return Err(PlanError::Input(format!(
"an external of {} columns for `{}` of {}",
ext.arity(),
info.name,
info.arity
)));
}
st.externals.insert(rel, ext.clone());
}
Some(Source::Columns(cols)) => {
if cols.len() != info.arity {
return Err(PlanError::Input(format!(
"{} columns for `{}` of {}",
cols.len(),
info.name,
info.arity
)));
}
// u32 and u64 columns are used in place.
let out = crate::facts::columns_of(cols)?;
st.inputs.insert(rel, Facts::from_columns(out)?);
}
Some(Source::Table { table, columns }) => {
if columns.len() != info.arity {
return Err(PlanError::Input(format!(
"{} columns for `{}` of {}",
columns.len(),
info.name,
info.arity
)));
}
let cols: Vec<&str> = columns.iter().map(String::as_str).collect();
let batches = self
.context()
.read_table(table.clone())?
.select_columns(&cols)?
.collect()
.await?;
st.inputs
.insert(rel, Facts::from_batches(info.arity, &batches)?);
}
Some(Source::Graph { out, inn }) => {
if info.arity != 2 {
return Err(PlanError::Input(format!(
"a graph for `{}` of {} columns",
info.name, info.arity
)));
}
st.graphs.insert(rel, (out.clone(), inn.clone(), (0, 0)));
}
Some(Source::GraphAt { out, inn, bases }) => {
if info.arity != 2 {
return Err(PlanError::Input(format!(
"a graph for `{}` of {} columns",
info.name, info.arity
)));
}
st.graphs.insert(rel, (out.clone(), inn.clone(), *bases));
}
Some(Source::ColumnsAt { .. }) => unreachable!("read as columns above"),
}
}
let mut dict = None;
let mut resolved = None;
if typed {
let d = crate::resolve::load_typed(&self.par, p, &mut st.inputs, pending)?;
let q = crate::resolve::resolve(p, &d)?;
strata = plan(&q)?;
st.typed = true;
dict = (!d.is_empty() || !p.strings().is_empty() || p.makes_strings())
.then(|| Arc::new(d));
resolved = Some(Arc::new(q));
}
if chosen && resolved.is_none() {
resolved = Some(Arc::new(p.clone()));
}
let load = t0.elapsed();
Ok(Loaded {
st,
strata,
dict,
resolved,
load,
t0,
})
}
/// The source of typed input `rel`: facts in hand (codes; a string column refused) and
/// externals (no string column) taken at once, Arrow columns and table columns
/// returned as chunks per column, coded once the run's dictionary is known.
async fn typed_source(
&self,
p: &Plan,
st: &mut State,
rel: RelId,
inputs: &Inputs,
) -> Result<Option<Vec<Vec<ArrayRef>>>> {
let info = p.relation_info(rel);
let types = p.types(rel);
let has_str = types.contains(&Type::Str);
let width = |n: usize, what: &str| {
if n != info.arity {
Err(PlanError::Input(format!(
"{n} {what} for `{}` of {}",
info.name, info.arity
)))
} else {
Ok(())
}
};
let shifted;
let source = match inputs.source(rel) {
Some(Source::ColumnsAt { columns, bases }) => {
shifted = Source::Columns(crate::facts::columns_at(columns, bases)?);
Some(&shifted)
}
s => s,
};
match source {
None => Err(PlanError::Input(format!("no input for `{}`", info.name))),
Some(Source::Facts(f)) => {
width(f.arity(), "columns of facts")?;
if has_str {
return Err(PlanError::Input(format!(
"`{}` has a str column: give it as Arrow columns or a table, not as facts",
info.name
)));
}
st.inputs.insert(rel, f.clone());
Ok(None)
}
Some(Source::External(ext)) => {
width(ext.arity(), "columns of an external")?;
if has_str {
return Err(PlanError::Input(format!(
"the external `{}` has a str column; an external hands codes, and \
string codes are the run's",
info.name
)));
}
st.externals.insert(rel, ext.clone());
Ok(None)
}
Some(Source::Columns(cols)) => {
width(cols.len(), "columns")?;
Ok(Some(cols.iter().map(|c| vec![c.clone()]).collect()))
}
Some(Source::Table { table, columns }) => {
width(columns.len(), "columns")?;
let cols: Vec<&str> = columns.iter().map(String::as_str).collect();
let batches = self
.context()
.read_table(table.clone())?
.select_columns(&cols)?
.collect()
.await?;
Ok(Some(
(0..info.arity)
.map(|i| batches.iter().map(|b| b.column(i).clone()).collect())
.collect(),
))
}
Some(Source::ColumnsAt { .. }) => unreachable!("read as columns above"),
Some(Source::Graph { .. } | Source::GraphAt { .. }) => Err(PlanError::Input(format!(
"a graph for `{}`, which has typed columns (a graph holds u64 ids)",
info.name
))),
}
}
/// The union of the facts of `rules` (each over facts in hand), sorted; with explain
/// on, their derivations are kept for the head relation.
fn union_of(&self, p: &Plan, st: &mut State, rules: &[RuleId]) -> Result<Facts> {
let rel = p.rule_at(rules[0]).head.rel;
let mut set = self.row_set(p.relation_info(rel).arity, true);
let mut prov = self.explain.then(ProvBuilder::default);
let mut ix = Indexes::new();
let own: HashMap<RelId, RowSet> = HashMap::new();
for &r in rules {
let ins = self.inputs_for(p, st, p.rule_at(r), None, &own)?;
let t = self.bindings(p, st, r, &ins, None, &mut ix)?;
st.proof_rows += self.heads(p, r, t, &mut set, prov.as_mut(), 0)?;
}
let (facts, order) = set.finish(&self.par, prov.is_some());
if let (Some(pv), Some(why)) = (prov, st.why.as_mut()) {
why.derived.insert(rel, pv.finish(facts.clone(), order));
}
Ok(facts)
}
/// The edge relation as a square structural matrix of at least `min_n` rows (a graph
/// input as stored; facts through an edge list), and its transpose when stored.
/// The edges of `edge` as a matrix (and its transpose when given), over a numbering of
/// the vertices that covers the ids of `extra` too ([`Ids`]): a graph given whole keeps
/// its own size when every extra id is a vertex of it.
fn edge_matrix(
&self,
p: &Plan,
st: &mut State,
edge: RelId,
extra: &[&Column],
) -> Result<(Csr<u8>, Option<Csr<u8>>, Ids)> {
if let Some((out, inn, bases)) = st.graphs.get(&edge)
&& out.nrows() == out.ncols()
&& bases.0 == bases.1
{
// (a graph of one vertex type: its rows are the vertices, numbered from the base)
let ids = if bases.0 == 0 {
Ids::direct(out.nrows())
} else {
Ids::Shifted {
base: bases.0,
n: out.nrows(),
}
};
let fits = |c: &&Column| match ids {
Ids::Direct(n) => c.is_empty() || (c.max() as u128) < n as u128,
_ => c.iter().all(|v| ids.vertex(v).is_some()),
};
if extra.iter().all(fits) {
return Ok((out.clone(), inn.clone(), ids));
}
}
let f = st.facts(p, edge)?;
let mut cols = vec![f.column(0), f.column(1)];
cols.extend_from_slice(extra);
let ids = Ids::of(&cols, 0)?;
let (src, dst) = (ids.vertices(f.column(0))?, ids.vertices(f.column(1))?);
let n = ids.n();
let out = Csr::from_edges(n, n, &src, &dst, None, BoolOrAnd)?;
Ok((out, None, ids))
}
#[allow(clippy::too_many_arguments)]
fn reach(
&self,
p: &Plan,
st: &mut State,
k: usize,
rel: RelId,
seeds: &[RuleId],
step: RuleId,
edge: RelId,
way: Way,
trace: &mut dyn Trace,
) -> Result<StratumReport> {
let t0 = Instant::now();
let seed_facts = self.union_of(p, st, seeds)?;
let (out, inn, ids) = self.edge_matrix(p, st, edge, &[seed_facts.column(0)])?;
let sources: Vec<u32> = ids.vertices(seed_facts.column(0))?.into_owned();
let (fwd, back) = match way {
Way::Forward => (out, inn),
Way::Backward => match inn {
Some(t) => (t, Some(out)),
None => (out.transpose(), Some(out)),
},
};
if let Some(key) = &self.split {
// Over parts: each part's graph, the engine's search on each, local first.
let split = Split::from_csr(&fwd, key, BoolOrAnd)?;
let mut graphs: Vec<Graph<B>> = split
.parts()
.iter()
.map(|part| Graph::new(part.inner().clone(), &self.device))
.collect::<std::result::Result<_, _>>()?;
let mut states: Vec<BfsState<B>> = graphs
.iter()
.map(|g| BfsState::new(g.vertices(), &self.device))
.collect();
let prepare = t0.elapsed();
let t1 = Instant::now();
let starts: Vec<u64> = sources
.iter()
.map(|&v| split.ids().from_original(v).expect("a vertex of the graph"))
.collect();
let r = kleene_graph::reach_rounds(
&split,
&mut graphs,
&starts,
&mut states,
&self.device,
)?;
let mut vertices: Vec<u32> = r
.ids(split.ids())
.into_iter()
.map(|id| split.ids().original(id).expect("an id of the split"))
.collect();
vertices.sort_unstable();
trace.round(k, r.exchanges.exchanges + 1, vertices.len());
let facts = Facts::from_columns(vec![ids.column(vertices)])?;
let n = facts.len();
st.derived.insert(rel, facts);
return Ok(StratumReport {
kind: "",
relations: Vec::new(),
rounds: r.exchanges.exchanges + 1,
facts: n,
prepare,
compute: t1.elapsed(),
renumbered: ids.ranked(),
continued: false,
peak_rows: 0,
proof_rows: 0,
indexed_rows: 0,
range_joins: 0,
next_rows: 0,
});
}
let back_host = st.why.is_some().then(|| match &back {
Some(t) => t.clone(),
None => fwd.transpose(),
});
// One part: the whole graph, shared (no copy, no border, no exchange).
let whole = Split::whole(fwd.clone())?;
let g: Graph<B> = match back {
Some(t) => Graph::with_transpose(fwd, t, &self.device)?,
None => Graph::new(fwd, &self.device)?,
};
let prepare = t0.elapsed();
let t1 = Instant::now();
// The search runs on the engine's kept buffers; its levels give the facts (and the
// levels the explain path keeps) straight from the level vector.
let mut kept = self.search.lock().unwrap_or_else(|e| e.into_inner());
let n = g.vertices();
let mut graphs = vec![g];
let mut states = vec![
kept.take()
.unwrap_or_else(|| BfsState::new(n, &self.device)),
];
let starts: Vec<u64> = sources.iter().map(|&v| v as u64).collect();
let r = kleene_graph::reach_rounds(&whole, &mut graphs, &starts, &mut states, &self.device);
*kept = states.pop();
let r = r?;
let state = kept.as_ref().expect("the search's buffers given back");
for (i, s) in state.steps().iter().enumerate() {
trace.round(k, i as u32 + 1, s.reached);
}
let rounds = state.steps().len() as u32;
let vertices = r.reached.into_iter().next().unwrap_or_default();
let compute = t1.elapsed();
if let (Some(why), Some(back)) = (st.why.as_mut(), back_host) {
let rule = p.rule_at(step);
let to = rule.head.terms.first().and_then(var_of);
let from = rule
.body
.iter()
.find(|a| a.rel == rel)
.and_then(|a| a.terms.first())
.and_then(var_of);
if let (Some(from), Some(to)) = (from, to) {
let mut levels = vec![u32::MAX; back.nrows()];
for (v, l) in B::vector_to_host(state.levels()).iter() {
levels[v as usize] = l;
}
why.reach.insert(
rel,
ReachWhy {
step,
from,
to,
levels,
back,
ids: ids.clone(),
},
);
}
}
drop(kept);
let facts = Facts::from_columns(vec![ids.column(vertices)])?;
let n = facts.len();
st.derived.insert(rel, facts);
Ok(StratumReport {
kind: "",
relations: Vec::new(),
rounds,
facts: n,
prepare,
compute,
renumbered: ids.ranked(),
continued: false,
peak_rows: 0,
proof_rows: 0,
indexed_rows: 0,
range_joins: 0,
next_rows: 0,
})
}
/// A relation given by a walk: the starts' facts, the edges as a matrix the right way
/// round, then frontier steps (ends) or unmasked products ((start, end) pairs).
#[allow(clippy::too_many_arguments)]
fn walk(
&self,
p: &Plan,
st: &mut State,
k: usize,
rel: RelId,
from: RelId,
edge: RelId,
way: Way,
(hops, shortest): (crate::Hops, Option<crate::Shortest>),
trace: &mut dyn Trace,
) -> Result<StratumReport> {
if p.walk_of(rel).is_some_and(|w| w.counted) {
return self.walk_counted(p, st, k, rel, from, edge, way, hops, trace);
}
let t0 = Instant::now();
let starts = st.facts(p, from)?;
let (out, inn, ids) = self.edge_matrix(p, st, edge, &[starts.column(0)])?;
let mut sources: Vec<u32> = ids.vertices(starts.column(0))?.into_owned();
sources.sort_unstable();
sources.dedup();
let (fwd, back) = match way {
Way::Forward => (out, inn),
Way::Backward => match inn {
Some(t) => (t, Some(out)),
None => (out.transpose(), Some(out)),
},
};
let prepare = t0.elapsed();
let t1 = Instant::now();
let (facts, rounds) = if let Some(which) = shortest {
let host = fwd.clone();
let g: Graph<B> = match back {
Some(t) => Graph::with_transpose(fwd, t, &self.device)?,
None => Graph::new(fwd, &self.device)?,
};
let sp = kleene_graph::shortest_paths::<B>(
&g,
&host,
&sources,
hops,
which,
crate::rules::SHORTEST_PATHS_LIMIT,
&self.device,
)?;
let mut cols: [Vec<Value>; 5] = Default::default();
let mut prev: Option<(u32, u32)> = None;
let mut k = 0u64;
for path in &sp.paths {
let key = (path[0], *path.last().expect("a path has a vertex"));
k = if prev == Some(key) { k + 1 } else { 0 };
prev = Some(key);
for (i, &v) in path.iter().enumerate() {
for (c, x) in cols.iter_mut().zip([
ids.id(key.0),
ids.id(key.1),
k,
i as Value,
ids.id(v),
]) {
c.push(x);
}
}
}
(Facts::from_columns(Vec::from(cols))?, sp.steps)
} else if p.relation_info(rel).arity == 1 {
let g: Graph<B> = match back {
Some(t) => Graph::with_transpose(fwd, t, &self.device)?,
None => Graph::new(fwd, &self.device)?,
};
let w = kleene_graph::walk_ends::<B>(&g, &sources, hops, &self.device)?;
(Facts::from_columns(vec![ids.column(w.vertices)])?, w.steps)
} else {
let (pairs, steps) = kleene_graph::walk_pairs::<B>(&fwd, &sources, hops, &self.device)?;
(ids.facts(csr_pairs(&pairs))?, steps)
};
let compute = t1.elapsed();
let rounds = u32::try_from(rounds).unwrap_or(u32::MAX);
trace.round(k, rounds, facts.len());
let n = facts.len();
st.derived.insert(rel, facts);
Ok(StratumReport {
kind: "",
relations: Vec::new(),
rounds,
facts: n,
prepare,
compute,
renumbered: ids.ranked(),
continued: false,
peak_rows: 0,
proof_rows: 0,
indexed_rows: 0,
range_joins: 0,
next_rows: 0,
})
}
/// A relation given by [`Plan::walk_counted`]: the number of walks per (start, end) or
/// per end, one plus-times step per edge of the length ([`kleene_graph::walk_counts`]).
#[allow(clippy::too_many_arguments)]
fn walk_counted(
&self,
p: &Plan,
st: &mut State,
k: usize,
rel: RelId,
from: RelId,
edge: RelId,
way: Way,
hops: crate::Hops,
trace: &mut dyn Trace,
) -> Result<StratumReport> {
let t0 = Instant::now();
let starts = st.facts(p, from)?;
let (counts, ids) = if p.is_counted(edge) {
// (source, destination, parallel edges): the counts are the entries' values
let f = st.facts(p, edge)?;
let ids = Ids::of(&[f.column(0), f.column(1), starts.column(0)], 0)?;
let (a, b) = (ids.vertices(f.column(0))?, ids.vertices(f.column(1))?);
let (src, dst) = match way {
Way::Forward => (a, b),
Way::Backward => (b, a),
};
let vals: Vec<u64> = f.column(2).iter().collect();
let n = ids.n();
let m = Csr::from_edges(
n,
n,
&src,
&dst,
Some(&vals),
kleene_sparse::PlusTimes::<u64>::new(),
)?;
let sources = ids.vertices(starts.column(0))?.into_owned();
(kleene_graph::walk_counts(&m, &sources, hops)?, ids)
} else {
let (out, _, ids) = self.edge_matrix(p, st, edge, &[starts.column(0)])?;
let m = match way {
Way::Forward => out,
Way::Backward => out.transpose(),
};
let sources = ids.vertices(starts.column(0))?.into_owned();
(kleene_graph::walk_counts(&m, &sources, hops)?, ids)
};
let prepare = t0.elapsed();
let t1 = Instant::now();
let facts = if p.relation_info(rel).arity == 3 {
let mut cols: [Vec<Value>; 3] = Default::default();
for &(s, v, c) in &counts {
cols[0].push(ids.id(s));
cols[1].push(ids.id(v));
cols[2].push(c);
}
Facts::from_columns(Vec::from(cols))?
} else {
// the ends, summed over the starts
let mut by_end: Vec<(Value, u64)> =
counts.iter().map(|&(_, v, c)| (ids.id(v), c)).collect();
by_end.sort_unstable();
let mut cols: [Vec<Value>; 2] = Default::default();
for (v, c) in by_end {
if cols[0].last() == Some(&v) {
let last = cols[1].last_mut().expect("a count");
*last = last
.checked_add(c)
.ok_or_else(|| PlanError::Program("a count past u64".into()))?;
} else {
cols[0].push(v);
cols[1].push(c);
}
}
Facts::from_columns(Vec::from(cols))?
};
let compute = t1.elapsed();
let rounds = u32::try_from(hops.max.unwrap_or(0)).unwrap_or(u32::MAX);
trace.round(k, rounds, facts.len());
let n = facts.len();
st.derived.insert(rel, facts);
Ok(StratumReport {
kind: "",
relations: Vec::new(),
rounds,
facts: n,
prepare,
compute,
renumbered: ids.ranked(),
continued: false,
peak_rows: 0,
proof_rows: 0,
indexed_rows: 0,
range_joins: 0,
next_rows: 0,
})
}
/// A relation given by a graph procedure: the edges as a matrix (and its transpose),
/// then the kernel; one row per vertex (or the count).
#[allow(clippy::too_many_arguments)]
fn procedure(
&self,
p: &Plan,
st: &mut State,
k: usize,
rel: RelId,
edge: RelId,
procedure: crate::Procedure,
trace: &mut dyn Trace,
) -> Result<StratumReport> {
use crate::Procedure as Pr;
let t0 = Instant::now();
let source = match procedure {
Pr::Sssp { source, .. } => Column::from(vec![source]),
Pr::MaxFlow { source, target, .. } => Column::from(vec![source, target]),
_ => Column::from(Vec::<u64>::new()),
};
// ids too far apart to index directly are numbered by rank (their order kept) and
// every vertex of the answer is mapped back to its id
let (out, inn, numbering) = self.edge_matrix(p, st, edge, &[&source])?;
let vertex = |what: &str, v: Value| {
numbering.vertex(v).ok_or_else(|| {
PlanError::Program(format!(
"{} {what} {v} is no vertex of `{}`",
procedure.name(),
p.relation_info(edge).name
))
})
};
let inn = match inn {
Some(t) => t,
None => out.transpose(),
};
let n = out.nrows();
let prepare = t0.elapsed();
let t1 = Instant::now();
let cpu = || {
B::cpu(&self.device).ok_or_else(|| {
PlanError::Program(format!("{} runs on the CPU backend", procedure.name()))
})
};
let ids = || (0..n as Value).collect::<Vec<Value>>();
let float = |x: f64| {
crate::Type::F64
.encode(&crate::Datum::F64(x), None)
.expect("a float")
};
let (cols, rounds): (Vec<Vec<Value>>, u32) = match procedure {
Pr::PageRank => {
let opts = kleene_graph::PageRankOptions::default();
let r = kleene_graph::pagerank(&out, &inn, &opts, cpu()?)?;
let s = r.scores.iter().map(|&x| float(x as f64)).collect();
(vec![ids(), s], r.rounds)
}
Pr::WeakComponents | Pr::StrongComponents => {
if procedure == Pr::WeakComponents {
// The same code for one part (the whole graph: one components_of) and
// for a split.
let (fwd, back) = match &self.split {
Some(key) => (
Split::from_csr(&out, key, BoolOrAnd)?,
Split::from_csr(&inn, key, BoolOrAnd)?,
),
None => (Split::whole(out.clone())?, Split::whole(inn.clone())?),
};
let c = kleene_graph::components_rounds::<B>(&fwd, &back, &self.device)?;
let of: Vec<Value> = if fwd.ids().is_identity() {
c.of.iter().map(|&x| x as Value).collect()
} else {
(0..n as u32)
.map(|v| {
let id = fwd.ids().from_original(v).expect("a vertex of the graph");
c.of[id as usize] as Value
})
.collect()
};
(vec![ids(), of], c.rounds)
} else {
let c = B::scc_of(&out, &inn, &self.device)?;
(
vec![ids(), c.of.iter().map(|&x| x as Value).collect()],
c.rounds,
)
}
}
Pr::Sssp { source, weights } => {
let source = vertex("source", source)?;
let w: Csr<u32> = match weights {
None => Csr::with_pattern(out.pattern().clone(), None)?,
Some(r) => {
let f = st.facts(p, r)?;
let (a, b) = (
numbering.vertices(f.column(0))?,
numbering.vertices(f.column(1))?,
);
let c = f.column(2).to_u32()?;
if let Some(&v) = a.iter().chain(b.iter()).find(|&&v| v as usize >= n) {
return Err(PlanError::Program(format!(
"a weight on vertex {v}, past the edges' {n} vertices"
)));
}
Csr::from_edges(
n,
n,
&a,
&b,
Some(&c),
kleene_sparse::MinPlus::<u32>::new(),
)?
}
};
let opts = kleene_graph::SsspOptions::default();
// The same code for one part (the whole graph: one sssp_of) and for a split.
let split = match &self.split {
Some(key) => Split::from_csr(&w, key, kleene_sparse::MinPlus::<u32>::new())?,
None => Split::whole(w)?,
};
let from = split
.ids()
.from_original(source)
.expect("a vertex of the graph");
let r = kleene_graph::sssp_rounds::<B>(&split, from, &opts, &self.device)?;
let (mut vs, mut ds) = (Vec::new(), Vec::new());
if let Some(paths) = r.paths() {
for v in 0..n as u32 {
if let Some(d) = paths.distance(v) {
vs.push(v as Value);
ds.push(d);
}
}
} else if split.ids().is_identity() {
r.for_each(split.ids(), |id, d| {
vs.push(id as Value);
ds.push(d);
});
} else {
let mut found: Vec<(u32, u64)> = r
.ids(split.ids())
.into_iter()
.map(|(id, d)| (split.ids().original(id).expect("an id of the split"), d))
.collect();
found.sort_unstable();
(vs, ds) = found.into_iter().map(|(v, d)| (v as Value, d)).unzip();
}
(vec![vs, ds], r.rounds)
}
Pr::Betweenness => {
let sources: Vec<u32> = (0..n as u32).collect();
let s = kleene_graph::betweenness(&out, &inn, &sources, cpu()?)?;
(vec![ids(), s.iter().map(|&x| float(x)).collect()], 1)
}
Pr::SpanningForest { weights } => {
let forest = |cols: (Vec<u32>, Vec<u32>, Vec<Value>), rounds| {
(
vec![
cols.0.into_iter().map(Value::from).collect(),
cols.1.into_iter().map(Value::from).collect(),
cols.2,
],
rounds,
)
};
let unzip = |edges: Vec<(u32, u32, Value)>| {
let mut c = (Vec::new(), Vec::new(), Vec::new());
for (a, b, w) in edges {
c.0.push(a);
c.1.push(b);
c.2.push(w);
}
c
};
match weights {
None => {
let f = kleene_graph::spanning_forest(&out, cpu()?)?;
let e = f.edges.iter().map(|&(a, b, w)| (a, b, Value::from(w)));
forest(unzip(e.collect()), f.rounds)
}
Some(r) => {
let f = st.facts(p, r)?;
let (a, b) = (
numbering.vertices(f.column(0))?,
numbering.vertices(f.column(1))?,
);
if let Some(&v) = a.iter().chain(b.iter()).find(|&&v| v as usize >= n) {
return Err(PlanError::Program(format!(
"a weight on vertex {v}, past the edges' {n} vertices"
)));
}
let c: Vec<Value> = f.column(2).iter().collect();
if p.col_type(r, 2) == crate::Type::F64 {
let w: Vec<f64> = c
.iter()
.map(|&x| match crate::Type::F64.decode(x, None) {
crate::Datum::F64(x) => x,
_ => f64::NAN,
})
.collect();
let m = Csr::from_edges(
n,
n,
&a,
&b,
Some(&w),
kleene_sparse::MinPlus::<f64>::new(),
)?;
let f = kleene_graph::spanning_forest(&m, cpu()?)?;
let e = f.edges.iter().map(|&(a, b, w)| (a, b, float(w)));
forest(unzip(e.collect()), f.rounds)
} else if p.col_type(r, 2) == crate::Type::I64 {
let w: Vec<i64> = c.iter().map(|&x| crate::typed::i64_of(x)).collect();
let m = Csr::from_edges(
n,
n,
&a,
&b,
Some(&w),
kleene_sparse::MinPlus::<i64>::new(),
)?;
let f = kleene_graph::spanning_forest(&m, cpu()?)?;
let e = f
.edges
.iter()
.map(|&(a, b, w)| (a, b, crate::typed::i64_code(w)));
forest(unzip(e.collect()), f.rounds)
} else {
let m = Csr::from_edges(
n,
n,
&a,
&b,
Some(&c),
kleene_sparse::MinPlus::<u64>::new(),
)?;
let f = kleene_graph::spanning_forest(&m, cpu()?)?;
forest(unzip(f.edges), f.rounds)
}
}
}
}
Pr::MaxFlow {
source,
target,
capacities,
} => {
let (s, t) = (vertex("source", source)?, vertex("target", target)?);
if let Some(r) = capacities.filter(|&r| p.col_type(r, 2) == crate::Type::F64) {
// float capacities: a float flow
let f = st.facts(p, r)?;
let (a, b) = (
numbering.vertices(f.column(0))?,
numbering.vertices(f.column(1))?,
);
if let Some(&v) = a.iter().chain(b.iter()).find(|&&v| v as usize >= n) {
return Err(PlanError::Program(format!(
"a capacity on vertex {v}, past the edges' {n} vertices"
)));
}
let c: Vec<f64> = f
.column(2)
.iter()
.map(|x| match crate::Type::F64.decode(x, None) {
crate::Datum::F64(x) => x,
_ => f64::NAN,
})
.collect();
let m = Csr::from_edges(
n,
n,
&a,
&b,
Some(&c),
kleene_sparse::PlusTimes::<f64>::new(),
)?;
let f = kleene_graph::max_flow_f64(&m, s, t, cpu()?)?;
(vec![vec![float(f.value)]], f.phases + f.rounds)
} else {
let f = match capacities {
None => kleene_graph::max_flow(&out, s, t, cpu()?)?,
Some(r) => {
let f = st.facts(p, r)?;
let (a, b) = (
numbering.vertices(f.column(0))?,
numbering.vertices(f.column(1))?,
);
if let Some(&v) = a.iter().chain(b.iter()).find(|&&v| v as usize >= n) {
return Err(PlanError::Program(format!(
"a capacity on vertex {v}, past the edges' {n} vertices"
)));
}
let c: Vec<Value> = f.column(2).iter().collect();
let m = Csr::from_edges(
n,
n,
&a,
&b,
Some(&c),
kleene_sparse::PlusTimes::<u64>::new(),
)?;
kleene_graph::max_flow(&m, s, t, cpu()?)?
}
};
let v = u64::try_from(f.value).map_err(|_| {
PlanError::Program(format!("maximum flow {} is past u64", f.value))
})?;
(vec![vec![v]], f.phases + f.rounds)
}
}
Pr::Triangles => {
let und = kleene_graph::undirected(&out, &inn)?;
let t = kleene_graph::triangles(&und, kleene_graph::Relabel::Auto, cpu()?)?;
(vec![vec![t.count]], 1)
}
Pr::Harmonic { mode } => {
let mut opts = kleene_graph::HyperBallOptions::default();
let exact = match mode {
crate::HarmonicMode::Exact => true,
crate::HarmonicMode::Estimate { log2_registers } => {
opts.log2_registers = log2_registers;
false
}
_ => n <= crate::HARMONIC_EXACT_MAX,
};
let (s, rounds) = if exact {
(kleene_graph::harmonic(&out, &inn, cpu()?)?, 1)
} else {
let e = kleene_graph::harmonic_estimate(&out, &opts, cpu()?)?;
(e.scores, e.rounds)
};
(vec![ids(), s.iter().map(|&x| float(x)).collect()], rounds)
}
Pr::KTruss { k } => {
let und = kleene_graph::undirected(&out, &inn)?;
let t = kleene_graph::ktruss(&und, k, cpu()?)?;
let (mut a, mut b, mut c) = (Vec::new(), Vec::new(), Vec::new());
let vals: &[u32] = t.edges.values().map_or(&[], |v| &v[..]);
let off = t.edges.pattern().offsets();
for v in 0..n {
for (i, &w) in t.edges.row(v).iter().enumerate() {
if (w as usize) > v {
a.push(v as Value);
b.push(Value::from(w));
c.push(Value::from(vals[off[v] as usize + i]));
}
}
}
(vec![a, b, c], t.rounds)
}
Pr::TrussNumbers => {
let und = kleene_graph::undirected(&out, &inn)?;
let t = kleene_graph::truss_numbers(&und, cpu()?)?;
let (mut a, mut b, mut c) = (Vec::new(), Vec::new(), Vec::new());
let vals: &[u32] = t.values().map_or(&[], |v| &v[..]);
let off = t.pattern().offsets();
for v in 0..n {
for (i, &w) in t.row(v).iter().enumerate() {
if (w as usize) > v {
a.push(v as Value);
b.push(Value::from(w));
c.push(Value::from(vals[off[v] as usize + i]));
}
}
}
(vec![a, b, c], 1)
}
Pr::Mis { seed } => {
let und = kleene_graph::undirected(&out, &inn)?;
let m = kleene_graph::mis(&und, seed, cpu()?)?;
(
vec![m.members.iter().map(|&v| Value::from(v)).collect()],
m.rounds,
)
}
};
// Vertices as ids (a graph in an id space numbers them from its base; ids far apart
// were numbered by rank).
let nodes = procedure.vertex_columns();
let mut cols = cols;
if !matches!(numbering, Ids::Direct(_)) {
for &c in nodes {
for v in &mut cols[c] {
*v = numbering.id(*v as u32);
}
}
}
let facts = Facts::from_columns(cols)?;
let compute = t1.elapsed();
trace.round(k, rounds, facts.len());
let n = facts.len();
st.derived.insert(rel, facts);
Ok(StratumReport {
kind: "",
relations: Vec::new(),
rounds,
facts: n,
prepare,
compute,
renumbered: numbering.ranked(),
continued: false,
peak_rows: 0,
proof_rows: 0,
indexed_rows: 0,
range_joins: 0,
next_rows: 0,
})
}
#[allow(clippy::too_many_arguments)]
fn closure(
&self,
p: &Plan,
st: &mut State,
k: usize,
rel: RelId,
base: &[RuleId],
step: RuleId,
edge: RelId,
side: Side,
trace: &mut dyn Trace,
) -> Result<StratumReport> {
let t0 = Instant::now();
let b = self.union_of(p, st, base)?;
let (e, _, ids) = self.edge_matrix(p, st, edge, &[b.column(0), b.column(1)])?;
let (b0, b1) = (ids.vertices(b.column(0))?, ids.vertices(b.column(1))?);
let n = e.nrows();
if let Some(key) = &self.split {
// Over parts: base pairs (x, y) grown along the edges right-linearly; a left-linear
// closure is the right-linear one of the transposes, its pairs turned round.
let (g, pairs): (Csr<u8>, Vec<(u32, u32)>) = match side {
Side::Right => (e, b0.iter().copied().zip(b1.iter().copied()).collect()),
Side::Left => (
e.transpose(),
b1.iter().copied().zip(b0.iter().copied()).collect(),
),
};
let split = Split::from_csr(&g, key, BoolOrAnd)?;
let prepare = t0.elapsed();
let t1 = Instant::now();
let sid = |v: u32| split.ids().from_original(v).expect("a vertex of the graph");
let base: Vec<(u64, u64)> = pairs.iter().map(|&(a, b)| (sid(a), sid(b))).collect();
let r = kleene_graph::closure_rounds::<B>(&split, &base, &self.device)?;
let orig = |id: u64| split.ids().original(id).expect("an id of the split");
let (mut a, mut b): (Vec<u32>, Vec<u32>) =
r.pairs.iter().map(|&(x, z)| (orig(x), orig(z))).unzip();
if side == Side::Left {
std::mem::swap(&mut a, &mut b);
}
trace.round(k, r.exchanges.exchanges + 1, a.len());
let c = Csr::from_edges(n, n, &a, &b, None, BoolOrAnd)?;
let pairs = ids.facts(csr_pairs(&c))?;
let n = pairs.len();
st.derived.insert(rel, pairs);
return Ok(StratumReport {
kind: "",
relations: Vec::new(),
rounds: r.exchanges.exchanges + 1,
facts: n,
prepare,
compute: t1.elapsed(),
renumbered: ids.ranked(),
continued: false,
peak_rows: 0,
proof_rows: 0,
indexed_rows: 0,
range_joins: 0,
next_rows: 0,
});
}
let bm = Csr::from_edges(n, n, &b0, &b1, None, BoolOrAnd)?;
let prepare = t0.elapsed();
let t1 = Instant::now();
let c = kleene_graph::closure::<B>(&bm, &e, side, &self.device)?;
for (i, &g) in c.grown.iter().enumerate() {
trace.round(k, i as u32 + 1, g);
}
let rounds = c.rounds;
if let Some(why) = st.why.as_mut() {
let rule = p.rule_at(step);
let x = rule.head.terms.first().and_then(var_of);
let z = rule.head.terms.get(1).and_then(var_of);
if let (Some(x), Some(z)) = (x, z)
&& let Some(&y) = rule.vars().iter().find(|&&v| v != x && v != z)
{
why.closure.insert(
rel,
ClosureWhy::new(step, side, [x, y, z], bm, e, ids.clone()),
);
}
}
let pairs = ids.facts(csr_pairs(&c.pairs))?;
let compute = t1.elapsed();
let n = pairs.len();
st.derived.insert(rel, pairs);
Ok(StratumReport {
kind: "",
relations: Vec::new(),
rounds,
facts: n,
prepare,
compute,
renumbered: ids.ranked(),
continued: false,
peak_rows: 0,
proof_rows: 0,
indexed_rows: 0,
range_joins: 0,
next_rows: 0,
})
}
/// A labelled reach: the seed pairs from the other rules; the entries numbered in
/// rising order (bit `k` is the `k`-th); each label's set of entries from `has`; the
/// edges grouped by (source, target), a group passing the union of its labels' sets
/// (edges whose labels pass nothing dropped); then one entry-bitmask walk.
fn label_reach(
&self,
p: &Plan,
st: &mut State,
k: usize,
seeds: &[RuleId],
sh: LabelShape,
trace: &mut dyn Trace,
) -> Result<StratumReport> {
let t0 = Instant::now();
let sf = self.union_of(p, st, seeds)?;
let seed_e = sf.column(sh.entry);
let mut entries: Vec<Value> = seed_e.iter().collect();
entries.sort_unstable();
entries.dedup();
let words = entries.len().div_ceil(64).max(1);
// label id i passes set i; unions of several labels come after
let mut label_of: HashMap<Value, u32> = HashMap::new();
let mut label_values: Vec<Value> = Vec::new();
let mut set_words: Vec<u64> = Vec::new();
{
let hf = st.facts(p, sh.has)?;
let [lc, ec] = sh.has_cols;
for i in 0..hf.len() {
let Ok(e) = entries.binary_search(&hf.value(ec, i)) else {
continue;
};
let l = hf.value(lc, i);
let id = *label_of.entry(l).or_insert_with(|| {
label_values.push(l);
set_words.resize(set_words.len() + words, 0);
label_values.len() as u32 - 1
});
set_words[id as usize * words + e / 64] |= 1 << (e % 64);
}
}
let ef = st.facts(p, sh.edge)?;
let [sc, tc, lc] = sh.edge_cols;
// the vertices: the edges' ends and the seeds' (numbered densely when far apart)
let ids = Ids::of(&[ef.column(sc), ef.column(tc), sf.column(1 - sh.entry)], 0)?;
let seed_v = ids.vertices(sf.column(1 - sh.entry))?;
let mut trip: Vec<(u32, u32, u32)> = {
let (src, dst, lab) = (
ids.vertices(ef.column(sc))?,
ids.vertices(ef.column(tc))?,
ef.column(lc),
);
(0..ef.len())
.filter_map(|i| Some((src[i], dst[i], *label_of.get(&lab.get(i))?)))
.collect()
};
trip.sort_unstable();
trip.dedup();
let n = ids.n();
let mut off = vec![0u64; n + 1];
let mut adj: Vec<u32> = Vec::new();
let mut slot_set: Vec<u32> = Vec::new();
let mut label_off: Vec<u32> = vec![0];
let mut labels: Vec<u32> = Vec::new();
let mut unions: HashMap<Vec<u64>, u32> = HashMap::new();
let mut acc = vec![0u64; words];
let mut i = 0;
while i < trip.len() {
let (s, t) = (trip[i].0, trip[i].1);
let start = labels.len();
acc.fill(0);
while i < trip.len() && (trip[i].0, trip[i].1) == (s, t) {
let l = trip[i].2 as usize;
for (a, w) in acc.iter_mut().zip(&set_words[l * words..(l + 1) * words]) {
*a |= w;
}
labels.push(trip[i].2);
i += 1;
}
if acc.iter().all(|&w| w == 0) {
labels.truncate(start);
continue;
}
let set = if labels.len() - start == 1 {
labels[start]
} else {
*unions.entry(acc.clone()).or_insert_with(|| {
set_words.extend_from_slice(&acc);
(set_words.len() / words) as u32 - 1
})
};
off[s as usize + 1] += 1;
adj.push(t);
slot_set.push(set);
label_off.push(labels.len() as u32);
}
for v in 0..n {
off[v + 1] += off[v];
}
if set_words.is_empty() {
set_words.resize(words, 0);
}
let graph = Csr::new(n, n, off.into(), adj.into(), None)?;
let sets = EdgeSets::new(&slot_set, &set_words, words)?;
let mut seed_pairs: Vec<(u32, u32)> = Vec::with_capacity(sf.len());
let mut per_entry: Vec<Vec<u32>> = vec![Vec::new(); entries.len()];
for (i, e) in seed_e.iter().enumerate() {
let e = entries.binary_search(&e).expect("an entry of the seeds");
seed_pairs.push((seed_v[i], e as u32));
per_entry[e].push(seed_v[i]);
}
let prepare = t0.elapsed();
let t1 = Instant::now();
let r =
kleene_graph::label_reach::<B>(&graph, sets, &seed_pairs, entries.len(), &self.device)?;
let rounds = r.rounds.iter().copied().max().unwrap_or(0);
let (mut ecol, mut vcol): (Vec<Value>, Vec<u32>) = (Vec::new(), Vec::new());
for (b, batch) in r.batches().iter().enumerate() {
for (v, w) in batch.iter() {
let mut w = w;
while w != 0 {
ecol.push(entries[b * 64 + w.trailing_zeros() as usize]);
vcol.push(v);
w &= w - 1;
}
}
}
let compute = t1.elapsed();
let ecol: Column = if entries.last().is_none_or(|&e| e <= u32::MAX as Value) {
Column::from(ecol.iter().map(|&e| e as u32).collect::<Vec<u32>>())
} else {
Column::from(ecol)
};
let mut cols = vec![ecol, ids.column(vcol)];
if sh.entry == 1 {
cols.swap(0, 1);
}
let facts = Facts::from_columns(cols)?;
let n_facts = facts.len();
trace.round(k, rounds.max(1), n_facts);
if let Some(why) = st.why.as_mut() {
let rule = p.rule_at(sh.step);
let own = rule.body.iter().find(|a| a.rel == sh.rel);
let edge = rule.body.iter().find(|a| a.rel == sh.edge);
let at = |a: Option<&Atom>, i: usize| a.and_then(|a| a.terms.get(i)).and_then(var_of);
let vars = (
at(Some(&rule.head), sh.entry),
at(own, 1 - sh.entry),
at(Some(&rule.head), 1 - sh.entry),
at(edge, sh.edge_cols[2]),
);
if let (Some(e), Some(s), Some(t), Some(l)) = vars {
why.label.insert(
sh.rel,
LabelWhy {
step: sh.step,
vars: [e, s, t, l],
entry: sh.entry,
entries,
graph,
slot_set,
set_words,
words,
label_off,
labels,
label_values,
seeds: per_entry,
ids: ids.clone(),
},
);
}
}
st.derived.insert(sh.rel, facts);
Ok(StratumReport {
kind: "",
relations: Vec::new(),
rounds,
facts: n_facts,
prepare,
compute,
renumbered: ids.ranked(),
continued: false,
peak_rows: 0,
proof_rows: 0,
indexed_rows: 0,
range_joins: 0,
next_rows: 0,
})
}
/// A stratum of joins: its relations grown to a fixed point from nothing; each
/// relation's facts kept distinct as they arrive and sorted at the end.
fn joins(
&self,
p: &Plan,
st: &mut State,
k: usize,
rels: &[RelId],
rules: &[RuleId],
trace: &mut dyn Trace,
) -> Result<StratumReport> {
let t0 = Instant::now();
// A stratum whose rules read none of its relations keeps its rows as a bag, made
// distinct by the sort at the end.
let recursive = rules
.iter()
.any(|&r| p.rule_at(r).body.iter().any(|a| rels.contains(&a.rel)));
let set = |r: RelId| {
let arity = p.relation_info(r).arity;
if p.is_counted(r) {
// each counting rule's rows tagged by the rule, summed at the end
RowSet::new(arity + 1)
} else {
self.row_set(arity, !recursive)
}
};
let mut total: HashMap<RelId, RowSet> = rels.iter().map(|&r| (r, set(r))).collect();
let mut prov: HashMap<RelId, ProvBuilder> = if self.explain {
rels.iter().map(|&r| (r, ProvBuilder::default())).collect()
} else {
HashMap::new()
};
let mut ix = Indexes::growing();
let mut on_round = |n, new| trace.round(k, n, new);
let rounds = self.fixpoint(
p,
st,
rules,
&mut total,
&mut prov,
0,
&mut ix,
None,
&mut on_round,
)?;
let mut n = 0;
for (r, s) in total {
let (facts, order) = s.finish(&self.par, prov.contains_key(&r));
// A counted relation: the rows of several counting rules for one tuple add up.
if p.is_counted(r) {
// the derivations of the rows before they are added up (each with its
// counting rule's count and number), kept as they arrived
let added = match (prov.remove(&r), st.why.as_mut()) {
(Some(pv), Some(why)) => {
let added = summed(facts.clone())?;
why.counted.insert(r, pv.finish(facts, order));
added
}
_ => summed(facts)?,
};
n += added.len();
st.derived.insert(r, added);
continue;
}
n += facts.len();
if let (Some(pv), Some(why)) = (prov.remove(&r), st.why.as_mut()) {
why.derived.insert(r, pv.finish(facts.clone(), order));
}
st.derived.insert(r, facts);
}
Ok(StratumReport {
kind: "",
relations: Vec::new(),
rounds,
facts: n,
prepare: Duration::ZERO,
compute: t0.elapsed(),
renumbered: false,
continued: false,
peak_rows: 0,
proof_rows: 0,
indexed_rows: 0,
range_joins: 0,
next_rows: 0,
})
}
/// The relations of `total` (a recursion; each holding its facts so far) grown to a
/// fixed point by `rules`, semi-naive: first every rule over the whole facts, then
/// rounds that run a rule once per body atom whose relation grew, that atom reading
/// only the rows the round before added (a range of the relation's arrival order).
/// `tag` is the round of rounds the facts are kept under (0: none); `ix` keeps the
/// indexes of the relations that stay the same. Returns the number of semi-naive
/// rounds; `on_round` hears (round, new facts).
#[allow(clippy::too_many_arguments)]
fn fixpoint(
&self,
p: &Plan,
st: &mut State,
rules: &[RuleId],
total: &mut HashMap<RelId, RowSet>,
prov: &mut HashMap<RelId, ProvBuilder>,
tag: u32,
ix: &mut Indexes,
gained: Option<&HashMap<RelId, Facts>>,
on_round: &mut dyn FnMut(u32, usize),
) -> Result<u32> {
self.fixpoint_from(p, st, rules, total, prov, tag, ix, gained, None, on_round)
}
/// [`Engine::fixpoint`], the rows of each relation of `total` from `new[rel]` on taken
/// as new from the start (rows found again by a stratum that deleted and derives
/// again): the rounds go on from them as from the rows the first round finds.
#[allow(clippy::too_many_arguments)]
fn fixpoint_from(
&self,
p: &Plan,
st: &mut State,
rules: &[RuleId],
total: &mut HashMap<RelId, RowSet>,
prov: &mut HashMap<RelId, ProvBuilder>,
tag: u32,
ix: &mut Indexes,
gained: Option<&HashMap<RelId, Facts>>,
new: Option<&HashMap<RelId, usize>>,
on_round: &mut dyn FnMut(u32, usize),
) -> Result<u32> {
let start: HashMap<RelId, usize> = total
.iter()
.map(|(&r, s)| (r, new.and_then(|n| n.get(&r).copied()).unwrap_or(s.len())))
.collect();
for &r in rules {
let rule = p.rule_at(r);
let head = rule.head.rel;
// A rule that reads the gained relations only in positive atoms and does not
// aggregate finds nothing new but through a gained row: it runs once for each
// atom of one, that atom on the gained rows alone (a rule reading none of them
// finds nothing new at all). Any other rule runs on all.
let monotone = |g: &HashMap<RelId, Facts>| {
!rule.groups() && !rule.negated.iter().any(|a| g.contains_key(&a.rel))
};
match gained {
Some(g) if monotone(g) => {
for (pos, a) in rule.body.iter().enumerate() {
let Some(d) = g.get(&a.rel).filter(|d| !d.is_empty()) else {
continue;
};
let t = {
let ins = self.inputs_gained(p, st, rule, (pos, d), total)?;
self.bindings(p, st, r, &ins, Some(pos), ix)?
};
let set = total.get_mut(&head).expect("own relation");
st.proof_rows += self.heads(p, r, t, set, prov.get_mut(&head), tag)?;
}
}
_ => {
let t = {
let ins = self.inputs_for(p, st, rule, None, total)?;
self.bindings(p, st, r, &ins, None, ix)?
};
let set = total.get_mut(&head).expect("own relation");
st.proof_rows += self.heads(p, r, t, set, prov.get_mut(&head), tag)?;
}
}
}
let mut delta: HashMap<RelId, (usize, usize)> = total
.iter()
.map(|(&r, s)| (r, (start[&r], s.len())))
.collect();
let mut rounds = 1u32;
on_round(rounds, delta.values().map(|d| d.1 - d.0).sum());
while delta.values().any(|d| d.1 > d.0) {
let marks: HashMap<RelId, usize> = total.iter().map(|(&r, s)| (r, s.len())).collect();
for &r in rules {
let rule = p.rule_at(r);
for (pos, a) in rule.body.iter().enumerate() {
let Some(&(lo, hi)) = delta.get(&a.rel) else {
continue;
};
if hi == lo {
continue;
}
let t = {
let ins = self.inputs_for(p, st, rule, Some((pos, (lo, hi))), total)?;
self.bindings(p, st, r, &ins, Some(pos), ix)?
};
let head = rule.head.rel;
let set = total.get_mut(&head).expect("own relation");
st.proof_rows += self.heads(p, r, t, set, prov.get_mut(&head), tag)?;
}
}
delta = total
.iter()
.map(|(&r, s)| (r, (marks[&r], s.len())))
.collect();
rounds += 1;
on_round(rounds, delta.values().map(|d| d.1 - d.0).sum());
}
Ok(rounds)
}
/// A stratum of rounds: each round computes the parts in order, each a fixed point of
/// its rules over the facts in hand (`State::derived` holds this round's facts of the
/// parts already computed and the round before's of the rest); a kept part adds to
/// its facts, a fresh one is replaced. The rounds stop when one changes no part.
fn rounds(
&self,
p: &Plan,
st: &mut State,
k: usize,
parts: &[(RelId, Part)],
rules: &[RuleId],
trace: &mut dyn Trace,
) -> Result<StratumReport> {
let t0 = Instant::now();
let arity = |r: RelId| p.relation_info(r).arity;
let mut kept: HashMap<RelId, (RowSet, ProvBuilder)> = HashMap::new();
// the tables of sets (numbered into as the parts that number are computed), and
// what each numbering rule of a kept head has gathered
let mut tabs: HashMap<RelId, Tab> = HashMap::new();
let mut gathered: HashMap<RuleId, Gathered> = HashMap::new();
for (i, &(r, part)) in parts.iter().enumerate() {
st.derived.insert(r, Facts::empty(arity(r)));
if p.set_limit(r).is_some() {
tabs.insert(r, Tab::new(p, r));
} else if part == Part::Keep {
kept.insert(r, (RowSet::new(arity(r)), ProvBuilder::default()));
}
if let Some(why) = st.why.as_mut() {
let g = p.round_of(r).map_or(0, |x| x.0);
why.parts.insert(r, (g, i, part));
}
}
// the states of the fresh parts since a kept part last grew: one coming back means
// the rounds go in a circle and never settle
let mut seen: Vec<u64> = Vec::new();
let mut ix = Indexes::new();
let is_part = |r: RelId| parts.iter().any(|q| q.0 == r);
// what each kept part's rules read of the other parts when it last ran: from then on
// a rule that reads them in positive atoms alone (and does not aggregate) runs on
// the rows gained since (Engine::fixpoint), the facts it found before kept
let mut read: HashMap<RelId, HashMap<RelId, Facts>> = HashMap::new();
let mut n = 0u32;
loop {
n += 1;
let mut changed = false;
let mut added = 0usize;
for &(rel, part) in parts {
if tabs.contains_key(&rel) {
// (a table grows as the parts that number into it are computed)
continue;
}
let (numbering, own): (Vec<RuleId>, Vec<RuleId>) = rules
.iter()
.copied()
.filter(|&r| p.rule_at(r).head.rel == rel)
.partition(|&r| numbers_into(p.rule_at(r)).is_some());
// a fresh part whose rules do not read it is a bag
let reads_itself = own
.iter()
.any(|&r| p.rule_at(r).body.iter().any(|a| a.rel == rel));
let (set, pv) = match part {
Part::Keep => kept.remove(&rel).expect("a kept part"),
Part::Fresh => (
self.row_set(arity(rel), !reads_itself),
ProvBuilder::default(),
),
};
let before = set.len();
let mut total = HashMap::from([(rel, set)]);
let mut prov = HashMap::new();
if self.explain {
prov.insert(rel, pv);
}
if !numbering.is_empty() {
// A kept head whose rule reads only kept parts and negates none: its
// groups computed again where a binding reads a row gained since it last
// ran; any other numbering rule computes every group.
let mut batch = Vec::with_capacity(numbering.len());
for &r in &numbering {
let rule = p.rule_at(r);
let grows = part == Part::Keep
&& !rule.negated.iter().any(|a| is_part(a.rel))
&& rule.body.iter().all(|a| {
parts
.iter()
.find(|q| q.0 == a.rel)
.is_none_or(|q| q.1 == Part::Keep)
});
let g = grows.then(|| gathered.entry(r).or_default());
batch.push((r, self.set_groups(p, st, r, parts, g, &mut ix)?));
}
let grew = self.give_numbers(p, &mut tabs, batch, &mut total, &mut prov, n)?;
if grew > 0 {
added += grew;
changed = true;
for &r in &numbering {
let t = numbers_into(p.rule_at(r)).expect("a numbering rule");
st.derived.insert(t, tabs[&t].rows.facts());
}
}
}
let reads: HashSet<RelId> = own
.iter()
.map(|&r| p.rule_at(r))
.filter(|rule| !rule.groups() && !rule.negated.iter().any(|a| is_part(a.rel)))
.flat_map(|rule| rule.body.iter().map(|a| a.rel))
.filter(|&q| q != rel && is_part(q))
.collect();
let gained: Option<HashMap<RelId, Facts>> = read.get(&rel).map(|was| {
parts
.iter()
.filter(|q| q.0 != rel)
.map(|&(q, qp)| {
let d = match (was.get(&q), qp) {
(None, _) => Facts::empty(arity(q)),
// a kept part only grows, its new rows last
(Some(old), Part::Keep) => rows_from(&st.derived[&q], old.len()),
(Some(old), Part::Fresh) => {
new_rows(&self.par, old, &st.derived[&q])
}
};
(q, d)
})
.collect()
});
// (the facts numbered above are new to the part's other rules)
self.fixpoint_from(
p,
st,
&own,
&mut total,
&mut prov,
n,
&mut ix,
gained.as_ref(),
Some(&HashMap::from([(rel, before)])),
&mut |_, _| {},
)?;
if part == Part::Keep {
let was = reads.iter().map(|&q| (q, st.derived[&q].clone()));
read.insert(rel, was.collect());
}
// the indexes of parts go (they change), but a kept part's whole (it only
// grows at its end: extended when next read); those of the rest stay
ix.map.retain(|at, _| {
let rel = at.rel(p);
match parts.iter().find(|q| q.0 == rel) {
None => true,
Some(q) => q.1 == Part::Keep && matches!(at, IxKey::Rel(..)),
}
});
let set = total.remove(&rel).expect("the part");
let pv = prov.remove(&rel).unwrap_or_default();
match part {
Part::Keep => {
if set.len() > before {
added += set.len() - before;
changed = true;
st.derived.insert(rel, set.facts());
}
kept.insert(rel, (set, pv));
}
Part::Fresh => {
let (facts, order) = set.finish(&self.par, self.explain);
changed |= st.derived.get(&rel) != Some(&facts);
if let Some(why) = st.why.as_mut() {
why.rounds.insert((rel, n), pv.finish(facts.clone(), order));
}
st.derived.insert(rel, facts);
}
}
}
trace.round(k, n, added);
if !changed {
break;
}
if added > 0 {
seen.clear();
}
let state = parts
.iter()
.filter(|q| q.1 == Part::Fresh)
.fold(0u64, |h, q| {
h.rotate_left(7) ^ facts_hash(&st.derived[&q.0])
});
if seen.contains(&state) {
return Err(PlanError::Program(format!(
"the rounds of `{}` go in a circle: in round {n} the fresh parts are as they \
were in an earlier round and the kept parts did not grow",
p.relation_info(parts[0].0).name
)));
}
seen.push(state);
}
let mut facts = self.finish_tabs(st, tabs);
for (rel, (set, pv)) in kept {
let (f, order) = set.finish(&self.par, self.explain);
facts += f.len();
if let Some(why) = st.why.as_mut() {
why.derived.insert(rel, pv.finish(f.clone(), order));
}
st.derived.insert(rel, f);
}
Ok(StratumReport {
kind: "",
relations: Vec::new(),
rounds: n,
facts,
prepare: Duration::ZERO,
compute: t0.elapsed(),
renumbered: false,
continued: false,
peak_rows: 0,
proof_rows: 0,
indexed_rows: 0,
range_joins: 0,
next_rows: 0,
})
}
/// What each body atom of `rule` reads: at `delta` = (atom, rows), those rows of its
/// stratum relation; the stratum's other relations whole as they stand; facts in hand
/// for the rest (externals are asked when the rule runs).
/// What each body atom of `rule` reads when atom `gained.0` reads the rows `gained.1`
/// alone: the others as [`Engine::inputs_for`] gives them (the gained atom's relation is
/// not listed whole for it).
fn inputs_gained<'a>(
&self,
p: &Plan,
st: &mut State,
rule: &Rule,
gained: (usize, &Facts),
total: &'a HashMap<RelId, RowSet>,
) -> Result<Vec<In<'a>>> {
let mut out = Vec::with_capacity(rule.body.len());
for (i, a) in rule.body.iter().enumerate() {
out.push(match total.get(&a.rel) {
_ if i == gained.0 => In::Facts(gained.1.clone()),
Some(s) => In::Own(s, 0, s.len()),
None if st.is_external(p, a.rel) => In::External,
None => In::Facts(st.facts(p, a.rel)?),
});
}
Ok(out)
}
fn inputs_for<'a>(
&self,
p: &Plan,
st: &mut State,
rule: &Rule,
delta: Option<(usize, (usize, usize))>,
total: &'a HashMap<RelId, RowSet>,
) -> Result<Vec<In<'a>>> {
let mut out = Vec::with_capacity(rule.body.len());
for (i, a) in rule.body.iter().enumerate() {
out.push(match (delta, total.get(&a.rel)) {
(Some((at, (lo, hi))), Some(s)) if at == i => In::Own(s, lo, hi),
(_, Some(s)) => In::Own(s, 0, s.len()),
_ if st.is_external(p, a.rel) => In::External,
_ => In::Facts(st.facts(p, a.rel)?),
});
}
Ok(out)
}
/// The bindings of rule `r`'s variables (columns in [`Rule::vars`] order; only those
/// the head needs unless the why is kept or the rule aggregates) over `ins` that pass
/// its conditions and negated atoms. The atoms read from facts are joined
/// first, left-deep: from `start` (a delta) or the smallest, then always an atom that
/// shares the most bound variables (hash join on the packed shared columns), or one
/// tied to the bound ones by a range (range join), or else the smallest (every pair).
/// Each condition is checked as soon as its variables are bound. The externals then
/// extend the bindings in the first order in which each can answer; negated atoms are
/// anti-joins.
fn bindings(
&self,
p: &Plan,
st: &mut State,
r: RuleId,
ins: &[In],
start: Option<usize>,
ix: &mut Indexes,
) -> Result<Table> {
let rule = p.rule_at(r);
let vars = rule.vars();
let rows: Vec<Option<Rows>> = ins.iter().map(In::rows).collect();
let empty = Table {
vars: vars.clone(),
cols: vec![Vec::new(); vars.len()],
len: 0,
distinct: false,
perm: None,
};
if rows
.iter()
.any(|x| x.as_ref().is_some_and(|x| x.len() == 0))
{
return Ok(empty);
}
// the next row by a key: each row's winners alone, by a sort and a search
if self.next_rows
&& !self.reference()
&& start.is_none()
&& let Some(n) = crate::next::shape(rule, self.explain)
&& let (Some(rl), Some(rr)) = (rows[n.left].as_ref(), rows[n.right].as_ref())
{
st.next_rows += 1;
let t = crate::next::run(&self.par, rule, n, rl, rr, self.explain);
st.peak_rows = st.peak_rows.max(t.len);
return Ok(t);
}
let mut done = vec![false; rule.conds.len()];
// the computes not yet run (each runs once its operands are columns of the table)
let cleft = std::cell::RefCell::new(vec![true; rule.computes.len()]);
let fact: Vec<usize> = (0..rule.body.len())
.filter(|&i| rows[i].is_some())
.collect();
let mut todo = fact.clone();
let mut ext_left: Vec<usize> = (0..rule.body.len())
.filter(|&i| rows[i].is_none())
.collect();
// the negated atoms checked, and the atoms joined first for their shared columns
// alone, to join again whole at the end
let mut negd = vec![false; rule.negated.len()];
let mut rejoin: Vec<usize> = Vec::new();
// Whether a variable is still needed once the atoms in `todo` (and `rejoin`, to join
// again) and the externals in `ext` are left, the conditions not `done` and the
// negated atoms not `negd` are left to check: by the head or by one of those.
let need = |v: Var,
todo: &[usize],
rejoin: &[usize],
ext: &[usize],
done: &[bool],
negd: &[bool]| {
rule.head.vars().any(|w| w == v)
|| todo
.iter()
.chain(rejoin)
.chain(ext)
.any(|&i| rule.body[i].vars().any(|w| w == v))
|| rule
.conds
.iter()
.zip(done)
.any(|(c, d)| !*d && c.vars().any(|w| w == v))
|| rule
.negated
.iter()
.zip(negd)
.any(|(a, d)| !*d && a.vars().any(|w| w == v))
|| rule
.computes
.iter()
.zip(cleft.borrow().iter())
.any(|(c, &l)| l && (c.out == v || c.expr.vars().contains(&v)))
};
// A join step keeps only the columns still needed, but every variable when the why
// is kept (those no longer needed then ride along as the derivation's witnesses) or
// the rule aggregates (it reads every binding).
let all = self.explain || rule.groups();
// Once a variable is no longer needed, the bindings that differ only in such
// variables are made one after the step (the first of each kind kept, in order):
// every later step, condition, negation and the head read only the needed ones, so
// the facts are the same and each fact's first derivation is kept. Not for a rule
// that aggregates (it counts bindings), and not while a range condition is left to
// check (a range join orders its table side by value alone, so fewer rows could
// order its ties otherwise). `gone` holds the variables already made one.
let passes = !rule.groups() && !self.reference();
let ranges_left = |done: &[bool]| {
rule.conds
.iter()
.zip(done)
.any(|(c, d)| !*d && matches!(c, Cond::Within { .. }))
};
let mut gone: Vec<Var> = Vec::new();
// The rows each atom selects by its own constants and repeats, when worked out.
let mut sels: Vec<Option<Sel>> = vec![None; rule.body.len()];
let start = start.filter(|s| todo.contains(s));
if start.is_none() {
for &i in &todo {
if filters(&rule.body[i]) {
let rw = rows[i].as_ref().expect("facts");
sels[i] = Some(select(&self.par, &rule.body[i].terms, rw, &[]));
}
}
}
let sizes: Vec<usize> = (0..rule.body.len())
.map(|i| match &sels[i] {
Some(s) => s.len(),
None => rows[i].as_ref().map_or(usize::MAX, Rows::len),
})
.collect();
// The order of the steps. Today's: from `start` or the smallest atom, then always
// the atom that shares the most bound variables (then the smaller, then the first),
// the externals after the atoms. With `smart` (a rule that neither aggregates nor
// has a range condition), three changes, each cutting rows the join would carry:
// - an atom whose own variables (read by no other atom, condition or negation) the
// head reads, in a body that also has an atom that is not such, is joined at its
// place for its shared columns alone (made one), and joined whole at the end
// (its head variables multiply no row before);
// - where the next atom shares no bound variable, an external that answers from
// the bound columns and binds a variable a later atom reads is asked first;
// - an atom tied to the others by conditions alone (or by nothing) does not start
// while another can: the atoms it is crossed with are joined first, so the
// conditions cut the cross's pairs before any table holds them.
// A changed order changes the order of the rows; with the why kept, each atom's row
// numbers ride along (in hidden columns) and the rows are put back in today's order
// before the heads, so each fact keeps today's first derivation (an external moved
// must then be today a test of bound columns only).
let smart = passes
&& rule.computes.is_empty()
&& !rule.conds.iter().any(|c| matches!(c, Cond::Within { .. }));
let elsewhere = |i: usize, v: Var| {
rule.body
.iter()
.enumerate()
.any(|(j, a)| j != i && a.vars().any(|w| w == v))
|| rule.negated.iter().any(|a| a.vars().any(|w| w == v))
|| rule.conds.iter().any(|c| c.vars().any(|w| w == v))
};
let head_leaf = |i: usize| {
rule.body[i]
.vars()
.any(|v| !elsewhere(i, v) && rule.head.vars().any(|w| w == v))
};
let mut deferred = vec![false; rule.body.len()];
// (only where another atom, not such, binds a variable it does not hold: one the
// rows could multiply by before the end)
for &i in &fact {
deferred[i] = smart
&& head_leaf(i)
&& fact.iter().any(|&j| {
j != i
&& !head_leaf(j)
&& rule.body[j]
.vars()
.any(|v| !rule.body[i].vars().any(|w| w == v))
});
}
let steps;
let today;
{
let pure = |e: usize| {
rule.body[e]
.vars()
.all(|v| fact.iter().any(|&j| rule.body[j].vars().any(|w| w == v)))
};
let externals = &st.externals;
let connects = |e: usize, bound: &[Var], left: &[usize]| {
let a = &rule.body[e];
let m = mask_of(a, bound);
m != 0
&& externals.get(&a.rel).is_some_and(|x| x.can(m))
&& (!self.explain || pure(e))
&& a.vars().any(|v| {
!bound.contains(&v)
&& left.iter().any(|&i| rule.body[i].vars().any(|w| w == v))
})
};
let bands = rule_bands(rule);
let order = |smart: bool| -> Vec<Step> {
let mut out = Vec::new();
// with `smart`, an atom tied to the others by conditions alone, or by
// nothing, does not start while another can
let joins = |i: usize| {
rule.body[i].vars().any(|v| {
rule.body
.iter()
.enumerate()
.any(|(j, b)| j != i && b.vars().any(|w| w == v))
})
};
let can_start = |i: &usize| !smart || joins(*i) || !todo.iter().any(|&j| joins(j));
// with `smart` (or in a rule that groups: its rows are sorted before they are
// reduced) and the range joins on, a value between two ends held by atoms
// not linked to its own: the atoms of the ends start (each joined by its
// shared variables), then the value's atom joins them by a sort and a
// search, so no cross product comes before the conditions
let banding = (smart || rule.groups()) && self.range_joins && !self.reference();
let first_end = || -> Option<usize> {
let comp = components(rule, &todo);
let at = |v: Var| todo.iter().find(|&&i| rule.body[i].vars().any(|w| w == v));
bands.iter().find_map(|&(x, ends)| {
let cx = comp[*at(x)?];
let mut ce = ends.iter().flatten().map(|&v| at(v).map(|&i| comp[i]));
let c = ce.next()??;
if c == cx || !ce.all(|e| e == Some(c)) {
return None;
}
todo.iter()
.copied()
.filter(|&i| comp[i] == c)
.filter(can_start)
.min_by_key(|&i| sizes[i])
})
};
let Some(first) =
start
.or_else(|| banding.then(first_end).flatten())
.or_else(|| {
todo.iter()
.copied()
.filter(can_start)
.min_by_key(|&i| sizes[i])
})
else {
return out;
};
let mut left: Vec<usize> = todo.iter().copied().filter(|&i| i != first).collect();
let mut exts = ext_left.clone();
let mut bound: Vec<Var> = Vec::new();
let binds = |i: usize, bound: &mut Vec<Var>| {
for v in rule.body[i].vars() {
if (!smart || !deferred[i] || elsewhere(i, v)) && !bound.contains(&v) {
bound.push(v);
}
}
// the computes whose operands are now bound bind their variables
while let Some(c) = rule.computes.iter().find(|c| {
!bound.contains(&c.out) && c.expr.vars().iter().all(|v| bound.contains(v))
}) {
bound.push(c.out);
}
};
out.push(Step::Atom(first));
binds(first, &mut bound);
while !left.is_empty() {
let shared =
|i: usize| rule.body[i].vars().filter(|v| bound.contains(v)).count();
let next = *left
.iter()
.max_by(|&&i, &&j| {
shared(i)
.cmp(&shared(j))
.then_with(|| sizes[j].cmp(&sizes[i]))
.then_with(|| j.cmp(&i))
})
.expect("an atom");
// an atom holding a value whose two ends are bound joins by a band
if banding
&& shared(next) == 0
&& let Some(b) = left.iter().copied().find(|&i| {
bands.iter().any(|&(x, ends)| {
!bound.contains(&x)
&& rule.body[i].vars().any(|w| w == x)
&& ends.iter().flatten().all(|v| bound.contains(v))
&& ends.iter().any(|e| e.is_some())
})
})
{
left.retain(|&i| i != b);
out.push(Step::Atom(b));
binds(b, &mut bound);
continue;
}
if smart
&& shared(next) == 0
&& let Some(k) = exts.iter().position(|&e| connects(e, &bound, &left))
{
let e = exts.remove(k);
out.push(Step::Ext(e));
binds(e, &mut bound);
continue;
}
left.retain(|&i| i != next);
out.push(Step::Atom(next));
binds(next, &mut bound);
}
out
};
today = order(false);
steps = if smart { order(true) } else { today.clone() };
}
// The order of the rows is today's when no external moved, each atom joined for its
// shared columns found them all bound (a test of the rows), and the atoms joined whole
// come in today's order (those joined again last, as today's last).
let kept_order = {
let mut bound: Vec<Var> = Vec::new();
let mut whole: Vec<Step> = Vec::new();
let mut again: Vec<Step> = Vec::new();
let mut tests = true;
for s in &steps {
match *s {
Step::Ext(_) => tests = false,
Step::Atom(i) if deferred[i] => {
tests &= rule.body[i]
.vars()
.filter(|&v| elsewhere(i, v))
.all(|v| bound.contains(&v));
again.push(*s);
}
Step::Atom(i) => {
bound.extend(rule.body[i].vars());
whole.push(*s);
}
}
}
whole.extend(again);
tests && whole == today
};
let ranked = self.explain && smart && !kept_order;
// each atom's place in today's order (its row numbers' place in the rank of a row)
let mut tpos = vec![usize::MAX; rule.body.len()];
for (k, s) in today.iter().enumerate() {
if let Step::Atom(i) = *s {
tpos[i] = k;
}
}
let ranks = |t: &Table| rank_cols(t, &tpos);
let mut t = Table::unit();
for (s, step) in steps.iter().enumerate() {
if t.len == 0 {
break;
}
match *step {
Step::Ext(e) => {
ext_left.retain(|&x| x != e);
let a = &rule.body[e];
let m = mask_of(a, &t.vars);
t = extend_external(&self.par, p, st, a, r, e, m, &t, ix)?;
self.run_computes(
p,
r,
&mut t,
&mut cleft.borrow_mut(),
&mut done,
&mut st.dict,
)?;
self.negate_table(p, st, r, &mut t, &mut negd, ix)?;
if passes {
let left: Vec<Var> = t
.vars
.iter()
.copied()
.filter(|&v| {
!is_rank(v) && !need(v, &todo, &rejoin, &ext_left, &done, &negd)
})
.collect();
t = pass_table(&self.par, t, &left, &mut gone, &ranks);
}
}
Step::Atom(first) if s == 0 => {
todo.retain(|&i| i != first);
let a = &rule.body[first];
let rw = rows[first].as_ref().expect("facts");
let checks = place_checks(rule, &mut done, &[], a, p);
let mut sel = match sels[first].take() {
Some(s) if checks.is_empty() => s,
_ => select(&self.par, &a.terms, rw, &checks),
};
let mut full = new_vars(a, &[]);
if deferred[first] {
// its shared columns alone, each kind once
full.retain(|&(v, _)| elsewhere(first, v));
rejoin.push(first);
let key: Vec<usize> = full.iter().map(|x| x.1).collect();
let at = |c: usize, i: usize| rw.get(c, sel.at(i) as usize);
if key.is_empty() {
sel = Sel::Rows(if sel.len() > 0 {
vec![sel.at(0)]
} else {
vec![]
});
} else if let Some(k) = first_of_kind(
&self.par,
sel.len(),
true,
|i| hash_of(key.len(), |q| at(key[q], i)),
|i, j| key.iter().all(|&c| at(c, i) == at(c, j)),
) {
sel = sel.pick(&self.par, k);
}
} else if passes && !ranges_left(&done) {
let left: Vec<Var> = full
.iter()
.map(|x| x.0)
.filter(|&v| !need(v, &todo, &rejoin, &ext_left, &done, &negd))
.collect();
if left.iter().any(|v| !gone.contains(v)) {
let key: Vec<usize> = full
.iter()
.filter(|x| !left.contains(&x.0))
.map(|x| x.1)
.collect();
let at = |c: usize, i: usize| rw.get(c, sel.at(i) as usize);
if let Some(k) = first_of_kind(
&self.par,
sel.len(),
true,
|i| hash_of(key.len(), |q| at(key[q], i)),
|i, j| key.iter().all(|&c| at(c, i) == at(c, j)),
) {
sel = sel.pick(&self.par, k);
}
gone.extend(left);
}
}
let mut new = full;
new.retain(|&(v, _)| all || need(v, &todo, &rejoin, &ext_left, &done, &negd));
let mut cols = Vec::with_capacity(new.len() + 1);
let mut vars: Vec<Var> = new.iter().map(|&(v, _)| v).collect();
for &(_, j) in &new {
cols.push(gather_sel(&self.par, rw, j, &sel));
}
if ranked && !deferred[first] {
cols.push(self.par.fill(sel.len(), |i| Value::from(sel.at(i))));
vars.push(rank_var(first));
}
t = Table {
vars,
cols,
len: sel.len(),
distinct: false,
perm: None,
};
if passes {
self.negate_table(p, st, r, &mut t, &mut negd, ix)?;
}
}
Step::Atom(next) => {
todo.retain(|&i| i != next);
let a = &rule.body[next];
let rw = rows[next].as_ref().expect("facts");
let mut tk: Vec<usize> = Vec::new();
let mut rk: Vec<usize> = Vec::new();
for (j, term) in a.terms.iter().enumerate() {
if let Term::Var(v) = term
&& let Some(c) = t.col_of(*v)
&& !rk.iter().any(|&q| a.terms[q] == *term)
{
tk.push(c);
rk.push(j);
}
}
let mut new = new_vars(a, &t.vars);
let half = deferred[next];
if half {
new.retain(|&(v, _)| elsewhere(next, v));
rejoin.push(next);
}
let mut checks = place_checks(rule, &mut done, &t.vars, a, p);
let fixed = ix.keeps(&ins[next], a);
if half && new.is_empty() && checks.is_empty() {
// every shared column bound: the rows with a match stay
let any = match &sels[next] {
Some(s) => s.len() > 0,
None => rw.len() > 0,
};
if tk.is_empty() {
if !any {
t.keep_at(&self.par, Vec::new());
}
} else {
let mut sel = || {
sels[next]
.take()
.unwrap_or_else(|| select(&self.par, &a.terms, rw, &[]))
};
let mut scratch = None;
let at = IxKey::of(r, next, a, &rk, matches!(ins[next], In::Own(..)));
let index =
index_of(&self.par, ix, fixed, at, rw, &mut sel, &rk, &mut scratch);
let hits = semi_join(&self.par, &t, &tk, rw, index);
t.keep_at(&self.par, kept_places(&self.par, t.len, |l| hits[l]));
}
st.peak_rows = st.peak_rows.max(t.len);
continue;
}
// The atom's own constants and repeats select its rows (worked out only
// when its index is not kept); the bound columns and the conditions are
// matched pair by pair.
let mut sel = || {
sels[next]
.take()
.unwrap_or_else(|| select(&self.par, &a.terms, rw, &[]))
};
// a value between two ends from the other side: a sort and a search (a
// range with no key beside it as it ran before, below)
let band = (self.range_joins && !self.reference())
.then(|| Band::find(&checks))
.flatten()
.filter(|(_, used)| {
!(tk.is_empty() && matches!(checks[used[0]], Check::Within(..)))
});
let pairs: Pairs = if let Some((b, used)) = band {
for &u in used.iter().rev() {
checks.remove(u);
}
st.range_joins += 1;
band_join(&self.par, &t, rw, &sel(), &tk, &rk, b, &checks)
} else if !tk.is_empty() {
let mut scratch = None;
let at = IxKey::of(r, next, a, &rk, matches!(ins[next], In::Own(..)));
let index = index_of(&self.par, ix, fixed, at, rw, sel, &rk, &mut scratch);
hash_join(&self.par, &t, &tk, rw, index, &checks)
} else if let Some(w) = checks.iter().position(|c| ranged(c).is_some()) {
let (x, lo, hi) = ranged(&checks[w]).expect("a range");
checks.remove(w);
st.range_joins += 1;
range_join(&self.par, &t, rw, &sel(), x, lo, hi, &checks)
} else {
cross_join(&self.par, &t, rw, &sel(), &checks)
};
let mut pairs = pairs;
if passes {
// the negated atoms whose variables are now all bound, on the pairs
pairs = self.negate_pairs(p, st, r, &t, a, rw, pairs, &mut negd, ix)?;
}
let keep: Vec<bool> = t
.vars
.iter()
.map(|&v| all || need(v, &todo, &rejoin, &ext_left, &done, &negd))
.collect();
new.retain(|&(v, _)| all || need(v, &todo, &rejoin, &ext_left, &done, &negd));
if half {
// the shared columns alone: each table row with each kind once
let key: Vec<usize> = new.iter().map(|x| x.1).collect();
if let Some(k) = first_of_kind(
&self.par,
pairs.left.len(),
true,
|i| {
hash_of(key.len() + 1, |q| {
if q == 0 {
Value::from(pairs.left[i])
} else {
rw.get(key[q - 1], pairs.right[i] as usize)
}
})
},
|i, j| {
pairs.left[i] == pairs.left[j]
&& key.iter().all(|&c| {
rw.get(c, pairs.right[i] as usize)
== rw.get(c, pairs.right[j] as usize)
})
},
) {
pairs = pairs.at(&self.par, &k);
}
}
if passes && !ranges_left(&done) {
let bound: Vec<(Var, Src)> = t
.vars
.iter()
.enumerate()
.map(|(c, &v)| (v, Src::T(c)))
.chain(new.iter().map(|&(v, j)| (v, Src::R(j))))
.collect();
let left: Vec<Var> = bound
.iter()
.map(|x| x.0)
.filter(|&v| {
!is_rank(v) && !need(v, &todo, &rejoin, &ext_left, &done, &negd)
})
.collect();
if left.iter().any(|v| !gone.contains(v)) {
let key: Vec<Src> = bound
.iter()
.filter(|x| !left.contains(&x.0) && !is_rank(x.0))
.map(|x| x.1)
.collect();
let val = |s: Src, i: usize| match s {
Src::T(c) => t.cols[c][pairs.left[i] as usize],
Src::R(j) => rw.get(j, pairs.right[i] as usize),
Src::K(x) => x,
};
// with the rows' ranks: the least rank of each kind
let mut rank: Vec<(usize, Option<usize>)> = ranks(&t)
.into_iter()
.map(|c| (tpos[rank_atom(t.vars[c])], Some(c)))
.collect();
if ranked && !half {
rank.push((tpos[next], None));
}
rank.sort_unstable();
let rv = |i: usize, c: Option<usize>| match c {
Some(c) => t.cols[c][pairs.left[i] as usize],
None => Value::from(pairs.right[i]),
};
let kept = first_of_kind_by(
&self.par,
pairs.left.len(),
true,
|i| hash_of(key.len(), |q| val(key[q], i)),
|i, j| key.iter().all(|&s| val(s, i) == val(s, j)),
|i, j| {
for &(_, c) in &rank {
let (a, b) = (rv(i as usize, c), rv(j as usize, c));
if a != b {
return a < b;
}
}
i < j
},
);
if let Some(k) = kept {
pairs = pairs.at(&self.par, &k);
}
for v in left {
if !gone.contains(&v) {
gone.push(v);
}
}
}
}
let mut nt = extend_table(&self.par, &t, &keep, rw, &pairs, &new);
if ranked && !half {
nt.cols.push(
self.par
.fill(pairs.right.len(), |i| Value::from(pairs.right[i])),
);
nt.vars.push(rank_var(next));
}
t = nt;
}
}
self.run_computes(
p,
r,
&mut t,
&mut cleft.borrow_mut(),
&mut done,
&mut st.dict,
)?;
st.peak_rows = st.peak_rows.max(t.len);
}
if t.len == 0 {
return Ok(empty);
}
// The externals left, in the first order in which each can answer what is bound.
while !ext_left.is_empty() {
let answers = |a: &Atom, m: u64| match st.externals.get(&a.rel) {
Some(e) => e.can(m),
None => m == 0, // listed whole from facts in hand
};
let pick = ext_left
.iter()
.position(|&e| answers(&rule.body[e], mask_of(&rule.body[e], &t.vars)))
.or_else(|| ext_left.iter().position(|&e| answers(&rule.body[e], 0)));
let Some(i) = pick else {
return Err(PlanError::Program(format!(
"no order of `{}`'s body binds what the external `{}` needs",
p.relation_info(rule.head.rel).name,
p.relation_info(rule.body[ext_left[0]].rel).name
)));
};
let e = ext_left.remove(i);
let a = &rule.body[e];
let m = mask_of(a, &t.vars);
t = extend_external(&self.par, p, st, a, r, e, m, &t, ix)?;
self.run_computes(
p,
r,
&mut t,
&mut cleft.borrow_mut(),
&mut done,
&mut st.dict,
)?;
if passes {
self.negate_table(p, st, r, &mut t, &mut negd, ix)?;
let left: Vec<Var> = t
.vars
.iter()
.copied()
.filter(|&v| !is_rank(v) && !need(v, &[], &rejoin, &ext_left, &done, &negd))
.collect();
t = pass_table(&self.par, t, &left, &mut gone, &ranks);
}
st.peak_rows = st.peak_rows.max(t.len);
}
// The conditions not checked in a join step (a body of one atom read from facts
// checks them there; externals bind the rest).
let left: Vec<Check> = rule
.conds
.iter()
.zip(&done)
.filter(|(_, d)| !**d)
.filter_map(|(c, _)| Check::place(c, |v| t.col_of(v).map(Src::T), p))
.collect();
let none = Rows::of(&EMPTY);
if !left.is_empty() {
let at = kept_places(&self.par, t.len, |l| {
left.iter().all(|c| c.holds(&t, l, &none, 0))
});
t.keep_at(&self.par, at);
}
// Negated atoms left: anti-joins (an external asked with every column bound).
for (i, d) in negd.iter_mut().enumerate() {
if t.len == 0 {
break;
}
if *d {
continue;
}
let hits = self.neg_hits(p, st, r, i, &t, ix)?;
t.keep_at(&self.par, kept_places(&self.par, t.len, |l| !hits[l]));
*d = true;
}
// The atoms joined for their shared columns alone, joined again whole.
while !rejoin.is_empty() && t.len > 0 {
let i = rejoin.remove(0);
let a = &rule.body[i];
let rw = rows[i].as_ref().expect("facts");
let mut tk: Vec<usize> = Vec::new();
let mut rk: Vec<usize> = Vec::new();
for (j, term) in a.terms.iter().enumerate() {
if let Term::Var(v) = term
&& let Some(c) = t.col_of(*v)
&& !rk.iter().any(|&q| a.terms[q] == *term)
{
tk.push(c);
rk.push(j);
}
}
let mut new = new_vars(a, &t.vars);
let whole = new.len();
new.retain(|&(v, _)| all || need(v, &[], &rejoin, &[], &done, &negd));
let keep: Vec<bool> = t
.vars
.iter()
.map(|&v| all || is_rank(v) || need(v, &[], &rejoin, &[], &done, &negd))
.collect();
let mut sel = || {
sels[i]
.take()
.unwrap_or_else(|| select(&self.par, &a.terms, rw, &[]))
};
let pairs = if tk.is_empty() {
cross_join(&self.par, &t, rw, &sel(), &[])
} else {
// the start's rows may be a part only (a delta handed in as facts): their
// index is not kept
let fixed = ix.keeps(&ins[i], a) && start != Some(i);
let mut scratch = None;
let at = IxKey::of(r, i, a, &rk, matches!(ins[i], In::Own(..)));
let index = index_of(&self.par, ix, fixed, at, rw, sel, &rk, &mut scratch);
hash_join(&self.par, &t, &tk, rw, index, &[])
};
let mut nt = extend_table(&self.par, &t, &keep, rw, &pairs, &new);
if ranked {
nt.cols.push(
self.par
.fill(pairs.right.len(), |k| Value::from(pairs.right[k])),
);
nt.vars.push(rank_var(i));
}
t = nt;
if self.explain {
// the witnesses ride along: the rows that differ in them alone made one
let left: Vec<Var> = t
.vars
.iter()
.copied()
.filter(|&v| !is_rank(v) && !need(v, &[], &rejoin, &[], &done, &negd))
.collect();
t = pass_table(&self.par, t, &left, &mut Vec::new(), &ranks);
} else if new.len() < whole || keep.contains(&false) {
let every: Vec<usize> = (0..t.cols.len()).collect();
if let Some(k) = first_rows(&self.par, &t, &every) {
t = t.at_rows(&self.par, &k, &every);
}
}
st.peak_rows = st.peak_rows.max(t.len);
}
// No row left (an external asked last, a condition or a negation emptied the table
// before the atoms above were joined whole): the bindings are none, with every
// variable of the rule, so the head reads a column for each of its own.
if t.len == 0 {
return Ok(empty);
}
if ranked {
// today's order: by the rank (each atom's row in today's order), then as they are
let rank = ranks(&t);
let mut order: Vec<u32> = (0..t.len as u32).collect();
self.par.sort_by(&mut order, |&a, &b| {
cmp_cols(&t, &rank, a, b).then(a.cmp(&b))
});
// the order kept as a permutation: the columns are gathered into it once, where
// the head reads them (the rank columns go)
let kept: Vec<Var> = t.vars.iter().copied().filter(|&v| !is_rank(v)).collect();
t.reorder(&kept);
t.perm = Some(order);
}
// The head reads its variables only: the bindings that differ in others made one
// (the why keeps them as witnesses; without it they go).
let heads = |v: Var| rule.head.vars().any(|w| w == v);
if passes && t.len > 0 && t.vars.iter().any(|&v| !heads(v) && !gone.contains(&v)) {
let key: Vec<usize> = (0..t.vars.len()).filter(|&c| heads(t.vars[c])).collect();
let kinds = kinds_by(
&self.par,
t.len,
true,
|i| hash_of(key.len(), |q| t.cols[key[q]][t.row(i)]),
|i, j| {
key.iter()
.all(|&c| t.cols[c][t.row(i)] == t.cols[c][t.row(j)])
},
|i, j| i < j,
);
// rows found distinct by the head's variables need no second pass in the set
let distinct = !matches!(kinds, Kinds::Skipped);
if let Kinds::Kept(k) = kinds {
if let Some(perm) = &t.perm {
// in an order of their own: the kept rows' places, nothing gathered
let perm = self.par.fill(k.len(), |i| perm[k[i] as usize]);
t.len = perm.len();
t.perm = Some(perm);
} else {
let cols: Vec<usize> = if self.explain {
(0..t.cols.len()).collect()
} else {
key
};
t = t.at_rows(&self.par, &k, &cols);
}
}
t.distinct = distinct;
}
st.peak_rows = st.peak_rows.max(t.len);
let kept: Vec<Var> = vars
.iter()
.copied()
.filter(|&v| t.col_of(v).is_some() && (all || !passes || heads(v)))
.collect();
t.reorder(&kept);
st.indexed_rows += std::mem::take(&mut ix.rows);
Ok(t)
}
/// Run each compute of rule `r` still `left` whose operands are columns of `t`, in the
/// rule's order, on the device's workers: a row where it has no value goes; its variable
/// becomes a column, or, a column already, the rows where it is not equal go (a null is
/// never equal). A string the run's dictionary `dict` lacks is added to it once the
/// step's values are all in (sorted by their bytes, so its id is one at any thread
/// count). Then the conditions not `done` whose variables are all columns of `t` are
/// checked on it.
fn run_computes(
&self,
p: &Plan,
r: RuleId,
t: &mut Table,
left: &mut [bool],
done: &mut [bool],
dict: &mut Option<Arc<Dict>>,
) -> Result<()> {
let rule = p.rule_at(r);
let mut ran = false;
while let Some(i) = (0..left.len()).find(|&i| {
left[i]
&& rule.computes[i]
.expr
.vars()
.iter()
.all(|&v| t.col_of(v).is_some())
}) {
left[i] = false;
ran = true;
if t.len == 0 {
continue;
}
let c = &rule.computes[i];
t.resolve(&self.par);
let ty = p.var_type(r, c.out);
let slot = |v: Var| (t.col_of(v).expect("an operand column"), p.var_type(r, v));
let run = Compiled::new(&c.expr, &slot, ty);
let mut got: Vec<Got>;
if run.makes_string() {
// each piece's values, and the strings it made that the dictionary lacks
let d = dict.as_deref();
let pieces = self.par.split(t.len, |lo, hi| {
let mut g = Vec::with_capacity(hi - lo);
let mut made: Vec<(u32, String)> = Vec::new();
for l in lo..hi {
match run.eval_made(&|s| t.cols[s][l], d) {
Ok(x) => g.push(x),
Err(s) => {
g.push(Got::Made);
made.push((l as u32, s));
}
}
}
(g, made)
});
got = Vec::with_capacity(t.len);
let mut made: Vec<(u32, String)> = Vec::new();
for (g, m) in pieces {
got.extend(g);
made.extend(m);
}
if !made.is_empty() {
// added after the dictionary's strings, then coded
let d = Arc::make_mut(dict.get_or_insert_with(Default::default));
d.add_made(made.iter().map(|x| x.1.clone()).collect())?;
for (l, s) in &made {
got[*l as usize] = Got::Value(Value::from(d.id(s).expect("added")));
}
}
} else {
let d = dict.as_deref();
got = self.par.fill(t.len, |l| run.eval(&|s| t.cols[s][l], d));
}
match t.col_of(c.out) {
Some(o) => {
let col = &t.cols[o];
let at = kept_places(&self.par, t.len, |l| {
matches!(got[l], Got::Value(x)
if x == col[l] && !(ty.nullable() && x == NULL))
});
t.keep_at(&self.par, at);
}
None => {
let at = kept_places(&self.par, t.len, |l| got[l] != Got::None);
let value = |l: usize| match got[l] {
Got::Value(x) => x,
Got::None | Got::Made => unreachable!("a kept row has a code"),
};
let values = if at.len() == t.len {
self.par.fill(t.len, value)
} else {
let vs = self.par.fill(at.len(), |k| value(at[k] as usize));
t.keep_at(&self.par, at);
vs
};
t.cols.push(values);
t.vars.push(c.out);
}
}
}
if !ran || t.len == 0 {
return Ok(());
}
let mut checks = Vec::new();
for (c, d) in rule.conds.iter().zip(done.iter_mut()) {
if *d {
continue;
}
if let Some(ch) = Check::place(c, |v| t.col_of(v).map(Src::T), p) {
checks.push(ch);
*d = true;
}
}
if !checks.is_empty() {
let none = Rows::of(&EMPTY);
let at = kept_places(&self.par, t.len, |l| {
checks.iter().all(|c| c.holds(t, l, &none, 0))
});
t.keep_at(&self.par, at);
}
Ok(())
}
/// Which rows of `t` (every variable of rule `r`'s negated atom `i` bound) the atom
/// holds: an anti-join's hits (an external asked with every column bound).
fn neg_hits(
&self,
p: &Plan,
st: &mut State,
r: RuleId,
i: usize,
t: &Table,
ix: &mut Indexes,
) -> Result<Vec<bool>> {
self.neg_hits_by(p, st, r, i, &t.vars, t.len, |q, l| t.cols[q][l], ix)
}
/// Which of `n` rows the negated atom `i` of rule `r` holds, each row's value of
/// `vars[q]` read as `get(q, row)`: probed straight from where the values are (no
/// columns gathered, but for an external asked).
#[allow(clippy::too_many_arguments)]
fn neg_hits_by(
&self,
p: &Plan,
st: &mut State,
r: RuleId,
i: usize,
vars: &[Var],
n: usize,
get: impl Fn(usize, usize) -> Value + Sync,
ix: &mut Indexes,
) -> Result<Vec<bool>> {
let rule = p.rule_at(r);
let a = &rule.negated[i];
let q_of = |v: Var| vars.iter().position(|&w| w == v).expect("a bound variable");
let hits = if asks_external(p, st, a) {
// an external reads columns: the atom's variables gathered for it
let kt = Table {
vars: vars.to_vec(),
cols: (0..vars.len())
.map(|q| self.par.fill(n, |l| get(q, l)))
.collect(),
len: n,
distinct: false,
perm: None,
};
negated_lookup(p, st, a, &kt)?.expect("an external asked")
} else {
let f = st.facts(p, a.rel)?;
let rw = Rows::of(&f);
let sel = || select(&self.par, &a.terms, &rw, &[]);
let mut tq = Vec::new();
let mut rk = Vec::new();
for (j, term) in a.terms.iter().enumerate() {
if let Term::Var(v) = term
&& !rk.iter().any(|&q| a.terms[q] == *term)
{
tq.push(q_of(*v));
rk.push(j);
}
}
let mut scratch = None;
let pos = rule.body.len() + i;
let at = IxKey::of(r, pos, a, &rk, false);
let index = index_of(&self.par, ix, true, at, &rw, sel, &rk, &mut scratch);
semi_join_by(&self.par, n, tq.len(), |j, l| get(tq[j], l), &rw, index)
};
if st.typed {
// NOT EXISTS: a null key matches nothing
let nulls: Vec<usize> = a
.terms
.iter()
.filter_map(|term| match term {
Term::Var(v) if p.var_type(r, *v).nullable() => Some(q_of(*v)),
_ => None,
})
.collect();
if !nulls.is_empty() {
return Ok(self
.par
.fill(n, |l| hits[l] && nulls.iter().all(|&q| get(q, l) != NULL)));
}
}
Ok(hits)
}
/// The negated atoms of rule `r` not yet checked (`negd`) whose variables `t` binds,
/// checked on it (its rows kept in order).
fn negate_table(
&self,
p: &Plan,
st: &mut State,
r: RuleId,
t: &mut Table,
negd: &mut [bool],
ix: &mut Indexes,
) -> Result<()> {
let rule = p.rule_at(r);
for (i, a) in rule.negated.iter().enumerate() {
if negd[i] || t.len == 0 || !a.vars().all(|v| t.col_of(v).is_some()) {
continue;
}
let hits = self.neg_hits(p, st, r, i, t, ix)?;
t.keep_at(&self.par, kept_places(&self.par, t.len, |l| !hits[l]));
negd[i] = true;
}
Ok(())
}
/// The pairs of a join step of `t` with atom `a` (rows `rw`) less those that a negated
/// atom of rule `r` not yet checked holds, for each whose variables the step binds (its
/// columns gathered at the pairs alone): the step's table never holds those rows.
#[allow(clippy::too_many_arguments)]
fn negate_pairs(
&self,
p: &Plan,
st: &mut State,
r: RuleId,
t: &Table,
a: &Atom,
rw: &Rows,
mut pairs: Pairs,
negd: &mut [bool],
ix: &mut Indexes,
) -> Result<Pairs> {
let rule = p.rule_at(r);
for (i, n) in rule.negated.iter().enumerate() {
if negd[i] || pairs.left.is_empty() {
continue;
}
let src = |v: Var| match t.col_of(v) {
Some(c) => Some(Src::T(c)),
None => a.terms.iter().position(|&x| x == Term::Var(v)).map(Src::R),
};
if !n.vars().all(|v| src(v).is_some()) {
continue;
}
let mut vars: Vec<Var> = Vec::new();
for v in n.vars() {
if !vars.contains(&v) {
vars.push(v);
}
}
let srcs: Vec<Src> = vars.iter().map(|&v| src(v).expect("bound")).collect();
let (left, right) = (&pairs.left, &pairs.right);
let hits = self.neg_hits_by(
p,
st,
r,
i,
&vars,
left.len(),
|q, k| match srcs[q] {
Src::T(c) => t.cols[c][left[k] as usize],
Src::R(j) => rw.get(j, right[k] as usize),
Src::K(x) => x,
},
ix,
)?;
let at = kept_places(&self.par, hits.len(), |k| !hits[k]);
if at.len() < pairs.left.len() {
pairs = pairs.at(&self.par, &at);
}
negd[i] = true;
}
Ok(pairs)
}
}
/// The first row of each kind of `t` by the columns `key` (rising), when some row is a
/// repeat and the guard finds the pass worth it ([`first_of_kind`]).
fn first_rows(par: &Par, t: &Table, key: &[usize]) -> Option<Vec<u32>> {
first_of_kind(
par,
t.len,
true,
|i| hash_of(key.len(), |q| t.cols[key[q]][i]),
|i, j| key.iter().all(|&c| t.cols[c][i] == t.cols[c][j]),
)
}
/// A step of a rule body's join order: an atom read from facts, or an external asked.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Step {
Atom(usize),
Ext(usize),
}
/// The hidden variable of a table column holding body atom `i`'s row numbers (the rank of
/// a row when a rule's order changed and the why is kept).
fn rank_var(i: usize) -> Var {
Var(u32::MAX - i as u32)
}
/// Whether `v` is a hidden rank variable ([`rank_var`]).
fn is_rank(v: Var) -> bool {
v.0 > u32::MAX - 4096
}
/// The body atom whose row numbers rank variable `v` holds.
fn rank_atom(v: Var) -> usize {
(u32::MAX - v.0) as usize
}
/// The rank columns of `t`, in the order of their atoms in today's order (`tpos`).
fn rank_cols(t: &Table, tpos: &[usize]) -> Vec<usize> {
let mut cols: Vec<usize> = (0..t.vars.len()).filter(|&c| is_rank(t.vars[c])).collect();
cols.sort_by_key(|&c| tpos[rank_atom(t.vars[c])]);
cols
}
/// The columns of atom `a` that are constants or variables in `bound`, as a mask.
fn mask_of(a: &Atom, bound: &[Var]) -> u64 {
a.terms
.iter()
.enumerate()
.filter(|(_, term)| match term {
Term::Const(_) => true,
Term::Var(v) => bound.contains(v),
})
.fold(0u64, |m, (j, _)| m | 1 << j)
}
/// `t` with the rows that differ only in the variables `left` (and the rank columns) made
/// one, the least rank of each kind kept (the first row when there is no rank), when some
/// of `left` is not yet in `gone`; those are added to it.
The file goes on; the console shows all of it.