crates/kleene-gar/src/graph.rs
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, OnceLock};
use arrow_array::ArrayRef;
use arrow_buffer::ScalarBuffer;
use datafusion::error::{DataFusionError, Result};
use graphar::mapped::{MappedEdges, MappedGraph};
use kleene_sparse::CpuDevice;
use crate::chunked;
use crate::table::{GarTable, TableKind};
/// A one-chunk edge table's adjacency: buffers that share the mapping.
fn one_chunk(e: &MappedEdges) -> EdgeAdjacency {
let (out_offsets, out_neighbours) = e.shared_by_source();
let (in_offsets, in_neighbours) = e.shared_by_dest();
EdgeAdjacency {
sources: out_offsets.len().saturating_sub(1),
destinations: in_offsets.len().saturating_sub(1),
out_offsets,
out_neighbours,
in_offsets,
in_neighbours,
}
}
fn gar_err(e: graphar::GraphArError) -> DataFusionError {
DataFusionError::External(Box::new(e))
}
/// An edge type's three names.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct EdgeType {
/// The source vertex type.
pub src: String,
/// The edge name.
pub edge: String,
/// The destination vertex type.
pub dst: String,
}
impl EdgeType {
/// The three names.
pub fn new(src: &str, edge: &str, dst: &str) -> Self {
EdgeType {
src: src.into(),
edge: edge.into(),
dst: dst.into(),
}
}
/// The directory and table name: `src_edge_dst`.
pub fn table_name(&self) -> String {
format!("{}_{}_{}", self.src, self.edge, self.dst)
}
}
/// An edge type as compressed rows, both orders, sharing the mapped files: by source,
/// row `i`'s destinations are `dst[offsets[i]..offsets[i+1]]`; by destination, row `j`'s
/// sources likewise.
#[derive(Clone, Debug)]
pub struct EdgeAdjacency {
/// Source vertices (rows by source).
pub sources: usize,
/// Destination vertices (rows by destination).
pub destinations: usize,
/// By-source offsets (`sources + 1`).
pub out_offsets: ScalarBuffer<u64>,
/// By-source neighbours (destinations).
pub out_neighbours: ScalarBuffer<u32>,
/// By-destination offsets (`destinations + 1`).
pub in_offsets: ScalarBuffer<u64>,
/// By-destination neighbours (sources).
pub in_neighbours: ScalarBuffer<u32>,
}
/// An X.gar directory opened for reading: its vertex and edge types, found from the
/// directory tree when first asked for (edge types' three names from their `.edge.yml`
/// files when present, otherwise from the only split of the directory name into two
/// vertex types). Opening reads nothing but the directory's existence.
#[derive(Clone, Debug)]
pub struct GarGraph {
mapped: MappedGraph,
vertex_types: OnceLock<Vec<String>>,
edge_types: OnceLock<BTreeMap<String, EdgeType>>,
}
fn dir_names(dir: &Path) -> std::io::Result<Vec<String>> {
let mut out = Vec::new();
match std::fs::read_dir(dir) {
Ok(rd) => {
for e in rd {
let e = e?;
if e.file_type()?.is_dir()
&& let Ok(name) = e.file_name().into_string()
{
out.push(name);
}
}
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}
out.sort();
Ok(out)
}
/// The vertex types in the order the set's `<name>.graph.yml` lists them (its `vertices:`
/// items, `<type>.vertex.yml`), then any other vertex directory by name; with no graph info
/// file, by name. This order numbers the set's one id space ([`crate::IdSpace`]).
fn vertex_order(dir: &Path) -> Vec<String> {
let names = dir_names(&dir.join("vertex")).unwrap_or_default();
let mut ymls: Vec<std::path::PathBuf> = std::fs::read_dir(dir)
.into_iter()
.flatten()
.filter_map(|e| e.ok().map(|e| e.path()))
.filter(|p| {
p.file_name()
.and_then(|n| n.to_str())
.is_some_and(|n| n.ends_with(".graph.yml"))
})
.collect();
ymls.sort();
let text = ymls
.first()
.and_then(|p| std::fs::read_to_string(p).ok())
.unwrap_or_default();
let mut listed: Vec<String> = Vec::new();
let mut inside = false;
for line in text.lines() {
if !line.starts_with([' ', '\t', '-']) {
inside = line.trim_end() == "vertices:";
continue;
}
if !inside {
continue;
}
let item = line.trim().trim_start_matches('-').trim();
let item = item.trim_matches(['"', '\'']);
let file = item.rsplit('/').next().unwrap_or(item);
if let Some(t) = file.strip_suffix(".vertex.yml")
&& names.iter().any(|n| n == t)
&& !listed.iter().any(|n| n == t)
{
listed.push(t.to_string());
}
}
let rest: Vec<String> = names.into_iter().filter(|n| !listed.contains(n)).collect();
listed.extend(rest);
listed
}
/// `src_type`, `edge_type` and `dst_type` from an edge info file (top-level `key: value`
/// lines; nothing else of the YAML is read).
fn edge_info(path: &Path) -> Option<EdgeType> {
let text = std::fs::read_to_string(path).ok()?;
let get = |key: &str| {
text.lines().find_map(|l| {
l.strip_prefix(key)
.and_then(|r| r.strip_prefix(':'))
.map(|v| v.trim().trim_matches(['"', '\'']).to_string())
})
};
Some(EdgeType {
src: get("src_type")?,
edge: get("edge_type")?,
dst: get("dst_type")?,
})
}
impl GarGraph {
/// Open the X.gar directory `dir`.
pub fn open(dir: impl AsRef<Path>) -> Result<Self> {
let mapped = MappedGraph::open(dir.as_ref()).map_err(gar_err)?;
Ok(GarGraph {
mapped,
vertex_types: OnceLock::new(),
edge_types: OnceLock::new(),
})
}
fn edge_map(&self) -> &BTreeMap<String, EdgeType> {
self.edge_types.get_or_init(|| {
let dir = self.dir();
let mut edge_types = BTreeMap::new();
for name in dir_names(&dir.join("edge")).unwrap_or_default() {
let found = edge_info(&dir.join(format!("{name}.edge.yml")))
.filter(|t| t.table_name() == name)
.or_else(|| {
let vertex_types = self.vertex_types();
let splits: Vec<EdgeType> = vertex_types
.iter()
.filter_map(|s| {
name.strip_prefix(s.as_str())?
.strip_prefix('_')
.map(|r| (s, r))
})
.flat_map(|(s, rest)| {
vertex_types.iter().filter_map(move |d| {
let e = rest.strip_suffix(d.as_str())?.strip_suffix('_')?;
(!e.is_empty()).then(|| EdgeType::new(s, e, d))
})
})
.collect();
(splits.len() == 1).then(|| splits[0].clone())
});
if let Some(t) = found {
edge_types.insert(name, t);
}
}
edge_types
})
}
fn is_vertex_type(&self, name: &str) -> bool {
!name.is_empty()
&& !name.contains(['/', '\\', '\0'])
&& name != "."
&& name != ".."
&& self
.dir()
.join("vertex")
.join(name)
.join("vertex_count")
.is_file()
}
/// The directory.
pub fn dir(&self) -> &Path {
self.mapped.dir()
}
/// The vertex types: in the order the set's `<name>.graph.yml` lists them, then any
/// other by name (by name with no graph info file). The same on every open; the set's
/// id space ([`GarGraph::id_space`]) numbers them in this order.
pub fn vertex_types(&self) -> &[String] {
self.vertex_types.get_or_init(|| vertex_order(self.dir()))
}
/// The edge types, by table name.
pub fn edge_types(&self) -> impl Iterator<Item = (&str, &EdgeType)> {
self.edge_map().iter().map(|(k, v)| (k.as_str(), v))
}
/// The edge type named `table` (`src_edge_dst`).
pub fn edge_type(&self, table: &str) -> Option<&EdgeType> {
self.edge_map().get(table)
}
/// Every table name: vertex types, then edge types.
pub fn table_names(&self) -> Vec<String> {
self.vertex_types()
.iter()
.cloned()
.chain(self.edge_map().keys().cloned())
.collect()
}
/// The number of vertices of a type.
pub fn vertex_count(&self, vertex_type: &str) -> Result<u32> {
Ok(self.mapped.vertices(vertex_type).map_err(gar_err)?.count())
}
/// The stored column names of a vertex type, sorted.
pub fn vertex_columns(&self, vertex_type: &str) -> Result<Vec<String>> {
Ok(dir_names(&self.dir().join("vertex").join(vertex_type))?)
}
/// One stored vertex column as an Arrow array: mapped in place when the mapped reader
/// takes it (integers, byte strings, integer lists, no nulls), else, for a column
/// another writer wrote with nulls or of another type (signed, float, boolean, string,
/// any other), read from its Arrow IPC chunk onto the heap as the type it has. Either
/// way the column has one row per vertex.
pub fn vertex_column(&self, vertex_type: &str, column: &str) -> Result<ArrayRef> {
let vertices = self.mapped.vertices(vertex_type).map_err(gar_err)?;
let mapped = match vertices.column(column) {
Ok(col) => col,
Err(refused) => {
if !plain_name(column) {
return Err(gar_err(refused));
}
let path = self
.dir()
.join("vertex")
.join(vertex_type)
.join(column)
.join("chunk0");
return read_chunk(&path, column, vertices.count() as usize).map_err(|e| {
DataFusionError::Plan(format!(
"{vertex_type}.{column}: {e} (the mapped reader: {refused})"
))
});
}
};
let batch = mapped.chunk().batch();
batch
.column_by_name(column)
.cloned()
.ok_or_else(|| DataFusionError::Plan(format!("{vertex_type}.{column}: no such column")))
}
fn edges(&self, t: &EdgeType) -> Result<MappedEdges> {
self.mapped.edges(&t.src, &t.edge, &t.dst).map_err(gar_err)
}
/// The edge property names of an edge type, sorted.
pub fn edge_properties(&self, t: &EdgeType) -> Result<Vec<String>> {
let dir: PathBuf = self
.dir()
.join("edge")
.join(t.table_name())
.join("ordered_by_source");
Ok(dir_names(&dir)?
.into_iter()
.filter(|n| n != "adj_list" && n != "offset")
.collect())
}
/// One edge property (by-source row order) as an Arrow array: mapped in place when the
/// mapped reader takes it (integers, no nulls), else, for a property another writer
/// wrote with nulls or of another type (signed, float, boolean, string, any other),
/// read from its Arrow IPC chunk (`part0/chunk0`: one chunk of one part) onto the heap as the type it
/// has, one row per edge.
pub fn edge_property(&self, t: &EdgeType, name: &str) -> Result<ArrayRef> {
let col = match self.edges(t)?.property(name) {
Ok(col) => col,
Err(refused) => {
if !plain_name(name) {
return Err(gar_err(refused));
}
let path = self
.dir()
.join("edge")
.join(t.table_name())
.join("ordered_by_source")
.join(name)
.join("part0")
.join("chunk0");
let rows = self.adjacency(t)?.out_neighbours.len();
return read_chunk(&path, name, rows).map_err(|e| {
DataFusionError::Plan(format!(
"{}.{name}: {e} (the mapped reader: {refused})",
t.table_name()
))
});
}
};
col.chunk()
.batch()
.column_by_name(name)
.cloned()
.ok_or_else(|| {
DataFusionError::Plan(format!("{}.{name}: no such property", t.table_name()))
})
}
/// An edge type's adjacency, both orders. A table of one part in one chunk per order
/// shares the mapping (no copy); a table cut in several parts or chunks is joined once
/// into compressed rows (see the `chunked` module).
pub fn adjacency(&self, t: &EdgeType) -> Result<EdgeAdjacency> {
let edge_dir = self.dir().join("edge").join(t.table_name());
if !chunked::is_one_chunk(&edge_dir) {
let label = format!("edge type {}", t.table_name());
let count = |order: &str| -> Result<usize> {
let p = edge_dir.join(order).join("vertex_count");
let raw = std::fs::read(&p)?;
let b: [u8; 8] = raw.as_slice().try_into().map_err(|_| {
DataFusionError::Execution(format!("{}: a count is 8 bytes", p.display()))
})?;
Ok(i64::from_le_bytes(b).max(0) as usize)
};
let (ns, nd) = (count("ordered_by_source")?, count("ordered_by_dest")?);
let (sources, out_offsets, out_neighbours) =
chunked::read_order(&edge_dir, "ordered_by_source", nd, &label)?;
let (destinations, in_offsets, in_neighbours) =
chunked::read_order(&edge_dir, "ordered_by_dest", ns, &label)?;
if out_neighbours.len() != in_neighbours.len() {
return Err(DataFusionError::Execution(format!(
"{label}: {} edges by source, {} by destination",
out_neighbours.len(),
in_neighbours.len()
)));
}
return Ok(EdgeAdjacency {
sources,
destinations,
out_offsets,
out_neighbours,
in_offsets,
in_neighbours,
});
}
Ok(one_chunk(&self.edges(t)?))
}
/// [`GarGraph::adjacency`] with the checks of a one-chunk table (offsets, neighbours,
/// `back` rows of both orders) run in pieces on `device`'s threads, so each page of the
/// mapping is first touched there; the same adjacency, the same refusal of a bad set
/// (the first bad value by lowest piece). A table in several parts or chunks is read as
/// [`GarGraph::adjacency`] reads it.
pub fn adjacency_on(&self, t: &EdgeType, device: &CpuDevice) -> Result<EdgeAdjacency> {
let edge_dir = self.dir().join("edge").join(t.table_name());
if !chunked::is_one_chunk(&edge_dir) {
return self.adjacency(t);
}
let e = self
.mapped
.edges_unchecked(&t.src, &t.edge, &t.dst)
.map_err(gar_err)?;
let pieces = e.pieces(device.threads().max(1) * 4);
// One piece per share of the split, results in piece order: the first error found
// is the lowest failing piece's.
let one = device.clone().with_grain(1);
let bad = one
.split(pieces.len(), |r| {
r.into_iter().find_map(|i| e.check(&pieces[i]).err())
})
.into_iter()
.flatten()
.next();
if let Some(refused) = bad {
return Err(gar_err(refused));
}
Ok(one_chunk(&e.assume_checked()))
}
/// A vertex or edge type as a table.
pub fn table(&self, name: &str) -> Result<Option<Arc<GarTable>>> {
if self.is_vertex_type(name) {
return Ok(Some(Arc::new(GarTable::vertex(self, name)?)));
}
match self.edge_map().get(name) {
Some(t) => Ok(Some(Arc::new(GarTable::edge(self, t)?))),
None => Ok(None),
}
}
/// Whether `name` is a table, and which kind.
pub fn kind(&self, name: &str) -> Option<TableKind> {
if self.is_vertex_type(name) {
Some(TableKind::Vertex)
} else if self.edge_map().contains_key(name) {
Some(TableKind::Edge)
} else {
None
}
}
}
/// Whether `name` is one plain path component.
fn plain_name(name: &str) -> bool {
!(name.is_empty() || name == "." || name == ".." || name.contains(['/', '\\', '\0']))
}
/// Column `name` of the one record batch of the Arrow IPC file at `path` (a regular file,
/// no link), read onto the heap; refused unless it has `rows` rows.
fn read_chunk(path: &Path, name: &str, rows: usize) -> std::result::Result<ArrayRef, String> {
let (file, _) = graphar::mapped::open_regular(path).map_err(|e| e.to_string())?;
let reader = arrow_ipc::reader::FileReader::try_new(std::io::BufReader::new(file), None)
.map_err(|e| format!("{}: {e}", path.display()))?;
let mut batches = Vec::new();
for b in reader {
batches.push(b.map_err(|e| format!("{}: {e}", path.display()))?);
}
let [batch] = batches.as_slice() else {
return Err(format!(
"{}: {} record batches, a chunk holds one",
path.display(),
batches.len()
));
};
if batch.num_rows() != rows {
return Err(format!(
"{}: {} rows, the table has {rows}",
path.display(),
batch.num_rows()
));
}
batch
.column_by_name(name)
.cloned()
.ok_or_else(|| format!("{}: no column `{name}`", path.display()))
}