crates/kleene-ballista/src/codec.rs
//! The plan codec the client, the scheduler and every executor share: kleene's operators
//! behind a leading byte, everything else Ballista's own codec.
use std::sync::Arc;
use ballista_core::serde::BallistaPhysicalExtensionCodec;
use datafusion::error::{DataFusionError, Result};
use datafusion::execution::TaskContext;
use datafusion::physical_plan::ExecutionPlan;
use datafusion_proto::physical_plan::{PhysicalExtensionCodec, PhysicalProtoConverterExtension};
use crate::exec::{CollectExec, Job, Query, StepExec, routes_of};
use crate::spec::GraphSpec;
use crate::whole::{AnswerExec, EndExec, SliceExec, WholeJob};
const STEP: u8 = b'S';
const COLLECT: u8 = b'C';
const SLICE: u8 = b'L';
const ANSWER: u8 = b'A';
const END: u8 = b'E';
const BALLISTA: u8 = b'B';
fn encode_job(job: &Job, buf: &mut Vec<u8>) {
let machines = job
.machines
.as_ref()
.map_or("-".to_string(), |m| m.join(","));
let levels = if job.levels.is_empty() {
"-".to_string()
} else {
crate::exec::join(&job.levels)
};
let text = format!(
"{}\n{}\n{}\n{}\n{}\n{}",
job.kind.name(),
job.query,
crate::exec::join(&job.woken),
machines,
levels,
job.spec.encode()
);
buf.extend_from_slice(text.as_bytes());
}
fn decode_job(bytes: &[u8]) -> Result<Job> {
let bad = |what: &str| DataFusionError::Internal(format!("a kleene operator's {what}"));
let text = std::str::from_utf8(bytes).map_err(|_| bad("text"))?;
let mut it = text.splitn(6, '\n');
let mut next = |what: &str| it.next().ok_or_else(|| bad(what));
let kind = Query::parse(next("query kind")?)?;
let query = next("query id")?.to_string();
let woken = next("woken parts")?
.split(',')
.map(|p| p.parse().map_err(|_| bad("woken parts")))
.collect::<Result<Vec<u32>>>()?;
let machines = match next("machines")? {
"-" => None,
m => Some(m.split(',').map(str::to_string).collect()),
};
let levels = match next("levels")? {
"-" => Vec::new(),
l => l
.split(',')
.map(|x| x.parse().map_err(|_| bad("levels")))
.collect::<Result<_>>()?,
};
let spec = GraphSpec::decode(next("graph")?)?;
Ok(Job {
spec,
query,
kind,
woken,
machines,
levels,
})
}
/// kleene's operators and Ballista's own ([`BallistaPhysicalExtensionCodec`]).
#[derive(Debug, Default)]
pub struct KleeneCodec {
ballista: BallistaPhysicalExtensionCodec,
}
impl PhysicalExtensionCodec for KleeneCodec {
fn try_decode(
&self,
buf: &[u8],
inputs: &[Arc<dyn ExecutionPlan>],
ctx: &TaskContext,
proto_converter: &dyn PhysicalProtoConverterExtension,
) -> Result<Arc<dyn ExecutionPlan>> {
match buf.split_first() {
Some((&STEP, rest)) => {
let job = decode_job(rest)?;
let routes = Arc::new(routes_of(&job.woken, job.spec.key.parts())?);
let input = inputs.first().cloned().ok_or_else(|| {
DataFusionError::Internal("StepExec decoded without its input".into())
})?;
Ok(Arc::new(StepExec::new(input, job, routes)))
}
Some((&COLLECT, rest)) => {
let input = inputs.first().cloned().ok_or_else(|| {
DataFusionError::Internal("CollectExec decoded without its input".into())
})?;
Ok(Arc::new(CollectExec::new(input, decode_job(rest)?)))
}
Some((&SLICE, rest)) | Some((&ANSWER, rest)) => {
let job =
WholeJob::decode(std::str::from_utf8(rest).map_err(|_| {
DataFusionError::Internal("a whole-graph job's text".into())
})?)?;
let input = inputs.first().cloned().ok_or_else(|| {
DataFusionError::Internal("a whole-graph operator without its input".into())
})?;
Ok(if buf[0] == SLICE {
Arc::new(SliceExec::new(input, job))
} else {
Arc::new(AnswerExec::new(input, job))
})
}
Some((&END, rest)) => {
let machines = std::str::from_utf8(rest)
.ok()
.and_then(|t| t.parse().ok())
.ok_or_else(|| DataFusionError::Internal("an EndExec's machines".into()))?;
let input = inputs.first().cloned().ok_or_else(|| {
DataFusionError::Internal("EndExec decoded without its input".into())
})?;
Ok(Arc::new(EndExec::new(input, machines)))
}
Some((&BALLISTA, rest)) => self.ballista.try_decode(rest, inputs, ctx, proto_converter),
_ => Err(DataFusionError::Internal(
"not a plan of kleene's codec".into(),
)),
}
}
fn try_encode(
&self,
node: Arc<dyn ExecutionPlan>,
buf: &mut Vec<u8>,
proto_converter: &dyn PhysicalProtoConverterExtension,
) -> Result<()> {
if let Some(s) = node.downcast_ref::<StepExec>() {
buf.push(STEP);
encode_job(s.job(), buf);
return Ok(());
}
if let Some(c) = node.downcast_ref::<CollectExec>() {
buf.push(COLLECT);
encode_job(c.job(), buf);
return Ok(());
}
if let Some(s) = node.downcast_ref::<SliceExec>() {
buf.push(SLICE);
buf.extend_from_slice(s.job().encode().as_bytes());
return Ok(());
}
if let Some(a) = node.downcast_ref::<AnswerExec>() {
buf.push(ANSWER);
buf.extend_from_slice(a.job().encode().as_bytes());
return Ok(());
}
if let Some(e) = node.downcast_ref::<EndExec>() {
buf.push(END);
buf.extend_from_slice(e.machines().to_string().as_bytes());
return Ok(());
}
buf.push(BALLISTA);
self.ballista.try_encode(node, buf, proto_converter)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::spec::Key;
#[test]
fn a_job_travels_through_the_codec_text() {
for (machines, kind) in [
(None, Query::Reach),
(
Some(vec!["oden".to_string(), "loki".to_string()]),
Query::Khop(10),
),
(None, Query::Wcc),
(None, Query::Sweep),
(None, Query::Load),
(None, Query::Sssp),
(None, Query::Closure),
] {
let job = Job {
spec: GraphSpec::new("/d/rmat22", "v_link_v", Key::Blocks(vec![0, 7])).unwrap(),
query: "q1".into(),
kind,
woken: vec![0, 1],
machines,
levels: if kind == Query::Sweep {
vec![0, 1]
} else {
vec![]
},
};
let mut buf = Vec::new();
encode_job(&job, &mut buf);
assert_eq!(decode_job(&buf).unwrap(), job);
}
}
}