crates/kleene-datafusion/src/lib.rs
//! kleene's hop and a part's local fixpoint as DataFusion execution operators.
//!
//! | Operator | In | Out | Kernel |
//! |---|---|---|---|
//! | [`HopExec`] | Arrow batches of frontier node ids (one column of its input) | the nodes one hop reaches, each once, ids rising, column `id` | kleene-sparse's `vxm` over (or, and) on the graph's matrix |
//! | [`LocalFixpointExec`] | Arrow batches of start node ids of one part of a [`kleene_graph::Split`] | what the starts newly reach inside the part (`border` false) and the border nodes those reach in other parts (`border` true), columns `id`, `part`, `border` | kleene-graph's [`ReachPart`] (the engine's breadth-first search on the part's graph), kept in a [`KeptPart`] between rounds and queries |
//!
//! An adapter only: the operators hold a shared reference to their matrix (the local
//! fixpoint: to its [`KeptPart`], which a runner keeps where the part sits) and map Arrow
//! columns onto the core's kernels and back; nothing is evaluated here. What a codec needs
//! to rebuild an operator elsewhere is plain data: [`HopSpec`], [`LocalFixpointSpec`]. Both read their whole
//! input first (a hop is of the whole frontier) and give one output partition. They use the
//! few DataFusion calls every operator needs (its plan properties, children, `execute`), so
//! a change of DataFusion version is a dependency change.
use std::fmt;
use std::sync::{Arc, Mutex};
use arrow_array::{Array, ArrayRef, BooleanArray, RecordBatch, UInt32Array, UInt64Array};
use arrow_schema::{DataType, Field, Schema, SchemaRef};
use datafusion::arrow::compute::cast;
use datafusion::common::tree_node::TreeNodeRecursion;
use datafusion::error::{DataFusionError, Result};
use datafusion::execution::TaskContext;
use datafusion::physical_expr::{EquivalenceProperties, PhysicalExpr};
use datafusion::physical_plan::execution_plan::{Boundedness, EmissionType};
use datafusion::physical_plan::stream::RecordBatchStreamAdapter;
use datafusion::physical_plan::{
DisplayAs, DisplayFormatType, ExecutionPlan, Partitioning, PlanProperties,
SendableRecordBatchStream,
};
use futures::{StreamExt, TryStreamExt};
use kleene_graph::{BfsState, Graph, Part, ReachPart, SplitIds};
use kleene_sparse::{BoolOrAnd, CpuBackend, CpuDevice, SparseBackend, Vector};
/// The output column of node ids.
pub const ID: &str = "id";
/// [`LocalFixpointExec`]'s column of each node's part.
pub const PART: &str = "part";
/// [`LocalFixpointExec`]'s column: true for a border node (another part's).
pub const BORDER: &str = "border";
fn ext(e: impl fmt::Display) -> DataFusionError {
DataFusionError::Execution(e.to_string())
}
fn properties(schema: &SchemaRef) -> Arc<PlanProperties> {
Arc::new(PlanProperties::new(
EquivalenceProperties::new(schema.clone()),
Partitioning::UnknownPartitioning(1),
EmissionType::Final,
Boundedness::Bounded,
))
}
/// Every id of column `column` in every partition of `input`, as `u64`.
async fn read_ids(
input: Arc<dyn ExecutionPlan>,
column: usize,
context: Arc<TaskContext>,
) -> Result<Vec<u64>> {
let mut ids = Vec::new();
let parts = input.properties().partitioning.partition_count();
for p in 0..parts {
let mut s = input.execute(p, context.clone())?;
while let Some(batch) = s.next().await {
let batch = batch?;
if column >= batch.num_columns() {
return Err(DataFusionError::Plan(format!(
"no column {column} in the operator's input of {} columns",
batch.num_columns()
)));
}
let c = cast(batch.column(column), &DataType::UInt64)?;
let c = c
.as_any()
.downcast_ref::<UInt64Array>()
.ok_or_else(|| ext("node ids cast to u64"))?;
if c.null_count() > 0 {
return Err(DataFusionError::Execution(
"a null node id in the operator's input".to_string(),
));
}
ids.extend_from_slice(c.values());
}
}
Ok(ids)
}
/// Batches of at most `size` rows of `columns`.
fn batches(schema: &SchemaRef, columns: Vec<ArrayRef>, size: usize) -> Result<Vec<RecordBatch>> {
let n = columns.first().map_or(0, |c| c.len());
let size = size.max(1);
let mut out = Vec::with_capacity(n.div_ceil(size));
let mut at = 0;
while at < n {
let len = size.min(n - at);
let cols = columns.iter().map(|c| c.slice(at, len)).collect();
out.push(RecordBatch::try_new(schema.clone(), cols)?);
at += len;
}
Ok(out)
}
fn stream(
schema: SchemaRef,
work: impl std::future::Future<Output = Result<Vec<RecordBatch>>> + Send + 'static,
) -> SendableRecordBatchStream {
let s = futures::stream::once(work)
.map_ok(|bs| futures::stream::iter(bs.into_iter().map(Ok)))
.try_flatten();
Box::pin(RecordBatchStreamAdapter::new(schema, s))
}
fn one_child(name: &str, children: Vec<Arc<dyn ExecutionPlan>>) -> Result<Arc<dyn ExecutionPlan>> {
match <[_; 1]>::try_from(children) {
Ok([c]) => Ok(c),
Err(c) => Err(DataFusionError::Plan(format!(
"{name} takes one input, {} given",
c.len()
))),
}
}
/// One hop as an operator: the frontier is column `column` of its input (node ids, any
/// unsigned or signed integer type); the output is every node an edge leads to from it,
/// each once, rising, in column [`ID`] (`u64`). The kernel is kleene-sparse's `vxm` over
/// (or, and) on the graph's adjacency, the same call the engine makes.
#[derive(Debug)]
pub struct HopExec {
input: Arc<dyn ExecutionPlan>,
column: usize,
graph: Arc<Graph<CpuBackend>>,
device: CpuDevice,
schema: SchemaRef,
props: Arc<PlanProperties>,
}
impl HopExec {
/// The hop along `graph` of column `column` of `input`, run on `device`.
pub fn new(
input: Arc<dyn ExecutionPlan>,
column: usize,
graph: Arc<Graph<CpuBackend>>,
device: CpuDevice,
) -> Self {
let schema = Arc::new(Schema::new(vec![Field::new(ID, DataType::UInt64, false)]));
let props = properties(&schema);
HopExec {
input,
column,
graph,
device,
schema,
props,
}
}
/// The operator from its spec.
pub fn from_spec(
spec: HopSpec,
input: Arc<dyn ExecutionPlan>,
graph: Arc<Graph<CpuBackend>>,
device: CpuDevice,
) -> Self {
HopExec::new(input, spec.column as usize, graph, device)
}
/// Its spec.
pub fn spec(&self) -> HopSpec {
HopSpec {
column: self.column as u32,
}
}
/// The hop on the core's kernel, ids in hand: the targets of `frontier`'s edges, rising.
pub fn hop(
graph: &Graph<CpuBackend>,
frontier: &[u64],
device: &CpuDevice,
) -> Result<Vec<u32>> {
let n = graph.vertices();
let f: Vec<u32> = frontier
.iter()
.map(|&v| {
u32::try_from(v)
.ok()
.filter(|&v| (v as usize) < n)
.ok_or_else(|| ext(format!("node {v} past the graph's {n} nodes")))
})
.collect::<Result<_>>()?;
let x = Vector::from_indices(n, &f, 1u8).map_err(ext)?;
let y = CpuBackend::vxm(&x, graph.out(), None, BoolOrAnd, device).map_err(ext)?;
Ok(CpuBackend::indices(&y))
}
}
impl DisplayAs for HopExec {
fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"HopExec: column={}, nodes={}, edges={}",
self.column,
self.graph.vertices(),
self.graph.edges()
)
}
}
impl ExecutionPlan for HopExec {
fn name(&self) -> &str {
"HopExec"
}
fn properties(&self) -> &Arc<PlanProperties> {
&self.props
}
fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
vec![&self.input]
}
fn apply_expressions(
&self,
_f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
) -> Result<TreeNodeRecursion> {
Ok(TreeNodeRecursion::Continue)
}
fn with_new_children(
self: Arc<Self>,
children: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>> {
Ok(Arc::new(HopExec::new(
one_child("HopExec", children)?,
self.column,
self.graph.clone(),
self.device.clone(),
)))
}
fn execute(
&self,
partition: usize,
context: Arc<TaskContext>,
) -> Result<SendableRecordBatchStream> {
if partition != 0 {
return Err(DataFusionError::Plan(format!(
"HopExec has one partition, {partition} asked"
)));
}
let (input, column, graph, device, schema) = (
self.input.clone(),
self.column,
self.graph.clone(),
self.device.clone(),
self.schema.clone(),
);
let size = context.session_config().batch_size();
let out = schema.clone();
Ok(stream(schema, async move {
let frontier = read_ids(input, column, context).await?;
let reached = HopExec::hop(&graph, &frontier, &device)?;
let ids: ArrayRef = Arc::new(UInt64Array::from_iter_values(
reached.into_iter().map(u64::from),
));
batches(&out, vec![ids], size)
}))
}
}
/// One round of a part's local fixpoint as an operator: the starts are column `column` of
/// its input (split ids of this part's nodes); the part's kept side ([`KeptPart`], a
/// [`ReachPart`]: the engine's breadth-first search on the part's graph, entering only nodes
/// it has not reached) hops inside the part until a hop finds nothing new, and the operator
/// gives back the nodes newly reached (column [`BORDER`] false, [`PART`] this part) and the
/// border nodes they lead to (true, their part), ids in the split's id space, each once. A
/// start of another part is refused.
#[derive(Debug)]
pub struct LocalFixpointExec {
input: Arc<dyn ExecutionPlan>,
column: usize,
kept: Arc<KeptPart>,
device: CpuDevice,
schema: SchemaRef,
props: Arc<PlanProperties>,
}
/// A part of a split kept between rounds and between queries: the part, the split's ids
/// and the part's reach side ([`ReachPart`]: its graph, search buffers and what it has
/// reached). A runner over machines keeps it where the part sits and hands it to each
/// round's [`LocalFixpointExec`]; one round's work is [`KeptPart::round`].
#[derive(Debug)]
pub struct KeptPart {
part: Arc<Part<u8>>,
ids: Arc<SplitIds>,
side: Mutex<Option<ReachPart<CpuBackend>>>,
}
impl KeptPart {
/// Part `part` of the split with `ids`, searched on `graph` (the part's inner matrix as
/// a [`Graph`]); nothing reached yet.
pub fn new(
part: Arc<Part<u8>>,
ids: Arc<SplitIds>,
graph: Graph<CpuBackend>,
device: &CpuDevice,
) -> Self {
let state = BfsState::new(graph.vertices(), device);
let side = ReachPart::new(&part, ids.parts(), graph, state);
KeptPart {
part,
ids,
side: Mutex::new(Some(side)),
}
}
/// The part.
pub fn part(&self) -> &Part<u8> {
&self.part
}
/// The split's ids.
pub fn ids(&self) -> &SplitIds {
&self.ids
}
fn with<R>(&self, f: impl FnOnce(&mut ReachPart<CpuBackend>) -> Result<R>) -> Result<R> {
let mut g = self.side.lock().unwrap_or_else(|e| e.into_inner());
let side = g
.as_mut()
.ok_or_else(|| ext("the part's side was lost in a failed restart"))?;
f(side)
}
/// What the part has reached since the last [`KeptPart::restart`], split ids rising.
pub fn reached(&self) -> Result<Vec<u64>> {
let base = self.part.base();
self.with(|s| Ok(s.reached().iter().map(|&l| base + l as u64).collect()))
}
/// A new query: nothing reached (the graph and the search buffers are kept).
pub fn restart(&self) {
let mut g = self.side.lock().unwrap_or_else(|e| e.into_inner());
if let Some(side) = g.take() {
let (graph, state, _) = side.into_parts();
*g = Some(ReachPart::new(&self.part, self.ids.parts(), graph, state));
}
}
/// One round from `starts` (split ids of this part; any order, repeats allowed):
/// `(newly reached split ids, (border id, its part))`, both rising, each once.
#[allow(clippy::type_complexity)]
pub fn round(&self, starts: &[u64], device: &CpuDevice) -> Result<(Vec<u64>, Vec<(u64, u32)>)> {
let p = self.part.index();
let mut arrivals: Vec<(u32, u8)> = starts
.iter()
.map(|&s| match self.ids.locate(s) {
Some((q, l)) if q == p => Ok((l, 1)),
_ => Err(ext(format!("node {s} is not in part {p}"))),
})
.collect::<Result<_>>()?;
let (part, ids) = (&self.part, &self.ids);
self.with(|side| {
let before: Vec<u32> = side.reached().to_vec();
let sends = side.step(part, ids, &mut arrivals, device).map_err(ext)?;
let mut fresh = Vec::new();
let mut k = 0;
for &l in side.reached() {
while k < before.len() && before[k] < l {
k += 1;
}
if k == before.len() || before[k] != l {
fresh.push(part.base() + l as u64);
}
}
let mut border: Vec<(u64, u32)> = (0..sends.len())
.map(|k| {
(
ids.base(sends.part[k]) + sends.node[k] as u64,
sends.part[k],
)
})
.collect();
border.sort_unstable();
border.dedup();
Ok((fresh, border))
})
}
}
/// What a codec needs to rebuild a [`HopExec`] elsewhere (its input and graph come from
/// the plan and the runner).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct HopSpec {
/// The input's column of node ids.
pub column: u32,
}
/// What a codec needs to rebuild a [`LocalFixpointExec`] elsewhere: the input column and the
/// part's number (the runner gives the [`KeptPart`] of that number).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LocalFixpointSpec {
/// The input's column of start ids.
pub column: u32,
/// The part.
pub part: u32,
}
impl HopSpec {
/// Four bytes, little-endian.
pub fn to_bytes(&self) -> Vec<u8> {
self.column.to_le_bytes().to_vec()
}
/// The spec [`HopSpec::to_bytes`] wrote.
pub fn from_bytes(b: &[u8]) -> Result<Self> {
let b: [u8; 4] = b
.try_into()
.map_err(|_| ext(format!("a hop spec of {} bytes, 4 wanted", b.len())))?;
Ok(HopSpec {
column: u32::from_le_bytes(b),
})
}
}
impl LocalFixpointSpec {
/// Eight bytes, little-endian: the column, then the part.
pub fn to_bytes(&self) -> Vec<u8> {
let mut v = self.column.to_le_bytes().to_vec();
v.extend(self.part.to_le_bytes());
v
}
/// The spec [`LocalFixpointSpec::to_bytes`] wrote.
pub fn from_bytes(b: &[u8]) -> Result<Self> {
if b.len() != 8 {
return Err(ext(format!(
"a local fixpoint spec of {} bytes, 8 wanted",
b.len()
)));
}
let w = |i: usize| u32::from_le_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]);
Ok(LocalFixpointSpec {
column: w(0),
part: w(4),
})
}
}
impl LocalFixpointExec {
/// One round of the part kept in `kept`, from column `column` of `input`, run on
/// `device`. A second execution goes on from what the part has reached.
pub fn new(
input: Arc<dyn ExecutionPlan>,
column: usize,
kept: Arc<KeptPart>,
device: CpuDevice,
) -> Self {
let schema = Arc::new(Schema::new(vec![
Field::new(ID, DataType::UInt64, false),
Field::new(PART, DataType::UInt32, false),
Field::new(BORDER, DataType::Boolean, false),
]));
let props = properties(&schema);
LocalFixpointExec {
input,
column,
kept,
device,
schema,
props,
}
}
/// The operator from its spec: `kept` must be the spec's part.
pub fn from_spec(
spec: LocalFixpointSpec,
input: Arc<dyn ExecutionPlan>,
kept: Arc<KeptPart>,
device: CpuDevice,
) -> Result<Self> {
if kept.part().index() != spec.part {
return Err(ext(format!(
"the spec's part {} given part {}",
spec.part,
kept.part().index()
)));
}
Ok(LocalFixpointExec::new(
input,
spec.column as usize,
kept,
device,
))
}
/// Its spec.
pub fn spec(&self) -> LocalFixpointSpec {
LocalFixpointSpec {
column: self.column as u32,
part: self.kept.part().index(),
}
}
/// The part it runs.
pub fn kept(&self) -> &Arc<KeptPart> {
&self.kept
}
/// The local fixpoint on the core, ids in hand, from nothing kept: `(reached split ids,
/// (border id, its part))`, both rising.
#[allow(clippy::type_complexity)]
pub fn run(
part: &Part<u8>,
graph: &Graph<CpuBackend>,
ids: &SplitIds,
starts: &[u64],
device: &CpuDevice,
) -> Result<(Vec<u64>, Vec<(u64, u32)>)> {
let kept = KeptPart::new(
Arc::new(part.clone()),
Arc::new(ids.clone()),
graph.clone(),
device,
);
kept.round(starts, device)
}
}
impl DisplayAs for LocalFixpointExec {
fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"LocalFixpointExec: column={}, part={}, nodes={}, border edges={}",
self.column,
self.kept.part().index(),
self.kept.part().count(),
self.kept.part().border().len()
)
}
}
impl ExecutionPlan for LocalFixpointExec {
fn name(&self) -> &str {
"LocalFixpointExec"
}
fn properties(&self) -> &Arc<PlanProperties> {
&self.props
}
fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
vec![&self.input]
}
fn apply_expressions(
&self,
_f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
) -> Result<TreeNodeRecursion> {
Ok(TreeNodeRecursion::Continue)
}
fn with_new_children(
self: Arc<Self>,
children: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>> {
Ok(Arc::new(LocalFixpointExec::new(
one_child("LocalFixpointExec", children)?,
self.column,
self.kept.clone(),
self.device.clone(),
)))
}
fn execute(
&self,
partition: usize,
context: Arc<TaskContext>,
) -> Result<SendableRecordBatchStream> {
if partition != 0 {
return Err(DataFusionError::Plan(format!(
"LocalFixpointExec has one partition, {partition} asked"
)));
}
let (input, column, kept, device, schema) = (
self.input.clone(),
self.column,
self.kept.clone(),
self.device.clone(),
self.schema.clone(),
);
let size = context.session_config().batch_size();
let out = schema.clone();
Ok(stream(schema, async move {
let starts = read_ids(input, column, context).await?;
let (reached, border) = kept.round(&starts, &device)?;
let part = kept.part();
let n = reached.len();
let id: ArrayRef = Arc::new(UInt64Array::from_iter_values(
reached.iter().copied().chain(border.iter().map(|b| b.0)),
));
let pt: ArrayRef = Arc::new(UInt32Array::from_iter_values(
std::iter::repeat_n(part.index(), n).chain(border.iter().map(|b| b.1)),
));
let bd: ArrayRef = Arc::new(BooleanArray::from_iter(
(0..n)
.map(|_| Some(false))
.chain(border.iter().map(|_| Some(true))),
));
batches(&out, vec![id, pt, bd], size)
}))
}
}