crates/kleene-ballista/src/spec.rs
//! Which graph a job runs on and how it is split: the same on the client, the scheduler and
//! every executor, carried in the plan as text.
use std::fmt;
use datafusion::error::{DataFusionError, Result};
use kleene_graph::SplitKey;
/// How the graph is split into parts (kleene-graph's [`SplitKey`], in a form that travels).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Key {
/// Parts by a hash of the node id ([`SplitKey::Hash`]).
Hash(u32),
/// Parts as blocks of ids starting at these ids, rising, the first 0
/// ([`SplitKey::Blocks`]).
Blocks(Vec<u64>),
/// A computed split of this many parts (`kleene_graph::computed_split`), made once and
/// saved beside the set (`kleene split-report --save`); read, never computed, here
/// ([`GraphSpec::split_key`]).
Computed(u32),
}
impl Key {
/// The number of parts the split makes.
pub fn parts(&self) -> usize {
match self {
Key::Hash(n) => *n as usize,
Key::Blocks(b) => b.len(),
Key::Computed(k) => *k as usize,
}
}
}
/// A graph on every executor's disk at the same path, one edge type of it, and its split.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GraphSpec {
/// The X.gar directory, the same path on every machine.
pub path: String,
/// The edge type (its table name, as `v_link_v`).
pub edge: String,
/// The split.
pub key: Key,
}
impl GraphSpec {
/// The text that names the graph and its split, as kept in a plan and as part of the
/// executors' state keys.
pub fn encode(&self) -> String {
let key = match &self.key {
Key::Hash(n) => format!("hash:{n}"),
Key::Computed(k) => format!("computed:{k}"),
Key::Blocks(b) => format!(
"blocks:{}",
b.iter().map(u64::to_string).collect::<Vec<_>>().join(",")
),
};
format!("{}|{}|{}", self.path, self.edge, key)
}
/// The spec [`GraphSpec::encode`] wrote.
pub fn decode(text: &str) -> Result<Self> {
let bad = || DataFusionError::Plan(format!("not a graph spec: {text}"));
let mut it = text.split('|');
let (path, edge, key) = match (it.next(), it.next(), it.next(), it.next()) {
(Some(p), Some(e), Some(k), None) => (p, e, k),
_ => return Err(bad()),
};
let key = match key.split_once(':') {
Some(("hash", n)) => Key::Hash(n.parse().map_err(|_| bad())?),
Some(("computed", k)) => Key::Computed(k.parse().map_err(|_| bad())?),
Some(("blocks", b)) => Key::Blocks(
b.split(',')
.map(|x| x.parse().map_err(|_| bad()))
.collect::<Result<_>>()?,
),
_ => return Err(bad()),
};
Ok(GraphSpec {
path: path.to_string(),
edge: edge.to_string(),
key,
})
}
/// The split's key: hash and id blocks as they are; a computed split read from the
/// store beside the set (`<set>.kix`, kleene-index [`kleene_index::load_computed_split`],
/// snapshot 0, checked against the set's node count), an error when none is saved.
pub fn split_key(&self) -> Result<SplitKey> {
match &self.key {
Key::Hash(n) => Ok(SplitKey::Hash(*n)),
Key::Blocks(b) => Ok(SplitKey::Blocks(b.clone())),
Key::Computed(k) => {
let ext = |e: kleene_index::IndexError| DataFusionError::Execution(e.to_string());
let g = kleene_gar::GarGraph::open(&self.path)?;
let t = g.edge_type(&self.edge).ok_or_else(|| {
DataFusionError::Plan(format!("no edge type {} in {}", self.edge, self.path))
})?;
let nodes = g.vertex_count(&t.src.clone())? as usize;
let mut store = kleene_index::Store::beside(&self.path).map_err(ext)?;
if store.dir().is_none() {
// A set without a root file: the store keyed as it was saved (its own
// key, written in the store), not by a fingerprint of every edge.
let dir = std::path::PathBuf::from(format!("{}.kix", self.path));
if let Ok(key) = std::fs::read(dir.join("root")) {
store = kleene_index::Store::keyed(dir, key).map_err(ext)?;
}
}
let kept = kleene_index::load_computed_split(&store, &self.edge, 0, *k, nodes)
.map_err(ext)?;
let (_, split) = kept.ok_or_else(|| {
DataFusionError::Plan(format!(
"no saved computed split of {k} parts for {} ({}): make it with \
`kleene split-report --save {} --edge {} --parts {k}`",
self.path, self.edge, self.path, self.edge
))
})?;
Ok(split.key())
}
}
}
/// A spec refuses a path or edge name with the separator in it.
pub fn new(path: impl Into<String>, edge: impl Into<String>, key: Key) -> Result<Self> {
let (path, edge) = (path.into(), edge.into());
if path.contains('|') || edge.contains('|') {
return Err(DataFusionError::Plan(format!(
"a graph path or edge name holds `|`: {path} {edge}"
)));
}
Ok(GraphSpec { path, edge, key })
}
}
impl fmt::Display for GraphSpec {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(&self.encode())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_spec_travels_as_text() {
for key in [Key::Hash(3), Key::Blocks(vec![0, 10, 20]), Key::Computed(4)] {
let s = GraphSpec::new("/data/rmat22", "v_link_v", key).unwrap();
assert_eq!(GraphSpec::decode(&s.encode()).unwrap(), s);
}
assert!(GraphSpec::new("/a|b", "e", Key::Hash(2)).is_err());
assert!(GraphSpec::decode("/a|e").is_err());
assert!(GraphSpec::decode("/a|e|ring:3").is_err());
}
}