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

nordisk/kleene

crates/kleene-graph/src/rounds.rs

//! Local-first rounds over the parts of a [`Split`]: each part runs the engine's own kernel on
//! its part until it finds nothing new, then the parts hand each other only the border nodes
//! whose value is new, and it ends when no part receives anything new.
//!
//! One code for one machine and for many: the number of parts is the split's. A split of one
//! part ([`Split::whole`]) has no border, so each function is then one call of today's kernel
//! on the whole graph (a breadth-first search, the weak components, the shortest paths, a
//! set propagation) and no exchange. With more parts the same kernel runs on each part's own
//! matrix first; later rounds start from what arrived.
//!
//! Each function is a loop over per-part step objects ([`ReachPart`], ...): one part's side
//! of the rounds, kept between them, taking the entries that arrived for it and giving its
//! border sends ([`Sends`]). The loop here hands the sends over inside this process; a
//! runner over machines keeps the same objects where the parts sit and moves the same sends
//! (as Arrow batches, [`Sends::to_batch`]) between them.
//!
//! What runs here is what a value only improves in (reachability, closure, components,
//! shortest paths): the order of the work cannot change the answer, so every answer equals
//! the one-part answer.

use std::sync::Arc;

use arrow_array::{Array, RecordBatch, UInt32Array, UInt64Array};
use arrow_schema::{DataType, Field, Schema};
use kleene_sparse::{
    BitsetUnion, BoolOrAnd, CpuDevice, Csr, Mask, MinPlus, SparseBackend, Value, Vector,
};

use crate::backend::GraphBackend;
use crate::bfs::{BfsOptions, BfsState, bfs_with};
use crate::graph::{Graph, GraphError};
use crate::order::PartOrder;
use crate::paths::SsspOptions;
use crate::slices::{NodeSet, each_on, pack, unpack};
use crate::split::{Part, Split, SplitIds};

/// What the rounds of a run did.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Exchanges {
    /// Exchanges between parts (0 with one part, or when nothing crossed a border).
    pub exchanges: u32,
    /// Border entries handed over, summed over the exchanges (each a node and its value).
    pub sent: u64,
    /// Per part the number of times it ran (a part nothing reaches runs 0 times).
    pub runs: Vec<u32>,
}

impl Exchanges {
    fn new(parts: usize) -> Self {
        Exchanges {
            runs: vec![0; parts],
            ..Exchanges::default()
        }
    }

    /// The parts that ran at least once.
    pub fn woken(&self) -> usize {
        self.runs.iter().filter(|&&r| r > 0).count()
    }
}

/// [`Sends::combine`] folds a bucket into an array over its node range when it holds at
/// least one send per this many nodes of the range, else it sorts the bucket. Measured on
/// oden (32 threads, `combine_costs` in `tests/slices.rs`, three parts of 5.6M nodes, half
/// the sends to a hundredth of the nodes): 4 was fastest or even at every density from
/// 1/64 to 16 sends a node (16.8M sends: 144 ms; always sorting 203 ms; one sort of all the
/// sends on one thread, as before, 3881 ms). See `bench/distributed.md` (JOB X2).
pub const COMBINE_DENSE_RATIO: u64 = 4;
/// [`Sends::combine`] cuts a part's node range into buckets of at least this many nodes.
pub const COMBINE_BUCKET_MIN: u64 = 1 << 14;
/// Fewer sends than this are combined in one piece (no worker is woken for them).
pub const COMBINE_SERIAL_BELOW: usize = 1 << 15;

/// Per part, `(local node, value)` entries waiting for it.
type Inbox<T> = Vec<Vec<(u32, T)>>;

/// Border sends: per entry the target part, the target's local node and the value. A
/// part's step gives them; the rounds hand them to the target parts.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Sends<T> {
    /// Per entry the part it goes to.
    pub part: Vec<u32>,
    /// Per entry the local node (in the target part) it goes to.
    pub node: Vec<u32>,
    /// Per entry the value.
    pub value: Vec<T>,
}

/// The column names of [`Sends::to_batch`].
pub const SEND_PART: &str = "part";
/// The column of target local nodes in [`Sends::to_batch`].
pub const SEND_NODE: &str = "node";
/// The column of values in [`Sends::to_batch`].
pub const SEND_VALUE: &str = "value";

impl<T: Value> Sends<T> {
    /// No sends.
    pub fn new() -> Self {
        Sends {
            part: Vec::new(),
            node: Vec::new(),
            value: Vec::new(),
        }
    }

    /// The number of entries.
    pub fn len(&self) -> usize {
        self.part.len()
    }

    /// Whether there is no entry.
    pub fn is_empty(&self) -> bool {
        self.part.is_empty()
    }

    /// One entry per (part, node), its values folded with the query's own `add` (or for
    /// reach and the closure, min for k hops, components and shortest paths), sorted by
    /// part and node: what a receiver folds anyway, folded at the sender, so a node crosses
    /// once however many border edges reach it.
    ///
    /// No sort over the sends: they are counted into buckets of node ranges per target part
    /// (pieces of the sends on the device's threads), and each bucket is folded on its own
    /// (one bucket a job): into an array over its range when the bucket's sends are at
    /// least `1 / COMBINE_DENSE_RATIO` of the range, else by sorting the bucket alone. `add`
    /// must be commutative and associative (or, min are): the result is then the same on
    /// every device and thread count.
    pub fn combine(self, add: impl Fn(T, T) -> T + Sync, device: Option<&CpuDevice>) -> Self {
        self.combine_dense_from(add, device, COMBINE_DENSE_RATIO)
    }

    /// [`Sends::combine`] with another density rule (`ratio` 0: always sort a bucket): for
    /// measuring the rule only.
    #[doc(hidden)]
    pub fn combine_dense_from(
        self,
        add: impl Fn(T, T) -> T + Sync,
        device: Option<&CpuDevice>,
        ratio: u64,
    ) -> Self {
        let n = self.len();
        if n == 0 {
            return self;
        }
        let threads = device.map_or(1, |d| d.threads()).max(1);
        let pieces = if n < COMBINE_SERIAL_BELOW {
            1
        } else {
            threads * 2
        };
        let piece = n.div_ceil(pieces);
        let range = |i: usize| i * piece..((i + 1) * piece).min(n);
        // Per target part: its sends and its highest node.
        let seen: Vec<Vec<(u64, u32)>> = each_on(pieces, device, |i| {
            let mut per: Vec<(u64, u32)> = Vec::new();
            for k in range(i) {
                let p = self.part[k] as usize;
                if p >= per.len() {
                    per.resize(p + 1, (0, 0));
                }
                per[p].0 += 1;
                per[p].1 = per[p].1.max(self.node[k]);
            }
            per
        });
        let parts = seen.iter().map(Vec::len).max().unwrap_or(0);
        let mut width = vec![0u64; parts];
        let mut first = vec![0usize; parts + 1];
        for p in 0..parts {
            let (count, top) = seen
                .iter()
                .filter_map(|s| s.get(p))
                .fold((0u64, 0u32), |a, b| (a.0 + b.0, a.1.max(b.1)));
            let buckets = if count == 0 {
                0
            } else {
                let span = u64::from(top) + 1;
                (threads as u64 * 4)
                    .min(span.div_ceil(COMBINE_BUCKET_MIN))
                    .max(1)
            };
            width[p] = if buckets == 0 {
                1
            } else {
                (u64::from(top) + 1).div_ceil(buckets)
            };
            first[p + 1] = first[p] + buckets as usize;
        }
        let buckets = first[parts];
        let bucket_of =
            |p: u32, v: u32| first[p as usize] + (u64::from(v) / width[p as usize]) as usize;
        // Each piece's sends, by bucket.
        let scattered: Vec<Vec<Vec<(u32, T)>>> = each_on(pieces, device, |i| {
            let mut out: Vec<Vec<(u32, T)>> = (0..buckets).map(|_| Vec::new()).collect();
            for k in range(i) {
                out[bucket_of(self.part[k], self.node[k])].push((self.node[k], self.value[k]));
            }
            out
        });
        let part_of = |b: usize| first.partition_point(|&f| f <= b) - 1;
        let folded: Vec<Vec<(u32, T)>> = each_on(buckets, device, |b| {
            let p = part_of(b);
            let lo = ((b - first[p]) as u64 * width[p]) as u32;
            let m: usize = scattered.iter().map(|s| s[b].len()).sum();
            let all = scattered.iter().flat_map(|s| s[b].iter().copied());
            if ratio > 0 && (m as u64).saturating_mul(ratio) >= width[p] {
                let w = width[p] as usize;
                let mut has = vec![0u64; w.div_ceil(64)];
                let mut val: Vec<T> = vec![T::default(); w];
                for (v, x) in all {
                    let at = (v - lo) as usize;
                    if has[at / 64] >> (at % 64) & 1 == 1 {
                        val[at] = add(val[at], x);
                    } else {
                        has[at / 64] |= 1 << (at % 64);
                        val[at] = x;
                    }
                }
                let mut out = Vec::new();
                for (wi, &word) in has.iter().enumerate() {
                    let mut bits = word;
                    while bits != 0 {
                        let at = wi * 64 + bits.trailing_zeros() as usize;
                        out.push((lo + at as u32, val[at]));
                        bits &= bits - 1;
                    }
                }
                out
            } else {
                let mut e: Vec<(u32, T)> = all.collect();
                e.sort_unstable_by_key(|e| e.0);
                e.dedup_by(|b, a| {
                    if a.0 == b.0 {
                        a.1 = add(a.1, b.1);
                        true
                    } else {
                        false
                    }
                });
                e
            }
        });
        let total: usize = folded.iter().map(Vec::len).sum();
        let mut out = Sends {
            part: Vec::with_capacity(total),
            node: Vec::with_capacity(total),
            value: Vec::with_capacity(total),
        };
        for (b, f) in folded.into_iter().enumerate() {
            let p = part_of(b) as u32;
            out.part.extend(std::iter::repeat_n(p, f.len()));
            for (v, x) in f {
                out.node.push(v);
                out.value.push(x);
            }
        }
        out
    }

    /// One entry.
    pub fn push(&mut self, part: u32, node: u32, value: T) {
        self.part.push(part);
        self.node.push(node);
        self.value.push(value);
    }

    /// Every entry of `other` after these (`other` left empty).
    pub fn append(&mut self, other: &mut Sends<T>) {
        self.part.append(&mut other.part);
        self.node.append(&mut other.node);
        self.value.append(&mut other.value);
    }

    /// No entries (the buffers kept).
    pub fn clear(&mut self) {
        self.part.clear();
        self.node.clear();
        self.value.clear();
    }

    /// The `(local node, value)` entries for `part`.
    pub fn for_part(&self, part: u32) -> Vec<(u32, T)> {
        (0..self.len())
            .filter(|&k| self.part[k] == part)
            .map(|k| (self.node[k], self.value[k]))
            .collect()
    }

    /// Each entry put in its part's inbox (`inbox[part]`).
    fn deliver(&mut self, inbox: &mut Inbox<T>) {
        for k in 0..self.len() {
            inbox[self.part[k] as usize].push((self.node[k], self.value[k]));
        }
        self.clear();
    }
}

impl<T: Value + Into<u64> + TryFrom<u64>> Sends<T> {
    /// The schema of [`Sends::to_batch`]: `part` u32, `node` u32, `value` u64.
    pub fn schema() -> Arc<Schema> {
        Arc::new(Schema::new(vec![
            Field::new(SEND_PART, DataType::UInt32, false),
            Field::new(SEND_NODE, DataType::UInt32, false),
            Field::new(SEND_VALUE, DataType::UInt64, false),
        ]))
    }

    /// The entries as one Arrow batch ([`Sends::schema`]); the columns move, nothing is
    /// copied but the values widened to u64.
    pub fn to_batch(self) -> crate::Result<RecordBatch> {
        let value: Vec<u64> = self.value.into_iter().map(Into::into).collect();
        RecordBatch::try_new(
            Self::schema(),
            vec![
                Arc::new(UInt32Array::from(self.part)),
                Arc::new(UInt32Array::from(self.node)),
                Arc::new(UInt64Array::from(value)),
            ],
        )
        .map_err(|e| GraphError::Split(format!("sends as a batch: {e}")))
    }

    /// The entries of a batch [`Sends::to_batch`] made (columns by name).
    pub fn from_batch(batch: &RecordBatch) -> crate::Result<Self> {
        fn col<'a, A: 'static>(b: &'a RecordBatch, name: &str) -> crate::Result<&'a A> {
            b.column_by_name(name)
                .and_then(|c| c.as_any().downcast_ref::<A>())
                .ok_or_else(|| GraphError::Split(format!("sends: no column {name} of its type")))
        }
        let part = col::<UInt32Array>(batch, SEND_PART)?;
        let node = col::<UInt32Array>(batch, SEND_NODE)?;
        let value = col::<UInt64Array>(batch, SEND_VALUE)?;
        if part.null_count() + node.null_count() + value.null_count() > 0 {
            return Err(GraphError::Split("sends: a null entry".to_string()));
        }
        let value = value
            .values()
            .iter()
            .map(|&v| {
                T::try_from(v).map_err(|_| GraphError::Split(format!("sends: value {v} too wide")))
            })
            .collect::<crate::Result<Vec<T>>>()?;
        Ok(Sends {
            part: part.values().to_vec(),
            node: node.values().to_vec(),
            value,
        })
    }
}

impl<T: Value + Into<u64> + TryFrom<u64>> Sends<T> {
    /// The entries compact, as they travel between machines: sorted by part, node and
    /// value; per target part its nodes as a [`NodeSet`] (a rising list of differences, or
    /// a bit map when the nodes are distinct and that is smaller) and the values in the
    /// same order, `size_of::<T>()` bytes each; all compressed by zstd (mzstd) when that is
    /// smaller. The order of the entries is not kept (the receiver folds them anyway).
    pub fn to_compact(&self) -> Vec<u8> {
        self.to_compact_on(None)
    }

    /// [`Sends::to_compact`], the zstd pieces coded on the device's threads when one is
    /// given (the same bytes), and no sort when the entries are already in order (as
    /// [`Sends::combine`] leaves them).
    pub fn to_compact_on(&self, device: Option<&CpuDevice>) -> Vec<u8> {
        let width = std::mem::size_of::<T>().min(8);
        let key = |k: usize| (self.part[k], self.node[k], Into::<u64>::into(self.value[k]));
        let mut order: Vec<usize> = (0..self.len()).collect();
        if !(1..self.len()).all(|k| key(k - 1) <= key(k)) {
            order.sort_unstable_by_key(|&k| key(k));
        }
        let mut raw = Vec::with_capacity(8 + order.len() * (4 + width));
        raw.push(width as u8);
        let mut at = 0;
        while at < order.len() {
            let p = self.part[order[at]];
            let end = at
                + order[at..]
                    .iter()
                    .take_while(|&&k| self.part[k] == p)
                    .count();
            let group = &order[at..end];
            let nodes: Vec<u32> = group.iter().map(|&k| self.node[k]).collect();
            let distinct = nodes.windows(2).all(|w| w[0] < w[1]);
            let set = if distinct {
                NodeSet::from_sorted(nodes)
            } else {
                NodeSet::List(nodes)
            };
            raw.extend_from_slice(&p.to_le_bytes());
            raw.extend_from_slice(&(group.len() as u32).to_le_bytes());
            let enc = set.encode_raw();
            raw.extend_from_slice(&(enc.len() as u32).to_le_bytes());
            raw.extend_from_slice(&enc);
            for &k in group {
                let v: u64 = self.value[k].into();
                raw.extend_from_slice(&v.to_le_bytes()[..width]);
            }
            at = end;
        }
        pack(&raw, device)
    }

    /// The entries [`Sends::to_compact`] wrote (sorted by part, node and value).
    pub fn from_compact(bytes: &[u8]) -> crate::Result<Self> {
        let bad = |m: &str| GraphError::Slices(format!("compact sends: {m}"));
        let raw = unpack(bytes, None)?;
        let Some((&width, mut rest)) = raw.split_first() else {
            return Err(bad("no header"));
        };
        let width = width as usize;
        if width == 0 || width > 8 {
            return Err(bad("a value width outside 1..=8"));
        }
        let mut out = Sends::new();
        let take4 = |rest: &mut &[u8]| -> crate::Result<u32> {
            let (h, r) = rest
                .split_first_chunk::<4>()
                .ok_or_else(|| bad("cut short"))?;
            *rest = r;
            Ok(u32::from_le_bytes(*h))
        };
        while !rest.is_empty() {
            let p = take4(&mut rest)?;
            let count = take4(&mut rest)? as usize;
            let len = take4(&mut rest)? as usize;
            if rest.len() < len + count * width {
                return Err(bad("cut short"));
            }
            let nodes = NodeSet::decode_raw(&rest[..len], false)?.nodes();
            if nodes.len() != count {
                return Err(bad("a part's nodes and values differ in number"));
            }
            rest = &rest[len..];
            for (i, &l) in nodes.iter().enumerate() {
                let mut v = [0u8; 8];
                v[..width].copy_from_slice(&rest[i * width..(i + 1) * width]);
                let v = u64::from_le_bytes(v);
                let v = T::try_from(v).map_err(|_| bad("a value too wide"))?;
                out.push(p, l, v);
            }
            rest = &rest[count * width..];
        }
        Ok(out)
    }
}

/// Hand `touched` (local nodes of `part` with their new values) along the part's border:
/// each border edge sends `value ⊗ weight` to its target's part.
fn send<T: Value, U: Value>(
    part: &Part<T>,
    ids: &SplitIds,
    touched: impl Iterator<Item = (u32, U)>,
    along: impl Fn(U, Option<T>) -> U,
    out: &mut Sends<U>,
) {
    let b = part.border();
    if b.is_empty() {
        return;
    }
    for (l, v) in touched {
        for k in b.range(l) {
            let q = b.target_parts()[k];
            let tl = (b.targets()[k] - ids.base(q)) as u32;
            out.push(q, tl, along(v, b.values().map(|w| w[k])));
        }
    }
}

/// End of a round inside this process: the sends go to their parts' inboxes (repeats
/// folded with `add`); `false` when nothing was sent.
fn exchange<T: Value>(
    inbox: &mut Inbox<T>,
    out: &mut Sends<T>,
    add: impl Fn(T, T) -> T + Copy,
    x: &mut Exchanges,
) -> bool {
    for i in inbox.iter_mut() {
        i.clear();
    }
    out.deliver(inbox);
    let mut any = false;
    for i in inbox.iter_mut() {
        fold(i, add);
        x.sent += i.len() as u64;
        any |= !i.is_empty();
    }
    if any {
        x.exchanges += 1;
    }
    any
}

/// Sort `entries` by local node and fold repeats with `add`.
fn fold<T: Value>(entries: &mut Vec<(u32, T)>, add: impl Fn(T, T) -> T) {
    entries.sort_unstable_by_key(|e| e.0);
    entries.dedup_by(|b, a| {
        if a.0 == b.0 {
            a.1 = add(a.1, b.1);
            true
        } else {
            false
        }
    });
}

/// The sources (split ids) as each part's local nodes.
fn locate<T: Value>(ids: &SplitIds, sources: &[u64], value: T) -> crate::Result<Inbox<T>> {
    let mut inbox: Inbox<T> = vec![Vec::new(); ids.parts()];
    for &s in sources {
        let (p, l) = ids.locate(s).ok_or_else(|| {
            GraphError::Split(format!("source {s} past the split's {} ids", ids.total()))
        })?;
        inbox[p as usize].push((l, value));
    }
    Ok(inbox)
}

/// What [`reach_rounds`] found: per part its reached local nodes, rising.
#[derive(Clone, Debug)]
pub struct ReachRounds {
    /// Per part, the local nodes reached (sources included), rising.
    pub reached: Vec<Vec<u32>>,
    /// The rounds.
    pub exchanges: Exchanges,
}

impl ReachRounds {
    /// The reached split ids, rising.
    pub fn ids(&self, ids: &SplitIds) -> Vec<u64> {
        let mut out = Vec::new();
        for (p, r) in self.reached.iter().enumerate() {
            let base = ids.base(p as u32);
            out.extend(r.iter().map(|&l| base + l as u64));
        }
        out
    }
}

/// One part's side of [`reach_rounds`], kept between the rounds: its graph, its search
/// buffers, the nodes it has reached (closed for its later searches when there are more
/// parts) and how often it searched.
#[derive(Debug)]
pub struct ReachPart<B: GraphBackend> {
    index: u32,
    graph: Graph<B>,
    state: BfsState<B>,
    open: Option<Mask>,
    reached: Vec<u32>,
    track: bool,
    runs: u32,
}

impl<B: GraphBackend> ReachPart<B> {
    /// Part `part`'s side, searching `graph` (the part's inner matrix as a [`Graph`]) with the
    /// buffers `state`; `parts` is the split's number of parts.
    pub fn new(part: &Part<u8>, parts: usize, graph: Graph<B>, state: BfsState<B>) -> Self {
        ReachPart {
            index: part.index(),
            graph,
            state,
            open: None,
            reached: Vec::new(),
            track: parts > 1,
            runs: 0,
        }
    }

    /// One round: the entries that arrived (`(local node, 1)`, in any order, repeats
    /// allowed; emptied) are searched from (those reached before are passed over); the
    /// nodes newly reached are kept and the border sends they lead to are given. A part of a
    /// split of one part searches the first time even from no start, as the engine's search
    /// does.
    pub fn step(
        &mut self,
        part: &Part<u8>,
        ids: &SplitIds,
        arrivals: &mut Vec<(u32, u8)>,
        device: &B::Device,
    ) -> crate::Result<Sends<u8>> {
        if part.index() != self.index {
            return Err(GraphError::Split(format!(
                "part {} stepped with part {}'s side",
                part.index(),
                self.index
            )));
        }
        let mut sends = Sends::new();
        if arrivals.is_empty() && (self.track || self.runs > 0) {
            return Ok(sends);
        }
        fold(arrivals, |a, b| a | b);
        let starts: Vec<u32> = arrivals.drain(..).map(|e| e.0).collect();
        let got = part_search(
            &self.graph,
            &starts,
            &mut self.open,
            self.track,
            &mut self.state,
            device,
        )?;
        if got.is_empty() {
            return Ok(sends);
        }
        self.runs += 1;
        send(
            part,
            ids,
            got.iter().map(|&l| (l, 1u8)),
            |v, _| v,
            &mut sends,
        );
        if self.reached.is_empty() {
            self.reached = got;
        } else {
            self.reached.extend(got);
            self.reached.sort_unstable();
        }
        Ok(sends)
    }

    /// The local nodes reached so far, rising.
    pub fn reached(&self) -> &[u32] {
        &self.reached
    }

    /// How often the part searched.
    pub fn runs(&self) -> u32 {
        self.runs
    }

    /// The search buffers (the last search's levels and steps).
    pub fn state(&self) -> &BfsState<B> {
        &self.state
    }

    /// The graph, the buffers and the reached nodes back.
    pub fn into_parts(self) -> (Graph<B>, BfsState<B>, Vec<u32>) {
        (self.graph, self.state, self.reached)
    }
}

/// Reachability from `sources` (split ids) over `split`: each part's [`ReachPart`] (made
/// from `graphs[p]`, part `p`'s inner matrix as a [`Graph`], and its buffers `states[p]`)
/// searches by the engine's breadth-first search ([`bfs_with`]) from what arrived; its
/// sends go to their parts until no part receives anything. With one part this is one
/// [`bfs_with`] with default options. The graphs and buffers are given back in `graphs` and
/// `states` (the levels of each part's last search in its state).
pub fn reach_rounds<B: GraphBackend>(
    split: &Split<u8>,
    graphs: &mut Vec<Graph<B>>,
    sources: &[u64],
    states: &mut Vec<BfsState<B>>,
    device: &B::Device,
) -> crate::Result<ReachRounds> {
    reach_rounds_upto(split, graphs, sources, states, u32::MAX, device)
}

/// [`reach_rounds`] stopped after at most `max_exchanges` exchanges: when it stops there
/// (`exchanges.exchanges == max_exchanges` and something was still sent), the reached
/// nodes are those found so far, a part of the answer. For measuring a split whose rounds
/// would run for very long (a hash split of a road grid takes thousands).
pub fn reach_rounds_upto<B: GraphBackend>(
    split: &Split<u8>,
    graphs: &mut Vec<Graph<B>>,
    sources: &[u64],
    states: &mut Vec<BfsState<B>>,
    max_exchanges: u32,
    device: &B::Device,
) -> crate::Result<ReachRounds> {
    let ids = split.ids();
    let np = ids.parts();
    if graphs.len() != np || states.len() != np {
        return Err(GraphError::Split(format!(
            "{} graphs and {} search states for {np} parts",
            graphs.len(),
            states.len()
        )));
    }
    let mut sides: Vec<ReachPart<B>> = graphs
        .drain(..)
        .zip(states.drain(..))
        .zip(split.parts())
        .map(|((g, st), part)| ReachPart::new(part, np, g, st))
        .collect();
    let mut x = Exchanges::new(np);
    let mut inbox = locate(ids, sources, 1u8)?;
    let mut out: Sends<u8> = Sends::new();
    let run = (|| -> crate::Result<()> {
        loop {
            for (p, side) in sides.iter_mut().enumerate() {
                let mut sent = side.step(split.part(p as u32), ids, &mut inbox[p], device)?;
                out.append(&mut sent);
            }
            if x.exchanges >= max_exchanges || !exchange(&mut inbox, &mut out, |a, b| a | b, &mut x)
            {
                return Ok(());
            }
        }
    })();
    let mut reached = Vec::with_capacity(np);
    for (p, side) in sides.into_iter().enumerate() {
        x.runs[p] = side.runs();
        let (g, st, r) = side.into_parts();
        graphs.push(g);
        states.push(st);
        reached.push(r);
    }
    run?;
    Ok(ReachRounds {
        reached,
        exchanges: x,
    })
}

/// [`reach_rounds`] as one sweep in `order` (the strong components of the split's part
/// graph, [`PartOrder`]): level by level, the parts of a level run on what arrived for
/// them, and their sends wait in the inboxes of the later parts they lead to. A part
/// outside a circle therefore runs at most once, after every part that feeds it, and sends
/// each border entry once; the parts of a circle loop among themselves until nothing inside
/// it is new. The answer is [`reach_rounds`]'s. An exchange is one hand-over of a level's
/// sends (or of one loop of a circle): as many as the levels that send, which can be more
/// than the rounds' when a search reaches far parts in one hop and the longer ways bring
/// nothing new. With one part it is one [`bfs_with`] with default options, as there.
pub fn reach_sweep<B: GraphBackend>(
    split: &Split<u8>,
    graphs: &mut Vec<Graph<B>>,
    sources: &[u64],
    states: &mut Vec<BfsState<B>>,
    order: &PartOrder,
    device: &B::Device,
) -> crate::Result<ReachRounds> {
    let ids = split.ids();
    let np = ids.parts();
    if graphs.len() != np || states.len() != np {
        return Err(GraphError::Split(format!(
            "{} graphs and {} search states for {np} parts",
            graphs.len(),
            states.len()
        )));
    }
    if order.groups().iter().map(Vec::len).sum::<usize>() != np {
        return Err(GraphError::Split(format!(
            "an order of {} parts for {np} parts",
            order.groups().iter().map(Vec::len).sum::<usize>()
        )));
    }
    let mut sides: Vec<ReachPart<B>> = graphs
        .drain(..)
        .zip(states.drain(..))
        .zip(split.parts())
        .map(|((g, st), part)| ReachPart::new(part, np, g, st))
        .collect();
    let mut x = Exchanges::new(np);
    let mut inbox = locate(ids, sources, 1u8)?;
    let mut out: Sends<u8> = Sends::new();
    let mut fresh: Inbox<u8> = vec![Vec::new(); np];
    let run = (|| -> crate::Result<()> {
        for level in 0..order.levels() {
            let here = order.parts_at(level);
            loop {
                for &p in &here {
                    let pu = p as usize;
                    let mut sent = sides[pu].step(split.part(p), ids, &mut inbox[pu], device)?;
                    out.append(&mut sent);
                }
                if out.is_empty() {
                    break;
                }
                // a level's sends lead to later levels, or inside a circle of this level
                let inside =
                    (0..out.len()).any(|k| order.level(order.group_of(out.part[k])) == level);
                x.exchanges += 1;
                out.deliver(&mut fresh);
                for (q, f) in fresh.iter_mut().enumerate() {
                    if f.is_empty() {
                        continue;
                    }
                    fold(f, |a, b| a | b);
                    x.sent += f.len() as u64;
                    inbox[q].append(f);
                    fold(&mut inbox[q], |a, b| a | b);
                }
                if !inside {
                    break;
                }
            }
        }
        Ok(())
    })();
    let mut reached = Vec::with_capacity(np);
    for (p, side) in sides.into_iter().enumerate() {
        x.runs[p] = side.runs();
        let (g, st, r) = side.into_parts();
        graphs.push(g);
        states.push(st);
        reached.push(r);
    }
    run?;
    Ok(ReachRounds {
        reached,
        exchanges: x,
    })
}

/// One part's side of [`khop_rounds`], level by level: each round is one hop everywhere.
/// What arrives is the frontier entering the part with its depth; the part takes the nodes
/// it has not seen, and unless they are at depth `k` it hops them once: the targets inside
/// the part go to itself for the next round, the border targets to their parts, all at
/// depth + 1. A round therefore always sends while the frontier lives, and the run ends
/// when nothing is sent (at the latest after `k` hops).
#[derive(Debug)]
pub struct KhopPart<B: GraphBackend> {
    index: u32,
    graph: Graph<B>,
    k: u32,
    seen: Vec<bool>,
    reached: Vec<u32>,
    runs: u32,
}

impl<B: GraphBackend> KhopPart<B> {
    /// Part `part`'s side, hopping on `graph` (the part's inner matrix as a [`Graph`]) at
    /// most `k` hops from the source.
    pub fn new(part: &Part<u8>, graph: Graph<B>, k: u32) -> Self {
        KhopPart {
            index: part.index(),
            seen: vec![false; graph.vertices()],
            graph,
            k,
            reached: Vec::new(),
            runs: 0,
        }
    }

    /// One round: the frontier that arrived (`(local node, depth)`, any order, repeats
    /// allowed; emptied; the source arrives at depth 0) is taken where not seen before and,
    /// below depth `k`, hopped once (the engine's [`SparseBackend::vxm`] over (or, and) on
    /// the part's matrix); gives the next frontier's sends (to this part and over the border).
    pub fn step(
        &mut self,
        part: &Part<u8>,
        ids: &SplitIds,
        arrivals: &mut Vec<(u32, u32)>,
        device: &B::Device,
    ) -> crate::Result<Sends<u32>> {
        if part.index() != self.index {
            return Err(GraphError::Split(format!(
                "part {} stepped with part {}'s side",
                part.index(),
                self.index
            )));
        }
        let mut sends = Sends::new();
        if arrivals.is_empty() {
            return Ok(sends);
        }
        fold(arrivals, |a, b| a.min(b));
        let mut fresh: Vec<(u32, u32)> = Vec::new();
        for (l, d) in arrivals.drain(..) {
            if (l as usize) < self.seen.len() && !self.seen[l as usize] {
                self.seen[l as usize] = true;
                fresh.push((l, d));
            }
        }
        if fresh.is_empty() {
            return Ok(sends);
        }
        self.runs += 1;
        self.reached.extend(fresh.iter().map(|e| e.0));
        self.reached.sort_unstable();
        let go: Vec<(u32, u32)> = fresh.into_iter().filter(|e| e.1 < self.k).collect();
        if go.is_empty() {
            return Ok(sends);
        }
        // Level by level every node of a round is at the same depth.
        let d = go.iter().map(|e| e.1).min().expect("a node to hop") + 1;
        let at: Vec<u32> = go.iter().map(|e| e.0).collect();
        let x = B::vector(
            Vector::from_indices(self.graph.vertices(), &at, 1u8)?,
            device,
        );
        let y = B::vxm(&x, self.graph.out(), None, BoolOrAnd, device)?;
        for l in B::indices(&y) {
            if !self.seen[l as usize] {
                sends.push(self.index, l, d);
            }
        }
        send(
            part,
            ids,
            go.iter().map(|&(l, _)| (l, d)),
            |v, _| v,
            &mut sends,
        );
        Ok(sends)
    }

    /// The local nodes within `k` hops (the source's part: the source included), rising.
    pub fn reached(&self) -> &[u32] {
        &self.reached
    }

    /// How often the part took a new frontier.
    pub fn runs(&self) -> u32 {
        self.runs
    }

    /// The graph back.
    pub fn into_graph(self) -> Graph<B> {
        self.graph
    }
}

/// The nodes within `k` hops of `source` (a split id) over `split`, level by level: each
/// round every part's [`KhopPart`] hops its frontier once, until nothing is sent (at most
/// `k` rounds after the first). The exchanges count the rounds that carried a frontier
/// (inside a part too). The graphs are lent to the parts and given back in `graphs`.
pub fn khop_rounds<B: GraphBackend>(
    split: &Split<u8>,
    graphs: &mut Vec<Graph<B>>,
    source: u64,
    k: u32,
    device: &B::Device,
) -> crate::Result<ReachRounds> {
    let ids = split.ids();
    let np = ids.parts();
    if graphs.len() != np {
        return Err(GraphError::Split(format!(
            "{} graphs for {np} parts",
            graphs.len()
        )));
    }
    let mut sides: Vec<KhopPart<B>> = graphs
        .drain(..)
        .zip(split.parts())
        .map(|(g, part)| KhopPart::new(part, g, k))
        .collect();
    let mut x = Exchanges::new(np);
    let mut inbox = locate(ids, &[source], 0u32)?;
    let mut out: Sends<u32> = Sends::new();
    let run = (|| -> crate::Result<()> {
        loop {
            for (p, side) in sides.iter_mut().enumerate() {
                let mut sent = side.step(split.part(p as u32), ids, &mut inbox[p], device)?;
                out.append(&mut sent);
            }
            if !exchange(&mut inbox, &mut out, |a, b| a.min(b), &mut x) {
                return Ok(());
            }
        }
    })();
    let mut reached = Vec::with_capacity(np);
    for (p, side) in sides.into_iter().enumerate() {
        x.runs[p] = side.runs();
        reached.push(side.reached().to_vec());
        graphs.push(side.into_graph());
    }
    run?;
    Ok(ReachRounds {
        reached,
        exchanges: x,
    })
}

/// One part's search in a round: a breadth-first search ([`bfs_with`]) on its graph `g`
/// from `starts` (local nodes; those reached before are passed over), entering only the
/// nodes `open` allows (`None`: all); gives the nodes newly reached, rising (empty when
/// every start was reached before: then no search runs, unless `open` is `None`). With `track` the reached nodes are
/// closed in `open` for the part's later rounds.
pub fn part_search<B: GraphBackend>(
    g: &Graph<B>,
    starts: &[u32],
    open: &mut Option<Mask>,
    track: bool,
    state: &mut BfsState<B>,
    device: &B::Device,
) -> crate::Result<Vec<u32>> {
    let fresh: Vec<u32>;
    let starts = match open.as_ref() {
        Some(m) => {
            fresh = starts
                .iter()
                .copied()
                .filter(|&l| (l as usize) < m.len() && m.allows(l as usize))
                .collect();
            &fresh[..]
        }
        None => starts,
    };
    if starts.is_empty() && open.is_some() {
        return Ok(Vec::new());
    }
    let opts = BfsOptions {
        allowed: open.clone(),
        ..BfsOptions::default()
    };
    bfs_with(g, starts, &opts, device, state)?;
    let got = B::indices(state.levels());
    if track {
        let m = open.get_or_insert_with(|| Mask::all(g.vertices()));
        for &l in &got {
            m.close(l as usize);
        }
    }
    Ok(got)
}

/// What [`components_rounds`] found.
#[derive(Clone, Debug)]
pub struct ComponentsRounds {
    /// Per split id its component, named by its least original node.
    pub of: Vec<u32>,
    /// The kernel's rounds, summed over the parts.
    pub rounds: u32,
    /// The rounds between parts.
    pub exchanges: Exchanges,
}

/// One part's side of [`components_rounds`], kept between the rounds: each local node's
/// local component (by the engine's kernel on the part's inner matrices), each component's
/// name (its least original node, lowered as smaller names arrive), and the nodes with a
/// border edge by component.
#[derive(Clone, Debug)]
pub struct ComponentsPart {
    index: u32,
    roots: Vec<u32>,
    /// Per root its name; `None` for the one part of a split with the graph's own ids
    /// (then the kernel's roots are the names).
    names: Option<Vec<u32>>,
    /// `(root, local node)` of the nodes with a border edge either way, rising.
    members: Vec<(u32, u32)>,
    rounds: u32,
    runs: u32,
}

impl ComponentsPart {
    /// Part `out`'s side (`inn`: the same part of the transpose's split): its components by
    /// [`GraphBackend::components_of`] and the first sends (every border node's component
    /// name).
    pub fn new<B: GraphBackend>(
        out: &Part<u8>,
        inn: &Part<u8>,
        ids: &SplitIds,
        device: &B::Device,
    ) -> crate::Result<(Self, Sends<u32>)> {
        if out.index() != inn.index() {
            return Err(GraphError::Split(format!(
                "part {} with the transpose's part {}",
                out.index(),
                inn.index()
            )));
        }
        let c = B::components_of(out.inner(), inn.inner(), device)?;
        let mut side = ComponentsPart {
            index: out.index(),
            roots: c.of,
            names: None,
            members: Vec::new(),
            rounds: c.rounds,
            runs: 1,
        };
        let mut sends = Sends::new();
        if ids.parts() == 1 && ids.is_identity() {
            return Ok((side, sends));
        }
        let base = ids.base(out.index());
        let mut name = vec![u32::MAX; side.roots.len()];
        for (l, &r) in side.roots.iter().enumerate() {
            let v = ids.original(base + l as u64).expect("an id of the split");
            name[r as usize] = name[r as usize].min(v);
        }
        for l in 0..out.count() as u32 {
            if !out.border().range(l).is_empty() || !inn.border().range(l).is_empty() {
                side.members.push((side.roots[l as usize], l));
            }
        }
        side.members.sort_unstable();
        side.names = Some(name);
        let mut all: Vec<u32> = side.members.iter().map(|e| e.0).collect();
        all.dedup();
        side.send_roots(out, inn, ids, &all, &mut sends);
        Ok((side, sends))
    }

    fn send_roots(
        &self,
        out: &Part<u8>,
        inn: &Part<u8>,
        ids: &SplitIds,
        changed: &[u32],
        sends: &mut Sends<u32>,
    ) {
        let Some(name) = &self.names else { return };
        let m = &self.members;
        for &r in changed {
            let at = m.partition_point(|e| e.0 < r);
            let touched = m[at..]
                .iter()
                .take_while(|e| e.0 == r)
                .map(|e| (e.1, name[r as usize]));
            send(out, ids, touched.clone(), |v, _| v, sends);
            send(inn, ids, touched, |v, _| v, sends);
        }
    }

    /// One round: the names that arrived (`(local node, name)`, any order, repeats allowed;
    /// emptied) lower their components' names; the border nodes of every component whose
    /// name fell send it on.
    pub fn step(
        &mut self,
        out: &Part<u8>,
        inn: &Part<u8>,
        ids: &SplitIds,
        arrivals: &mut Vec<(u32, u32)>,
    ) -> crate::Result<Sends<u32>> {
        if out.index() != self.index || inn.index() != self.index {
            return Err(GraphError::Split(format!(
                "part {} stepped with part {}'s side",
                out.index(),
                self.index
            )));
        }
        let mut sends = Sends::new();
        let Some(names) = self.names.as_mut() else {
            arrivals.clear();
            return Ok(sends);
        };
        let mut changed: Vec<u32> = Vec::new();
        for (l, v) in arrivals.drain(..) {
            let r = self.roots[l as usize];
            if v < names[r as usize] {
                names[r as usize] = v;
                changed.push(r);
            }
        }
        if changed.is_empty() {
            return Ok(sends);
        }
        self.runs += 1;
        changed.sort_unstable();
        changed.dedup();
        self.send_roots(out, inn, ids, &changed, &mut sends);
        Ok(sends)
    }

    /// Each local node's component name (its least original node), as far as the rounds
    /// have gone.
    pub fn names(&self) -> Vec<u32> {
        match &self.names {
            Some(n) => self.roots.iter().map(|&r| n[r as usize]).collect(),
            None => self.roots.clone(),
        }
    }

    /// [`ComponentsPart::names`], the buffers moved where they can be.
    pub fn into_names(self) -> Vec<u32> {
        match self.names {
            Some(n) => self.roots.iter().map(|&r| n[r as usize]).collect(),
            None => self.roots,
        }
    }

    /// The kernel's rounds on this part.
    pub fn rounds(&self) -> u32 {
        self.rounds
    }

    /// How often the part ran (its components once, then each round a name fell).
    pub fn runs(&self) -> u32 {
        self.runs
    }
}

/// Weak components over `out` (the graph's split) and `inn` (its transpose's split by the
/// same key): each part's [`ComponentsPart`] (its components by the engine's kernel,
/// [`GraphBackend::components_of`], each named by its least original node), then the parts
/// hand each other a component's name along both borders while a smaller name arrives.
/// With one part this is one [`GraphBackend::components_of`].
pub fn components_rounds<B: GraphBackend>(
    out: &Split<u8>,
    inn: &Split<u8>,
    device: &B::Device,
) -> crate::Result<ComponentsRounds> {
    components_rounds_upto::<B>(out, inn, u32::MAX, device)
}

/// [`components_rounds`] stopped after at most `max_exchanges` exchanges: when it stops
/// there (`exchanges.exchanges == max_exchanges`), the names are those reached so far (a
/// component may still carry several). For measuring a split whose rounds would run for
/// very long.
pub fn components_rounds_upto<B: GraphBackend>(
    out: &Split<u8>,
    inn: &Split<u8>,
    max_exchanges: u32,
    device: &B::Device,
) -> crate::Result<ComponentsRounds> {
    let ids = out.ids();
    if ids != inn.ids() {
        return Err(GraphError::Split(
            "the graph and its transpose split differently".to_string(),
        ));
    }
    let np = ids.parts();
    let mut x = Exchanges::new(np);
    let mut outbox: Sends<u32> = Sends::new();
    let mut sides: Vec<ComponentsPart> = Vec::with_capacity(np);
    for p in 0..np as u32 {
        let (side, mut first) = ComponentsPart::new::<B>(out.part(p), inn.part(p), ids, device)?;
        outbox.append(&mut first);
        sides.push(side);
    }
    let mut inbox: Inbox<u32> = vec![Vec::new(); np];
    while x.exchanges < max_exchanges && exchange(&mut inbox, &mut outbox, |a, b| a.min(b), &mut x)
    {
        for (p, side) in sides.iter_mut().enumerate() {
            let pp = p as u32;
            let mut s = side.step(out.part(pp), inn.part(pp), ids, &mut inbox[p])?;
            outbox.append(&mut s);
        }
    }
    let mut rounds = 0;
    let mut of: Vec<u32> = Vec::new();
    for (p, side) in sides.into_iter().enumerate() {
        x.runs[p] = side.runs();
        rounds += side.rounds();
        if np == 1 {
            of = side.into_names();
        } else {
            of.extend(side.into_names());
        }
    }
    Ok(ComponentsRounds {
        of,
        rounds,
        exchanges: x,
    })
}

/// A part's min-plus weights and distances, made when a distance first arrives.
type Kept<B> = Option<(
    <B as SparseBackend>::Matrix<u64>,
    <B as SparseBackend>::Vector<u64>,
)>;

/// What [`sssp_rounds`] found.
#[derive(Clone, Debug)]
pub struct SsspRounds {
    /// With one part: the kernel's answer as it is (no copy).
    whole: Option<crate::Paths>,
    /// With more parts: per part, `(local node, distance)` of every node reached, local
    /// nodes rising.
    distances: Vec<Vec<(u32, u64)>>,
    /// The kernel's relaxation steps (the source part's search; then one per propagation
    /// round in the other parts).
    pub rounds: u32,
    /// The rounds between parts.
    pub exchanges: Exchanges,
}

impl SsspRounds {
    /// With one part, the kernel's own answer.
    pub fn paths(&self) -> Option<&crate::Paths> {
        self.whole.as_ref()
    }

    /// `f(split id, distance)` for every node reached, ids rising.
    pub fn for_each(&self, ids: &SplitIds, mut f: impl FnMut(u64, u64)) {
        if let Some(paths) = &self.whole {
            for v in 0..ids.total() as u32 {
                if let Some(d) = paths.distance(v) {
                    f(v as u64, d);
                }
            }
            return;
        }
        for (p, d) in self.distances.iter().enumerate() {
            let base = ids.base(p as u32);
            for &(l, x) in d {
                f(base + l as u64, x);
            }
        }
    }

    /// `(split id, distance)` of every node reached, ids rising.
    pub fn ids(&self, ids: &SplitIds) -> Vec<(u64, u64)> {
        let mut out = Vec::new();
        self.for_each(ids, |i, d| out.push((i, d)));
        out
    }
}

/// One part's side of [`sssp_rounds`], kept between the rounds: the part's distances, and
/// (made when a distance first arrives) its weights as a min-plus matrix and its distances
/// as a vector.
pub struct SsspPart<B: GraphBackend> {
    index: u32,
    whole: Option<crate::Paths>,
    distances: Vec<(u32, u64)>,
    kept: Kept<B>,
    rounds: u32,
    runs: u32,
}

impl<B: GraphBackend> std::fmt::Debug for SsspPart<B> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SsspPart")
            .field("index", &self.index)
            .field("reached", &self.distances.len())
            .field("rounds", &self.rounds)
            .field("runs", &self.runs)
            .finish()
    }
}

impl<B: GraphBackend> SsspPart<B> {
    /// Part `part`'s side, nothing reached.
    pub fn new(part: &Part<u32>) -> Self {
        SsspPart {
            index: part.index(),
            whole: None,
            distances: Vec::new(),
            kept: None,
            rounds: 0,
            runs: 0,
        }
    }

    fn check(&self, part: &Part<u32>) -> crate::Result<()> {
        if part.index() != self.index {
            return Err(GraphError::Split(format!(
                "part {} stepped with part {}'s side",
                part.index(),
                self.index
            )));
        }
        Ok(())
    }

    /// The source's part: the engine's search ([`GraphBackend::sssp_of`]) from local node
    /// `source`, and the border sends of every node it reached. With one part the kernel's
    /// answer is kept as it is ([`SsspPart::paths`]) and nothing is sent.
    pub fn start(
        &mut self,
        part: &Part<u32>,
        ids: &SplitIds,
        source: u32,
        opts: &SsspOptions,
        device: &B::Device,
    ) -> crate::Result<Sends<u64>> {
        self.check(part)?;
        let paths = B::sssp_of(part.inner(), None, source, opts, device)?;
        self.runs += 1;
        self.rounds += paths.rounds;
        let mut sends = Sends::new();
        if ids.parts() == 1 {
            self.whole = Some(paths);
            return Ok(sends);
        }
        let first: Vec<(u32, u64)> = (0..part.count() as u32)
            .filter_map(|v| paths.distance(v).map(|d| (v, d)))
            .collect();
        send(part, ids, first.iter().copied(), along, &mut sends);
        self.distances = first;
        Ok(sends)
    }

    /// One round: the distances that arrived (`(local node, distance)`, any order, repeats
    /// allowed; emptied) improve the part's by min-plus propagation
    /// ([`SparseBackend::vxm`], [`SparseBackend::accumulate`]) until nothing improves; every
    /// improved node's border sends are given.
    pub fn step(
        &mut self,
        part: &Part<u32>,
        ids: &SplitIds,
        arrivals: &mut Vec<(u32, u64)>,
        device: &B::Device,
    ) -> crate::Result<Sends<u64>> {
        self.check(part)?;
        let mut sends = Sends::new();
        if arrivals.is_empty() {
            return Ok(sends);
        }
        fold(arrivals, |a, b| a.min(b));
        let s = MinPlus::<u64>::new();
        let distances = &self.distances;
        let (m, v) = self.kept.get_or_insert_with(|| {
            let a = part.inner();
            let w: Vec<u64> = match a.values() {
                Some(w) => w.iter().map(|&x| x as u64).collect(),
                None => vec![1; a.nnz()],
            };
            let a = Csr::with_pattern(a.pattern().clone(), Some(w.into()))
                .expect("one weight per entry");
            let (i, d): (Vec<u32>, Vec<u64>) = distances.iter().copied().unzip();
            let v = Vector::sparse(part.count(), i, d).expect("rising local nodes");
            (B::matrix(a, device), B::vector(v, device))
        });
        let (i, d): (Vec<u32>, Vec<u64>) = arrivals.drain(..).unzip();
        let arrived = B::vector(Vector::sparse(part.count(), i, d)?, device);
        let mut changed = B::accumulate(v, &arrived, s)?;
        if B::nvals(&changed) == 0 {
            return Ok(sends);
        }
        self.runs += 1;
        let mut touched: Vec<u64> = vec![u64::MAX; part.count()];
        let mut list: Vec<u32> = Vec::new();
        loop {
            for (l, d) in B::vector_to_host(&changed).iter() {
                if touched[l as usize] == u64::MAX {
                    list.push(l);
                }
                touched[l as usize] = d;
            }
            let next = B::vxm(&changed, m, None, s, device)?;
            self.rounds += 1;
            changed = B::accumulate(v, &next, s)?;
            if B::nvals(&changed) == 0 {
                break;
            }
        }
        send(
            part,
            ids,
            list.iter().map(|&l| (l, touched[l as usize])),
            along,
            &mut sends,
        );
        self.distances = B::vector_to_host(v).iter().collect();
        Ok(sends)
    }

    /// `(local node, distance)` of every node reached, rising (with one part: empty, see
    /// [`SsspPart::paths`]).
    pub fn distances(&self) -> &[(u32, u64)] {
        &self.distances
    }

    /// With one part, the kernel's own answer.
    pub fn paths(&self) -> Option<&crate::Paths> {
        self.whole.as_ref()
    }

    /// The kernel's relaxation steps on this part.
    pub fn rounds(&self) -> u32 {
        self.rounds
    }

    /// How often the part ran.
    pub fn runs(&self) -> u32 {
        self.runs
    }
}

/// A distance carried along a border edge of weight `w` (no weight: 1).
fn along(d: u64, w: Option<u32>) -> u64 {
    d.saturating_add(w.map_or(1, u64::from))
}

/// Shortest paths from `source` (a split id) over `split` (weights as its values; a
/// structural split: every edge weight 1, as [`GraphBackend::sssp_of`] reads it). The
/// source's part's [`SsspPart`] runs the engine's search ([`GraphBackend::sssp_of`]);
/// distances that arrive over a border start min-plus propagation rounds on the part they
/// reach, and every improved border node is handed on. With one part this is one
/// [`GraphBackend::sssp_of`].
pub fn sssp_rounds<B: GraphBackend>(
    split: &Split<u32>,
    source: u64,
    opts: &SsspOptions,
    device: &B::Device,
) -> crate::Result<SsspRounds> {
    let ids = split.ids();
    let np = ids.parts();
    let mut x = Exchanges::new(np);
    let (sp, sl) = ids.locate(source).ok_or_else(|| {
        GraphError::Split(format!(
            "source {source} past the split's {} ids",
            ids.total()
        ))
    })?;
    let mut sides: Vec<SsspPart<B>> = split.parts().iter().map(SsspPart::new).collect();
    let mut outbox = sides[sp as usize].start(split.part(sp), ids, sl, opts, device)?;
    let mut inbox: Inbox<u64> = vec![Vec::new(); np];
    while exchange(&mut inbox, &mut outbox, |a, b| a.min(b), &mut x) {
        for (p, side) in sides.iter_mut().enumerate() {
            let mut s = side.step(split.part(p as u32), ids, &mut inbox[p], device)?;
            outbox.append(&mut s);
        }
    }
    let mut rounds = 0;
    let mut distances = Vec::with_capacity(np);
    let mut whole = None;
    for (p, mut side) in sides.into_iter().enumerate() {
        x.runs[p] = side.runs();
        rounds += side.rounds();
        whole = whole.or(side.whole.take());
        distances.push(std::mem::take(&mut side.distances));
    }
    if whole.is_some() {
        distances.clear();
    }
    Ok(SsspRounds {
        whole,
        distances,
        rounds,
        exchanges: x,
    })
}

/// What [`closure_rounds`] found.
#[derive(Clone, Debug)]
pub struct ClosureRounds {
    /// `(x, z)` split ids, rising: each base pair's `(x, y)` and every `(x, z)` with `z`
    /// reached from `y`.
    pub pairs: Vec<(u64, u64)>,
    /// The rounds between parts, summed over the batches of 64 starts.
    pub exchanges: Exchanges,
}

/// One part's side of [`closure_rounds`], kept between the rounds: the part's edges as a
/// set-union matrix and, per local node, the word of starts (up to 64 a batch) that reach it.
pub struct ClosurePart<B: SparseBackend> {
    index: u32,
    count: usize,
    matrix: B::Matrix<u64>,
    words: B::Vector<u64>,
    runs: u32,
}

impl<B: SparseBackend> std::fmt::Debug for ClosurePart<B> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ClosurePart")
            .field("index", &self.index)
            .field("count", &self.count)
            .field("runs", &self.runs)
            .finish()
    }
}

impl<B: SparseBackend> ClosurePart<B> {
    /// Part `part`'s side, no word yet.
    pub fn new(part: &Part<u8>, device: &B::Device) -> Self {
        ClosurePart {
            index: part.index(),
            count: part.count(),
            matrix: B::matrix(part.inner().pattern().to_structural::<u64>(), device),
            words: B::vector(Vector::empty(part.count()), device),
            runs: 0,
        }
    }

    /// A new batch of starts: every word empty.
    pub fn begin(&mut self, device: &B::Device) {
        self.words = B::vector(Vector::empty(self.count), device);
    }

    /// One round: the words that arrived (`(local node, word)`, any order, repeats allowed;
    /// emptied) are propagated by set union ([`SparseBackend::vxm`] over [`BitsetUnion`],
    /// [`SparseBackend::accumulate`]) until nothing changes; every changed node's border
    /// sends are given.
    pub fn step(
        &mut self,
        part: &Part<u8>,
        ids: &SplitIds,
        arrivals: &mut Vec<(u32, u64)>,
        device: &B::Device,
    ) -> crate::Result<Sends<u64>> {
        if part.index() != self.index {
            return Err(GraphError::Split(format!(
                "part {} stepped with part {}'s side",
                part.index(),
                self.index
            )));
        }
        let mut sends = Sends::new();
        if arrivals.is_empty() {
            return Ok(sends);
        }
        fold(arrivals, |a, b| a | b);
        let s = BitsetUnion;
        let (i, w): (Vec<u32>, Vec<u64>) = arrivals.drain(..).unzip();
        let arrived = B::vector(Vector::sparse(self.count, i, w)?, device);
        let mut changed = B::accumulate(&mut self.words, &arrived, s)?;
        if B::nvals(&changed) == 0 {
            return Ok(sends);
        }
        self.runs += 1;
        let mut touched: Vec<u64> = vec![0; self.count];
        let mut list: Vec<u32> = Vec::new();
        loop {
            for (l, w) in B::vector_to_host(&changed).iter() {
                if touched[l as usize] == 0 {
                    list.push(l);
                }
                touched[l as usize] = w;
            }
            let next = B::vxm(&changed, &self.matrix, None, s, device)?;
            changed = B::accumulate(&mut self.words, &next, s)?;
            if B::nvals(&changed) == 0 {
                break;
            }
        }
        send(
            part,
            ids,
            list.iter().map(|&l| (l, touched[l as usize])),
            |w, _| w,
            &mut sends,
        );
        Ok(sends)
    }

    /// `(local node, word)` of every node some start of the batch reaches, rising.
    pub fn words(&self) -> Vec<(u32, u64)> {
        self.host_words()
    }

    fn host_words(&self) -> Vec<(u32, u64)> {
        B::vector_to_host(&self.words).iter().collect()
    }

    /// How often the part ran (summed over the batches).
    pub fn runs(&self) -> u32 {
        self.runs
    }
}

/// The closure of `base` pairs `(x, y)` (split ids) along `split`'s edges:
/// `tc(X, Z) :- base(X, Z). tc(X, Z) :- tc(X, Y), edge(Y, Z).` The starts `x` go 64 to a
/// word; each part's [`ClosurePart`] propagates the words by set union (as
/// [`crate::reach_sets`] does) until nothing changes, then hands on its changed border
/// nodes' words. With one part this is one set propagation per batch.
pub fn closure_rounds<B: SparseBackend>(
    split: &Split<u8>,
    base: &[(u64, u64)],
    device: &B::Device,
) -> crate::Result<ClosureRounds> {
    let ids = split.ids();
    let np = ids.parts();
    let mut x = Exchanges::new(np);
    let mut sides: Vec<ClosurePart<B>> = split
        .parts()
        .iter()
        .map(|p| ClosurePart::new(p, device))
        .collect();
    let mut starts: Vec<u64> = base.iter().map(|e| e.0).collect();
    starts.sort_unstable();
    starts.dedup();
    let mut pairs: Vec<(u64, u64)> = Vec::new();
    let mut outbox: Sends<u64> = Sends::new();
    for (k, batch) in starts.chunks(64).enumerate() {
        let bit = |x: u64| 1u64 << batch.binary_search(&x).expect("a start of the batch");
        // The base pairs are where the starts sit: no exchange.
        let mut inbox: Inbox<u64> = vec![Vec::new(); np];
        for &(a, y) in base {
            if batch.binary_search(&a).is_ok() {
                let (p, l) = ids
                    .locate(y)
                    .ok_or_else(|| GraphError::Split(format!("pair end {y} past the split")))?;
                inbox[p as usize].push((l, bit(a)));
            }
        }
        if k > 0 {
            for side in sides.iter_mut() {
                side.begin(device);
            }
        }
        let mut go = true;
        while go {
            for (p, side) in sides.iter_mut().enumerate() {
                let mut s = side.step(split.part(p as u32), ids, &mut inbox[p], device)?;
                outbox.append(&mut s);
            }
            go = exchange(&mut inbox, &mut outbox, |a, b| a | b, &mut x);
        }
        for (p, side) in sides.iter().enumerate() {
            let b = ids.base(p as u32);
            for (l, word) in side.host_words() {
                let mut word = word;
                while word != 0 {
                    let k = word.trailing_zeros() as usize;
                    word &= word - 1;
                    pairs.push((batch[k], b + l as u64));
                }
            }
        }
    }
    for (p, side) in sides.iter().enumerate() {
        x.runs[p] = side.runs();
    }
    pairs.sort_unstable();
    Ok(ClosureRounds {
        pairs,
        exchanges: x,
    })
}