Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-plan/src/lib.rs

//! The plan between kleene's query clients and its engine.
//!
//! Clients (the Datalog rule builder in kleene-datalog, GQL text in kleene-gql) lower their
//! queries onto a [`Plan`]; the [`Engine`] runs it. Nothing here knows a query language.
//!
//! | Part | Here |
//! |---|---|
//! | Plan | [`Plan`]: relations by number ([`RelId`]) with their width and kind (input, external, derived), variables, rules ([`Rule`]: a join of positive atoms, filtered by conditions and negated atoms, projected to the head; or grouped and reduced by an [`Aggregate`]); a rule over its own relations recurses to a fixed point |
//! | Inputs | [`Inputs`]: facts in hand, Arrow columns (also in an id space: [`Source::ColumnsAt`], each column's base added only when a run reads it), columns of a DataFusion table, a two-column relation as a graph shared with no copy (also in an id space: [`Source::GraphAt`], rows and columns from bases, as a set's vertex types numbered one after the other; a graph of one type walks with its vertices numbered from its base, a procedure's vertices are ids), or an [`External`] (index lookups, Rust fact producers; [`Shifted`]: one over a type's own rows, handed as ids; [`IdRanges`]: the ids of an id space's types in some intervals, from the numbers alone, an `id(n)` lookup with no scan) |
//! | Catalog | [`Catalog`]: a set's schema (node labels, edge labels, properties of nodes and of edges with their types, id blocks, vertex tables, edge ends, the indexes that exist, refused properties), filled by kleene-gar where a set is opened or by hand; [`Catalog::relation`] gives a name's source and types (`L`, `E`, `L.k`, `E.k`), [`Plan::input_from`] declares an input by name, [`Inputs::bind`] gives every input the catalog names its source |
//! | Index choice | [`Index`] of an input ([`Inputs::index`], or from the catalog by [`Inputs::bind`]): a range index of a property, a name index of a string property, the id blocks of a label; [`Lookup::choose`] picks one for a variable's comparisons with constants (an id range, a name lookup, a range lookup with an equality preferred, a lookup per value of an OR of equalities), [`Choice::build`] the relation of the ids found, which leads the joins; the engine applies it to every rule ([`choose_indexes`], [`Engine::index_choice`]), dropping the label atom the found ids lie in, and asks an external atom of constants (a lookup written by hand) once in a relation of its own; it never changes an answer |
//! | Planner | [`plan`]: the derived relations cut into strata (strongly connected parts, dependencies first; negation and aggregates stratified); a one-column relation grown along a two-column one runs as a BFS on kleene-graph ([`Stratum::Reach`]), a two-column closure as masked products ([`Stratum::Closure`]), an (entry, vertex) relation grown along labelled edges whose labels hold the entry (`r(E, T) :- r(E, S), edge(S, T, L), has(L, E)`) as one entry-bitmask walk on kleene-graph ([`Stratum::LabelReach`]), the rest as column kernels ([`Stratum::Joins`]: hash joins on packed multi-column keys, range joins, anti-joins for negation, distinct rows by an open-addressing set, aggregates over sorted groups; large probes split over the parked workers of the engine's CPU device); a relation given by [`Plan::walk`] as frontier steps on kleene-graph ([`Stratum::Walk`]: the ends, or (start, end) pairs, of walks of bounded length), a relation given by [`Plan::shortest`] as one BFS per start ([`Stratum::Walk`] with `shortest`: (start, end, path, position, vertex) rows of the shortest paths, one per pair or all), a relation given by [`Plan::procedure`] as one kleene-graph kernel ([`Stratum::Procedure`]: PageRank, weak and strong components, single-source shortest paths, betweenness, triangles, harmonic centrality, the k-truss, every edge's truss number, a maximal independent set, a minimum spanning forest, a maximum flow), a group of [`Plan::rounds`] as inflationary rounds ([`Stratum::Rounds`]: count and negation inside recursion, each round reading the round before's facts of the parts after it, until a round changes nothing) |
//! | Split | [`Engine::split`]: the graph strata over the parts of their graph cut by a `kleene_graph::SplitKey`, local-first rounds; [`Stratum::splittable`] marks what splits (reach, closure, weak components, shortest paths, joins that do not recurse); a plan with a stratum that does not is refused ([`PlanError::NotSplittable`]) and runs on one machine; without a key every stratum runs as one part, the same code |
//! | Engine | [`Engine`]: runs the strata, semi-naive (each round joins only the facts the round before found, a range of each relation's arrival order); relations are columns, Arrow buffers used in place |
//! | Values | [`Value`] = `u64`; a [`Column`] keeps `u32` storage while its values fit and widens, never cuts; graph strata take `u32` vertex ids and refuse larger ones |
//! | Types | a relation's columns may have a [`Type`] ([`Plan::input_typed`], [`Plan::derived_typed`]): `u64`, `i64`, `f64`, `bool`, `str`, each with nulls but `u64`; a typed cell is still a `u64` inside every kernel, an order-preserving code (strings: ids in a per-run [`Dict`] sorted by the strings), so comparisons, joins, sorts and aggregates are the type's own; rules are typed when added (two types for one variable or one comparison refused); a comparison or join with null is not true; [`Output::arrow`] gives Arrow arrays of the column types, [`Output::render`] typed proofs |
//! | Output | [`Order`]: the output operator on a relation, keys ([`OrderKey`]: a column rising or falling, its nulls first or last ([`Nulls`]), null where a flag column is 0), an offset and a limit; [`Output::ordered`] gives a relation's rows through it (a counted relation's bag one row per match), ties broken by the whole row; with no key reading stops once the offset and limit are taken; [`Order::apply`] orders rows in hand |
//! | Several aggregates | [`Aggregate::many`] ([`Agg::Many`]): counts, sums, means, least and greatest values ([`Reduce`], [`ReduceOp`]) of one group in one pass, each skipping its nulls; a group with no value gets count 0 and null for the others (a `has` flag 0); a count without a variable takes each binding whole; [`Aggregate::times`] weighs the bindings of counted atoms |
//! | A number for each set | [`Plan::sets`] declares a table of sets `(n, element..)`; [`Aggregate::set_number`] ([`Agg::SetNumber`]) gives each group of a rule's bindings the number of its set of distinct elements, equal sets one number across rules and heads; the sets new at a moment numbered in rising order of their sorted members, so the same facts give the same numbers on every run and at every thread count; plain use runs as one stratum ([`Stratum::Sets`]), recursion through the table as a group of [`Plan::rounds`] whose kept numbered heads compute only the groups that gained a row; over the table's limit the run stops ([`PlanError::SetLimit`]); proofs [`How::Numbered`] (the group's members and the number) and [`How::Set`] (the fact that first gave the set) |
//! | A state machine | [`Plan::state_machine`]: the subset construction of a graph with labels (`edge(from, label, to)`, edges without a label `eps(from, to)`, start nodes by key) as relations and rules added to the plan, set numbers in a group of rounds: `{name}.member(state, node)` (the table of sets), `{name}.step(state, label, next)`, `{name}.start(key, state)`, `{name}.state(state)`; no code of its own, so every row has its proof |
//! | The position in an order | [`Aggregate::rank`] ([`Agg::Rank`]): each binding's key gets the number of distinct keys of its group before it, from 0 (one sort per run); its proof is its own binding and the group's number of keys |
//! | Edge tests of a walk | [`Plan::edge_filter`]: the edges that pass every [`EdgeTest`] (an AND of property comparisons held, or false), a relation a walk then takes (GQL's `all` / `none` over a path's edges) |
//! | Whole values | [`Engine::read_entities`]: every property of some nodes ([`NodeAsk`]) and edges ([`EdgeAsk`]) and which labels hold them, by one plan over the ids asked alone ([`Entities`]; an edge property of several edges between one pair the least) |
//! | Null marks, union | [`NullMark`]: where an optional part's flag column is 0 its columns are null; [`Marked::pick`] gives rows with their null cells ([`OrderKey::null_by`] orders by them), [`Marked::append`] is `UNION ALL`, [`Marked::distinct`] `UNION` with a null kept apart from every value |
//! | Rows as input | [`Inputs::datums`]: typed rows (another run's answer) as an input relation, counted or not: a stage feeding the next |
//! | Why | [`Engine::explain`] keeps how each fact was derived (for joined facts as columns: the rule and the values of its variables, one derivation row per fact appended by batch, a head variable's value read from the fact); a rule's bindings are made one once a variable is no longer needed ([`StratumReport::peak_rows`], [`StratumReport::proof_rows`] count what a stratum carried and wrote); [`Output::why`] gives a [`Proof`] down to input facts; [`Proof::render`] prints it in the plan's rule notation; a fact of a stratum of rounds names its round ([`Proof::round`]) |
//! | Computed values | [`Compute`] (`O = LO + I`, `T = INFO & 0xF`): a body literal that binds a variable to an [`Expr`] over bound values ([`BinOp`]: `+ - * / % & | ^ << >>`, [`UnOp`]: `-` and `!`, Rust's precedence), or tests it where it is bound; [`Test`]: a comparison or range with an expression on a side (`F & 4 != 0`), a compute of each such side plus a [`Cond`]. The value takes its variable's type (the column it is bound to, else the operands'); integers computed exactly over signed and unsigned operands, a value that does not fit an unsigned variable (below 0, over 64 bits, a division by 0, a shift of 64 or more) or a null operand gives no row, a signed one null; run as a step of the join as soon as its operands are bound, on the device's workers; a proof shows each computed value with its operands. Strings made by a rule ([`Func`]: `concat`, `substr`, `len`, counting characters from 0): a made string the run's dictionary lacks is added after its sorted strings, sorted by bytes per step, so a made string equal to one read has its id and joins its column; ordered tests and the output order of made strings go by their bytes; `concat` inside a recursion is refused |
//! | Counts | a counted relation ([`Plan::derived_counted`], [`Plan::input_counted`]) carries a count per row as its last column, a bag kept one row per distinct tuple: a counting rule ([`Plan::count_rule`]) gives each head row the number of the body's distinct bindings that give it, each weighed by the product of its counted atoms' counts (a join multiplies, a projection sums, rules of one relation add up); an ordinary rule reads it as any relation, so without its count it is the distinct rows; [`Plan::walk_counted`] counts the walks of bounded length per (start, end) or per end, one plus-times step per edge ([`kleene_graph::walk_counts`]); [`Output::expand`] is the one place a count becomes rows. Every plan without counted relations runs as before |
//! | Continue | [`Engine::continue_from`]: a run of the same plan on inputs that gained rows, continued from an earlier run's output (the rows each input gained named in `added`; an input not named compared with the one read before): a stratum nothing of whose reads changed is kept; joins and recursion continue as the engine's own semi-naive rounds started from the gained rows, a count adds the counts of its new bindings (an explaining engine's counted relation counts again: its proofs keep each counting rule's rows), a reach searches on from its new frontier (never into a vertex reached before), a closure grows by rounds; a stratum that negates or aggregates over a relation that changed, or is a walk, a procedure, a labelled reach or rounds, runs again; [`Engine::continue_with`] takes the rows inputs lost too (`removed`): joins and recursions of joins reading a relation that lost rows delete what derives from them and derive again what still has a proof, then go on by rounds; a count takes off the counts of the bindings lost; a reach or a closure that reads one runs again; the facts and proofs equal a run from scratch ([`StratumReport::continued`] says which strata did not run again) |
//! | Trace | [`Trace`]: new facts per round; [`Report`]: times per stratum |
//!
//! A typed client checks widths at compile time; [`Plan::rule`] checks them again when a
//! rule is added, and a run checks each input's width when it starts.

mod catalog;
mod cols;
mod compute;
mod entities;
mod error;
mod eval;
mod external;
mod facts;
mod ids;
mod index;
mod machine;
mod next;
mod order;
mod plan;
mod resolve;
mod rules;
mod side;
mod typed;
mod why;

pub use catalog::{Catalog, NameIndex, Schema};
pub use compute::{BinOp, Compute, Expr, Func, Test, UnOp};
pub use entities::{EdgeAsk, Entities, NodeAsk};
pub use error::PlanError;
pub use eval::{Engine, NoTrace, Output, Report, StratumReport, Trace};
pub use external::{External, IdRanges, IdShift, NameHits, Producer, Shifted};
pub use facts::{Column, Facts, Inputs, Source};
pub use index::{Bound, Choice, Chosen, Index, Key, Lookup, On, choose_indexes};
pub use machine::{Machine, MachineGraph};
pub use order::{Marked, NullMark, Nulls, Order, OrderKey};
pub use plan::{Side, Stratum, Way, plan};
pub use rules::{
    Agg, Aggregate, Atom, Call, Cmp, Cond, Constant, DEFAULT_SET_LIMIT, EdgeTest, Fold, FoldOp,
    HARMONIC_EXACT_MAX, HarmonicMode, Hops, List, ListId, ListMember, Literal, MIS_DEFAULT_SEED,
    Part, Plan, ProcArg, Procedure, Reduce, ReduceOp, RelId, RelInfo, RelKind, Rows, Rule, RuleId,
    SHORTEST_PATHS_LIMIT, Shortest, Term, TextOp, Value, Var, Walk, instantiate,
};
pub use typed::{Datum, Dict, NULL, Type, time_value};
pub use why::{How, Member, Proof};

/// The result of a fallible operation of this crate.
pub type Result<T> = std::result::Result<T, PlanError>;

/// The README's example, run as a doctest.
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
struct ReadmeDoctests;