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

nordisk/kleene

crates/kleene-datalog/src/engine.rs

use std::sync::Arc;

use arrow_array::ArrayRef;
use datafusion::catalog::TableProvider;
use datafusion::prelude::SessionContext;
use kleene_graph::GraphBackend;
use kleene_plan::{
    Catalog, Datum, Dict, Facts, Index, Order, Proof, RelId, Report, Source, Trace, Value,
};
use kleene_sparse::{Csr, SparseBackend};

use crate::program::{Program, Rel};
use crate::{DatalogError, External, Result};

/// The inputs of a run: a source per input relation, each checked against its relation's
/// arity when given.
#[derive(Clone, Debug, Default)]
pub struct Inputs {
    inner: kleene_plan::Inputs,
}

impl Inputs {
    /// No inputs yet.
    pub fn new() -> Self {
        Inputs::default()
    }

    /// Give `rel` its facts.
    pub fn facts<const N: usize>(&mut self, rel: &Rel<N>, facts: Facts) -> Result<&mut Self> {
        if facts.arity() != N {
            return Err(DatalogError::Input(format!(
                "{} columns of facts for a relation of {N}",
                facts.arity()
            )));
        }
        self.inner.facts(rel.id(), facts);
        Ok(self)
    }

    /// Give `rel`, a relation of no column (a flag), its one fact when `holds`, else none
    /// ([`kleene_plan::Inputs::flag`]).
    pub fn flag(&mut self, rel: &Rel<0>, holds: bool) -> &mut Self {
        self.inner.flag(rel.id(), holds);
        self
    }

    /// Read `rel` from Arrow columns in hand (any integer type up to 64 bits, kept whole).
    pub fn columns<const N: usize>(&mut self, rel: &Rel<N>, columns: [ArrayRef; N]) -> &mut Self {
        self.inner.columns(rel.id(), columns.to_vec());
        self
    }

    /// Read `rel` from `columns` of a DataFusion table.
    pub fn table<const N: usize>(
        &mut self,
        rel: &Rel<N>,
        table: Arc<dyn TableProvider>,
        columns: [&str; N],
    ) -> &mut Self {
        self.inner.table(
            rel.id(),
            table,
            columns.iter().map(|c| c.to_string()).collect(),
        );
        self
    }

    /// Give a two-column `rel` as a graph (and its transpose, if stored).
    pub fn graph(&mut self, rel: &Rel<2>, out: Csr<u8>, inn: Option<Csr<u8>>) -> &mut Self {
        self.inner.graph(rel.id(), out, inn);
        self
    }

    /// Let `ext` answer `rel` (an external relation, or an input listed whole).
    pub fn external<const N: usize>(
        &mut self,
        rel: &Rel<N>,
        ext: Arc<dyn External>,
    ) -> Result<&mut Self> {
        if ext.arity() != N {
            return Err(DatalogError::Input(format!(
                "an external of {} columns for a relation of {N}",
                ext.arity()
            )));
        }
        self.inner.external(rel.id(), ext);
        Ok(self)
    }

    /// Give every input relation of `program` that has no source yet and whose name
    /// `catalog` has its source and its index ([`kleene_plan::Inputs::bind`]); the
    /// relation's column types must be the catalog's. Inputs the catalog does not name are
    /// left as they are.
    pub fn bind(&mut self, program: &Program, catalog: &Catalog) -> Result<&mut Self> {
        self.inner.bind(program, catalog)?;
        Ok(self)
    }

    /// Give input `rel` typed rows, such as another run's ([`Output::datums`],
    /// [`Output::ordered`]): a stage feeding the next ([`kleene_plan::Inputs::datums`]). A
    /// counted input gets each distinct row once with its number of times.
    pub fn datums<const N: usize>(
        &mut self,
        program: &Program,
        rel: &Rel<N>,
        rows: &[Vec<Datum>],
    ) -> Result<&mut Self> {
        let types = program.types(rel.id());
        let counted = program.is_counted(rel.id());
        let types = if counted {
            &types[..types.len() - 1]
        } else {
            &types[..]
        };
        if let Some(r) = rows.iter().find(|r| r.len() != types.len()) {
            return Err(DatalogError::Input(format!(
                "a row of {} values for a relation of {} columns",
                r.len(),
                types.len()
            )));
        }
        self.inner.datums(rel.id(), types, rows, counted)?;
        Ok(self)
    }

    /// The source of a relation.
    pub fn source(&self, rel: RelId) -> Option<&Source> {
        self.inner.source(rel)
    }

    /// Give input relation `rel` an index for the engine's index choice
    /// ([`Engine::index_choice`]): a rule's comparisons of its values with constants find
    /// their ids by the index.
    pub fn index<const N: usize>(&mut self, rel: &Rel<N>, index: Index) -> &mut Self {
        self.inner.index(rel.id(), index);
        self
    }
}

/// The facts a run derived, and how it went.
#[derive(Clone, Debug)]
pub struct Output {
    inner: kleene_plan::Output,
    /// How the run went.
    pub report: Report,
}

impl Output {
    /// The facts of a derived relation.
    pub fn get<const N: usize>(&self, rel: &Rel<N>) -> Option<&Facts> {
        self.inner.get(rel.id())
    }

    /// Whether `rel`, a derived relation of no column (a flag), holds
    /// ([`kleene_plan::Output::holds`]).
    pub fn holds(&self, rel: &Rel<0>) -> bool {
        self.inner.holds(rel.id())
    }

    /// The rows of a counted relation as the bag they stand for, each without its count
    /// repeated its count's times ([`kleene_plan::Output::expand`]); refused past `limit`
    /// rows.
    pub fn expand<const N: usize>(
        &self,
        p: &Program,
        rel: &Rel<N>,
        limit: Option<u64>,
    ) -> Result<Vec<Vec<Value>>> {
        self.inner.expand(p, rel.id(), limit)
    }

    /// The facts of a derived relation, by number.
    pub fn get_id(&self, rel: RelId) -> Option<&Facts> {
        self.inner.get(rel)
    }

    /// Why `rel(tuple)` holds: a proof down to input facts, when the run was explained
    /// ([`Engine::explain`]) and derived it. `p` is the program that ran.
    pub fn why<const N: usize, V: Copy + Into<Value>>(
        &self,
        p: &Program,
        rel: &Rel<N>,
        tuple: [V; N],
    ) -> Option<Proof> {
        let t: Vec<Value> = tuple.iter().map(|&v| v.into()).collect();
        self.why_id(p, rel.id(), &t)
    }

    /// [`Output::why`] by relation number.
    pub fn why_id(&self, p: &Program, rel: RelId, tuple: &[Value]) -> Option<Proof> {
        self.inner.why(p, rel, tuple)
    }

    /// The facts of a derived relation as Arrow arrays of its column types
    /// ([`kleene_plan::Output::arrow`]): `Utf8`, `Int64`, `Float64`, `Boolean` with nulls,
    /// `UInt32`/`UInt64` as stored for [`kleene_plan::Type::U64`].
    pub fn arrow<const N: usize>(
        &self,
        p: &Program,
        rel: &Rel<N>,
    ) -> Option<Result<[ArrayRef; N]>> {
        Some(self.inner.arrow(p, rel.id())?.map(|v| {
            v.try_into()
                .unwrap_or_else(|_| unreachable!("one array per column"))
        }))
    }

    /// The facts of a derived relation as typed values, row by row.
    pub fn datums<const N: usize>(&self, p: &Program, rel: &Rel<N>) -> Option<Vec<[Datum; N]>> {
        Some(
            self.inner
                .datums(p, rel.id())?
                .into_iter()
                .map(|r| {
                    r.try_into()
                        .unwrap_or_else(|_| unreachable!("one value per column"))
                })
                .collect(),
        )
    }

    /// Why `rel(tuple)` holds, the fact given as typed values (strings by text).
    pub fn why_of<const N: usize>(
        &self,
        p: &Program,
        rel: &Rel<N>,
        tuple: [Datum; N],
    ) -> Option<Proof> {
        self.inner.why_of(p, rel.id(), &tuple)
    }

    /// A proof as an indented tree with every value printed by its type (strings from the
    /// run's dictionary).
    pub fn render(&self, p: &Program, proof: &Proof) -> String {
        self.inner.render(p, proof)
    }

    /// The rows of `rel` through the output operator `order` ([`kleene_plan::Output::ordered`]:
    /// keys rising or falling with their nulls first or last, an offset, a limit), each value
    /// by its type; a counted relation's rows without the count, each its count's times.
    pub fn ordered<const N: usize>(
        &self,
        p: &Program,
        rel: &Rel<N>,
        order: &Order,
    ) -> Result<Vec<Vec<Datum>>> {
        let rows = self
            .inner
            .ordered(p, rel.id(), kleene_plan::Rows::Bag, order)?;
        let types = p.types(rel.id());
        Ok(rows
            .into_iter()
            .map(|r| {
                r.into_iter()
                    .zip(&types)
                    .map(|(v, t)| t.decode(v, self.inner.dict()))
                    .collect()
            })
            .collect())
    }

    /// The run's strings, when the program has a string column or constant.
    pub fn dict(&self) -> Option<&Dict> {
        self.inner.dict()
    }
}

/// Runs programs on [`kleene_plan::Engine`]: recursive two-column shapes on a sparse
/// backend, the rest as column kernels (hash joins on packed keys, anti-joins, sorted
/// groups).
pub struct Engine<B: SparseBackend> {
    inner: kleene_plan::Engine<B>,
}

impl<B: SparseBackend> std::fmt::Debug for Engine<B> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.inner.fmt(f)
    }
}

impl<B: GraphBackend> Engine<B> {
    /// An engine on `device`; its DataFusion session is made the first time a join or a
    /// table input needs it.
    pub fn new(device: B::Device) -> Self {
        Engine {
            inner: kleene_plan::Engine::new(device),
        }
    }

    /// An engine on `device` that joins in `ctx`.
    pub fn with_context(device: B::Device, ctx: SessionContext) -> Self {
        Engine {
            inner: kleene_plan::Engine::with_context(device, ctx),
        }
    }

    /// Every property of some nodes and edges, and which labels hold them, read for the ids
    /// asked alone ([`kleene_plan::Engine::read_entities`]): the facts of a few returned
    /// values whole.
    pub async fn read_entities(
        &self,
        nodes: &[kleene_plan::NodeAsk],
        edges: &[kleene_plan::EdgeAsk],
    ) -> Result<kleene_plan::Entities> {
        self.inner.read_entities(nodes, edges).await
    }

    /// Keep the why of every derived fact ([`Output::why`]): the first derivation of each
    /// joined fact, the BFS levels of a reach, the operands of a closure (their proofs are
    /// walked back when asked).
    pub fn explain(self, on: bool) -> Self {
        Engine {
            inner: self.inner.explain(on),
        }
    }

    /// Whether a run applies the index choice ([`kleene_plan::Engine::index_choice`], on by
    /// default): a rule that filters an input with an index (given by [`Inputs::index`] or
    /// from a catalog by [`Inputs::bind`]) by constants finds its ids by a lookup of the
    /// index, with no index atom written; off, the rules run as written.
    pub fn index_choice(self, on: bool) -> Self {
        Engine {
            inner: self.inner.index_choice(on),
        }
    }

    /// Whether a join step runs a value between two ends from the other side as a sort and
    /// a search ([`kleene_plan::Engine::range_joins`], on by default): `A in LO..HI` beside
    /// equal keys, or `LO <= A, A < HI`; off, as a hash join or a cross product cut by the
    /// conditions. The answers and the proofs are the same either way.
    pub fn range_joins(self, on: bool) -> Self {
        Engine {
            inner: self.inner.range_joins(on),
        }
    }

    /// Whether an aggregate of the next row by a key (`next(A, B) :- min(B) by (A):
    /// bound(A), bound(B), A < B.`, `max` with `>`, more keys in `by (...)`) runs as a sort
    /// and one search per row ([`kleene_plan::Engine::next_rows`], on by default); off, as
    /// a cross product reduced per group. The answers and the proofs are the same either
    /// way.
    pub fn next_rows(self, on: bool) -> Self {
        Engine {
            inner: self.inner.next_rows(on),
        }
    }

    /// Whether a run reads a rule's atoms over columns side by side in one scan
    /// ([`kleene_plan::Engine::side_by_side`], on by default): columns of one vertex type read
    /// by name (`t.a(I, A), t.b(I, B)`) are one scan instead of a join per column, with the
    /// same answers and proofs; off, the rules run as written.
    pub fn side_by_side(self, on: bool) -> Self {
        Engine {
            inner: self.inner.side_by_side(on),
        }
    }

    /// The DataFusion session.
    pub fn context(&self) -> &SessionContext {
        self.inner.context()
    }

    /// Run `p` on `inputs`.
    pub async fn run(&self, p: &Program, inputs: &Inputs) -> Result<Output> {
        self.run_traced(p, inputs, &mut kleene_plan::NoTrace).await
    }

    /// Run `p` on `inputs`, telling `trace` as it goes.
    pub async fn run_traced(
        &self,
        p: &Program,
        inputs: &Inputs,
        trace: &mut dyn Trace,
    ) -> Result<Output> {
        let mut inner = self.inner.run_traced(p, &inputs.inner, trace).await?;
        let report = std::mem::take(&mut inner.report);
        Ok(Output { inner, report })
    }

    /// Run `p` on `inputs`, continuing from `prev` (an output of `p` on earlier inputs):
    /// `added` holds exactly the rows each input gained, `inputs` the old rows and these
    /// ([`kleene_plan::Engine::continue_from`]: the same facts and proofs as a run from
    /// scratch, each stratum kept, continued from the new rows, or computed again).
    pub async fn continue_from(
        &self,
        p: &Program,
        prev: &Output,
        inputs: &Inputs,
        added: &Inputs,
    ) -> Result<Output> {
        let mut inner = self
            .inner
            .continue_from(p, &prev.inner, &inputs.inner, &added.inner)
            .await?;
        let report = std::mem::take(&mut inner.report);
        Ok(Output { inner, report })
    }

    /// [`Engine::continue_from`] on inputs that also lost rows: `removed` holds exactly the
    /// rows each input lost, `inputs` the old rows without these and with those of `added`
    /// ([`kleene_plan::Engine::continue_with`]).
    pub async fn continue_with(
        &self,
        p: &Program,
        prev: &Output,
        inputs: &Inputs,
        added: &Inputs,
        removed: &Inputs,
    ) -> Result<Output> {
        let mut inner = self
            .inner
            .continue_with(p, &prev.inner, &inputs.inner, &added.inner, &removed.inner)
            .await?;
        let report = std::mem::take(&mut inner.report);
        Ok(Output { inner, report })
    }
}