Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-ballista/src/exec.rs

//! The two operators a query runs on the executors.
//!
//! - [`StepExec`]: one round of one part, the recursive term of the rounds job. Its input is
//!   what arrived for its part (border sends routed to its partition); it hands them to the
//!   core's part side ([`kleene_graph::ReachPart`]) kept on the executor and gives the sends
//!   of that step, routed to their parts' partitions.
//! - [`CollectExec`]: one partition per part, after the rounds in the same job: each part's
//!   answer from its kept side, in original node ids.
//!
//! A part's side is job state on its executor (dropped with the job); the graph is
//! executor-long state, kept for every later job.
//!
//! Both are mapping only: Arrow columns to the core's calls and back.

use std::fmt;
use std::sync::{Arc, Mutex};

use arrow_array::{Array, BinaryArray, RecordBatch, UInt32Array, UInt64Array};
use arrow_schema::{DataType, Field, Schema, SchemaRef};
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::{
    BfsState, ClosurePart, ComponentsPart, KhopPart, Part, PartSummary, ReachPart, Sends,
    SsspOptions, SsspPart,
};
use kleene_sparse::{CpuBackend, CpuDevice, Value};

use crate::spec::GraphSpec;
use crate::state::{self, Kept, query_key, task_state};

/// The round rows' route column (see [`crate::route`]).
pub const ROUTE: &str = "route";
/// The round rows' target part.
pub const PART: &str = "part";
/// [`CollectExec`]'s column of values (shortest paths' distances, the closure's words).
pub const VALUE: &str = "value";
/// The round rows' sends to their part, compact ([`Sends::to_compact`]).
pub const SENDS: &str = "sends";
/// [`CollectExec`]'s column of original node ids.
pub const ID: &str = "id";

fn ext(e: impl fmt::Display) -> DataFusionError {
    DataFusionError::Execution(e.to_string())
}

/// The schema of a round's rows: `route` u64, the target `part` u32 and its `sends`, the
/// core's compact form ([`Sends::to_compact`]): one row per target part a round.
pub fn round_schema() -> SchemaRef {
    Arc::new(Schema::new(vec![
        Field::new(ROUTE, DataType::UInt64, false),
        Field::new(PART, DataType::UInt32, false),
        Field::new(SENDS, DataType::Binary, false),
    ]))
}

/// Per part its route value when the job woke it (`None`: not woken), from the woken
/// parts in partition order.
pub fn routes_of(woken: &[u32], parts: usize) -> Result<Vec<Option<u64>>> {
    let values = crate::route::route_values(woken.len())?;
    let mut routes = vec![None; parts];
    for (&p, v) in woken.iter().zip(values) {
        *routes
            .get_mut(p as usize)
            .ok_or_else(|| ext(format!("woken part {p} of {parts}")))? = Some(v);
    }
    Ok(routes)
}

/// A step's sends as round rows, combined at the sender with the query's `add`
/// ([`Sends::combine`]: each node once), then compact per target part ([`rows_compact`]).
pub fn rows_of<T: Value + Into<u64> + TryFrom<u64>>(
    sends: Sends<T>,
    routes: &[Option<u64>],
    add: impl Fn(T, T) -> T + Sync,
    device: Option<&CpuDevice>,
) -> Result<RecordBatch> {
    rows_compact(&sends.combine(add, device), routes, device)
}

/// Sends as round rows as they are (start rows): one row per target part, its route value,
/// its entries compact ([`Sends::to_compact_on`], on the device's threads when given).
pub fn rows_compact<T: Value + Into<u64> + TryFrom<u64>>(
    sends: &Sends<T>,
    routes: &[Option<u64>],
    device: Option<&CpuDevice>,
) -> Result<RecordBatch> {
    let mut by: std::collections::BTreeMap<u32, Sends<T>> = Default::default();
    for k in 0..sends.len() {
        by.entry(sends.part[k])
            .or_default()
            .push(sends.part[k], sends.node[k], sends.value[k]);
    }
    let (mut route, mut part, mut bytes) = (Vec::new(), Vec::new(), Vec::new());
    for (p, s) in &by {
        route.push(routes.get(*p as usize).copied().flatten().ok_or_else(|| {
            ext(format!(
                "a send to part {p}, which the central index did not wake"
            ))
        })?);
        part.push(*p);
        bytes.push(s.to_compact_on(device));
    }
    Ok(RecordBatch::try_new(
        round_schema(),
        vec![
            Arc::new(UInt64Array::from(route)),
            Arc::new(UInt32Array::from(part)),
            Arc::new(BinaryArray::from_iter_values(bytes)),
        ],
    )?)
}

/// The placement key of a query's operators: the machines (executor ids, one per woken
/// part, in partition order) when there is a placement, the woken parts and the graph.
pub fn placement_key(spec: &GraphSpec, machines: &Option<Vec<String>>, woken: &[u32]) -> String {
    let m = machines.as_ref().map_or("-".to_string(), |m| m.join(","));
    format!("kleene|{m}|{}|{spec}", join(woken))
}

/// Numbers joined by commas.
pub(crate) fn join(v: &[u32]) -> String {
    v.iter().map(u32::to_string).collect::<Vec<_>>().join(",")
}

/// The executor id preferred for `partition` by a [`placement_key`], if it names machines.
pub fn preferred_of(key: &str, partition: usize) -> Option<String> {
    let rest = key.strip_prefix("kleene|")?;
    let (machines, _) = rest.split_once('|')?;
    if machines == "-" {
        return None;
    }
    machines.split(',').nth(partition).map(str::to_string)
}

/// What a query runs.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Query {
    /// Reachability from the sources ([`ReachPart`]).
    Reach,
    /// Weak components ([`ComponentsPart`]): every part woken, each started by a
    /// [`START`] row; the answer is each component's name (its least original node).
    Wcc,
    /// The nodes within `k` hops of the source ([`KhopPart`]): one hop a round.
    Khop(u32),
    /// Reachability in part order ([`kleene_graph::PartOrder`], the core's `reach_sweep`
    /// over machines): a round runs one level of the order, only the parts at that level
    /// step, on what waits for them; sends to later parts wait there; a level runs again
    /// only while a send went to a part of the same level (a circle). Every round each part
    /// also sends every woken part one [`START`] row whose value says whether it sent inside
    /// its level, so all parts move to the next level together.
    Sweep,
    /// Load each woken part on its executor ahead of the queries (the core's
    /// [`kleene_index::Loads`]); nothing is searched, and each part's answer is its
    /// summary ([`summary_rows`]), from which the client builds the central index.
    Load,
    /// Shortest paths from one source ([`SsspPart`], every edge weight 1): the source's
    /// row carries [`SOURCE`]; the answer is each reached node's distance.
    Sssp,
    /// The closure of base pairs ([`ClosurePart`], the Datalog `tc(X, Z) :- base(X, Z).
    /// tc(X, Z) :- tc(X, Y), edge(Y, Z).`), up to 64 starts a job: each start row carries
    /// its start's bit at the pair's end; the answer is each reached node's word of starts.
    Closure,
}

/// The value of the round row that starts a shortest-path search at its node.
pub const SOURCE: u64 = u64::MAX;

/// The node of the row that starts a part's side where the query has no sources (weak
/// components): it carries no node.
pub const START: u32 = u32::MAX;

impl Query {
    /// The query's name in a plan (`reach`, `wcc`, `khop:K`).
    pub fn name(self) -> String {
        match self {
            Query::Reach => "reach".into(),
            Query::Wcc => "wcc".into(),
            Query::Khop(k) => format!("khop:{k}"),
            Query::Sweep => "sweep".into(),
            Query::Load => "load".into(),
            Query::Sssp => "sssp".into(),
            Query::Closure => "closure".into(),
        }
    }

    /// The query named `name`.
    pub fn parse(name: &str) -> Result<Self> {
        match name {
            "reach" => Ok(Query::Reach),
            "wcc" => Ok(Query::Wcc),
            "sweep" => Ok(Query::Sweep),
            "load" => Ok(Query::Load),
            "sssp" => Ok(Query::Sssp),
            "closure" => Ok(Query::Closure),
            k if k.starts_with("khop:") => k[5..]
                .parse()
                .map(Query::Khop)
                .map_err(|_| DataFusionError::Plan(format!("a bad hop count in {name}"))),
            _ => Err(DataFusionError::Plan(format!(
                "no kleene query named {name}"
            ))),
        }
    }
}

/// What both operators know about their query.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Job {
    /// The graph and its split.
    pub spec: GraphSpec,
    /// The query's id (its parts' kept state is under it).
    pub query: String,
    /// What runs.
    pub kind: Query,
    /// The parts the central index woke for the query, rising: partition `i` is part
    /// `woken[i]`; the other parts get no task.
    pub woken: Vec<u32>,
    /// One executor id per woken part (in partition order) when the placement is given.
    pub machines: Option<Vec<String>>,
    /// For [`Query::Sweep`], per part of the split its level in the part order (empty for
    /// the other queries).
    pub levels: Vec<u32>,
}

impl Job {
    /// The placement key of the job's operators.
    pub fn key(&self) -> String {
        placement_key(&self.spec, &self.machines, &self.woken)
    }

    /// The part of stage partition `partition`.
    pub fn part(&self, partition: usize) -> Result<u32> {
        self.woken.get(partition).copied().ok_or_else(|| {
            ext(format!(
                "partition {partition} of {} woken parts",
                self.woken.len()
            ))
        })
    }
}

/// The rows arriving for `part` in one partition's input (`(local node, value)`), each
/// checked to be for it.
async fn arrivals(input: SendableRecordBatchStream, part: u32) -> Result<Vec<(u32, u64)>> {
    let batches: Vec<RecordBatch> = input.try_collect().await?;
    let mut out = Vec::new();
    for b in &batches {
        out.extend(round_entries(b, part)?);
    }
    Ok(out)
}

/// The `(local node, value)` entries of round rows `b`, each checked to be for `part`.
pub fn round_entries(b: &RecordBatch, part: u32) -> Result<Vec<(u32, u64)>> {
    let parts = b
        .column_by_name(PART)
        .and_then(|c| c.as_any().downcast_ref::<UInt32Array>())
        .ok_or_else(|| ext("a round row without a u32 `part`"))?;
    let sends = b
        .column_by_name(SENDS)
        .and_then(|c| c.as_any().downcast_ref::<BinaryArray>())
        .ok_or_else(|| ext("a round row without binary `sends`"))?;
    if parts.null_count() + sends.null_count() > 0 {
        return Err(ext("a null in a round row"));
    }
    let mut out = Vec::new();
    for (&p, bytes) in parts.values().iter().zip(sends.iter().flatten()) {
        let s = Sends::<u64>::from_compact(bytes).map_err(ext)?;
        if let Some(q) = std::iter::once(p)
            .chain(s.part.iter().copied())
            .find(|&q| q != part)
        {
            return Err(ext(format!(
                "a row for part {q} arrived in part {part}'s partition: the routing is off"
            )));
        }
        out.extend(s.node.into_iter().zip(s.value));
    }
    Ok(out)
}

fn props(schema: &SchemaRef, partitions: usize) -> Arc<PlanProperties> {
    Arc::new(PlanProperties::new(
        EquivalenceProperties::new(schema.clone()),
        Partitioning::UnknownPartitioning(partitions),
        EmissionType::Final,
        Boundedness::Bounded,
    ))
}

/// A part's side of a query, kept as job state between its rounds.
#[derive(Debug)]
pub enum Side {
    /// Reach (boxed: its buffers make it the large one).
    Reach(Box<ReachPart<CpuBackend>>),
    /// Weak components.
    Wcc(ComponentsPart),
    /// K hops.
    Khop(Box<KhopPart<CpuBackend>>),
    /// Reach in part order.
    Sweep(Box<SweepSide>),
    /// Shortest paths: the part with its edges weighted 1, and the core's side.
    Sssp(Box<(Part<u32>, SsspPart<CpuBackend>)>),
    /// The closure of base pairs.
    Closure(Box<ClosurePart<CpuBackend>>),
}

/// The rows a part's summary travels as (`(id, value)`): `id` is the part shifted up 32
/// bits plus a code (0: base, 1: node count, 2: inner edges, `3 + q`: the border edges to
/// part `q`).
pub fn summary_rows(s: &PartSummary) -> Vec<(u64, u64)> {
    let at = |code: u64| (u64::from(s.part) << 32) | code;
    let mut rows = vec![(at(0), s.base), (at(1), s.count), (at(2), s.inner_edges)];
    rows.extend(s.border.iter().map(|&(q, n)| (at(3 + u64::from(q)), n)));
    rows
}

/// The summaries `rows` ([`summary_rows`] of every part, any order) carry, by part.
pub fn summaries_of(rows: &[(u64, u64)]) -> Result<Vec<PartSummary>> {
    let mut by: std::collections::BTreeMap<u32, PartSummary> = Default::default();
    for &(id, v) in rows {
        let (p, code) = ((id >> 32) as u32, id & 0xFFFF_FFFF);
        let s = by.entry(p).or_insert_with(|| PartSummary {
            part: p,
            base: 0,
            count: 0,
            inner_edges: 0,
            border: Vec::new(),
        });
        match code {
            0 => s.base = v,
            1 => s.count = v,
            2 => s.inner_edges = v,
            c => s.border.push(((c - 3) as u32, v)),
        }
    }
    let mut out: Vec<PartSummary> = by.into_values().collect();
    for (k, s) in out.iter_mut().enumerate() {
        if s.part as usize != k {
            return Err(ext(format!("no summary of part {k}")));
        }
        s.border.sort_unstable();
    }
    Ok(out)
}

/// A part's side of a [`Query::Sweep`]: its reach side, what waits for it, and the level the
/// order is at (the same on every part).
#[derive(Debug)]
pub struct SweepSide {
    reach: ReachPart<CpuBackend>,
    inbox: Vec<(u32, u8)>,
    level: u32,
}

/// The [`START`] rows that tell every woken part whether `flag` (a send inside the level).
pub fn level_rows(routes: &[Option<u64>], woken: &[u32], flag: bool) -> Result<RecordBatch> {
    let mut rows = Sends::<u64>::new();
    for &p in woken {
        rows.push(p, START, u64::from(flag));
    }
    rows_compact(&rows, routes, None)
}

/// The values of `got` narrowed to `T`.
fn narrow<T: TryFrom<u64>>(got: Vec<(u32, u64)>) -> Result<Vec<(u32, T)>> {
    got.into_iter()
        .map(|(n, v)| {
            T::try_from(v)
                .map(|v| (n, v))
                .map_err(|_| ext(format!("a round value {v} too wide")))
        })
        .collect()
}

/// One round of each woken part (see the module doc). Partition `i` is part `woken[i]`.
#[derive(Debug)]
pub struct StepExec {
    input: Arc<dyn ExecutionPlan>,
    job: Job,
    routes: Arc<Vec<Option<u64>>>,
    metrics: ExecutionPlanMetricsSet,
    props: Arc<PlanProperties>,
}

impl StepExec {
    /// The step of `job` over `input` (round rows, hash-partitioned on [`ROUTE`] into
    /// one partition per woken part); `routes` from [`routes_of`].
    pub fn new(input: Arc<dyn ExecutionPlan>, job: Job, routes: Arc<Vec<Option<u64>>>) -> Self {
        // As many partitions as the input: a task's readers hold only its own partitions.
        let props = props(
            &round_schema(),
            input.properties().output_partitioning().partition_count(),
        );
        StepExec {
            input,
            job,
            routes,
            metrics: ExecutionPlanMetricsSet::new(),
            props,
        }
    }

    /// The job.
    pub fn job(&self) -> &Job {
        &self.job
    }
}

impl DisplayAs for StepExec {
    fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "StepExec: {} query={} parts={} graph={}",
            self.job.kind.name(),
            self.job.query,
            join(&self.job.woken),
            self.job.spec
        )
    }
}

impl ExecutionPlan for StepExec {
    fn name(&self) -> &str {
        "StepExec"
    }

    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 required_input_distribution(&self) -> Vec<Distribution> {
        vec![Distribution::KeyPartitioned(vec![Arc::new(Column::new(
            ROUTE, 0,
        ))])]
    }

    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!("StepExec takes one input, {} given", c.len()))
        })?;
        Ok(Arc::new(StepExec::new(
            input,
            self.job.clone(),
            self.routes.clone(),
        )))
    }

    fn execute(
        &self,
        partition: usize,
        context: Arc<TaskContext>,
    ) -> Result<SendableRecordBatchStream> {
        let ts = task_state(&context)?;
        let part = self.job.part(ts.stage_partition(partition))?;
        let input = self.input.execute(partition, context)?;
        let (job, routes) = (self.job.clone(), self.routes.clone());
        let received = MetricBuilder::new(&self.metrics).counter("arrived", partition);
        let sent = MetricBuilder::new(&self.metrics).counter("sent", partition);
        // The core's step alone (the search on the part), beside the task's whole time.
        let step_time = MetricBuilder::new(&self.metrics).subset_time("step_time", partition);
        let work = async move {
            let got = arrivals(input, part).await?;
            received.add(got.len());
            let device = state::device(&ts).await?;
            // Every query loads its part alone; the weak components also the part of the
            // transpose.
            let loaded = state::PartSrc::Alone(
                state::part_alone(&ts, &job.spec, part).await?,
                job.spec.key.parts(),
            );
            let spare = state::spare(&ts, &job.spec, part).await?;
            let transposed = match job.kind {
                Query::Wcc => Some(state::part_t_alone(&ts, &job.spec, part).await?),
                _ => None,
            };
            let side: Arc<Kept<Side>> = ts
                .job_state(&query_key(&job.query, part), partition, || async {
                    Ok(Mutex::new(None))
                })
                .await?;
            tokio::task::spawn_blocking(move || -> Result<RecordBatch> {
                let _timer = step_time.timer();
                let mut side = side.lock().map_err(|_| ext("a part's side was poisoned"))?;
                let (p, ids) = (loaded.part(part), loaded.ids());
                match job.kind {
                    Query::Reach => {
                        if side.is_none() {
                            let graph = loaded.graph(part, &device)?;
                            let bfs = spare
                                .lock()
                                .ok()
                                .and_then(|mut s| s.take())
                                .unwrap_or_else(|| BfsState::new(p.count(), &*device));
                            *side = Some(Side::Reach(Box::new(ReachPart::new(
                                p,
                                loaded.parts(),
                                graph,
                                bfs,
                            ))));
                        }
                        let Some(Side::Reach(side)) = side.as_mut() else {
                            return Err(ext("a reach query with another side"));
                        };
                        let mut got = narrow::<u8>(got)?;
                        let sends = side.step(p, ids, &mut got, &*device).map_err(ext)?;
                        sent.add(sends.len());
                        rows_of(sends, &routes, |a, b| a | b, Some(&*device))
                    }
                    Query::Wcc => {
                        let t = transposed.as_ref().expect("loaded above");
                        let (pt, mut got): (_, Vec<(u32, u32)>) = (
                            t.part(),
                            narrow(got.into_iter().filter(|g| g.0 != START).collect())?,
                        );
                        let sends = match side.as_mut() {
                            None => {
                                let (made, first) =
                                    ComponentsPart::new::<CpuBackend>(p, pt, ids, &*device)
                                        .map_err(ext)?;
                                *side = Some(Side::Wcc(made));
                                first
                            }
                            Some(Side::Wcc(side)) => {
                                side.step(p, pt, ids, &mut got).map_err(ext)?
                            }
                            Some(_) => return Err(ext("a components query with another side")),
                        };
                        sent.add(sends.len());
                        rows_of(sends, &routes, |a, b| a.min(b), Some(&*device))
                    }
                    // The part is loaded above: nothing more, and the loop ends.
                    Query::Load => Ok(RecordBatch::new_empty(round_schema())),
                    Query::Sssp => {
                        if side.is_none() {
                            let weighted = p.structural::<u32>();
                            let made = SsspPart::new(&weighted);
                            *side = Some(Side::Sssp(Box::new((weighted, made))));
                        }
                        let Some(Side::Sssp(b)) = side.as_mut() else {
                            return Err(ext("a shortest-path query with another side"));
                        };
                        let (wp, sp) = (&b.0, &mut b.1);
                        let (mut sends, mut arrived) = (Sends::new(), Vec::new());
                        for (n, v) in got {
                            if v == SOURCE {
                                let opts = SsspOptions::default();
                                let mut first =
                                    sp.start(wp, ids, n, &opts, &*device).map_err(ext)?;
                                sends.append(&mut first);
                            } else {
                                arrived.push((n, v));
                            }
                        }
                        let mut more = sp.step(wp, ids, &mut arrived, &*device).map_err(ext)?;
                        sends.append(&mut more);
                        sent.add(sends.len());
                        rows_of(sends, &routes, |a, b| a.min(b), Some(&*device))
                    }
                    Query::Closure => {
                        if side.is_none() {
                            *side = Some(Side::Closure(Box::new(ClosurePart::new(p, &*device))));
                        }
                        let Some(Side::Closure(cp)) = side.as_mut() else {
                            return Err(ext("a closure query with another side"));
                        };
                        let mut got = got;
                        let sends = cp.step(p, ids, &mut got, &*device).map_err(ext)?;
                        sent.add(sends.len());
                        rows_of(sends, &routes, |a, b| a | b, Some(&*device))
                    }
                    Query::Sweep => {
                        let levels = &job.levels;
                        let level_of = |q: u32| -> Result<u32> {
                            levels.get(q as usize).copied().ok_or_else(|| {
                                ext(format!("part {q} past the order's {} parts", levels.len()))
                            })
                        };
                        let first = side.is_none();
                        if first {
                            let graph = loaded.graph(part, &device)?;
                            let bfs = spare
                                .lock()
                                .ok()
                                .and_then(|mut s| s.take())
                                .unwrap_or_else(|| BfsState::new(p.count(), &*device));
                            *side = Some(Side::Sweep(Box::new(SweepSide {
                                reach: ReachPart::new(p, loaded.parts(), graph, bfs),
                                inbox: Vec::new(),
                                level: 0,
                            })));
                        }
                        let Some(Side::Sweep(side)) = side.as_mut() else {
                            return Err(ext("a sweep with another side"));
                        };
                        let (mut stay, mut flags) = (false, 0usize);
                        for (n, v) in got {
                            if n == START {
                                flags += 1;
                                stay |= v != 0;
                            } else {
                                side.inbox.push((n, u8::try_from(v).map_err(ext)?));
                            }
                        }
                        if flags == 0 {
                            return Err(ext("a sweep round without the level rows"));
                        }
                        if !first && !stay {
                            side.level += 1;
                        }
                        let levels_all = levels.iter().max().map_or(0, |m| m + 1);
                        if side.level >= levels_all {
                            // The order is done: nothing more, and the loop ends.
                            return Ok(RecordBatch::new_empty(round_schema()));
                        }
                        let mut inside = false;
                        let mut batches = Vec::new();
                        if level_of(part)? == side.level {
                            let mut inbox = std::mem::take(&mut side.inbox);
                            let sends =
                                side.reach.step(p, ids, &mut inbox, &*device).map_err(ext)?;
                            for &q in &sends.part {
                                inside |= level_of(q)? == side.level;
                            }
                            sent.add(sends.len());
                            batches.push(rows_of(sends, &routes, |a, b| a | b, Some(&*device))?);
                        }
                        batches.push(level_rows(&routes, &job.woken, inside)?);
                        Ok(datafusion::arrow::compute::concat_batches(
                            &round_schema(),
                            &batches,
                        )?)
                    }
                    Query::Khop(k) => {
                        if side.is_none() {
                            let graph = loaded.graph(part, &device)?;
                            *side = Some(Side::Khop(Box::new(KhopPart::new(p, graph, k))));
                        }
                        let Some(Side::Khop(side)) = side.as_mut() else {
                            return Err(ext("a k-hop query with another side"));
                        };
                        let mut got = narrow::<u32>(got)?;
                        let sends = side.step(p, ids, &mut got, &*device).map_err(ext)?;
                        sent.add(sends.len());
                        rows_of(sends, &routes, |a, b| a.min(b), Some(&*device))
                    }
                }
            })
            .await
            .map_err(ext)?
        };
        let s = futures::stream::once(work);
        Ok(Box::pin(RecordBatchStreamAdapter::new(round_schema(), s)))
    }

    fn metrics(&self) -> Option<MetricsSet> {
        Some(self.metrics.clone_inner())
    }
}

/// [`CollectExec`]'s column of rows arrived at a part over the job (stat rows only).
pub const ARRIVED: &str = "arrived";

/// Each woken part's answer after the rounds (see the module doc). Partition `i` is part
/// `woken[i]`. Its
/// input is the rounds' output (the sources and every round's sends) routed to the parts, so
/// it runs in the same job, after the last round, on each part's executor; it counts what
/// arrived and gives the part's reached nodes (column [`ID`]) and one stat row (column
/// [`ARRIVED`]).
#[derive(Debug)]
pub struct CollectExec {
    input: Arc<dyn ExecutionPlan>,
    job: Job,
    schema: SchemaRef,
    props: Arc<PlanProperties>,
}

impl CollectExec {
    /// The answers of `job` after `input` (the rounds, hash-partitioned on [`ROUTE`]).
    pub fn new(input: Arc<dyn ExecutionPlan>, job: Job) -> Self {
        let schema = Arc::new(Schema::new(vec![
            Field::new(ID, DataType::UInt64, true),
            Field::new(ARRIVED, DataType::UInt64, true),
            Field::new(VALUE, DataType::UInt64, true),
        ]));
        let props = props(
            &schema,
            input.properties().output_partitioning().partition_count(),
        );
        CollectExec {
            input,
            job,
            schema,
            props,
        }
    }

    /// The job.
    pub fn job(&self) -> &Job {
        &self.job
    }
}

impl DisplayAs for CollectExec {
    fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "CollectExec: {} query={} parts={}",
            self.job.kind.name(),
            self.job.query,
            join(&self.job.woken)
        )
    }
}

impl ExecutionPlan for CollectExec {
    fn name(&self) -> &str {
        "CollectExec"
    }

    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 required_input_distribution(&self) -> Vec<Distribution> {
        vec![Distribution::KeyPartitioned(vec![Arc::new(Column::new(
            ROUTE, 0,
        ))])]
    }

    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!("CollectExec takes one input, {} given", c.len()))
        })?;
        Ok(Arc::new(CollectExec::new(input, self.job.clone())))
    }

    fn execute(
        &self,
        partition: usize,
        context: Arc<TaskContext>,
    ) -> Result<SendableRecordBatchStream> {
        let ts = task_state(&context)?;
        let part = self.job.part(ts.stage_partition(partition))?;
        let input = self.input.execute(partition, context)?;
        let job = self.job.clone();
        let schema = self.schema.clone();
        let out = schema.clone();
        let work = async move {
            // Border rows only, not the start and level rows.
            let arrived = arrivals(input, part)
                .await?
                .iter()
                .filter(|(n, _)| *n != START)
                .count() as u64;
            let loaded = state::PartSrc::Alone(
                state::part_alone(&ts, &job.spec, part).await?,
                job.spec.key.parts(),
            );
            let spare = state::spare(&ts, &job.spec, part).await?;
            let keep_spare = |bfs| {
                if let Ok(mut s) = spare.lock() {
                    *s = Some(bfs);
                }
            };
            // A part no row reached was never stepped: it reached nothing.
            let side: Arc<Kept<Side>> = ts
                .job_state(&query_key(&job.query, part), partition, || async {
                    Ok(Mutex::new(None))
                })
                .await?;
            let taken = side
                .lock()
                .map_err(|_| ext("a part's side was poisoned"))?
                .take();
            let (ids, base) = (loaded.ids(), loaded.part(part).base());
            let original = |l: u32| -> Result<u32> {
                ids.original(base + u64::from(l))
                    .ok_or_else(|| ext(format!("local node {l} past part {part}")))
            };
            let mut reached: Vec<Option<u64>> = Vec::new();
            let mut values: Vec<Option<u64>> = Vec::new();
            if job.kind == Query::Load {
                let state::PartSrc::Alone(l, _) = &loaded;
                for (id, v) in summary_rows(&l.summary()) {
                    reached.push(Some(id));
                    values.push(Some(v));
                }
            }
            match taken {
                None => {}
                Some(Side::Sssp(b)) => {
                    let (wp, sp) = (&b.0, &b.1);
                    match sp.paths() {
                        // One part: the kernel's own answer.
                        Some(paths) => {
                            for l in 0..wp.count() as u32 {
                                if let Some(d) = paths.distance(l) {
                                    reached.push(Some(u64::from(original(l)?)));
                                    values.push(Some(d));
                                }
                            }
                        }
                        None => {
                            for &(l, d) in sp.distances() {
                                reached.push(Some(u64::from(original(l)?)));
                                values.push(Some(d));
                            }
                        }
                    }
                }
                Some(Side::Closure(cp)) => {
                    for (l, w) in cp.words() {
                        reached.push(Some(u64::from(original(l)?)));
                        values.push(Some(w));
                    }
                }
                Some(Side::Reach(side)) => {
                    for &l in side.reached() {
                        reached.push(Some(u64::from(original(l)?)));
                    }
                    let (_, bfs, _) = side.into_parts();
                    keep_spare(bfs);
                }
                Some(Side::Sweep(side)) => {
                    for &l in side.reach.reached() {
                        reached.push(Some(u64::from(original(l)?)));
                    }
                    let (_, bfs, _) = side.reach.into_parts();
                    keep_spare(bfs);
                }
                Some(Side::Khop(side)) => {
                    for &l in side.reached() {
                        reached.push(Some(u64::from(original(l)?)));
                    }
                }
                // Each component once: the node it is named after.
                Some(Side::Wcc(side)) => {
                    for (l, name) in side.into_names().into_iter().enumerate() {
                        let v = original(l as u32)?;
                        if name == v {
                            reached.push(Some(u64::from(v)));
                        }
                    }
                }
            }
            values.resize(reached.len(), None);
            let mut stat: Vec<Option<u64>> = vec![None; reached.len()];
            reached.push(None);
            values.push(None);
            stat.push(Some(arrived));
            Ok(RecordBatch::try_new(
                out,
                vec![
                    Arc::new(UInt64Array::from(reached)),
                    Arc::new(UInt64Array::from(stat)),
                    Arc::new(UInt64Array::from(values)),
                ],
            )?)
        };
        let s = futures::stream::once(work);
        Ok(Box::pin(RecordBatchStreamAdapter::new(schema, s)))
    }
}