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

nordisk/kleene

crates/kleene-gar/tests/zero_copy.rs

//! The adjacency of an edge type comes out of the mapped files themselves: every buffer of
//! a one-chunk edge table lies inside the mapping of its own chunk file (read back from
//! `/proc/self/maps`, so a copy anywhere would show). An edge table cut in several parts
//! and chunks (the GraphAr layout with more than one vertex chunk or edge chunk) reads as
//! the same compressed rows and columns.

use std::path::{Path, PathBuf};
use std::sync::Arc;

use arrow_array::{ArrayRef, RecordBatch, UInt32Array, UInt64Array};
use arrow_buffer::ScalarBuffer;
use graphar::mapped::{IntEdges, IntGraphWriter, write_ipc};
use graphar::{DST_INDEX_COL, OFFSET_COL, SRC_INDEX_COL};
use kleene_gar::{EdgeAdjacency, GarGraph};

struct TempDir(PathBuf);

impl TempDir {
    fn new(tag: &str) -> Self {
        let p = std::env::temp_dir().join(format!(
            "kleene-gar-zc-{tag}-{}-{:?}",
            std::process::id(),
            std::thread::current().id()
        ));
        let _ = std::fs::remove_dir_all(&p);
        std::fs::create_dir_all(&p).unwrap();
        TempDir(p)
    }
}

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

/// The file mapped at the address range of `buf` (one mapping holding all of it), from
/// `/proc/self/maps`; none when the bytes are on the heap or span mappings. Linux only:
/// other systems (macOS) have no `/proc`, and the proofs that need it are not run there.
#[cfg(target_os = "linux")]
fn mapped_file_of<T: arrow_buffer::ArrowNativeType>(buf: &ScalarBuffer<T>) -> Option<PathBuf> {
    let lo = buf.as_ptr() as usize;
    let hi = lo + std::mem::size_of_val(&buf[..]);
    let maps = std::fs::read_to_string("/proc/self/maps").ok()?;
    maps.lines().find_map(|l| {
        let mut f = l.split_whitespace();
        let (a, b) = f.next()?.split_once('-')?;
        let (a, b) = (
            usize::from_str_radix(a, 16).ok()?,
            usize::from_str_radix(b, 16).ok()?,
        );
        let path = f.nth(4)?;
        (a <= lo && hi <= b && path.starts_with('/')).then(|| PathBuf::from(path))
    })
}

/// A plain CSR of `pairs` over `n` rows (the reference).
/// Whether `/proc/self/maps` lists every mapping: not under qemu-user, whose emulated maps
/// leave some file mappings out (the runner in `.cargo/aarch64-qemu.toml` says so through
/// `KLEENE_QEMU_USER`). The mapping proofs are skipped there; they run natively.
#[cfg(target_os = "linux")]
fn maps_listed() -> bool {
    std::env::var_os("KLEENE_QEMU_USER").is_none()
}

fn csr_of(n: usize, pairs: &[(u32, u32)]) -> (Vec<u64>, Vec<u32>) {
    let mut sorted = pairs.to_vec();
    sorted.sort_unstable();
    let mut off = vec![0u64; n + 1];
    for &(s, _) in &sorted {
        off[s as usize + 1] += 1;
    }
    for i in 0..n {
        off[i + 1] += off[i];
    }
    (off, sorted.iter().map(|p| p.1).collect())
}

/// `n` vertices of type `v` and one edge type `v_link_v` over `pairs`, written by graph-ar's
/// writer (one part, one chunk per order).
fn write_set(dir: &Path, n: u32, pairs: &[(u32, u32)]) -> PathBuf {
    let mut w = IntGraphWriter::new(dir, "X").unwrap();
    w.vertices("v", n, vec![]).unwrap();
    let src: Vec<u32> = pairs.iter().map(|p| p.0).collect();
    let dst: Vec<u32> = pairs.iter().map(|p| p.1).collect();
    w.edges(IntEdges::from_pairs(("v", "link", "v"), (n, n), &src, &dst, vec![]).unwrap())
        .unwrap();
    w.finish().unwrap();
    dir.join("edge").join("v_link_v")
}

fn batch(cols: Vec<(&str, ArrayRef)>) -> RecordBatch {
    RecordBatch::try_from_iter(cols).unwrap()
}

fn count_file(path: &Path, n: u64) {
    std::fs::write(path, (n as i64).to_le_bytes()).unwrap();
}

/// Rewrite one order of an edge type in the chunked GraphAr layout: vertex chunks of
/// `vchunk` rows (one adjacency part and one offset chunk each, offsets counted from the
/// part's start) and edge chunks of `echunk` edges within a part.
fn write_chunked_order(
    edge_dir: &Path,
    order: &str,
    n: usize,
    far: &str,
    pairs: &[(u32, u32)],
    vchunk: usize,
    echunk: usize,
) {
    let root = edge_dir.join(order);
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(root.join("offset")).unwrap();
    count_file(&root.join("vertex_count"), n as u64);
    let (off, idx) = csr_of(n, pairs);
    for (p, lo) in (0..n).step_by(vchunk).enumerate() {
        let hi = (lo + vchunk).min(n);
        let (a, b) = (off[lo] as usize, off[hi] as usize);
        let local: Vec<u64> = off[lo..=hi].iter().map(|o| o - a as u64).collect();
        write_ipc(
            root.join("offset").join(format!("chunk{p}")),
            &batch(vec![(
                OFFSET_COL,
                Arc::new(UInt64Array::from(local)) as ArrayRef,
            )]),
        )
        .unwrap();
        count_file(&root.join(format!("edge_count{p}")), (b - a) as u64);
        let part = root.join("adj_list").join(format!("part{p}"));
        std::fs::create_dir_all(&part).unwrap();
        let rows: Vec<u32> = (lo..hi)
            .flat_map(|r| std::iter::repeat_n(r as u32, (off[r + 1] - off[r]) as usize))
            .collect();
        // At least one chunk per part (an empty one for a part with no edges).
        let mut c = 0;
        let mut k = a;
        loop {
            let e = (k + echunk).min(b);
            let near = UInt32Array::from(rows[k - a..e - a].to_vec());
            let farv = UInt32Array::from(idx[k..e].to_vec());
            let (sname, dname) = if far == DST_INDEX_COL {
                (SRC_INDEX_COL, DST_INDEX_COL)
            } else {
                (DST_INDEX_COL, SRC_INDEX_COL)
            };
            write_ipc(
                part.join(format!("chunk{c}")),
                &batch(vec![
                    (sname, Arc::new(near) as ArrayRef),
                    (dname, Arc::new(farv) as ArrayRef),
                ]),
            )
            .unwrap();
            c += 1;
            k = e;
            if k >= b {
                break;
            }
        }
    }
}

fn adjacency(dir: &Path) -> EdgeAdjacency {
    let g = GarGraph::open(dir).unwrap();
    let t = g.edge_type("v_link_v").unwrap().clone();
    g.adjacency(&t).unwrap()
}

fn sample(n: u32) -> Vec<(u32, u32)> {
    // Every vertex has some edges, a few none, one row longer than an edge chunk.
    let mut pairs = Vec::new();
    for v in 0..n {
        for k in 0..(v * 7 % 5) {
            pairs.push((v, (v * 13 + k * 29 + 3) % n));
        }
    }
    for k in 0..9 {
        pairs.push((4, (k * 5 + 1) % n));
    }
    pairs.sort_unstable();
    pairs.dedup();
    pairs
}

#[cfg(target_os = "linux")]
#[test]
fn every_adjacency_buffer_lies_in_its_own_mapped_chunk_file() {
    if !maps_listed() {
        eprintln!("skipped under qemu-user: its /proc/self/maps leaves mappings out");
        return;
    }
    let t = TempDir::new("one");
    let pairs = sample(40);
    let edge_dir = write_set(&t.0, 40, &pairs);
    let adj = adjacency(&t.0);
    let want = |order: &str, what: &str| {
        let p = edge_dir.join(order).join(what);
        std::fs::canonicalize(p).unwrap()
    };
    let cases: [(Option<PathBuf>, PathBuf); 4] = [
        (
            mapped_file_of(&adj.out_offsets),
            want("ordered_by_source", "offset/chunk0"),
        ),
        (
            mapped_file_of(&adj.out_neighbours),
            want("ordered_by_source", "adj_list/part0/chunk0"),
        ),
        (
            mapped_file_of(&adj.in_offsets),
            want("ordered_by_dest", "offset/chunk0"),
        ),
        (
            mapped_file_of(&adj.in_neighbours),
            want("ordered_by_dest", "adj_list/part0/chunk0"),
        ),
    ];
    for (got, want) in cases {
        assert_eq!(
            got.as_deref(),
            Some(want.as_path()),
            "a buffer is not mapped"
        );
    }
    let (off, idx) = csr_of(40, &pairs);
    assert_eq!(&adj.out_offsets[..], &off[..]);
    assert_eq!(&adj.out_neighbours[..], &idx[..]);
}

#[test]
fn a_table_in_several_parts_and_chunks_reads_as_the_same_rows() {
    let n = 41u32;
    let pairs = sample(n);
    let reversed: Vec<(u32, u32)> = pairs.iter().map(|&(s, d)| (d, s)).collect();
    for (vchunk, echunk) in [(8usize, 3usize), (16, 1000), (41, 4), (5, 2)] {
        let t = TempDir::new(&format!("chunked-{vchunk}-{echunk}"));
        let edge_dir = write_set(&t.0, n, &pairs);
        write_chunked_order(
            &edge_dir,
            "ordered_by_source",
            n as usize,
            DST_INDEX_COL,
            &pairs,
            vchunk,
            echunk,
        );
        write_chunked_order(
            &edge_dir,
            "ordered_by_dest",
            n as usize,
            SRC_INDEX_COL,
            &reversed,
            vchunk,
            echunk,
        );
        let adj = adjacency(&t.0);
        let (off, idx) = csr_of(n as usize, &pairs);
        let (roff, ridx) = csr_of(n as usize, &reversed);
        assert_eq!((adj.sources, adj.destinations), (n as usize, n as usize));
        assert_eq!(&adj.out_offsets[..], &off[..], "{vchunk}/{echunk}");
        assert_eq!(&adj.out_neighbours[..], &idx[..], "{vchunk}/{echunk}");
        assert_eq!(&adj.in_offsets[..], &roff[..], "{vchunk}/{echunk}");
        assert_eq!(&adj.in_neighbours[..], &ridx[..], "{vchunk}/{echunk}");
        // One part with one edge chunk still shares the mapping.
        #[cfg(target_os = "linux")]
        if maps_listed() && vchunk >= n as usize && echunk >= pairs.len() {
            assert!(mapped_file_of(&adj.out_neighbours).is_some());
        }
    }
}

#[test]
fn a_chunked_table_that_does_not_check_is_refused() {
    let n = 20u32;
    let pairs = sample(n);
    let t = TempDir::new("bad");
    let edge_dir = write_set(&t.0, n, &pairs);
    let mut bad = pairs.clone();
    bad.push((3, 25));
    write_chunked_order(
        &edge_dir,
        "ordered_by_source",
        n as usize,
        DST_INDEX_COL,
        &bad,
        8,
        3,
    );
    let g = GarGraph::open(&t.0).unwrap();
    let et = g.edge_type("v_link_v").unwrap().clone();
    assert!(g.adjacency(&et).is_err());
}

/// Write `value` over row `row` of the `u32` column `col` of the chunk at `path`.
fn put_u32(path: &Path, col: &str, row: usize, value: u32) {
    let off = {
        let chunk = graphar::mapped::MappedChunk::open(path).unwrap();
        let base = chunk.file().as_ptr() as usize;
        chunk.values::<u32>(col).unwrap().as_ptr() as usize - base + row * 4
    };
    let mut bytes = std::fs::read(path).unwrap();
    bytes[off..off + 4].copy_from_slice(&value.to_le_bytes());
    std::fs::write(path, bytes).unwrap();
}

#[test]
fn the_adjacency_checked_on_the_workers_is_the_plain_one_and_refuses_the_same() {
    let t = TempDir::new("on");
    let pairs = sample(40);
    let edge_dir = write_set(&t.0, 40, &pairs);
    let devices = [
        kleene_sparse::CpuDevice::new(1),
        kleene_sparse::CpuDevice::new(4),
    ];
    let g = GarGraph::open(&t.0).unwrap();
    let et = g.edge_type("v_link_v").unwrap().clone();
    let want = g.adjacency(&et).unwrap();
    for d in &devices {
        let got = g.adjacency_on(&et, d).unwrap();
        assert_eq!(&got.out_offsets[..], &want.out_offsets[..]);
        assert_eq!(&got.out_neighbours[..], &want.out_neighbours[..]);
        assert_eq!(&got.in_offsets[..], &want.in_offsets[..]);
        assert_eq!(&got.in_neighbours[..], &want.in_neighbours[..]);
    }
    drop((want, g));
    // Two neighbours outside the vertices: the first one is named, on every device.
    let adj = edge_dir.join("ordered_by_dest/adj_list/part0/chunk0");
    put_u32(&adj, SRC_INDEX_COL, pairs.len() - 2, 77);
    put_u32(&adj, SRC_INDEX_COL, 5, 41);
    let g = GarGraph::open(&t.0).unwrap();
    let refused = g.adjacency(&et).unwrap_err().to_string();
    assert!(refused.contains("neighbour 41"), "{refused}");
    for d in &devices {
        assert_eq!(g.adjacency_on(&et, d).unwrap_err().to_string(), refused);
    }
}