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

//! Parts loaded ahead, before any query: each built once from a source at a snapshot, with
//! its own indexes, kept, and found by every later query instead of built again.
//!
//! A machine of a split graph loads its parts ([`Loads::load`]) and hands their summaries
//! to [`Central::build`](crate::Central::build); a machine of the whole graph loads the
//! one part of [`LoadKey::whole`]. A query asks [`Loads::get_or_load`]: a part loaded
//! ahead is found; one not loaded is loaded then, as a query always did. A part is read
//! with [`Split::part_only`]: only the rows of its own nodes.

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};

use kleene_gar::GarGraph;
use kleene_graph::{
    BfsOptions, BfsState, BfsSummary, Graph, Part, PartSummary, Split, SplitIds, SplitKey, bfs_with,
};
use kleene_sparse::{BoolOrAnd, CpuBackend, CpuDevice, Csr, Pattern, SparseBackend};

use crate::error::{bad, gar};
use crate::{Reach, Result};

/// Where a graph's edges come from: one edge type of a set, the same on every machine.
pub trait EdgeSource: Send + Sync {
    /// The name of the set and its edge type, the same on every machine (part of the key a
    /// loaded part is kept under).
    fn name(&self) -> String;

    /// The edges by source, as a matrix whose rows are the sources. A source that maps its
    /// files gives the mapping (no copy): a part then reads only its rows' pages.
    fn by_source(&self) -> Result<Csr<u8>>;

    /// [`EdgeSource::by_source`] with the device's workers at hand for any pass it makes
    /// over the edges (a transpose); by default the same as `by_source`.
    fn by_source_on(&self, device: &CpuDevice) -> Result<Csr<u8>> {
        let _ = device;
        self.by_source()
    }
}

/// One edge type of a GraphAr set on disk ([`GarGraph::adjacency`]): a table of one chunk
/// is mapped, so a part reads only its rows' pages; a table cut in chunks is joined whole
/// once per load (every row read, the part's kept).
#[derive(Clone, Debug)]
pub struct GarEdges {
    /// The X.gar directory.
    pub path: PathBuf,
    /// The edge type's table name (as `v_link_v`).
    pub edge: String,
}

impl EdgeSource for GarEdges {
    fn name(&self) -> String {
        format!("{}|{}", self.path.display(), self.edge)
    }

    fn by_source(&self) -> Result<Csr<u8>> {
        let g = GarGraph::open(&self.path).map_err(gar)?;
        let t = g
            .edge_type(&self.edge)
            .ok_or_else(|| bad(format!("no edge type {} in {}", self.edge, self.name())))?
            .clone();
        let adj = g.adjacency(&t).map_err(gar)?;
        if adj.sources != adj.destinations {
            return Err(bad(format!(
                "{}: {} sources and {} targets: a graph needs one vertex type",
                self.name(),
                adj.sources,
                adj.destinations
            )));
        }
        Ok(Csr::with_pattern(
            Pattern::trusted(
                adj.sources,
                adj.destinations,
                adj.out_offsets,
                adj.out_neighbours,
                "by source",
            )?,
            None,
        )?)
    }
}

/// The edges of a source by target: its matrix transposed, kept under its own name (a
/// part of it split by a key has the same ids as the source's part by that key).
#[derive(Clone, Debug)]
pub struct Transposed<S>(pub S);

impl<S: EdgeSource> EdgeSource for Transposed<S> {
    fn name(&self) -> String {
        format!("{}|transposed", self.0.name())
    }

    fn by_source(&self) -> Result<Csr<u8>> {
        Ok(self.0.by_source()?.transpose())
    }

    /// The transpose made on the device's workers.
    fn by_source_on(&self, device: &CpuDevice) -> Result<Csr<u8>> {
        Ok(CpuBackend::transpose(&self.0.by_source_on(device)?, device))
    }
}

/// What a loaded part is kept under: the source, its snapshot, the split and the part.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct LoadKey {
    /// [`EdgeSource::name`].
    pub source: String,
    /// The snapshot the rows were read at (an Iceberg snapshot id; a set that never
    /// changes, as a GraphAr set, gives one number for its life, as its root hash's).
    pub snapshot: u64,
    /// The split; `None`: the whole graph, one part, its matrix shared as the source gave
    /// it ([`Split::whole`]).
    pub split: Option<SplitKey>,
    /// The part.
    pub part: u32,
}

impl LoadKey {
    /// The whole graph of `source` at `snapshot`: one machine, one part.
    pub fn whole(source: &dyn EdgeSource, snapshot: u64) -> Self {
        LoadKey {
            source: source.name(),
            snapshot,
            split: None,
            part: 0,
        }
    }

    /// Part `part` of `source` at `snapshot` split by `key`.
    pub fn part(source: &dyn EdgeSource, snapshot: u64, key: SplitKey, part: u32) -> Self {
        LoadKey {
            source: source.name(),
            snapshot,
            split: Some(key),
            part,
        }
    }
}

/// One part as a machine keeps it: the split's ids, the part (its inner matrix and its
/// border), its graph in both directions, and its indexes.
#[derive(Debug)]
pub struct LoadedPart {
    ids: SplitIds,
    part: Part<u8>,
    graph: Arc<Graph<CpuBackend>>,
    reach: OnceLock<Reach>,
    /// Search buffers kept for the next query.
    spare: Mutex<Option<BfsState<CpuBackend>>>,
    builds: Arc<AtomicU64>,
}

impl LoadedPart {
    /// The split's ids (the whole graph: one part, the ids the source's).
    pub fn ids(&self) -> &SplitIds {
        &self.ids
    }

    /// The part.
    pub fn part(&self) -> &Part<u8> {
        &self.part
    }

    /// The part's summary, for [`Central::build`](crate::Central::build).
    pub fn summary(&self) -> PartSummary {
        self.part.summary()
    }

    /// The part's inner graph with its transpose (pull steps), shared: a
    /// [`kleene_graph::ReachSlice`] on the whole graph takes it as it is.
    pub fn graph(&self) -> &Arc<Graph<CpuBackend>> {
        &self.graph
    }

    /// The part's "can A reach B" index ([`Reach`], local ids), built on the first call or
    /// by [`Loads::load`] with `reach`.
    pub fn reach(&self) -> Result<&Reach> {
        if let Some(r) = self.reach.get() {
            return Ok(r);
        }
        let inner = self.part.inner();
        let r = Reach::build(inner.pattern().offsets(), inner.pattern().indices())?;
        self.builds.fetch_add(1, Ordering::Relaxed);
        Ok(self.reach.get_or_init(|| r))
    }

    /// A search inside the part from local vertices `sources` on kept buffers: the
    /// vertices reached (local ids, rising) and the search's summary.
    pub fn search(
        &self,
        sources: &[u32],
        opts: &BfsOptions,
        device: &CpuDevice,
    ) -> Result<(Vec<u32>, BfsSummary)> {
        let mut spare = self.spare.lock().unwrap_or_else(|e| e.into_inner());
        let st = match spare.as_mut() {
            Some(st) => st,
            None => spare.insert(BfsState::new(self.graph.vertices(), device)),
        };
        let sum = bfs_with(&self.graph, sources, opts, device, st)?;
        Ok((CpuBackend::indices(st.levels()), sum))
    }
}

/// The parts a machine has loaded, by [`LoadKey`], and how many builds it ran.
#[derive(Debug, Default)]
pub struct Loads {
    kept: Mutex<HashMap<LoadKey, Arc<LoadedPart>>>,
    builds: Arc<AtomicU64>,
}

impl Loads {
    /// Nothing loaded.
    pub fn new() -> Self {
        Self::default()
    }

    /// Load the part `at` names from `source` ahead of any query, with the reach index
    /// too when `reach`; give back its summary for [`Central::build`](crate::Central::build).
    /// A part already loaded is not built again.
    pub fn load(
        &self,
        source: &dyn EdgeSource,
        at: &LoadKey,
        reach: bool,
        device: &CpuDevice,
    ) -> Result<PartSummary> {
        let p = self.get_or_load(source, at, device)?;
        if reach {
            p.reach()?;
        }
        Ok(p.summary())
    }

    /// The part `at` names: the one loaded, or loaded now from `source` (a query on a part
    /// not loaded ahead).
    pub fn get_or_load(
        &self,
        source: &dyn EdgeSource,
        at: &LoadKey,
        device: &CpuDevice,
    ) -> Result<Arc<LoadedPart>> {
        if let Some(p) = self.get(at) {
            return Ok(p);
        }
        if at.source != source.name() {
            return Err(bad(format!(
                "a part of {} asked of the source {}",
                at.source,
                source.name()
            )));
        }
        let a = source.by_source_on(device)?;
        let (ids, part) = match &at.split {
            None => {
                if at.part != 0 {
                    return Err(bad(format!("no part {} in the whole graph", at.part)));
                }
                let (ids, mut parts) = Split::whole(a)?.into_parts();
                (ids, parts.pop().expect("one part"))
            }
            Some(key) => Split::part_only(&a, key, at.part, BoolOrAnd)?,
        };
        let inner = part.inner().clone();
        let graph = Arc::new(Graph::with_transpose(
            inner.clone(),
            // On the device's workers.
            CpuBackend::transpose(&inner, device),
            device,
        )?);
        self.builds.fetch_add(1, Ordering::Relaxed);
        let loaded = Arc::new(LoadedPart {
            ids,
            part,
            graph,
            reach: OnceLock::new(),
            spare: Mutex::new(None),
            builds: self.builds.clone(),
        });
        let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner());
        Ok(kept.entry(at.clone()).or_insert(loaded).clone())
    }

    /// The part `at` names, if loaded.
    pub fn get(&self, at: &LoadKey) -> Option<Arc<LoadedPart>> {
        let kept = self.kept.lock().unwrap_or_else(|e| e.into_inner());
        kept.get(at).cloned()
    }

    /// Drop the part `at` names (a later query loads it again); whether it was loaded.
    pub fn unload(&self, at: &LoadKey) -> bool {
        let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner());
        kept.remove(at).is_some()
    }

    /// The parts loaded.
    pub fn loaded(&self) -> Vec<LoadKey> {
        let kept = self.kept.lock().unwrap_or_else(|e| e.into_inner());
        kept.keys().cloned().collect()
    }

    /// How many builds ran: a part's graph, or an index of one.
    pub fn builds(&self) -> u64 {
        self.builds.load(Ordering::Relaxed)
    }
}