crates/kleene-ballista/src/state.rs
//! What an executor keeps between tasks: the graph and its split (built once per executor,
//! kept for every job on it: the fork's executor-long state, CLONE mode, keyed by the
//! [`GraphSpec`]), and each query's part side between the rounds of its job (job state,
//! dropped with the job).
use std::sync::{Arc, Mutex};
use ballista_core::executor_state::TaskState;
use datafusion::error::{DataFusionError, Result};
use datafusion::execution::TaskContext;
use kleene_gar::GarGraph;
use kleene_graph::{BfsState, Graph, Split, SplitKey};
use kleene_index::{EdgeSource, GarEdges, LoadKey, LoadedPart, Loads, Transposed};
use kleene_sparse::{BoolOrAnd, CpuBackend, CpuDevice, Csr, Pattern};
use crate::spec::GraphSpec;
fn ext(e: impl std::fmt::Display) -> DataFusionError {
DataFusionError::Execution(e.to_string())
}
/// The structural matrix of edge type `edge` of the X.gar at `path`.
pub fn read_graph(path: &str, edge: &str) -> Result<Csr<u8>> {
let g = GarGraph::open(path)?;
let t = g
.edge_type(edge)
.ok_or_else(|| DataFusionError::Plan(format!("no edge type {edge} in {path}")))?
.clone();
let adj = g.adjacency(&t)?;
Csr::<u8>::with_pattern(
Pattern::trusted(
adj.sources,
adj.destinations,
adj.out_offsets.clone(),
adj.out_neighbours.clone(),
"by source",
)
.map_err(ext)?,
None,
)
.map_err(ext)
}
/// `spec`'s graph split as it says (the client builds the same to locate the sources).
pub fn split_of(spec: &GraphSpec) -> Result<Split<u8>> {
let a = read_graph(&spec.path, &spec.edge)?;
Split::from_csr(&a, &spec.split_key()?, BoolOrAnd).map_err(ext)
}
/// The executor's task state, which every operator here needs.
pub fn task_state(context: &TaskContext) -> Result<Arc<TaskState>> {
TaskState::from_context(context).ok_or_else(|| {
DataFusionError::Internal(
"the executor keeps no state: kleene-ballista needs the fork's executor state".into(),
)
})
}
/// The executor's device for kleene's kernels: one per executor, every core.
pub async fn device(state: &TaskState) -> Result<Arc<CpuDevice>> {
state
.executor_state("kleene/device", || async { Ok((CpuDevice::default(), 0)) })
.await
}
/// `spec`'s split key on this executor, made on the first call and kept (a computed
/// split's saved list is read once per executor, not per task).
pub async fn split_key(state: &TaskState, spec: &GraphSpec) -> Result<Arc<SplitKey>> {
let spec = spec.clone();
state
.executor_state(&format!("kleene/key/{spec}"), || async move {
let key = tokio::task::spawn_blocking(move || spec.split_key())
.await
.map_err(ext)??;
let bytes = match &key {
SplitKey::Property(v) => v.len() * 4,
SplitKey::Blocks(b) => b.len() * 8,
SplitKey::Hash(_) => 0,
};
Ok((key, bytes))
})
.await
}
/// The key of query `query`'s state for part `p`.
pub fn query_key(query: &str, p: u32) -> String {
format!("kleene/query/{query}/{p}")
}
/// A query's state for one part, kept across the rounds and taken by the collect step
/// (`None` until the part's first step).
pub type Kept<T> = Mutex<Option<T>>;
/// The executor's loaded parts and whole graphs ([`Loads`], the core's load-ahead store),
/// kept for every job.
pub async fn loads(state: &TaskState) -> Result<Arc<Loads>> {
state
.executor_state("kleene/loads", || async { Ok((Loads::new(), 0)) })
.await
}
/// `spec`'s edges as the core reads them.
pub fn source(path: &str, edge: &str) -> GarEdges {
GarEdges {
path: path.into(),
edge: edge.to_string(),
}
}
/// Part `p` of `spec` alone ([`kleene_graph::Split::part_only`], through [`Loads`]):
/// loaded ahead, or now; kept per executor after the first call, so a round finds it
/// without the load key (a computed split's key holds every node's part).
pub async fn part_alone(state: &TaskState, spec: &GraphSpec, p: u32) -> Result<Arc<LoadedPart>> {
let src = source(&spec.path, &spec.edge);
kept_part(state, spec, p, "part", src).await
}
/// Part `p` of `spec`'s transpose alone, split by the same key (the same ids as
/// [`part_alone`]'s): the weak components' other direction, through [`Loads`] like the
/// part, kept per executor.
pub async fn part_t_alone(state: &TaskState, spec: &GraphSpec, p: u32) -> Result<Arc<LoadedPart>> {
let src = Transposed(source(&spec.path, &spec.edge));
kept_part(state, spec, p, "part-t", src).await
}
async fn kept_part<S: EdgeSource + 'static>(
state: &TaskState,
spec: &GraphSpec,
p: u32,
what: &str,
src: S,
) -> Result<Arc<LoadedPart>> {
let (loads, device) = (loads(state).await?, device(state).await?);
let key = split_key(state, spec).await?;
let kept = state
.executor_state(&format!("kleene/{what}/{spec}/{p}"), || async move {
let at = LoadKey::part(&src, 0, (*key).clone(), p);
let part = tokio::task::spawn_blocking(move || loads.get_or_load(&src, &at, &device))
.await
.map_err(ext)?
.map_err(ext)?;
// The memory is the load store's; this is a handle to it.
Ok((part, 0))
})
.await?;
Ok((*kept).clone())
}
/// The whole graph at `path` (edge type `edge`) through [`Loads`]: loaded ahead, or now.
pub async fn whole_graph(state: &TaskState, path: &str, edge: &str) -> Result<Arc<LoadedPart>> {
let (loads, device) = (loads(state).await?, device(state).await?);
let src = source(path, edge);
let at = LoadKey::whole(&src, 0);
tokio::task::spawn_blocking(move || loads.get_or_load(&src, &at, &device).map_err(ext))
.await
.map_err(ext)?
}
/// Search buffers a finished query left for the next query on a part, kept per executor.
pub async fn spare(
state: &TaskState,
spec: &GraphSpec,
p: u32,
) -> Result<Arc<Kept<BfsState<CpuBackend>>>> {
state
.executor_state(&format!("kleene/spare/{spec}/{p}"), || async {
Ok((Mutex::new(None), 0))
})
.await
}
/// Where a part's step finds its part: the part alone.
#[derive(Debug, Clone)]
pub enum PartSrc {
/// This part only, and the number of parts.
Alone(Arc<LoadedPart>, usize),
}
impl PartSrc {
/// Part `p` (for [`PartSrc::Alone`], the part it holds).
pub fn part(&self, p: u32) -> &kleene_graph::Part<u8> {
match self {
PartSrc::Alone(l, _) => {
let _ = p;
l.part()
}
}
}
/// The split's ids.
pub fn ids(&self) -> &kleene_graph::SplitIds {
match self {
PartSrc::Alone(l, _) => l.ids(),
}
}
/// The number of parts.
pub fn parts(&self) -> usize {
match self {
PartSrc::Alone(_, n) => *n,
}
}
/// Part `p`'s graph (a copy the query's side owns).
pub fn graph(&self, p: u32, device: &CpuDevice) -> Result<Graph<CpuBackend>> {
Ok(match self {
PartSrc::Alone(l, _) => {
let _ = (p, device);
(**l.graph()).clone()
}
})
}
}