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/src/chunked.rs

//! Edge tables in the chunked GraphAr layout: an order cut in vertex chunks (one offset
//! chunk and one adjacency part each, offsets counted from the part's start) and each part
//! in edge chunks.
//!
//! ```text
//! edge/<name>/<order>/vertex_count
//! edge/<name>/<order>/offset/chunk<p>             one per vertex chunk
//! edge/<name>/<order>/adj_list/part<p>/chunk<c>   edge chunks of part p
//! ```
//!
//! A table of one part in one chunk is graph-ar's own layout and is read by graph-ar with
//! no copy. A cut table is mapped chunk by chunk and joined once into one compressed row
//! store (a row may straddle two chunk files, so the rows cannot stay in the files); a
//! buffer that comes from one file only (the offsets of a single part, the neighbours of a
//! single chunk) still shares the mapping.

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

use arrow_array::Array;
use arrow_array::cast::AsArray;
use arrow_array::types::{Int64Type, UInt32Type, UInt64Type};
use arrow_buffer::ScalarBuffer;
use arrow_schema::DataType;
use datafusion::error::{DataFusionError, Result};
use graphar::mapped::MappedChunk;
use graphar::{DST_INDEX_COL, OFFSET_COL, SRC_INDEX_COL};

fn bad(label: &str, why: impl std::fmt::Display) -> DataFusionError {
    DataFusionError::Execution(format!("{label}: {why}"))
}

fn gar_err(e: graphar::GraphArError) -> DataFusionError {
    DataFusionError::External(Box::new(e))
}

/// The files `<prefix>0`, `<prefix>1`, ... in `dir`, in number order; a gap in the numbers
/// or another name with the prefix is refused.
fn numbered(dir: &Path, prefix: &str, label: &str) -> Result<Vec<PathBuf>> {
    let mut found: Vec<(usize, PathBuf)> = Vec::new();
    for e in std::fs::read_dir(dir).map_err(|e| bad(label, format!("{}: {e}", dir.display())))? {
        let e = e?;
        let name = e.file_name();
        let Some(rest) = name.to_str().and_then(|n| n.strip_prefix(prefix)) else {
            continue;
        };
        let k: usize = rest
            .parse()
            .map_err(|_| bad(label, format!("{}: not {prefix}<n>", e.path().display())))?;
        found.push((k, e.path()));
    }
    found.sort_unstable();
    if found.iter().enumerate().any(|(i, (k, _))| i != *k) {
        return Err(bad(
            label,
            format!(
                "{}: {prefix}<n> files are not numbered 0, 1, ...",
                dir.display()
            ),
        ));
    }
    Ok(found.into_iter().map(|f| f.1).collect())
}

/// Whether both orders of the edge type in `edge_dir` are one part in one chunk (graph-ar's
/// layout).
pub(crate) fn is_one_chunk(edge_dir: &Path) -> bool {
    ["ordered_by_source", "ordered_by_dest"].iter().all(|o| {
        let root = edge_dir.join(o);
        let count = |dir: PathBuf, prefix: &str| {
            std::fs::read_dir(dir).map_or(0, |rd| {
                rd.filter_map(|e| e.ok())
                    .filter(|e| {
                        e.file_name()
                            .to_str()
                            .is_some_and(|n| n.starts_with(prefix))
                    })
                    .count()
            })
        };
        count(root.join("offset"), "chunk") <= 1
            && count(root.join("adj_list"), "part") <= 1
            && count(root.join("adj_list").join("part0"), "chunk") <= 1
    })
}

fn read_count(path: &Path, label: &str) -> Result<usize> {
    let raw = std::fs::read(path).map_err(|e| bad(label, format!("{}: {e}", path.display())))?;
    let bytes: [u8; 8] = raw
        .as_slice()
        .try_into()
        .map_err(|_| bad(label, format!("{}: a count is 8 bytes", path.display())))?;
    usize::try_from(i64::from_le_bytes(bytes))
        .map_err(|_| bad(label, format!("{}: a negative count", path.display())))
}

/// An integer column of a chunk as `u32` ids: shared when stored as `u32`, otherwise
/// (`u64`, `i64`, as GraphAr's own writers store ids) converted.
fn ids(chunk: &MappedChunk, name: &str, label: &str) -> Result<ScalarBuffer<u32>> {
    let col = chunk.batch().column_by_name(name).ok_or_else(|| {
        bad(
            label,
            format!("{}: no column {name}", chunk.path().display()),
        )
    })?;
    if col.null_count() > 0 {
        return Err(bad(
            label,
            format!("{}: {name} has nulls", chunk.path().display()),
        ));
    }
    let wide: Vec<u64> = match col.data_type() {
        DataType::UInt32 => return Ok(col.as_primitive::<UInt32Type>().values().clone()),
        DataType::UInt64 => col.as_primitive::<UInt64Type>().values().to_vec(),
        DataType::Int64 => col
            .as_primitive::<Int64Type>()
            .values()
            .iter()
            .map(|&v| u64::try_from(v).unwrap_or(u64::MAX))
            .collect(),
        t => {
            return Err(bad(
                label,
                format!("{}: {name} is {t}", chunk.path().display()),
            ));
        }
    };
    wide.iter()
        .map(|&v| u32::try_from(v))
        .collect::<std::result::Result<Vec<u32>, _>>()
        .map(ScalarBuffer::from)
        .map_err(|_| {
            bad(
                label,
                format!("{}: {name} holds an id past u32", chunk.path().display()),
            )
        })
}

fn offsets(chunk: &MappedChunk, label: &str) -> Result<ScalarBuffer<u64>> {
    let col = chunk.batch().column_by_name(OFFSET_COL).ok_or_else(|| {
        bad(
            label,
            format!("{}: no {OFFSET_COL}", chunk.path().display()),
        )
    })?;
    match col.data_type() {
        DataType::UInt64 => Ok(col.as_primitive::<UInt64Type>().values().clone()),
        DataType::Int64 => col
            .as_primitive::<Int64Type>()
            .values()
            .iter()
            .map(|&v| u64::try_from(v))
            .collect::<std::result::Result<Vec<u64>, _>>()
            .map(ScalarBuffer::from)
            .map_err(|_| bad(label, "a negative offset")),
        t => Err(bad(
            label,
            format!("{}: offsets are {t}", chunk.path().display()),
        )),
    }
}

/// One order of a cut edge table as compressed rows: (rows, offsets, neighbours).
pub(crate) fn read_order(
    edge_dir: &Path,
    order: &str,
    far_vertices: usize,
    label: &str,
) -> Result<(usize, ScalarBuffer<u64>, ScalarBuffer<u32>)> {
    let label = format!("{label} {order}");
    let label = label.as_str();
    let root = edge_dir.join(order);
    let far_col = if order == "ordered_by_source" {
        DST_INDEX_COL
    } else {
        SRC_INDEX_COL
    };
    let rows = read_count(&root.join("vertex_count"), label)?;
    let offset_files = numbered(&root.join("offset"), "chunk", label)?;
    let part_dirs = numbered(&root.join("adj_list"), "part", label)?;
    if offset_files.len() != part_dirs.len() {
        return Err(bad(
            label,
            format!(
                "{} offset chunks for {} parts",
                offset_files.len(),
                part_dirs.len()
            ),
        ));
    }
    let mut part_offsets: Vec<ScalarBuffer<u64>> = Vec::with_capacity(part_dirs.len());
    let mut neighbours: Vec<ScalarBuffer<u32>> = Vec::new();
    let mut seen_rows = 0usize;
    for (p, (of, pd)) in offset_files.iter().zip(&part_dirs).enumerate() {
        let off = offsets(&MappedChunk::open(of).map_err(gar_err)?, label)?;
        if off.is_empty() || off.windows(2).any(|w| w[0] > w[1]) {
            return Err(bad(
                label,
                format!("part {p}: offsets that fall or are empty"),
            ));
        }
        let edges = (off[off.len() - 1] - off[0]) as usize;
        let mut got = 0usize;
        for cf in numbered(pd, "chunk", label)? {
            let ids = ids(&MappedChunk::open(&cf).map_err(gar_err)?, far_col, label)?;
            if let Some(&v) = ids.iter().find(|&&v| v as usize >= far_vertices) {
                return Err(bad(
                    label,
                    format!("{}: neighbour {v} is outside {far_vertices}", cf.display()),
                ));
            }
            got += ids.len();
            neighbours.push(ids);
        }
        if got != edges {
            return Err(bad(
                label,
                format!("part {p}: {got} edges in its chunks, its offsets say {edges}"),
            ));
        }
        if let Ok(n) = read_count(&root.join(format!("edge_count{p}")), label)
            && n != edges
        {
            return Err(bad(
                label,
                format!("part {p}: edge_count{p} {n}, offsets {edges}"),
            ));
        }
        seen_rows += off.len() - 1;
        part_offsets.push(off);
    }
    if seen_rows != rows {
        return Err(bad(
            label,
            format!("{seen_rows} rows in the parts, vertex_count {rows}"),
        ));
    }
    let offsets = match part_offsets.as_slice() {
        [one] if one[0] == 0 => one.clone(),
        _ => {
            let mut all = Vec::with_capacity(rows + 1);
            all.push(0u64);
            let mut base = 0u64;
            for off in &part_offsets {
                all.extend(off[1..].iter().map(|o| base + o - off[0]));
                base += off[off.len() - 1] - off[0];
            }
            ScalarBuffer::from(all)
        }
    };
    let neighbours = match neighbours.len() {
        0 => ScalarBuffer::from(Vec::<u32>::new()),
        1 => neighbours.pop().expect("one"),
        _ => {
            let total = neighbours.iter().map(|n| n.len()).sum();
            let mut all = Vec::with_capacity(total);
            for n in &neighbours {
                all.extend_from_slice(n);
            }
            ScalarBuffer::from(all)
        }
    };
    Ok((rows, offsets, neighbours))
}