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

//! Parts loaded ahead of any query: built once from a source at a snapshot, their
//! summaries the split's, and a later query finds them: loaded then queried equals queried
//! cold, and the second query builds nothing.

use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU32, Ordering};

use graphar::mapped::{IntEdges, IntGraphWriter};
use kleene_graph::{BfsOptions, Graph, Split, SplitKey, bfs};
use kleene_index::{Central, EdgeSource, GarEdges, LoadKey, Loads, Result};
use kleene_sparse::{BoolOrAnd, CpuDevice, Csr};

/// A pseudo-random graph: (n, src, dst).
fn graph(n: u32, m: usize, seed: u64) -> (u32, Vec<u32>, Vec<u32>) {
    let mut x = seed;
    let mut next = || {
        x = x
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);
        (x >> 33) as u32
    };
    let (mut s, mut d) = (Vec::new(), Vec::new());
    for _ in 0..m {
        s.push(next() % n);
        d.push(next() % n);
    }
    (n, s, d)
}

/// A source in memory that counts its reads.
struct Memory {
    a: Csr<u8>,
    reads: AtomicU32,
}

impl EdgeSource for Memory {
    fn name(&self) -> String {
        "memory|v_link_v".to_string()
    }

    fn by_source(&self) -> Result<Csr<u8>> {
        self.reads.fetch_add(1, Ordering::Relaxed);
        Ok(self.a.clone())
    }
}

fn memory(n: u32, src: &[u32], dst: &[u32]) -> Memory {
    let n = n as usize;
    Memory {
        a: Csr::from_edges(n, n, src, dst, None, BoolOrAnd).unwrap(),
        reads: AtomicU32::new(0),
    }
}

fn keys(n: u32) -> Vec<Option<SplitKey>> {
    vec![
        None,
        Some(SplitKey::Blocks(vec![0, n as u64 / 3, n as u64 / 2])),
        Some(SplitKey::Hash(4)),
        Some(SplitKey::Property((0..n).map(|v| v % 3 * 5).collect())),
    ]
}

#[test]
fn loaded_ahead_then_queried_equals_queried_cold_and_builds_nothing_more() {
    let (n, src, dst) = graph(400, 2400, 5);
    let device = CpuDevice::default();
    for key in keys(n) {
        let whole = Split::<u8>::new(
            n as usize,
            &src,
            &dst,
            None,
            key.as_ref().unwrap_or(&SplitKey::Blocks(vec![0])),
            BoolOrAnd,
        )
        .unwrap();
        let parts = whole.parts().len() as u32;
        let at = |p: u32| LoadKey {
            source: "memory|v_link_v".to_string(),
            snapshot: 7,
            split: key.clone(),
            part: p,
        };
        // ahead: every part loaded, their summaries the split's, Central built from them
        let src_m = memory(n, &src, &dst);
        let ahead = Loads::new();
        let summaries: Vec<_> = (0..parts)
            .map(|p| ahead.load(&src_m, &at(p), true, &device).unwrap())
            .collect();
        assert_eq!(summaries, whole.summaries(), "{key:?}");
        let c = Central::build(&summaries, vec![0; parts as usize]).unwrap();
        let c_split = Central::build(&whole.summaries(), vec![0; parts as usize]).unwrap();
        assert_eq!(c.tables(), c_split.tables(), "{key:?}");
        assert_eq!(
            ahead.builds(),
            2 * parts as u64,
            "{key:?}: a graph and a reach index each"
        );
        assert_eq!(src_m.reads.load(Ordering::Relaxed), parts, "{key:?}");
        // cold: nothing loaded; the query loads
        let src_c = memory(n, &src, &dst);
        let cold = Loads::new();
        let opts = BfsOptions::default();
        for p in 0..parts {
            let part = whole.part(p);
            if part.count() == 0 {
                continue;
            }
            let sources = [0u32, part.count() as u32 / 2];
            let want = {
                let g =
                    Graph::<kleene_sparse::CpuBackend>::new(part.inner().clone(), &device).unwrap();
                bfs(&g, &sources, &opts, &device).unwrap().vertices()
            };
            let before = ahead.builds();
            let (got_ahead, _) = ahead
                .get_or_load(&src_m, &at(p), &device)
                .unwrap()
                .search(&sources, &opts, &device)
                .unwrap();
            assert_eq!(ahead.builds(), before, "{key:?} part {p}: a query built");
            let (got_cold, _) = cold
                .get_or_load(&src_c, &at(p), &device)
                .unwrap()
                .search(&sources, &opts, &device)
                .unwrap();
            assert_eq!(got_ahead, want, "{key:?} part {p}");
            assert_eq!(got_cold, want, "{key:?} part {p}");
            // the second cold query builds nothing
            let b = cold.builds();
            let (again, _) = cold
                .get_or_load(&src_c, &at(p), &device)
                .unwrap()
                .search(&sources, &opts, &device)
                .unwrap();
            assert_eq!(again, want);
            assert_eq!(cold.builds(), b, "{key:?} part {p}: the second query built");
            // the reach index loaded ahead answers as the search does
            let r = ahead.get(&at(p)).unwrap();
            let reach = r.reach().unwrap();
            for v in 0..part.count() as u32 {
                let by_search = want.binary_search(&v).is_ok();
                let by_index = sources.iter().any(|&s| reach.reaches(s, v));
                assert_eq!(by_index, by_search, "{key:?} part {p} vertex {v}");
            }
            assert_eq!(
                ahead.builds(),
                before,
                "{key:?} part {p}: an index built twice"
            );
        }
        assert_eq!(
            src_m.reads.load(Ordering::Relaxed),
            parts,
            "{key:?}: read again"
        );
        // another snapshot is another load
        let mut later = at(0);
        later.snapshot = 8;
        assert!(ahead.get(&later).is_none());
        ahead.get_or_load(&src_m, &later, &device).unwrap();
        assert_eq!(src_m.reads.load(Ordering::Relaxed), parts + 1);
        assert!(ahead.unload(&later));
        assert!(ahead.get(&later).is_none());
    }
}

#[test]
fn the_whole_graph_is_one_part_with_the_sources_matrix_shared() {
    let (n, src, dst) = graph(300, 1500, 9);
    let device = CpuDevice::default();
    let m = memory(n, &src, &dst);
    let loads = Loads::new();
    let at = LoadKey::whole(&m, 3);
    let s = loads.load(&m, &at, false, &device).unwrap();
    assert_eq!((s.part, s.base, s.count), (0, 0, n as u64));
    assert!(s.border.is_empty());
    let p = loads.get(&at).unwrap();
    // shared, not copied: the same buffer as the source's matrix
    assert_eq!(
        p.part().inner().pattern().indices().as_ptr(),
        m.a.pattern().indices().as_ptr()
    );
    assert!(p.ids().is_identity());
    // a part past the whole graph's one is refused; a key of another source too
    let mut bad = at.clone();
    bad.part = 1;
    assert!(Loads::new().get_or_load(&m, &bad, &device).is_err());
    let mut other = at.clone();
    other.source = "elsewhere".into();
    assert!(Loads::new().get_or_load(&m, &other, &device).is_err());
}

struct Tmp(PathBuf);

impl Tmp {
    fn new(tag: &str) -> Tmp {
        let d = std::env::temp_dir().join(format!("kleene-loads-{tag}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&d);
        std::fs::create_dir_all(&d).unwrap();
        Tmp(d)
    }
}

impl Drop for Tmp {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

fn write_set(dir: &Path, n: u32, src: &[u32], dst: &[u32]) {
    let mut w = IntGraphWriter::new(dir, "X").unwrap();
    w.vertices("v", n, vec![]).unwrap();
    let e = IntEdges::from_pairs(("v", "link", "v"), (n, n), src, dst, vec![]).unwrap();
    w.edges(e).unwrap();
    w.finish().unwrap();
}

#[test]
fn a_part_of_a_graphar_set_is_the_splits_part() {
    let (n, src, dst) = graph(500, 3000, 13);
    let t = Tmp::new("gar");
    write_set(&t.0, n, &src, &dst);
    let gar = GarEdges {
        path: t.0.clone(),
        edge: "v_link_v".to_string(),
    };
    let a = gar.by_source().unwrap();
    let key = SplitKey::Blocks(vec![0, 100, 350]);
    let split = Split::from_csr(&a, &key, BoolOrAnd).unwrap();
    let device = CpuDevice::default();
    let loads = Loads::new();
    for p in 0..3 {
        let s = loads
            .load(
                &gar,
                &LoadKey::part(&gar, 0, key.clone(), p),
                false,
                &device,
            )
            .unwrap();
        assert_eq!(s, split.part(p).summary());
    }
    assert_eq!(loads.loaded().len(), 3);
}