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/client.rs

//! The client side: a query as one Ballista job.
//!
//! The plan is a recursive query whose static term is the sources (as round rows to their
//! parts) and whose recursive term is [`StepExec`] over the work table hash-shuffled on the
//! route column, so each round is a stage of the fork's loop and the border sends cross
//! machines as Arrow batches through Ballista's Flight shuffle; it ends with the first round
//! that sends nothing. Above it, [`CollectExec`] (one partition per part, on the part's
//! executor) gives the answer in original node ids.
//!
//! The client holds the core's central index ([`kleene_index::Central`]), never the graph's
//! edges: from it each source is placed in its part by the id ranges alone, only the parts
//! the sources can reach (the part graph's `Reach`) are woken (one partition each, the
//! others get no task), and its placement table names each part's executor. The loop stops
//! at the first round that sends nothing. The client never reads the graph: a load job
//! ([`Cluster::prepare`]) loads every part on its executor and brings back the parts'
//! summaries, from which the client builds the central index; the split's ids come from the
//! node count and the key alone ([`kleene_graph::SplitIds::of`]).

use std::sync::Arc;
use std::time::{Duration, Instant};

use arrow_array::{Array, RecordBatch, UInt64Array};
use ballista::prelude::SessionConfigExt;
use ballista_core::config::{BALLISTA_RECURSIVE_MAX_ROUNDS, BallistaConfig};
use ballista_core::execution_plans::execute_physical_plan;
use datafusion::catalog::memory::MemorySourceConfig;
use datafusion::error::{DataFusionError, Result};
use datafusion::physical_plan::ExecutionPlan;
use datafusion::physical_plan::Partitioning;
use datafusion::physical_plan::coalesce_partitions::CoalescePartitionsExec;
use datafusion::physical_plan::common::collect;
use datafusion::physical_plan::expressions::Column;
use datafusion::physical_plan::recursive_query::RecursiveQueryExec;
use datafusion::physical_plan::repartition::RepartitionExec;
use datafusion::physical_plan::work_table::WorkTableExec;
use datafusion::prelude::SessionConfig;
use datafusion_proto::protobuf::PhysicalPlanNode;
use kleene_graph::{PartSummary, Sends, SplitIds};
use kleene_index::Central;

use crate::codec::KleeneCodec;
use crate::exec::{
    ARRIVED, CollectExec, ID, Job, Query, ROUTE, SOURCE, START, StepExec, VALUE, round_schema,
    routes_of, rows_compact, summaries_of,
};
use crate::spec::GraphSpec;
use crate::whole::{
    AnswerExec, COUNT, EndExec, SliceExec, UNIT, WholeJob, WholeQuery, slice_schema,
};

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

/// A graph prepared for queries ([`Cluster::prepare`]): its split's ids and the central
/// index built from the executors' summaries of their parts.
#[derive(Debug)]
pub struct Prepared {
    /// The graph and its split.
    pub spec: GraphSpec,
    /// The split's ids (from the node count and the key).
    pub ids: SplitIds,
    /// Per part its summary, as its executor gave it.
    pub summaries: Vec<PartSummary>,
    /// The central index: its placement names each part's machine, its part graph's reach
    /// picks the parts a query wakes.
    pub central: Central,
    /// Per part its executor id, from the central index's placement and the machine names,
    /// or `None` (each part where its first task runs).
    pub machines: Option<Vec<String>>,
}

/// A query's start as the central index sees it: the parts it wakes and the sources as
/// round rows to them.
#[derive(Debug)]
pub struct Start {
    /// The parts the sources can reach, rising (partition `i` is part `woken[i]`).
    pub woken: Vec<u32>,
    /// Per part its route value, for the woken parts.
    pub routes: Arc<Vec<Option<u64>>>,
    /// The sources as sends to their parts (local node, value).
    pub sends: Sends<u64>,
    /// The sources as round rows ([`rows_compact`] of `sends`).
    pub rows: RecordBatch,
}

impl Start {
    /// The start of `sends` to the woken parts.
    pub fn new(woken: Vec<u32>, routes: Arc<Vec<Option<u64>>>, sends: Sends<u64>) -> Result<Self> {
        let rows = rows_compact(&sends, &routes, None)?;
        Ok(Start {
            woken,
            routes,
            sends,
            rows,
        })
    }

    /// The start rows with every value `v`.
    pub fn with_values(&self, v: u64) -> Result<RecordBatch> {
        let mut sends = self.sends.clone();
        sends.value.iter_mut().for_each(|x| *x = v);
        rows_compact(&sends, &self.routes, None)
    }
}

/// Per part its executor id: part `p` on machine `placement[p]` of `names`.
fn machines_of(placement: &[u32], names: Option<Vec<String>>) -> Result<Option<Vec<String>>> {
    let Some(names) = names else {
        return Ok(None);
    };
    placement
        .iter()
        .enumerate()
        .map(|(p, &m)| {
            names
                .get(m as usize)
                .cloned()
                .ok_or_else(|| ext(format!("part {p} on machine {m} of {}", names.len())))
        })
        .collect::<Result<Vec<_>>>()
        .map(Some)
}

impl Prepared {
    /// The graph of `spec` from its parts' `summaries` (one per part, by part): the central
    /// index places part `p` on machine `placement[p]` (an index into `machines`, the
    /// executor ids; no machines: no placement).
    pub fn from_summaries(
        spec: GraphSpec,
        summaries: Vec<PartSummary>,
        placement: Vec<u32>,
        machines: Option<Vec<String>>,
    ) -> Result<Self> {
        let n: u64 = summaries.iter().map(|s| s.count).sum();
        let ids = SplitIds::of(n as usize, &spec.split_key()?).map_err(ext)?;
        if ids.parts() != summaries.len() {
            return Err(ext(format!(
                "{} summaries for a split of {} parts",
                summaries.len(),
                ids.parts()
            )));
        }
        let machines = machines_of(&placement, machines)?;
        let central = Central::build(&summaries, placement).map_err(ext)?;
        Ok(Prepared {
            spec,
            ids,
            summaries,
            central,
            machines,
        })
    }

    /// The number of parts.
    pub fn parts(&self) -> usize {
        self.ids.parts()
    }

    /// Where a query from `sources` (original node ids) starts: the central index places
    /// each source in its part from the id ranges alone and wakes the parts they reach.
    pub fn start(&self, sources: &[u32]) -> Result<Start> {
        let rows: Vec<(u32, u64)> = sources.iter().map(|&s| (s, 1)).collect();
        self.start_values(&rows)
    }

    /// As [`Prepared::start`], each row `(original node, value)` with its own value.
    pub fn start_values(&self, rows: &[(u32, u64)]) -> Result<Start> {
        let ids = &self.ids;
        let sids = rows
            .iter()
            .map(|&(s, _)| {
                ids.from_original(s)
                    .ok_or_else(|| ext(format!("source {s} past the graph")))
            })
            .collect::<Result<Vec<u64>>>()?;
        let woken = self.central.wake_from(&sids).map_err(ext)?;
        let routes = Arc::new(routes_of(&woken, self.parts())?);
        let mut sends = Sends::<u64>::new();
        for (&sid, &(_, v)) in sids.iter().zip(rows) {
            let p = self
                .central
                .part_of(sid)
                .ok_or_else(|| ext(format!("node {sid} in no part")))?;
            let (_, l) = self
                .central
                .ids()
                .position(sid)
                .ok_or_else(|| ext(format!("node {sid} in no part")))?;
            sends.push(p, l as u32, v);
        }
        Start::new(woken, routes, sends)
    }

    /// Where a query over every part starts (weak components): every part woken, each by
    /// one [`START`] row.
    pub fn start_all(&self) -> Result<Start> {
        start_all(self.parts())
    }

    fn job(&self, query: &str, kind: Query, woken: &[u32]) -> Result<Job> {
        let levels = match kind {
            Query::Sweep => {
                let order = self.central.order().map_err(ext)?;
                (0..self.parts() as u32)
                    .map(|p| order.level(order.group_of(p)))
                    .collect()
            }
            _ => Vec::new(),
        };
        Ok(Job {
            spec: self.spec.clone(),
            query: query.to_string(),
            kind,
            woken: woken.to_vec(),
            levels,
            machines: self
                .machines
                .as_ref()
                .map(|m| woken.iter().map(|&p| m[p as usize].clone()).collect()),
        })
    }

    /// The job's plan for `kind` from `start`.
    pub fn plan(&self, query: &str, kind: Query, start: &Start) -> Result<Arc<dyn ExecutionPlan>> {
        plan_of(self.job(query, kind, &start.woken)?, start)
    }
}

/// Every part of a split of `parts` woken, each by one [`START`] row.
fn start_all(parts: usize) -> Result<Start> {
    let woken: Vec<u32> = (0..parts as u32).collect();
    let routes = Arc::new(routes_of(&woken, parts)?);
    let mut sends = Sends::<u64>::new();
    for &p in &woken {
        sends.push(p, START, 0);
    }
    Start::new(woken, routes, sends)
}

/// The plan of `job` from `start`: the rounds, then the collect.
fn plan_of(job: Job, start: &Start) -> Result<Arc<dyn ExecutionPlan>> {
    {
        let schema = round_schema();
        let n = start.woken.len();
        let route = || -> Arc<dyn datafusion::physical_expr::PhysicalExpr> {
            Arc::new(Column::new(ROUTE, 0))
        };
        let first =
            MemorySourceConfig::try_new_exec(&[vec![start.rows.clone()]], schema.clone(), None)?;
        let work: Arc<dyn ExecutionPlan> =
            Arc::new(WorkTableExec::new(ROUNDS.into(), schema.clone(), None)?);
        let routed: Arc<dyn ExecutionPlan> = Arc::new(RepartitionExec::try_new(
            work,
            Partitioning::Hash(vec![route()], n),
        )?);
        let step: Arc<dyn ExecutionPlan> =
            Arc::new(StepExec::new(routed, job.clone(), start.routes.clone()));
        // One partition on top, as DataFusion plans a recursive term.
        let step = Arc::new(CoalescePartitionsExec::new(step));
        let rounds: Arc<dyn ExecutionPlan> = Arc::new(RecursiveQueryExec::try_new(
            ROUNDS.into(),
            schema,
            first,
            step,
            false,
        )?);
        let routed: Arc<dyn ExecutionPlan> = Arc::new(RepartitionExec::try_new(
            rounds,
            Partitioning::Hash(vec![route()], n),
        )?);
        let collect = Arc::new(CollectExec::new(routed, job));
        Ok(Arc::new(CoalescePartitionsExec::new(collect)))
    }
}

/// A job's answer rows as a [`Run`].
fn read_run(out: &[RecordBatch], woken: Vec<u32>, wall: Duration) -> Result<Run> {
    let (mut ids, mut values, mut arrived) = (Vec::new(), Vec::new(), 0u64);
    for b in out {
        let col = |name: &str| {
            b.column_by_name(name)
                .and_then(|c| c.as_any().downcast_ref::<UInt64Array>())
                .ok_or_else(|| ext(format!("the job's rows without `{name}`")))
        };
        let (id, n, v) = (col(ID)?, col(ARRIVED)?, col(VALUE)?);
        for k in 0..b.num_rows() {
            if id.is_valid(k) {
                ids.push(id.value(k));
                if v.is_valid(k) {
                    values.push((id.value(k), v.value(k)));
                }
            } else if n.is_valid(k) {
                arrived += n.value(k);
            }
        }
    }
    ids.sort_unstable();
    values.sort_unstable();
    Ok(Run {
        ids,
        sent: arrived,
        wall,
        woken,
        values,
    })
}

/// The recursive query's name.
const ROUNDS: &str = "kleene_rounds";

/// A Ballista cluster by its scheduler's address.
#[derive(Clone, Debug)]
pub struct Cluster {
    /// `http://host:port` of the scheduler.
    pub url: String,
}

/// What one query gave and cost.
#[derive(Clone, Debug)]
pub struct Run {
    /// The answer: original node ids, rising.
    pub ids: Vec<u64>,
    /// Border sends over all rounds (rows that arrived at the parts, past the start rows).
    pub sent: u64,
    /// Wall time of the job.
    pub wall: Duration,
    /// The parts the central index woke (each one task per stage; the others none).
    pub woken: Vec<u32>,
    /// Per answer row with a value, `(id, value)`, rising: a shortest-path search's
    /// `(original node, distance)`, a closure's `(original node, word of starts)`, a load
    /// job's summary rows.
    pub values: Vec<(u64, u64)>,
}

/// What a closure gave and cost ([`Cluster::closure`]).
#[derive(Clone, Debug)]
pub struct ClosureRun {
    /// `(x, z)` in original node ids, rising: each base pair's start `x` and every node `z`
    /// reached from its end (the end included).
    pub pairs: Vec<(u32, u32)>,
    /// Border sends over all batches.
    pub sent: u64,
    /// Wall time of all batches.
    pub wall: Duration,
    /// Jobs run (one per batch of 64 starts).
    pub jobs: usize,
}

impl Cluster {
    /// The cluster whose scheduler is at `url`.
    pub fn new(url: impl Into<String>) -> Self {
        Cluster { url: url.into() }
    }

    /// The session the jobs run with: one partition per part (no coalescing), the loop
    /// without a round limit of its own, kleene's codec.
    pub fn session(parts: usize) -> SessionConfig {
        SessionConfig::new_with_ballista()
            .with_target_partitions(parts)
            .set_str(BALLISTA_RECURSIVE_MAX_ROUNDS, "1000000")
            .with_ballista_physical_extension_codec(Arc::new(KleeneCodec::default()))
    }

    async fn run(&self, plan: Arc<dyn ExecutionPlan>, parts: usize) -> Result<Vec<RecordBatch>> {
        let stream = execute_physical_plan::<PhysicalPlanNode>(
            self.url.clone(),
            &BallistaConfig::default(),
            plan,
            &KleeneCodec::default(),
            uuid::Uuid::new_v4().to_string(),
            Self::session(parts),
        )
        .await?;
        collect(stream).await
    }

    /// Reachability from `sources` (original node ids) over `g`.
    pub async fn reach(&self, g: &Prepared, sources: &[u32]) -> Result<Run> {
        let t = Instant::now();
        let start = g.start(sources)?;
        let r = self.query(g, Query::Reach, start, t).await?;
        Ok(Run {
            sent: r.sent.saturating_sub(sources.len() as u64),
            ..r
        })
    }

    /// Reachability from `sources` over `g` in part order: one pass over the levels of the
    /// part graph's strong components, feeders first (see [`Query::Sweep`]).
    pub async fn sweep(&self, g: &Prepared, sources: &[u32]) -> Result<Run> {
        let t = Instant::now();
        let mut start = g.start(sources)?;
        let levels = crate::exec::level_rows(&start.routes, &start.woken, false)?;
        start.rows = datafusion::arrow::compute::concat_batches(
            &round_schema(),
            &[start.rows.clone(), levels],
        )?;
        let r = self.query(g, Query::Sweep, start, t).await?;
        Ok(Run {
            sent: r.sent.saturating_sub(sources.len() as u64),
            ..r
        })
    }

    /// `spec`'s graph made ready for queries without the client reading it: a load job
    /// loads every part on its executor (each part alone, [`kleene_graph::Split::part_only`],
    /// kept for the queries) and brings back the parts' summaries; the central index is
    /// built from them, part `p` placed on machine `placement[p]` (an index into
    /// `machines`, the executor ids).
    pub async fn prepare(
        &self,
        spec: GraphSpec,
        placement: Vec<u32>,
        machines: Option<Vec<String>>,
    ) -> Result<Prepared> {
        let parts = spec.key.parts();
        if placement.len() != parts {
            return Err(ext(format!(
                "a placement of {} parts for a split of {parts}",
                placement.len()
            )));
        }
        let start = start_all(parts)?;
        let by_part = machines_of(&placement, machines.clone())?;
        let job = Job {
            spec: spec.clone(),
            query: uuid::Uuid::new_v4().simple().to_string(),
            kind: Query::Load,
            woken: start.woken.clone(),
            machines: by_part,
            levels: Vec::new(),
        };
        let out = self.run(plan_of(job, &start)?, parts).await?;
        let r = read_run(&out, start.woken, Duration::ZERO)?;
        let summaries = summaries_of(&r.values)?;
        Prepared::from_summaries(spec, summaries, placement, machines)
    }

    /// Shortest paths (every edge weight 1) from `source` (original id) over `g`:
    /// [`Run::values`] holds `(original node, distance)` of every node reached.
    pub async fn sssp(&self, g: &Prepared, source: u32) -> Result<Run> {
        let t = Instant::now();
        let start = g.start_values(&[(source, SOURCE)])?;
        let r = self.query(g, Query::Sssp, start, t).await?;
        Ok(Run {
            sent: r.sent.saturating_sub(1),
            ..r
        })
    }

    /// The closure of `base` pairs `(x, y)` (original ids) along `g`'s edges: every `(x,
    /// z)` with `z` reached from `y` (the Datalog `tc(X, Z) :- base(X, Z). tc(X, Z) :-
    /// tc(X, Y), edge(Y, Z).`). The starts go 64 to a job, each a bit of a word.
    pub async fn closure(&self, g: &Prepared, base: &[(u32, u32)]) -> Result<ClosureRun> {
        let t = Instant::now();
        let mut starts: Vec<u32> = base.iter().map(|e| e.0).collect();
        starts.sort_unstable();
        starts.dedup();
        let (mut pairs, mut sent, mut jobs) = (Vec::new(), 0u64, 0usize);
        for batch in starts.chunks(64) {
            let rows: Vec<(u32, u64)> = base
                .iter()
                .filter_map(|&(x, y)| batch.binary_search(&x).ok().map(|k| (y, 1u64 << k)))
                .collect();
            let start = g.start_values(&rows)?;
            let r = self.query(g, Query::Closure, start, Instant::now()).await?;
            jobs += 1;
            sent += r.sent.saturating_sub(rows.len() as u64);
            for &(z, word) in &r.values {
                let z = u32::try_from(z).map_err(ext)?;
                let mut w = word;
                while w != 0 {
                    let k = w.trailing_zeros() as usize;
                    w &= w - 1;
                    pairs.push((batch[k], z));
                }
            }
        }
        pairs.sort_unstable();
        Ok(ClosureRun {
            pairs,
            sent,
            wall: t.elapsed(),
            jobs,
        })
    }

    /// Load every part of `g` on its executor ahead of the queries (each part alone,
    /// [`kleene_graph::Split::part_only`]).
    pub async fn load_parts(&self, g: &Prepared) -> Result<Run> {
        let t = Instant::now();
        let start = g.start_all()?;
        self.query(g, Query::Load, start, t).await
    }

    /// The nodes within `k` hops of `source` (original id) over `g`, the source included.
    pub async fn khop(&self, g: &Prepared, source: u32, k: u32) -> Result<Run> {
        let t = Instant::now();
        let mut start = g.start(&[source])?;
        // The source arrives at depth 0.
        start.rows = start.with_values(0)?;
        let r = self.query(g, Query::Khop(k), start, t).await?;
        Ok(Run {
            sent: r.sent.saturating_sub(1),
            ..r
        })
    }

    /// Weak components of `g`: [`Run::ids`] holds each component's name (its least
    /// original node), so their number is the count of components.
    pub async fn wcc(&self, g: &Prepared) -> Result<Run> {
        let t = Instant::now();
        let start = g.start_all()?;
        self.query(g, Query::Wcc, start, t).await
    }

    /// `kind` from `start` as one job; `sent` counts every row that arrived.
    async fn query(&self, g: &Prepared, kind: Query, start: Start, t: Instant) -> Result<Run> {
        let query = uuid::Uuid::new_v4().simple().to_string();
        let out = self
            .run(g.plan(&query, kind, &start)?, start.woken.len())
            .await?;
        read_run(&out, start.woken, t.elapsed())
    }
}

/// A graph every machine of the cluster holds whole (Distributed v1.1, see
/// [`crate::whole`]): nothing on the client but its path and the machines' weights.
#[derive(Clone, Debug)]
pub struct WholeGraph {
    /// 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.
    pub weights: Vec<u32>,
    /// Per machine its executor id (machine `m` runs partition `m`), when given.
    pub machines: Option<Vec<String>>,
    /// A sliced search's levels below this many edges run whole on every machine
    /// ([`kleene_graph::LOCAL_BELOW`] by default).
    pub local_below: u64,
}

impl WholeGraph {
    /// The graph at `path` (edge type `edge`) on machines of `weights`, levels below
    /// [`kleene_graph::LOCAL_BELOW`] edges whole on every machine.
    pub fn new(path: &str, edge: &str, weights: Vec<u32>, machines: Option<Vec<String>>) -> Self {
        WholeGraph {
            path: path.into(),
            edge: edge.into(),
            weights,
            machines,
            local_below: kleene_graph::LOCAL_BELOW,
        }
    }
}

/// What a whole-graph query gave and cost.
#[derive(Clone, Debug)]
pub struct WholeRun {
    /// Per unit (a search, in source order; one unit for a sliced search or the
    /// components) its count: vertices reached with the sources, or components.
    pub counts: Vec<u64>,
    /// Wall time of the job.
    pub wall: Duration,
}

impl WholeGraph {
    fn job(&self, kind: WholeQuery, sources: &[u32]) -> WholeJob {
        WholeJob {
            path: self.path.clone(),
            edge: self.edge.clone(),
            weights: self.weights.clone(),
            machines: self.machines.clone(),
            query: uuid::Uuid::new_v4().simple().to_string(),
            kind,
            sources: sources.to_vec(),
            local_below: self.local_below,
        }
    }

    /// The job's plan: the start rows (one per machine, no bytes) routed to the machines;
    /// for a sliced search the rounds (the fork's loop, a level a round, the finds sent to
    /// every machine) between them and the answers.
    pub fn plan(&self, job: &WholeJob) -> Result<Arc<dyn ExecutionPlan>> {
        let n = job.count();
        let routes = job.routes()?;
        let schema = slice_schema();
        let start = RecordBatch::try_new(
            schema.clone(),
            vec![
                Arc::new(UInt64Array::from(routes)),
                Arc::new(crate::whole::found_rows(Vec::new(), n)?),
            ],
        )?;
        let route = || -> Arc<dyn datafusion::physical_expr::PhysicalExpr> {
            Arc::new(Column::new(ROUTE, 0))
        };
        let first: Arc<dyn ExecutionPlan> =
            MemorySourceConfig::try_new_exec(&[vec![start]], schema.clone(), None)?;
        let answer = |input: Arc<dyn ExecutionPlan>| -> Arc<dyn ExecutionPlan> {
            Arc::new(CoalescePartitionsExec::new(Arc::new(AnswerExec::new(
                input,
                job.clone(),
            ))))
        };
        match job.kind {
            WholeQuery::Slice(_) => {
                let work: Arc<dyn ExecutionPlan> =
                    Arc::new(WorkTableExec::new(ROUNDS.into(), schema.clone(), None)?);
                let routed: Arc<dyn ExecutionPlan> = Arc::new(RepartitionExec::try_new(
                    work,
                    Partitioning::Hash(vec![route()], n),
                )?);
                let step = Arc::new(CoalescePartitionsExec::new(Arc::new(SliceExec::new(
                    routed,
                    job.clone(),
                ))));
                let rounds: Arc<dyn ExecutionPlan> = Arc::new(RecursiveQueryExec::try_new(
                    ROUNDS.into(),
                    schema,
                    first,
                    step,
                    false,
                )?);
                // The answers wait for the last round but read none of the rounds' finds
                // again: each machine's side holds its answer.
                Ok(answer(Arc::new(EndExec::new(rounds, n))))
            }
            _ => Ok(answer(Arc::new(RepartitionExec::try_new(
                first,
                Partitioning::Hash(vec![route()], n),
            )?))),
        }
    }
}

impl Cluster {
    async fn whole(&self, g: &WholeGraph, kind: WholeQuery, sources: &[u32]) -> Result<WholeRun> {
        let t = Instant::now();
        let job = g.job(kind, sources);
        let units = match job.kind {
            WholeQuery::Many(_) => sources.len(),
            WholeQuery::Load => job.count(),
            _ => 1,
        };
        let out = self.run(g.plan(&job)?, job.count()).await?;
        let wall = t.elapsed();
        let mut counts = vec![None; units];
        for b in &out {
            let col = |name: &str| {
                b.column_by_name(name)
                    .and_then(|c| c.as_any().downcast_ref::<UInt64Array>())
                    .ok_or_else(|| ext(format!("the job's answers without `{name}`")))
            };
            let (unit, count) = (col(UNIT)?, col(COUNT)?);
            for k in 0..b.num_rows() {
                let slot = counts
                    .get_mut(unit.value(k) as usize)
                    .ok_or_else(|| ext(format!("an answer for unit {}", unit.value(k))))?;
                if slot.replace(count.value(k)).is_some() {
                    return Err(ext(format!("unit {} answered twice", unit.value(k))));
                }
            }
        }
        let counts = counts
            .into_iter()
            .enumerate()
            .map(|(i, c)| c.ok_or_else(|| ext(format!("no answer for unit {i}"))))
            .collect::<Result<_>>()?;
        Ok(WholeRun { counts, wall })
    }

    /// One search from `sources` (original ids) cut in slices over the machines: reach
    /// (`hops` `None`) or k hops; [`WholeRun::counts`] holds the vertices reached, the
    /// sources included.
    pub async fn sliced(
        &self,
        g: &WholeGraph,
        sources: &[u32],
        hops: Option<u32>,
    ) -> Result<WholeRun> {
        self.whole(g, WholeQuery::Slice(hops), sources).await
    }

    /// One search per source handed out whole (each machine today's kernel on its share):
    /// per source the vertices reached, the source included.
    pub async fn many(
        &self,
        g: &WholeGraph,
        sources: &[u32],
        hops: Option<u32>,
    ) -> Result<WholeRun> {
        self.whole(g, WholeQuery::Many(hops), sources).await
    }

    /// Weak components, whole on machine 0: their number.
    pub async fn components(&self, g: &WholeGraph) -> Result<WholeRun> {
        self.whole(g, WholeQuery::Wcc, &[]).await
    }

    /// Load the graph on every machine before any query: per machine its vertices.
    pub async fn load(&self, g: &WholeGraph) -> Result<WholeRun> {
        self.whole(g, WholeQuery::Load, &[]).await
    }
}