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/catalog.rs

//! An X.gar set as a catalog with its indexes ([`catalog`], [`indexed`]): kleene-gar reads
//! the set's schema ([`GarGraph::catalog`]), this module builds the indexes over it, the
//! same for both clients (GQL's `kleene gql`, Datalog's `Inputs::bind`).
//!
//! | Name | Here |
//! |---|---|
//! | Node label `T` | vertex type `T`: its ids in the set's id space ([`GarGraph::id_space`]: `base..base + count`) |
//! | Edge label `src_edge_dst` | that edge type, shared from its files in both orders, read in the id space by its ends' bases (kleene-plan's [`Source::GraphAt`]: a walk over it copies nothing) |
//! | Edge label `edge` | the same, when one edge type alone has that edge name |
//! | Property `T.c` | unsigned integer column `c` of vertex type `T`: id to value |
//! | Property `T.c`, signed or float | a signed integer (`Int8`..`Int64`) or float (`Float32`, `Float64`) column, read by its type; a null slot is null |
//! | Property `T.c`, a boolean | a `Boolean` column; a null slot is null |
//! | Property index `T.c` | for an unsigned, signed or float column `c`: a [`RangeRel`] of its (value, row) pairs (a typed value's order-keeping code; a null in none), sorted at the first lookup |
//! | Property `T.c`, a string | string column `c` (a set's `Binary` string table read as UTF-8): a string property with a name index (a [`NameRowsRel`]: kleene-index's minimal perfect hash, then each name's rows) |
//! | Node label `T_c_k` | for an integer column `c` named `kind` (at most 256 distinct values, each at least 0): the rows of kind `k`, read through a [`KindsRel`] (kleene-index's bitmap per kind) |
//! | Reach index `E` | for each edge label: a [`LazyReachRel`] (kleene-index's 2-hop labels), built at the first lookup |
//! | Edge property `E.p` | unsigned integer property `p` of edge type `E` (both its names): (source, destination, value), listed from the mapped files when a query reads it |
//! | Edge property `E.p`, signed, float, boolean or string | read by its Arrow type as vertex columns are (`Int8`..`Int64`, `Float32`, `Float64`, `Boolean`, UTF-8 strings; a null slot null): (source, destination, value) columns, the ends listed once per edge type in by-source order |
//!
//! A bytes column is a string property as kleene-gar reads it (its text; fixed-size bytes
//! their hex), named by a name index when it is read as text. A column of any other type (a
//! date, a decimal), on a vertex or an edge, is a
//! property refused by name and type when a query reads it. Columns another writer wrote with nulls
//! or of types the mapped reader does not take are read from their chunks
//! ([`GarGraph::vertex_column`]).
//!
//! Every node is its id in the set's one id space (kleene-gar's [`kleene_gar::IdSpace`]: the
//! vertex types in the set's order, each numbered from the sum of the counts before it), so
//! nodes of two types never share a number: an edge either way between two types, a union
//! of edge labels, label alternatives, `MATCH (n)` with no label and `id(n)` (the node
//! itself) need nothing more here. Indexes built here on a type's rows (ranges, names,
//! kinds) hand ids, the rows shifted by the type's base.

use std::sync::Arc;

use arrow_array::cast::AsArray;
use arrow_array::types::{Int8Type, Int16Type, Int32Type, Int64Type};
use arrow_array::{Array, ArrayRef};
use arrow_schema::DataType;
use kleene_gar::{GarGraph, unsigned_value, value_code};
use kleene_plan::{
    Catalog, External, NameIndex, PlanError, Producer, Result, Shifted, Source, Type,
};

use crate::relations::{KindsRel, LazyReachRel, NameRowsRel, RangeRel};

/// The catalog of `g`: its schema as kleene-gar reads it ([`GarGraph::catalog`]: vertex
/// types as node labels, edge types as edge labels, vertex columns and edge properties as
/// properties, each by its type), with the indexes of [`indexed`] built over it.
pub fn catalog(g: &GarGraph) -> Result<Catalog> {
    let c = g
        .catalog()
        .map_err(|e| PlanError::Input(format!("the set's schema: {e}")))?;
    indexed(c)
}

/// `c` with the indexes built here over it, from the catalog alone (so a catalog filled
/// from an X.gar set and one filled from Iceberg tables get the same): a range index per
/// numeric property, a name index per string property, kind labels per `kind` column (when
/// the label's ids are one block), a reach index per edge label (a graph source). A
/// property's ids are the ids its source lists beside the values.
pub fn indexed(mut c: Catalog) -> Result<Catalog> {
    let labels: Vec<String> = c.top_labels().map(str::to_string).collect();
    for v in &labels {
        for (col, source, ty) in c.label_props(v) {
            let Source::Columns(cols) = source else {
                continue;
            };
            let (ids, values) = (cols[0].clone(), cols[1].clone());
            let id = |ids: &ArrayRef, k: usize| unsigned_value(ids, k) as u32;
            match ty {
                Type::U64 => {
                    if col == "kind" {
                        kind_labels(&mut c, v, &col, &values, &ids);
                    }
                    // (a row whose value is null has none: in no range)
                    let pairs = move || {
                        (0..values.len())
                            .filter(|&k| values.is_valid(k))
                            .map(|k| (unsigned_value(&values, k), id(&ids, k)))
                            .collect()
                    };
                    let ext: Arc<dyn External> = Arc::new(RangeRel::new(pairs));
                    c.property_index(v, &col, Source::External(ext));
                }
                ty @ (Type::I64 | Type::F64) => {
                    if col == "kind" && ty == Type::I64 {
                        kind_labels(&mut c, v, &col, &values, &ids);
                    }
                    // the (code, id) pairs of the values: a null is in no range
                    let pairs = move || {
                        (0..values.len())
                            .filter_map(|k| Some((value_code(&values, k)?, id(&ids, k))))
                            .collect()
                    };
                    let ext: Arc<dyn External> = Arc::new(RangeRel::new(pairs));
                    c.property_index(v, &col, Source::External(ext));
                }
                // (a str column of strings or bytes read as text; not a fixed-size bytes
                // column, read as hex, nor a dictionary)
                Type::Str
                    if !matches!(
                        values.data_type(),
                        DataType::FixedSizeBinary(_) | DataType::Dictionary(..)
                    ) =>
                {
                    let names = NameIds(NameRowsRel::new(values), ids);
                    c.name_index(v, &col, Arc::new(names));
                }
                _ => {}
            }
        }
    }
    // each edge label's graph, an alias sharing the index of the label it names
    let edges: Vec<String> = c.edge_labels().map(str::to_string).collect();
    let mut made: std::collections::BTreeMap<String, Arc<dyn External>> = Default::default();
    let own: Vec<String> = edges
        .iter()
        .filter(|e| c.alias_of(e).is_none())
        .cloned()
        .collect();
    for name in &own {
        let (out, bases) = match c.relation(name)?.0 {
            Source::GraphAt { out, bases, .. } => (out, bases),
            Source::Graph { out, .. } => (out, (0, 0)),
            _ => continue,
        };
        let reach: Arc<dyn External> = Arc::new(Shifted::new(
            Arc::new(LazyReachRel::new(
                out.pattern().offsets().clone(),
                out.pattern().indices().clone(),
            )),
            vec![bases.0, bases.1],
        )?);
        c.reach_index(name, Source::External(reach.clone()));
        made.insert(name.clone(), reach);
    }
    for name in &edges {
        if let Some(reach) = c.alias_of(name).and_then(|of| made.get(of)).cloned() {
            c.reach_index(name, Source::External(reach));
        }
    }
    Ok(c)
}

/// The kind labels of integer column `col` of label `t` whose ids are `ids` (one block; at
/// most 256 distinct values, each at least 0): label `t_col_k` for the rows of kind `k`, answered by a
/// [`KindsRel`] named `t.col` (its rows shifted to ids by `base`); the label's own source
/// lists the same ids.
fn kind_labels(c: &mut Catalog, t: &str, col: &str, values: &ArrayRef, ids: &ArrayRef) {
    if values.null_count() > 0 {
        return;
    }
    // the rows are numbered from the label's first id: only a block of ids
    let base = if ids.is_empty() {
        0
    } else {
        unsigned_value(ids, 0)
    };
    if (0..ids.len()).any(|k| unsigned_value(ids, k) != base + k as u64) {
        return;
    }
    let n = values.len();
    let at = |k: usize| -> i128 {
        match values.data_type() {
            DataType::Int8 => values.as_primitive::<Int8Type>().value(k) as i128,
            DataType::Int16 => values.as_primitive::<Int16Type>().value(k) as i128,
            DataType::Int32 => values.as_primitive::<Int32Type>().value(k) as i128,
            DataType::Int64 => values.as_primitive::<Int64Type>().value(k) as i128,
            _ => unsigned_value(values, k) as i128,
        }
    };
    let wide: Vec<i128> = (0..n).map(at).collect();
    if wide.iter().any(|&x| x < 0) {
        return;
    }
    let kinds: Vec<u64> = wide.iter().map(|&x| x as u64).collect();
    let mut distinct = kinds.clone();
    distinct.sort_unstable();
    distinct.dedup();
    if distinct.len() > 256 {
        return;
    }
    let index = format!("{t}.{col}");
    let rel = Arc::new(KindsRel::new(kinds));
    let ids: Arc<dyn External> = Arc::new(
        Shifted::new(rel.clone(), vec![0, base]).expect("a kinds relation of two columns"),
    );
    c.kinds_index(&index, Source::External(ids));
    for k in distinct {
        let label = format!("{t}_{col}_{k}");
        let r = rel.clone();
        let rows = move |out: &mut dyn FnMut(&[u64])| -> kleene_plan::Result<()> {
            for v in r.kinds()?.ids(k) {
                out(&[base + v as u64]);
            }
            Ok(())
        };
        let ext: Arc<dyn External> = Arc::new(Producer::new(1, rows));
        c.label(&label, Source::External(ext));
        c.kind_label(&label, &index, k);
        c.sub_label(&label, t);
    }
}

/// A name index of a label's rows, handing ids (each row's id beside its value).
#[derive(Debug)]
struct NameIds(NameRowsRel, ArrayRef);

impl NameIndex for NameIds {
    fn nodes(&self, name: &str, out: &mut dyn FnMut(u32)) -> kleene_plan::Result<()> {
        for &r in self.0.rows(name)? {
            out(unsigned_value(&self.1, r as usize) as u32);
        }
        Ok(())
    }
}