crates/kleene-ballista/src/whole.rs
//! Queries over machines that each hold the WHOLE graph (Distributed v1.1): nothing is split,
//! every executor loads the graph once and keeps it, and a query travels as plain data.
//!
//! - One search cut in slices ([`kleene_graph::ReachSlice`]): each level's edges are cut into
//! slices weighted by the machines' cores ([`kleene_graph::Slices`]); every machine
//! expands its own slice and only its new vertices travel ([`kleene_graph::Found`], a list
//! or a bit map, compressed), to every other machine. A round of the fork's loop is one
//! level that is cut; the loop ends at the first level where no machine has a slice (the
//! small levels run whole on every machine, nothing sent). Reach and k hops.
//! - Many searches handed out whole ([`kleene_graph::Slices::portion`]): one task per
//! machine runs its share of the sources side by side on its threads
//! ([`kleene_graph::BfsMany`]); only the answers come back.
//! Weak components, which do not divide, go whole to machine 0 the same way.
//! - Load ahead: every machine loads the graph before any query.
//!
//! [`SliceExec`] is the loop's step, [`AnswerExec`] gives the answers; both map rows to the
//! core's calls and back, nothing else.
use std::collections::HashMap;
use std::fmt;
use std::sync::{Arc, Mutex};
use arrow_array::builder::BinaryViewBuilder;
use arrow_array::{Array, ArrayRef, BinaryViewArray, RecordBatch, UInt64Array};
use arrow_schema::{DataType, Field, Schema, SchemaRef};
use ballista_core::executor_state::TaskState;
use datafusion::arrow::buffer::Buffer;
use datafusion::common::tree_node::TreeNodeRecursion;
use datafusion::error::{DataFusionError, Result};
use datafusion::execution::TaskContext;
use datafusion::physical_expr::{Distribution, EquivalenceProperties, PhysicalExpr};
use datafusion::physical_plan::execution_plan::{Boundedness, EmissionType};
use datafusion::physical_plan::expressions::Column;
use datafusion::physical_plan::metrics::{ExecutionPlanMetricsSet, MetricBuilder, MetricsSet};
use datafusion::physical_plan::stream::RecordBatchStreamAdapter;
use datafusion::physical_plan::{
DisplayAs, DisplayFormatType, ExecutionPlan, Partitioning, PlanProperties,
SendableRecordBatchStream,
};
use futures::TryStreamExt;
use kleene_graph::{AfforestState, BfsMany, BfsOptions, Graph, ReachSlice, Slices, afforest_with};
use kleene_sparse::CpuBackend;
use crate::exec::ROUTE;
use crate::state::{self, task_state};
fn ext(e: impl fmt::Display) -> DataFusionError {
DataFusionError::Execution(e.to_string())
}
/// The rows of a sliced search's rounds: `route` (the target machine's partition) and one
/// machine's [`kleene_graph::Found`] of a level as bytes (empty in the start rows). The bytes are a binary
/// view column: a machine's rows to every machine point at one buffer, the encoded
/// [`kleene_graph::Found`] moved in.
pub const FOUND: &str = "found";
/// The schema of a sliced search's round rows.
pub fn slice_schema() -> SchemaRef {
Arc::new(Schema::new(vec![
Field::new(ROUTE, DataType::UInt64, false),
Field::new(FOUND, DataType::BinaryView, false),
]))
}
/// [`AnswerExec`]'s columns: the unit (the search's place in the source list) and its count.
pub const UNIT: &str = "unit";
/// See [`UNIT`].
pub const COUNT: &str = "count";
/// The schema of the answers.
pub fn answer_schema() -> SchemaRef {
Arc::new(Schema::new(vec![
Field::new(UNIT, DataType::UInt64, false),
Field::new(COUNT, DataType::UInt64, false),
]))
}
/// What runs over the whole graph.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum WholeQuery {
/// One search from the sources cut in slices: reach (`None`) or k hops; the answer is
/// the vertices reached, the sources included.
Slice(Option<u32>),
/// One search per source (reach or k hops), handed out whole: per source the vertices
/// reached, the source included.
Many(Option<u32>),
/// Weak components, whole on machine 0: their number.
Wcc,
/// Load the graph on every machine: per machine its vertices.
Load,
}
impl WholeQuery {
/// The name in a plan.
pub fn name(&self) -> String {
let k = |k: &Option<u32>| k.map_or("-".to_string(), |k| k.to_string());
match self {
WholeQuery::Slice(h) => format!("slice:{}", k(h)),
WholeQuery::Many(h) => format!("many:{}", k(h)),
WholeQuery::Wcc => "wcc".into(),
WholeQuery::Load => "load".into(),
}
}
/// The query [`WholeQuery::name`] wrote.
pub fn parse(name: &str) -> Result<Self> {
let bad = || DataFusionError::Plan(format!("no whole-graph query named {name}"));
let hops = |h: &str| -> Result<Option<u32>> {
if h == "-" {
Ok(None)
} else {
h.parse().map(Some).map_err(|_| bad())
}
};
match name.split_once(':') {
Some(("slice", h)) => Ok(WholeQuery::Slice(hops(h)?)),
Some(("many", h)) => Ok(WholeQuery::Many(hops(h)?)),
None if name == "wcc" => Ok(WholeQuery::Wcc),
None if name == "load" => Ok(WholeQuery::Load),
_ => Err(bad()),
}
}
fn opts(hops: Option<u32>) -> BfsOptions {
BfsOptions {
max_depth: hops,
..BfsOptions::default()
}
}
}
/// What both operators know about a whole-graph query; the same text on the client, the
/// scheduler and every executor.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WholeJob {
/// The X.gar directory, the same path on every machine.
pub path: String,
/// The edge type.
pub edge: String,
/// Per machine its weight (its cores), in machine order: machine `m` is partition `m`.
pub weights: Vec<u32>,
/// Per machine its executor id, when the placement is given.
pub machines: Option<Vec<String>>,
/// The query's id.
pub query: String,
/// What runs.
pub kind: WholeQuery,
/// The sources (original ids = the graph's vertices).
pub sources: Vec<u32>,
/// A sliced search's levels below this many edges run whole on every machine
/// ([`ReachSlice::with_local_below`]; [`kleene_graph::LOCAL_BELOW`] by default).
pub local_below: u64,
}
impl WholeJob {
/// The job as text.
pub fn encode(&self) -> String {
let join = |v: &[u32]| v.iter().map(u32::to_string).collect::<Vec<_>>().join(",");
format!(
"{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}",
self.kind.name(),
self.local_below,
self.query,
join(&self.weights),
self.machines.as_ref().map_or("-".into(), |m| m.join(",")),
join(&self.sources),
self.edge,
self.path
)
}
/// The job [`WholeJob::encode`] wrote.
pub fn decode(text: &str) -> Result<Self> {
let bad = |what: &str| DataFusionError::Internal(format!("a whole-graph job's {what}"));
let mut it = text.splitn(8, '\n');
let mut next = |what: &str| it.next().ok_or_else(|| bad(what));
let nums = |s: &str, what: &str| -> Result<Vec<u32>> {
if s.is_empty() {
return Ok(Vec::new());
}
s.split(',')
.map(|x| x.parse().map_err(|_| bad(what)))
.collect()
};
let kind = WholeQuery::parse(next("kind")?)?;
let local_below = next("local bound")?
.parse()
.map_err(|_| bad("local bound"))?;
let query = next("id")?.to_string();
let weights = nums(next("weights")?, "weights")?;
let machines = match next("machines")? {
"-" => None,
m => Some(m.split(',').map(str::to_string).collect()),
};
let sources = nums(next("sources")?, "sources")?;
let edge = next("edge")?.to_string();
let path = next("path")?.to_string();
Ok(WholeJob {
path,
edge,
weights,
machines,
query,
kind,
sources,
local_below,
})
}
/// The machines.
pub fn count(&self) -> usize {
self.weights.len()
}
/// The slices by the weights.
pub fn slices(&self) -> Result<Slices> {
Slices::new(&self.weights).map_err(ext)
}
/// The placement key (machine `m` for partition `m`, the format
/// [`crate::exec::preferred_of`] reads).
pub fn key(&self) -> String {
let m = self.machines.as_ref().map_or("-".into(), |m| m.join(","));
let w = self
.weights
.iter()
.map(u32::to_string)
.collect::<Vec<_>>()
.join(",");
format!(
"kleene|{m}|whole:{w}:{}|{}|{}",
self.local_below, self.path, self.edge
)
}
/// Per machine its route value.
pub fn routes(&self) -> Result<Vec<u64>> {
crate::route::route_values(self.count())
}
}
/// The whole graph on an executor: both directions, built once, kept for every job; the
/// sliced searches under way, one side per query and machine; and the sides of finished
/// searches, per slicing and machine, kept for the next search (warm buffers).
#[derive(Debug)]
pub struct Whole {
/// The graph with its transpose.
pub graph: Arc<Graph<CpuBackend>>,
running: Mutex<HashMap<String, ReachSlice>>,
sides: Mutex<HashMap<String, Vec<ReachSlice>>>,
/// Kept searchers for many searches at once.
many: Mutex<BfsMany>,
components: Mutex<AfforestState>,
routes: Mutex<HashMap<usize, UInt64Array>>,
}
impl Whole {
/// The route values of `machines` partitions ([`crate::route::route_values`]), found
/// once per executor and kept as a column (a clone shares its buffer).
fn routes(&self, machines: usize) -> Result<UInt64Array> {
let mut kept = self
.routes
.lock()
.map_err(|_| ext("the kept routes were poisoned"))?;
if let Some(r) = kept.get(&machines) {
return Ok(r.clone());
}
let r = UInt64Array::from(crate::route::route_values(machines)?);
kept.insert(machines, r.clone());
Ok(r)
}
/// The side of the search `run`, taken out while its level runs (no lock held then).
fn take_running(&self, run: &str) -> Result<Option<ReachSlice>> {
let mut running = self
.running
.lock()
.map_err(|_| ext("the running searches were poisoned"))?;
Ok(running.remove(run))
}
fn put_running(&self, run: String, side: ReachSlice) -> Result<()> {
self.running
.lock()
.map_err(|_| ext("the running searches were poisoned"))?
.insert(run, side);
Ok(())
}
/// A kept side of the slicing `key`, if a finished search left one.
fn take_side(&self, key: &str) -> Result<Option<ReachSlice>> {
let mut sides = self
.sides
.lock()
.map_err(|_| ext("a slice side was poisoned"))?;
Ok(sides.get_mut(key).and_then(Vec::pop))
}
fn keep_side(&self, key: String, side: ReachSlice) -> Result<()> {
self.sides
.lock()
.map_err(|_| ext("a slice side was poisoned"))?
.entry(key)
.or_default()
.push(side);
Ok(())
}
}
/// The key of a slicing on machine `m` (its kept sides).
fn side_key(job: &WholeJob, m: usize) -> String {
format!("{}|{m}|{}", job.weights.len(), job.key())
}
/// The key of the search `job` on machine `m` while it runs.
fn run_key(job: &WholeJob, m: usize) -> String {
format!("{}|{m}", job.query)
}
/// The whole graph at `path` (edge type `edge`) on this executor: the core's load-ahead
/// store holds it ([`kleene_index::Loads`], loaded ahead or now); the sliced-search sides
/// and search buffers beside it.
pub async fn whole(ts: &TaskState, path: &str, edge: &str) -> Result<Arc<Whole>> {
let loaded = state::whole_graph(ts, path, edge).await?;
ts.executor_state(&format!("kleene/whole/{path}|{edge}"), || async move {
Ok((
Whole {
graph: Arc::clone(loaded.graph()),
running: Mutex::new(HashMap::new()),
sides: Mutex::new(HashMap::new()),
many: Mutex::new(BfsMany::new()),
components: Mutex::new(AfforestState::new()),
routes: Mutex::new(HashMap::new()),
},
0,
))
})
.await
}
fn props(schema: &SchemaRef, partitions: usize) -> Arc<PlanProperties> {
Arc::new(PlanProperties::new(
EquivalenceProperties::new(schema.clone()),
Partitioning::UnknownPartitioning(partitions),
EmissionType::Final,
Boundedness::Bounded,
))
}
/// One partition's input, kept whole: its [`FOUND`] bytes are read in place
/// ([`found_columns`]).
async fn founds(input: SendableRecordBatchStream) -> Result<Vec<RecordBatch>> {
input.try_collect().await
}
/// The [`FOUND`] columns of `batches`.
fn found_columns(batches: &[RecordBatch]) -> Result<Vec<&BinaryViewArray>> {
batches
.iter()
.map(|b| {
b.column_by_name(FOUND)
.and_then(|c| c.as_any().downcast_ref::<BinaryViewArray>())
.ok_or_else(|| ext("a round row without its found bytes"))
})
.collect()
}
/// One row per route, every row the same `bytes`: one buffer, moved in, not copied.
pub(crate) fn found_rows(bytes: Vec<u8>, routes: usize) -> Result<BinaryViewArray> {
let len = u32::try_from(bytes.len()).map_err(|_| ext("a found of 4 GiB or more"))?;
let mut b = BinaryViewBuilder::with_capacity(routes);
if routes > 0 {
let block = b.append_block(Buffer::from_vec(bytes));
for _ in 0..routes {
b.try_append_view(block, 0, len)?;
}
}
Ok(b.finish())
}
/// The machine of a stage partition.
fn machine_of(job: &WholeJob, ts: &TaskState, partition: usize) -> Result<usize> {
let m = ts.stage_partition(partition);
if m >= job.count() {
return Err(ext(format!("partition {m} of {} machines", job.count())));
}
Ok(m)
}
macro_rules! plan_boilerplate {
($name:literal) => {
fn name(&self) -> &str {
$name
}
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)
}
};
}
/// Rows routed to their machine on [`ROUTE`].
fn by_route() -> Vec<Distribution> {
vec![Distribution::KeyPartitioned(vec![Arc::new(Column::new(
ROUTE, 0,
))])]
}
/// One level of a sliced search on each machine (see the module doc). Partition `m` is
/// machine `m`.
#[derive(Debug)]
pub struct SliceExec {
input: Arc<dyn ExecutionPlan>,
job: WholeJob,
metrics: ExecutionPlanMetricsSet,
props: Arc<PlanProperties>,
}
impl SliceExec {
/// The step of `job` over `input` (round rows, hash-partitioned on [`ROUTE`] into one
/// partition per machine).
pub fn new(input: Arc<dyn ExecutionPlan>, job: WholeJob) -> Self {
let props = props(
&slice_schema(),
input.properties().output_partitioning().partition_count(),
);
SliceExec {
input,
job,
metrics: ExecutionPlanMetricsSet::new(),
props,
}
}
/// The job.
pub fn job(&self) -> &WholeJob {
&self.job
}
}
impl DisplayAs for SliceExec {
fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"SliceExec: {} query={} machines={}",
self.job.kind.name(),
self.job.query,
self.job.count()
)
}
}
impl ExecutionPlan for SliceExec {
plan_boilerplate!("SliceExec");
fn required_input_distribution(&self) -> Vec<Distribution> {
by_route()
}
fn with_new_children(
self: Arc<Self>,
children: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>> {
let [input] = <[_; 1]>::try_from(children).map_err(|c| {
DataFusionError::Plan(format!("SliceExec takes one input, {} given", c.len()))
})?;
Ok(Arc::new(SliceExec::new(input, self.job.clone())))
}
fn execute(
&self,
partition: usize,
context: Arc<TaskContext>,
) -> Result<SendableRecordBatchStream> {
let ts = task_state(&context)?;
let m = machine_of(&self.job, &ts, partition)?;
let input = self.input.execute(partition, context)?;
let job = self.job.clone();
let sent = MetricBuilder::new(&self.metrics).counter("sent", partition);
let found_bytes = MetricBuilder::new(&self.metrics).counter("found_bytes", partition);
let step_time = MetricBuilder::new(&self.metrics).subset_time("step_time", partition);
let work = async move {
let batches = founds(input).await?;
let device = state::device(&ts).await?;
let w = whole(&ts, &job.path, &job.edge).await?;
let WholeQuery::Slice(hops) = job.kind else {
return Err(ext("a sliced step of another query"));
};
let routes = w.routes(job.count())?;
let (side_key, run_key) = (side_key(&job, m), run_key(&job, m));
let slices = job.slices()?;
tokio::task::spawn_blocking(move || -> Result<RecordBatch> {
let _timer = step_time.timer();
let cols = found_columns(&batches)?;
let got = || cols.iter().flat_map(|c| c.iter().flatten());
// The start rows carry no bytes: a new search, on a kept side or a new one.
// Else every machine's finds, on this search's own side.
let mut side = if got().all(<[u8]>::is_empty) {
let mut side = match w.take_side(&side_key)? {
Some(side) => side,
None => ReachSlice::new(m, slices, Arc::clone(&w.graph))
.map_err(ext)?
.with_local_below(job.local_below),
};
side.start_on(&job.sources, &WholeQuery::opts(hops), &device)
.map_err(ext)?;
side
} else {
let mut side = w
.take_running(&run_key)?
.ok_or_else(|| ext("a level of a search not started here"))?;
// Read straight into the side's kept buffers.
side.take_bytes(got(), &device).map_err(ext)?;
side
};
let stepped = side.step(&device).map_err(ext).map(|f| {
f.map(|f| {
sent.add(f.nodes.len());
side.encode(&f, &device)
})
});
w.put_running(run_key, side)?;
let (route, found) = match stepped? {
None => (
UInt64Array::from(Vec::<u64>::new()),
found_rows(Vec::new(), 0)?,
),
Some(b) => {
let n = routes.len();
found_bytes.add(b.len() * n);
(routes, found_rows(b, n)?)
}
};
let cols: Vec<ArrayRef> = vec![Arc::new(route), Arc::new(found)];
Ok(RecordBatch::try_new(slice_schema(), cols)?)
})
.await
.map_err(ext)?
};
let s = futures::stream::once(work);
Ok(Box::pin(RecordBatchStreamAdapter::new(slice_schema(), s)))
}
fn metrics(&self) -> Option<MetricsSet> {
Some(self.metrics.clone_inner())
}
}
/// The end of a sliced search's rounds before its answers: it waits for its input (the
/// union of the rounds, so the answers run after the last one) but never reads it; each of
/// its partitions, one per machine, gives no rows. The answers need only each machine's
/// side, not the rounds' finds again.
#[derive(Debug)]
pub struct EndExec {
input: Arc<dyn ExecutionPlan>,
machines: usize,
props: Arc<PlanProperties>,
}
impl EndExec {
/// The end of `input` on `machines` partitions.
pub fn new(input: Arc<dyn ExecutionPlan>, machines: usize) -> Self {
EndExec {
input,
machines,
props: props(&slice_schema(), machines),
}
}
/// The partitions (machines).
pub fn machines(&self) -> usize {
self.machines
}
}
impl DisplayAs for EndExec {
fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "EndExec: machines={}", self.machines)
}
}
impl ExecutionPlan for EndExec {
fn name(&self) -> &str {
"EndExec"
}
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>> {
let [input] = <[_; 1]>::try_from(children).map_err(|c| {
DataFusionError::Plan(format!("EndExec takes one input, {} given", c.len()))
})?;
Ok(Arc::new(EndExec::new(input, self.machines)))
}
fn execute(
&self,
partition: usize,
_context: Arc<TaskContext>,
) -> Result<SendableRecordBatchStream> {
if partition >= self.machines {
return Err(ext(format!(
"partition {partition} of {} machines",
self.machines
)));
}
let s = futures::stream::empty();
Ok(Box::pin(RecordBatchStreamAdapter::new(slice_schema(), s)))
}
}
/// The answers of a whole-graph query on each machine (see the module doc). Partition `m` is
/// machine `m`; its input is routed to it on [`ROUTE`] (the rounds of a sliced search, or the
/// start rows).
#[derive(Debug)]
pub struct AnswerExec {
input: Arc<dyn ExecutionPlan>,
job: WholeJob,
metrics: ExecutionPlanMetricsSet,
props: Arc<PlanProperties>,
}
impl AnswerExec {
/// The answers of `job` after `input`.
pub fn new(input: Arc<dyn ExecutionPlan>, job: WholeJob) -> Self {
let props = props(
&answer_schema(),
input.properties().output_partitioning().partition_count(),
);
AnswerExec {
input,
job,
metrics: ExecutionPlanMetricsSet::new(),
props,
}
}
/// The job.
pub fn job(&self) -> &WholeJob {
&self.job
}
}
impl DisplayAs for AnswerExec {
fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"AnswerExec: {} query={} machines={}",
self.job.kind.name(),
self.job.query,
self.job.count()
)
}
}
impl ExecutionPlan for AnswerExec {
plan_boilerplate!("AnswerExec");
fn required_input_distribution(&self) -> Vec<Distribution> {
// A sliced search's answers read no rows: their input is an [`EndExec`] of one
// partition per machine.
match self.job.kind {
WholeQuery::Slice(_) => vec![Distribution::UnspecifiedDistribution],
_ => by_route(),
}
}
fn with_new_children(
self: Arc<Self>,
children: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>> {
let [input] = <[_; 1]>::try_from(children).map_err(|c| {
DataFusionError::Plan(format!("AnswerExec takes one input, {} given", c.len()))
})?;
Ok(Arc::new(AnswerExec::new(input, self.job.clone())))
}
fn execute(
&self,
partition: usize,
context: Arc<TaskContext>,
) -> Result<SendableRecordBatchStream> {
let ts = task_state(&context)?;
let m = machine_of(&self.job, &ts, partition)?;
let input = self.input.execute(partition, context)?;
let job = self.job.clone();
let step_time = MetricBuilder::new(&self.metrics).subset_time("step_time", partition);
let work = async move {
// Only the start rows (no bytes) or, for a sliced search, nothing: drained, not
// copied.
input
.try_for_each(|_| futures::future::ready(Ok(())))
.await?;
let device = state::device(&ts).await?;
let w = whole(&ts, &job.path, &job.edge).await?;
let slices = job.slices()?;
let (side_key, run_key) = (side_key(&job, m), run_key(&job, m));
tokio::task::spawn_blocking(move || -> Result<RecordBatch> {
let _timer = step_time.timer();
let (mut unit, mut count) = (Vec::new(), Vec::new());
match &job.kind {
WholeQuery::Slice(_) => {
// The search ends: its side goes back to the kept ones.
let side = w.take_running(&run_key)?;
if m == 0 {
let side = side
.as_ref()
.ok_or_else(|| ext("an answer with no search run"))?;
unit.push(0);
count.push(side.reached() as u64);
}
if let Some(side) = side {
w.keep_side(side_key, side)?;
}
}
WholeQuery::Many(hops) => {
// This machine's share of the searches, side by side on the
// device's threads (each search's answer is its own alone).
let opts = WholeQuery::opts(*hops);
let mine = slices.portion(m, job.sources.len());
unit.extend(mine.clone().map(|i| i as u64));
count.resize(mine.len(), 0);
let mut many = w.many.lock().map_err(|_| ext("searchers poisoned"))?;
many.run(&w.graph, &job.sources[mine], &opts, &device, &mut count)
.map_err(ext)?;
}
WholeQuery::Wcc => {
if m == 0 {
let inn = w
.graph
.inn()
.ok_or_else(|| ext("a whole graph without its transpose"))?;
// The CPU backend's weak components on kept buffers, counted
// on the workers.
let mut st = w
.components
.lock()
.map_err(|_| ext("the components' buffers were poisoned"))?;
afforest_with(w.graph.out(), inn, &device, &mut st).map_err(ext)?;
unit.push(0);
count.push(st.count(&device) as u64);
}
}
WholeQuery::Load => {
unit.push(m as u64);
count.push(w.graph.vertices() as u64);
}
}
Ok(RecordBatch::try_new(
answer_schema(),
vec![
Arc::new(UInt64Array::from(unit)),
Arc::new(UInt64Array::from(count)),
],
)?)
})
.await
.map_err(ext)?
};
let s = futures::stream::once(work);
Ok(Box::pin(RecordBatchStreamAdapter::new(answer_schema(), s)))
}
fn metrics(&self) -> Option<MetricsSet> {
Some(self.metrics.clone_inner())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_whole_graph_job_travels_as_text() {
for kind in [
WholeQuery::Slice(None),
WholeQuery::Slice(Some(10)),
WholeQuery::Many(Some(3)),
WholeQuery::Wcc,
WholeQuery::Load,
] {
let job = WholeJob {
path: "/d/rmat22".into(),
edge: "v_link_v".into(),
weights: vec![32, 12, 12],
machines: Some(vec!["oden".into(), "loki".into(), "dwarf".into()]),
query: "q".into(),
sources: if kind == WholeQuery::Wcc {
vec![]
} else {
vec![3, 7]
},
kind,
local_below: 0,
};
assert_eq!(WholeJob::decode(&job.encode()).unwrap(), job);
assert_eq!(
crate::exec::preferred_of(&job.key(), 2).as_deref(),
Some("dwarf")
);
}
assert!(WholeQuery::parse("slice:x").is_err());
}
}