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

nordisk/kleene

crates/kleene-index/src/relations.rs

//! The indexes as relations of rules ([`External`]): a kleene-plan input whose lookups the
//! index answers, for kleene-datalog rules and for the GQL catalog's indexes alike.
//!
//! | Relation | Index | Columns | Answers when bound |
//! |---|---|---|---|
//! | [`AddrRel`] | [`AddrColumn`] (static search tree) | `(addr, row)` | `addr` (the batch descends 32 lanes at a time) |
//! | [`ReachRel`] | [`Reach`] (condensation + 2-hop labels) | `(a, b)`: a path leads from a to b | both |
//! | [`ReverseReachRel`] | [`ReverseReach`] (a bitset per target set) | `(v, s)`: v reaches set s | `s` (lists who), `v` (lists sets), both |
//! | [`NestRel`] | [`Nesting`] (pre/post numbers) | `(a, b)`: a lies inside b | both |
//! | [`IntervalRel`] | [`Intervals`] (static interval tree) | `(x, id)`: range id holds x | `x` |
//! | [`GroupRel`] | [`Groups`] (sorted 128-bit keys) | `(hi, lo, id)`: id filed under (hi, lo) | `hi` and `lo` |
//! | [`ParentRel`] | [`ParentTree`] (BFS parents from a root) | `(v, p)`: p is v's parent | `v` |
//! | [`LazyReachRel`] (kleene-plan) | [`Reach`], built at the first lookup | `(a, b)`: a path leads from a to b | both |
//! | [`NameRowsRel`] (kleene-gql's name index) | [`Names`] (a minimal perfect hash), then each name's rows | the name |
//! | [`KindsRel`] (kleene-plan) | [`Kinds`] (a bitmap per kind), built at the first lookup | `(kind, id)`: id has that kind | `kind` |
//! | [`RangeRel`] (kleene-plan) | (value, id) pairs sorted, built at the first lookup | `(lo, hi, id)`: id's value lies in `lo..=hi` | `lo` and `hi` |
//!
//! Vertex and row ids are `u32`; a value over `u32` (or past the index) names no vertex,
//! so it simply has no row. Lookups allocate per batch, never per key.

use kleene_plan::{External, PlanError, Result, Value};

use crate::{
    AddrColumn, Groups, Intervals, Kinds, Names, Nesting, ParentTree, Reach, ReverseReach,
};

/// A key as a vertex id below `n`, if it is one.
#[inline]
fn id(v: Value, n: usize) -> Option<u32> {
    u32::try_from(v).ok().filter(|&x| (x as usize) < n)
}

fn index_err(e: impl std::fmt::Display) -> PlanError {
    PlanError::Input(format!("index: {e}"))
}

/// Which row of an address column an address picks.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AddrMode {
    /// The row whose range `start..end` holds the address (the floor, checked against its
    /// end; a column without ends answers as `Floor`).
    Covering,
    /// The row of the last start at or below the address.
    Floor,
    /// The row whose start is the address.
    Exact,
}

/// `(addr, row)`: address to function, block, line or scope row, on the static search
/// tree. Answers when `addr` is bound (and checks `row` when that is bound too).
#[derive(Clone, Debug)]
pub struct AddrRel {
    col: AddrColumn,
    mode: AddrMode,
}

impl AddrRel {
    /// Lookups of `mode` on `col`.
    pub fn new(col: AddrColumn, mode: AddrMode) -> Self {
        AddrRel { col, mode }
    }
}

impl External for AddrRel {
    fn arity(&self) -> usize {
        2
    }

    fn can(&self, bound: u64) -> bool {
        bound & 1 != 0
    }

    fn lookup(
        &self,
        bound: u64,
        keys: &[&[Value]],
        n: usize,
        out: &mut dyn FnMut(usize, &[Value]),
    ) -> Result<()> {
        let lk = self.col.lookup().map_err(index_err)?;
        let addrs = keys[0];
        let mut rows = vec![None; n];
        match self.mode {
            AddrMode::Covering => lk.covering_batch(addrs, &mut rows),
            AddrMode::Floor => lk.floor_batch(addrs, &mut rows),
            AddrMode::Exact => {
                for (r, &a) in rows.iter_mut().zip(addrs) {
                    *r = lk.exact(a);
                }
            }
        }
        for (k, r) in rows.iter().enumerate() {
            if let Some(r) = *r
                && (bound & 2 == 0 || keys[1][k] == r as Value)
            {
                out(k, &[addrs[k], r as Value]);
            }
        }
        Ok(())
    }
}

/// `(a, b)`: a path leads from `a` to `b` (every vertex reaches itself). Answers with
/// both bound.
#[derive(Clone, Debug)]
pub struct ReachRel(pub Reach);

impl External for ReachRel {
    fn arity(&self) -> usize {
        2
    }

    fn can(&self, bound: u64) -> bool {
        bound == 0b11
    }

    fn lookup(
        &self,
        _bound: u64,
        keys: &[&[Value]],
        n: usize,
        out: &mut dyn FnMut(usize, &[Value]),
    ) -> Result<()> {
        let vs = self.0.vertices();
        for (k, (&a, &b)) in keys[0].iter().zip(keys[1]).enumerate().take(n) {
            if let (Some(x), Some(y)) = (id(a, vs), id(b, vs))
                && self.0.reaches(x, y)
            {
                out(k, &[a, b]);
            }
        }
        Ok(())
    }
}

/// `(v, s)`: vertex `v` reaches target set `s`. Answers with `s` bound (the vertices, rising),
/// `v` bound (the sets, rising) or both.
#[derive(Clone, Debug)]
pub struct ReverseReachRel(pub ReverseReach);

impl External for ReverseReachRel {
    fn arity(&self) -> usize {
        2
    }

    fn can(&self, bound: u64) -> bool {
        bound != 0
    }

    fn lookup(
        &self,
        bound: u64,
        keys: &[&[Value]],
        n: usize,
        out: &mut dyn FnMut(usize, &[Value]),
    ) -> Result<()> {
        let (vs, sets) = (self.0.vertices(), self.0.sets());
        match bound {
            0b11 => {
                for (k, (&v, &s)) in keys[0].iter().zip(keys[1]).enumerate().take(n) {
                    if let (Some(x), Some(t)) = (id(v, vs), id(s, sets))
                        && self.0.reaches(x, t as usize)
                    {
                        out(k, &[v, s]);
                    }
                }
            }
            0b10 => {
                for (k, &s) in keys[1].iter().enumerate().take(n) {
                    if let Some(t) = id(s, sets) {
                        for v in self.0.who(t as usize) {
                            out(k, &[v as Value, s]);
                        }
                    }
                }
            }
            _ => {
                for (k, &v) in keys[0].iter().enumerate().take(n) {
                    if let Some(x) = id(v, vs) {
                        for t in 0..sets {
                            if self.0.reaches(x, t) {
                                out(k, &[v, t as Value]);
                            }
                        }
                    }
                }
            }
        }
        Ok(())
    }
}

/// `(a, b)`: `a` lies inside `b` in a tree (`b` is `a` or an ancestor). Answers with both
/// bound.
#[derive(Clone, Debug)]
pub struct NestRel(pub Nesting);

impl External for NestRel {
    fn arity(&self) -> usize {
        2
    }

    fn can(&self, bound: u64) -> bool {
        bound == 0b11
    }

    fn lookup(
        &self,
        _bound: u64,
        keys: &[&[Value]],
        n: usize,
        out: &mut dyn FnMut(usize, &[Value]),
    ) -> Result<()> {
        let nodes = self.0.words().len();
        for (k, (&a, &b)) in keys[0].iter().zip(keys[1]).enumerate().take(n) {
            if let (Some(x), Some(y)) = (id(a, nodes), id(b, nodes))
                && self.0.inside(x, y)
            {
                out(k, &[a, b]);
            }
        }
        Ok(())
    }
}

/// `(x, id)`: range `id` holds `x`. Answers with `x` bound (every covering range; `id`
/// checked when bound too).
#[derive(Clone, Debug)]
pub struct IntervalRel(pub Intervals);

impl External for IntervalRel {
    fn arity(&self) -> usize {
        2
    }

    fn can(&self, bound: u64) -> bool {
        bound & 1 != 0
    }

    fn lookup(
        &self,
        bound: u64,
        keys: &[&[Value]],
        n: usize,
        out: &mut dyn FnMut(usize, &[Value]),
    ) -> Result<()> {
        for (k, &x) in keys[0].iter().enumerate().take(n) {
            self.0.stab(x, |r| {
                if bound & 2 == 0 || keys[1][k] == r as Value {
                    out(k, &[x, r as Value]);
                }
            });
        }
        Ok(())
    }
}

/// `(hi, lo, id)`: `id` is filed under the 128-bit key `(hi, lo)`. Answers with `hi` and
/// `lo` bound.
#[derive(Clone, Debug)]
pub struct GroupRel(pub Groups);

impl External for GroupRel {
    fn arity(&self) -> usize {
        3
    }

    fn can(&self, bound: u64) -> bool {
        bound & 0b11 == 0b11
    }

    fn lookup(
        &self,
        bound: u64,
        keys: &[&[Value]],
        n: usize,
        out: &mut dyn FnMut(usize, &[Value]),
    ) -> Result<()> {
        for (k, (&hi, &lo)) in keys[0].iter().zip(keys[1]).enumerate().take(n) {
            for &i in self.0.get(hi, lo) {
                if bound & 0b100 == 0 || keys[2][k] == i as Value {
                    out(k, &[hi, lo, i as Value]);
                }
            }
        }
        Ok(())
    }
}

/// `(v, p)`: `p` is `v`'s parent on a fewest-edges path from the tree's root (the root's
/// parent is the root). Answers with `v` bound.
#[derive(Clone, Debug)]
pub struct ParentRel(pub ParentTree);

impl External for ParentRel {
    fn arity(&self) -> usize {
        2
    }

    fn can(&self, bound: u64) -> bool {
        bound & 1 != 0
    }

    fn lookup(
        &self,
        bound: u64,
        keys: &[&[Value]],
        n: usize,
        out: &mut dyn FnMut(usize, &[Value]),
    ) -> Result<()> {
        let vs = self.0.parents().len();
        for (k, &v) in keys[0].iter().enumerate().take(n) {
            if let Some(x) = id(v, vs)
                && let Some(p) = self.0.parent(x)
                && (bound & 2 == 0 || keys[1][k] == p as Value)
            {
                out(k, &[v, p as Value]);
            }
        }
        Ok(())
    }
}

/// [`ReachRel`] for kleene-plan (a GQL reach index, kleene-gql's `Catalog::reach_index`):
/// `(a, b)` when a path of zero or more edges leads from `a` to `b`, answered with both
/// bound. The index is built from the by-source offsets and neighbours at the first lookup
/// (a query that never asks builds nothing), then kept.
pub struct LazyReachRel {
    offsets: arrow_buffer::ScalarBuffer<u64>,
    neighbours: arrow_buffer::ScalarBuffer<u32>,
    reach: std::sync::OnceLock<std::result::Result<Reach, String>>,
}

impl LazyReachRel {
    /// The reach index of the graph with by-source `offsets` (vertices + 1) and
    /// `neighbours`.
    pub fn new(
        offsets: arrow_buffer::ScalarBuffer<u64>,
        neighbours: arrow_buffer::ScalarBuffer<u32>,
    ) -> Self {
        LazyReachRel {
            offsets,
            neighbours,
            reach: std::sync::OnceLock::new(),
        }
    }

    /// The index, built the first time.
    pub fn reach(&self) -> kleene_plan::Result<&Reach> {
        self.reach
            .get_or_init(|| {
                Reach::build(&self.offsets, &self.neighbours).map_err(|e| e.to_string())
            })
            .as_ref()
            .map_err(|e| kleene_plan::PlanError::Input(format!("reach index: {e}")))
    }
}

impl std::fmt::Debug for LazyReachRel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "LazyReachRel({} vertices, built: {})",
            self.offsets.len().saturating_sub(1),
            self.reach.get().is_some()
        )
    }
}

impl kleene_plan::External for LazyReachRel {
    fn arity(&self) -> usize {
        2
    }

    fn can(&self, bound: u64) -> bool {
        bound == 0b11
    }

    fn lookup(
        &self,
        _bound: u64,
        keys: &[&[Value]],
        n: usize,
        out: &mut dyn FnMut(usize, &[Value]),
    ) -> kleene_plan::Result<()> {
        let r = self.reach()?;
        let vs = r.vertices();
        for (k, (&a, &b)) in keys[0].iter().zip(keys[1]).enumerate().take(n) {
            if let (Some(x), Some(y)) = (id(a, vs), id(b, vs))
                && r.reaches(x, y)
            {
                out(k, &[a, b]);
            }
        }
        Ok(())
    }
}

/// The (value, id) pairs of a [`RangeRel`], listed when it is built.
type Pairs = Box<dyn Fn() -> Vec<(Value, u32)> + Send + Sync>;

/// A range index of a property for kleene-plan (a GQL property index,
/// kleene-gql's `Catalog::property_index`): `(lo, hi, id)` for each id whose value lies in
/// `lo..=hi`, answered with `lo` and `hi` bound (two binary searches per key; the ids of a
/// range rising by value, then id). The pairs are listed and sorted at the first lookup,
/// then kept.
pub struct RangeRel {
    pairs: Pairs,
    sorted: std::sync::OnceLock<Vec<(Value, u32)>>,
}

impl RangeRel {
    /// The index of the (value, id) pairs `pairs` lists.
    pub fn new(pairs: impl Fn() -> Vec<(Value, u32)> + Send + Sync + 'static) -> Self {
        RangeRel {
            pairs: Box::new(pairs),
            sorted: std::sync::OnceLock::new(),
        }
    }

    /// The pairs sorted, built the first time.
    pub fn sorted(&self) -> &[(Value, u32)] {
        self.sorted.get_or_init(|| {
            let mut v = (self.pairs)();
            v.sort_unstable();
            v
        })
    }

    /// The pairs whose value lies in `lo..=hi`.
    pub fn range(&self, lo: Value, hi: Value) -> &[(Value, u32)] {
        let s = self.sorted();
        if lo > hi {
            return &[];
        }
        let a = s.partition_point(|p| p.0 < lo);
        let b = s.partition_point(|p| p.0 <= hi);
        &s[a..b]
    }
}

impl std::fmt::Debug for RangeRel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "RangeRel(built: {})", self.sorted.get().is_some())
    }
}

impl kleene_plan::External for RangeRel {
    fn arity(&self) -> usize {
        3
    }

    fn can(&self, bound: u64) -> bool {
        bound & 0b11 == 0b11
    }

    fn lookup(
        &self,
        bound: u64,
        keys: &[&[Value]],
        n: usize,
        out: &mut dyn FnMut(usize, &[Value]),
    ) -> kleene_plan::Result<()> {
        for (k, (&lo, &hi)) in keys[0].iter().zip(keys[1]).enumerate().take(n) {
            for &(_, i) in self.range(lo, hi) {
                if bound & 0b100 == 0 || keys[2][k] == i as Value {
                    out(k, &[lo, hi, i as Value]);
                }
            }
        }
        Ok(())
    }
}

/// Each string of a column, by row (`None` for a null or a column that is no string).
fn string_at(col: &arrow_array::ArrayRef, r: usize) -> Option<&str> {
    use arrow_array::Array;
    use arrow_array::cast::AsArray;
    use arrow_schema::DataType;
    if col.is_null(r) {
        return None;
    }
    match col.data_type() {
        DataType::Utf8 => Some(col.as_string::<i32>().value(r)),
        DataType::LargeUtf8 => Some(col.as_string::<i64>().value(r)),
        DataType::Utf8View => Some(col.as_string_view().value(r)),
        // bytes read as text: a value that is not UTF-8 has none
        DataType::Binary => std::str::from_utf8(col.as_binary::<i32>().value(r)).ok(),
        DataType::LargeBinary => std::str::from_utf8(col.as_binary::<i64>().value(r)).ok(),
        DataType::BinaryView => std::str::from_utf8(col.as_binary_view().value(r)).ok(),
        _ => None,
    }
}

/// A name's rows: kleene-index's [`Names`] (a minimal perfect hash: one hash and one compare
/// per name) over a string column, and for each name every row that holds it (the rows by
/// the name's number, rising). Built at the first lookup, then kept.
pub struct NameRowsRel {
    col: arrow_array::ArrayRef,
    built: std::sync::OnceLock<std::result::Result<NameRows, String>>,
}

/// The built parts of a [`NameRowsRel`].
struct NameRows {
    names: Names,
    /// Per name number, where its rows begin in `rows` (one more at the end).
    offsets: Vec<u32>,
    rows: Vec<u32>,
}

impl NameRowsRel {
    /// The name index of string column `col` (`Utf8`, `LargeUtf8` or `Utf8View`, or bytes
    /// read as text: `Binary`, `LargeBinary`, `BinaryView`), row `r` being node `r`.
    pub fn new(col: arrow_array::ArrayRef) -> Self {
        NameRowsRel {
            col,
            built: std::sync::OnceLock::new(),
        }
    }

    fn built(&self) -> kleene_plan::Result<&NameRows> {
        self.built
            .get_or_init(|| {
                let names = Names::build(&self.col).map_err(|e| e.to_string())?;
                let n = self.col.len();
                let mut count = vec![0u32; names.len() + 1];
                let slot: Vec<Option<usize>> = (0..n)
                    .map(|r| string_at(&self.col, r).map(|s| names.hash_of(s)))
                    .collect();
                for s in slot.iter().flatten() {
                    count[s + 1] += 1;
                }
                for i in 1..count.len() {
                    count[i] += count[i - 1];
                }
                let mut at = count.clone();
                let mut rows = vec![0u32; count[names.len()] as usize];
                for (r, s) in slot.iter().enumerate() {
                    if let Some(s) = *s {
                        rows[at[s] as usize] = r as u32;
                        at[s] += 1;
                    }
                }
                Ok(NameRows {
                    names,
                    offsets: count,
                    rows,
                })
            })
            .as_ref()
            .map_err(|e| kleene_plan::PlanError::Input(format!("name index: {e}")))
    }

    /// Every row holding `name`, rising (none for a name the column lacks).
    pub fn rows(&self, name: &str) -> kleene_plan::Result<&[u32]> {
        let b = self.built()?;
        if b.names.id(name).is_none() {
            return Ok(&[]);
        }
        let s = b.names.hash_of(name);
        Ok(&b.rows[b.offsets[s] as usize..b.offsets[s + 1] as usize])
    }
}

impl std::fmt::Debug for NameRowsRel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "NameRowsRel({} rows, built: {})",
            self.col.len(),
            self.built.get().is_some()
        )
    }
}

/// `(kind, id)` for each id of each kind, on kleene-index's [`Kinds`] (a bitmap per kind
/// value), answered with `kind` bound: the ids of a kind are its bitmap's set bits.
/// Built from the kind column at the first lookup, then kept.
pub struct KindsRel {
    kinds: Vec<u64>,
    built: std::sync::OnceLock<std::result::Result<Kinds, String>>,
}

impl KindsRel {
    /// The kinds index of `kinds` (vertex `v`'s kind at `kinds[v]`).
    pub fn new(kinds: Vec<u64>) -> Self {
        KindsRel {
            kinds,
            built: std::sync::OnceLock::new(),
        }
    }

    /// The bitmaps, built the first time.
    pub fn kinds(&self) -> kleene_plan::Result<&Kinds> {
        self.built
            .get_or_init(|| {
                Kinds::build(&self.kinds, crate::KINDS_MAX_BYTES).map_err(|e| e.to_string())
            })
            .as_ref()
            .map_err(|e| kleene_plan::PlanError::Input(format!("kinds index: {e}")))
    }
}

impl std::fmt::Debug for KindsRel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "KindsRel({} vertices, built: {})",
            self.kinds.len(),
            self.built.get().is_some()
        )
    }
}

impl kleene_plan::External for KindsRel {
    fn arity(&self) -> usize {
        2
    }

    fn can(&self, bound: u64) -> bool {
        bound & 1 == 1
    }

    fn lookup(
        &self,
        bound: u64,
        keys: &[&[Value]],
        n: usize,
        out: &mut dyn FnMut(usize, &[Value]),
    ) -> kleene_plan::Result<()> {
        let k = self.kinds()?;
        for (i, &kind) in keys[0].iter().enumerate().take(n) {
            if bound & 2 != 0 {
                let v = keys[1][i];
                if u32::try_from(v).is_ok_and(|v| k.has(kind, v)) {
                    out(i, &[kind, v]);
                }
                continue;
            }
            for v in k.ids(kind) {
                out(i, &[kind, v as Value]);
            }
        }
        Ok(())
    }
}