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

//! One search over machines that all hold the same whole graph: each level's work is cut
//! into slices by edge count, one slice per machine, weighted by the machines' cores
//! ([`Slices`]). Gatling's cut, over machines instead of threads.
//!
//! Every machine holds the same graph and, after each level, the same frontier and the same
//! open set, so each computes ITS OWN slice by the same deterministic cut, and nobody sends
//! anybody a slice. A machine expands its slice on its own threads and drops what is
//! already reached; only the new vertices travel ([`Found`], a [`NodeSet`]: a sorted list or a
//! bit map, whichever is smaller, compressed with mzstd). Every machine then joins every
//! machine's new vertices into the next frontier, and the search goes on.
//!
//! The levels are the direction-optimizing search's ([`crate::beamer_bfs`]): push from the
//! frontier, or let the open vertices pull from their in-edges, by Beamer's rule. The state
//! the rule reads is the same on every machine (the edges a pull looked at travel with the
//! new vertices), so every machine takes the same direction, and the steps are the
//! one-machine search's: the same frontiers, vertices reached and edges looked at.
//!
//! - A push cuts the frontier by its out-edges: machine `m` takes the frontier vertices
//!   whose running sum of out-edges falls in its share.
//! - A pull cuts the open set's words by their open vertices (a pull looks at an open
//!   vertex's in-edges until the first on the frontier).
//!
//! One code for one machine and for many: with one slice ([`Slices::one`]) a side's first
//! step is one call of today's kernel ([`bfs_with`], on the side's kept buffers) and nothing
//! is sent. A k-hop count is the same search with a depth bound ([`BfsOptions::max_depth`]).
//!
//! Many searches at once divide with no exchange at all: [`Slices::portion`] cuts a list of
//! units (queries, the sources of a many-source search) by the same weights; each machine
//! runs today's kernel on its portion, and the answers are joined in unit order.

use std::ops::Range;
use std::sync::Arc;
use std::sync::atomic::Ordering::Relaxed;
use std::sync::atomic::{AtomicU64, AtomicUsize};

use kleene_sparse::{CpuBackend, CpuDevice, Simd, SparseBackend, atomic_u32s, atomic_words};

use crate::bfs::{BfsOptions, BfsState, Direction, Step, bfs_with};
use crate::graph::{Graph, GraphError};

mod coder;
mod frame;
pub use coder::FoundCoder;

/// Open-set words a pull hands to a thread at a time.
const PULL_WORDS: usize = 64;

/// Frontier places a push hands to a thread at a time.
const PUSH_PIECE: usize = 256;

/// The zstd level of [`NodeSet::encode`].
const LEVEL: i32 = 1;

/// Bytes below which a set travels uncompressed.
const PACK_FROM: usize = 256;

/// The bytes compressed apart (the pieces compress on a machine's threads).
const PIECE: usize = 1 << 17;

/// Edges a level is expected to look at below which every machine runs the whole level
/// itself (the default of [`ReachSlice::with_local_below`]): a hand-over between machines
/// costs more than such a level.
pub const LOCAL_BELOW: u64 = 1 << 18;

/// Edges below which a level runs on the calling thread alone.
const ONE_THREAD_BELOW: u64 = 1 << 14;

fn refuse<T>(m: impl Into<String>) -> crate::Result<T> {
    Err(GraphError::Slices(m.into()))
}

/// Machine weights (their cores, say 32 / 12 / 12), and the deterministic cuts by them.
/// Every machine computes every cut from the same input, so a cut is never sent.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Slices {
    /// Per machine the weights summed up to it, itself included.
    upto: Vec<u64>,
}

impl Slices {
    /// Slices for machines of `weights` (at least one machine, not all of weight 0; a
    /// machine of weight 0 gets nothing).
    pub fn new(weights: &[u32]) -> crate::Result<Self> {
        if weights.is_empty() {
            return refuse("no machine");
        }
        let upto: Vec<u64> = weights
            .iter()
            .scan(0u64, |acc, &w| {
                *acc += u64::from(w);
                Some(*acc)
            })
            .collect();
        if upto.last() == Some(&0) {
            return refuse("every machine has weight 0");
        }
        Ok(Slices { upto })
    }

    /// One machine: one slice, today's kernel.
    pub fn one() -> Self {
        Slices { upto: vec![1] }
    }

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

    /// Machine `m`'s weight.
    pub fn weight(&self, m: usize) -> u64 {
        self.upto[m] - if m == 0 { 0 } else { self.upto[m - 1] }
    }

    /// Where machine `m`'s share of `total` starts: `total` times the weights before `m`
    /// over all weights, rounded down (`total` for `m` past the last machine).
    pub fn start_of(&self, m: usize, total: u64) -> u64 {
        let all = *self.upto.last().expect("a machine");
        match m {
            0 => 0,
            m if m >= self.upto.len() => total,
            m => (u128::from(total) * u128::from(self.upto[m - 1]) / u128::from(all)) as u64,
        }
    }

    /// Machine `m`'s share of `0..total`.
    pub fn share(&self, m: usize, total: u64) -> Range<u64> {
        self.start_of(m, total)..self.start_of(m + 1, total)
    }

    /// Machine `m`'s portion of `n` units handed out whole: consecutive units, as many as
    /// its weight's share. Every unit goes to exactly one machine.
    pub fn portion(&self, m: usize, n: usize) -> Range<usize> {
        let r = self.share(m, n as u64);
        r.start as usize..r.end as usize
    }

    /// Machine `m`'s items of a sequence whose weights' running sum is `prefix` (`prefix[0]
    /// = 0`, `prefix[i]` the weights before item `i`, `n + 1` entries): the items whose
    /// running sum before them falls in its share. Items of weight 0 at a cut go to the
    /// later machine; the last machine takes the rest.
    pub fn cut(&self, m: usize, prefix: &[u64]) -> Range<usize> {
        let n = prefix.len().saturating_sub(1);
        let total = prefix.last().copied().unwrap_or(0);
        let at = |j: usize| {
            if j == 0 {
                0
            } else if j >= self.machines() {
                n
            } else {
                let t = self.start_of(j, total);
                prefix[..n].partition_point(|&s| s < t)
            }
        };
        at(m)..at(m + 1)
    }

    /// [`Slices::cut`] of `n` items of weight `weight(i)`, the running sum taken on the
    /// device's threads (piece sums first, then a walk inside the piece of each cut). The
    /// answer does not depend on the device.
    pub fn cut_by(
        &self,
        m: usize,
        n: usize,
        weight: impl Fn(usize) -> u64 + Sync,
        device: &CpuDevice,
    ) -> Range<usize> {
        if self.machines() == 1 {
            return 0..n;
        }
        let sums = device.split(n, |r| (r.start, r.end, r.map(&weight).sum::<u64>()));
        let total: u64 = sums.iter().map(|s| s.2).sum();
        // the first item whose running sum before it is at least `t`
        let first = |t: u64| {
            let mut acc = 0u64;
            for &(a, b, s) in &sums {
                if acc >= t {
                    return a;
                }
                if acc + s < t {
                    acc += s;
                    continue;
                }
                let mut x = acc;
                for i in a..b {
                    if x >= t {
                        return i;
                    }
                    x += weight(i);
                }
                acc += s;
            }
            n
        };
        let at = |j: usize| {
            if j == 0 {
                0
            } else if j >= self.machines() {
                n
            } else {
                first(self.start_of(j, total))
            }
        };
        at(m)..at(m + 1)
    }
}

/// A set of vertices as it travels: a rising list, or a bit map over a range of words,
/// whichever is smaller once compressed ([`NodeSet::from_sorted`], [`NodeSet::from_words`]:
/// a bit map above one vertex in 256 places).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum NodeSet {
    /// The vertices, rising, each once.
    List(Vec<u32>),
    /// Vertex `64 * (first + i) + b` is in the set when bit `b` of `words[i]` is set.
    Bits {
        /// The first word's place.
        first: u32,
        /// The words.
        words: Vec<u64>,
    },
}

impl Default for NodeSet {
    fn default() -> Self {
        NodeSet::List(Vec::new())
    }
}

/// Whether a bit map is the smaller form, once compressed, of a set of `count` vertices
/// whose words lie in `span` words: above one vertex in 256 places. Measured with mzstd
/// at level 1: a bit map at 2 % compresses to 0.19 of its words (1.2 bytes a vertex), at
/// 10 % to 0.49, and a list of differences keeps about 2 to 3 bytes a vertex; a bit map is
/// also joined by OR word by word, where a list is sorted and set vertex by vertex.
fn bits_smaller(count: usize, span: usize) -> bool {
    span < count * 4
}

impl NodeSet {
    /// The set of the rising `nodes` (each once), as a list or, when smaller, a bit map.
    pub fn from_sorted(nodes: Vec<u32>) -> Self {
        match (nodes.first(), nodes.last()) {
            (Some(&lo), Some(&hi))
                if bits_smaller(nodes.len(), (hi / 64 - lo / 64) as usize + 1) =>
            {
                let first = lo / 64;
                let mut words = vec![0u64; (hi / 64 - first) as usize + 1];
                for &v in &nodes {
                    words[(v / 64 - first) as usize] |= 1 << (v % 64);
                }
                NodeSet::Bits { first, words }
            }
            _ => NodeSet::List(nodes),
        }
    }

    /// The set of the bits of `words` (word `i` at place `first + i`), as a bit map
    /// trimmed of empty words at both ends or, when smaller, a list.
    pub fn from_words(first: u32, words: Vec<u64>) -> Self {
        let simd = Simd::detect();
        let count = simd.popcount(&words);
        let Some(lo) = words.iter().position(|&w| w != 0) else {
            return NodeSet::default();
        };
        let hi = words.iter().rposition(|&w| w != 0).expect("a word set");
        if bits_smaller(count, hi - lo + 1) {
            let words = if lo == 0 && hi + 1 == words.len() {
                words
            } else {
                words[lo..=hi].to_vec()
            };
            return NodeSet::Bits {
                first: first + lo as u32,
                words,
            };
        }
        let mut list = vec![0u32; count];
        simd.bits_to_places(&words[lo..=hi], (first + lo as u32) * 64, &mut list);
        NodeSet::List(list)
    }

    /// The number of vertices.
    pub fn len(&self) -> usize {
        match self {
            NodeSet::List(l) => l.len(),
            NodeSet::Bits { words, .. } => Simd::detect().popcount(words),
        }
    }

    /// Whether the set is empty.
    pub fn is_empty(&self) -> bool {
        match self {
            NodeSet::List(l) => l.is_empty(),
            NodeSet::Bits { words, .. } => words.iter().all(|&w| w == 0),
        }
    }

    /// The bytes of the set before compression (4 a vertex, or 8 a word).
    pub fn raw_bytes(&self) -> usize {
        match self {
            NodeSet::List(l) => 4 * l.len(),
            NodeSet::Bits { words, .. } => 8 * words.len(),
        }
    }

    /// `f` of every vertex, rising.
    pub fn for_each(&self, mut f: impl FnMut(u32)) {
        match self {
            NodeSet::List(l) => l.iter().for_each(|&v| f(v)),
            NodeSet::Bits { first, words } => {
                for (i, &w) in words.iter().enumerate() {
                    each_bit(w, (*first as usize + i) * 64, &mut f);
                }
            }
        }
    }

    /// The vertices, rising.
    pub fn nodes(&self) -> Vec<u32> {
        let mut out = Vec::with_capacity(self.len());
        self.for_each(|v| out.push(v));
        out
    }

    /// The largest vertex, if any.
    fn last(&self) -> Option<u32> {
        match self {
            NodeSet::List(l) => l.last().copied(),
            NodeSet::Bits { first, words } => {
                let i = words.iter().rposition(|&w| w != 0)?;
                Some((*first + i as u32) * 64 + 63 - words[i].leading_zeros())
            }
        }
    }

    /// The set as bytes: a header (the length before compression, whether compressed),
    /// then the form, and the list as differences from the vertex before (4 bytes each) or
    /// the first word's place and the words (8 bytes each), compressed by zstd (mzstd) when
    /// that is smaller.
    pub fn encode(&self) -> Vec<u8> {
        pack(&self.encode_raw(), None)
    }

    /// [`NodeSet::encode`], its pieces compressed on the device's threads (the same bytes).
    pub fn encode_on(&self, device: &CpuDevice) -> Vec<u8> {
        pack(&self.encode_raw(), Some(device))
    }

    /// The set from [`NodeSet::encode`]'s bytes.
    pub fn decode(bytes: &[u8]) -> crate::Result<Self> {
        Self::decode_raw(&unpack(bytes, None)?, true)
    }

    /// [`NodeSet::decode`], the pieces decompressed on the device's threads.
    pub fn decode_on(bytes: &[u8], device: &CpuDevice) -> crate::Result<Self> {
        Self::decode_raw(&unpack(bytes, Some(device))?, true)
    }

    /// [`NodeSet::encode`] before compression.
    pub(crate) fn encode_raw(&self) -> Vec<u8> {
        let mut raw = Vec::with_capacity(5 + self.raw_bytes());
        match self {
            NodeSet::List(l) => {
                raw.push(0);
                raw.extend_from_slice(&(l.len() as u32).to_le_bytes());
                let mut before = 0u32;
                for &v in l {
                    raw.extend_from_slice(&(v - before).to_le_bytes());
                    before = v;
                }
            }
            NodeSet::Bits { first, words } => {
                raw.push(1);
                raw.extend_from_slice(&first.to_le_bytes());
                for w in words {
                    raw.extend_from_slice(&w.to_le_bytes());
                }
            }
        }
        raw
    }

    /// The set [`NodeSet::encode_raw`] wrote; a list must rise when `rising` (else it may
    /// repeat a vertex: the nodes of compact sends).
    pub(crate) fn decode_raw(raw: &[u8], rising: bool) -> crate::Result<Self> {
        let Some((&form, body)) = raw.split_first() else {
            return refuse("an empty node set body");
        };
        let Some((head, body)) = body.split_first_chunk::<4>() else {
            return refuse("a node set body shorter than its header");
        };
        let head = u32::from_le_bytes(*head);
        match form {
            0 => {
                let (deltas, tail) = body.as_chunks::<4>();
                if !tail.is_empty() || deltas.len() != head as usize {
                    return refuse("a node list of another length than it says");
                }
                let mut at = 0u32;
                let mut list = Vec::with_capacity(deltas.len());
                for (i, d) in deltas.iter().enumerate() {
                    let d = u32::from_le_bytes(*d);
                    if rising && i > 0 && d == 0 {
                        return refuse("a node list that does not rise");
                    }
                    at = at
                        .checked_add(d)
                        .ok_or_else(|| GraphError::Slices("a node past u32".into()))?;
                    list.push(at);
                }
                Ok(NodeSet::List(list))
            }
            1 => {
                let (words, tail) = body.as_chunks::<8>();
                if !tail.is_empty() {
                    return refuse("a bit map of a broken word");
                }
                if (u64::from(head) + words.len() as u64) * 64 > 1 << 32 {
                    return refuse("a bit map past u32");
                }
                Ok(NodeSet::Bits {
                    first: head,
                    words: words.iter().map(|w| u64::from_le_bytes(*w)).collect(),
                })
            }
            _ => refuse("a node set of an unknown form"),
        }
    }
}

/// `f(i)` for every `i` in `0..n`, on the device's threads when given (each thread takes
/// the next `i` from a shared counter), the answers in order.
pub(crate) fn each_on<R: Send>(
    n: usize,
    device: Option<&CpuDevice>,
    f: impl Fn(usize) -> R + Sync,
) -> Vec<R> {
    match device {
        Some(d) if n > 1 && d.threads() > 1 => {
            let at = AtomicUsize::new(0);
            let mut bufs: Vec<Vec<(usize, R)>> =
                (0..d.threads().min(n)).map(|_| Vec::new()).collect();
            d.each_block(&mut bufs, |_, buf| {
                loop {
                    let i = at.fetch_add(1, Relaxed);
                    if i >= n {
                        break;
                    }
                    buf.push((i, f(i)));
                }
            });
            let mut all: Vec<(usize, R)> = bufs.into_iter().flatten().collect();
            all.sort_unstable_by_key(|e| e.0);
            all.into_iter().map(|e| e.1).collect()
        }
        _ => (0..n).map(f).collect(),
    }
}

/// `raw` as it travels: its length (8 bytes), a flag, and `raw` compressed by zstd (mzstd)
/// in pieces of [`PIECE`] bytes (flag 1: the number of pieces, each frame's length, the
/// frames) when that is smaller, else `raw` itself (flag 0). The pieces are compressed on
/// the device's threads when one is given; the bytes do not depend on it.
pub(crate) fn pack(raw: &[u8], device: Option<&CpuDevice>) -> Vec<u8> {
    let pieces = raw.len().div_ceil(PIECE);
    let frames: Option<Vec<Vec<u8>>> = (raw.len() >= PACK_FROM)
        .then(|| {
            each_on(pieces, device, |i| {
                let piece = &raw[i * PIECE..((i + 1) * PIECE).min(raw.len())];
                frame::Compressor::new(LEVEL).and_then(|mut c| c.compress(piece))
            })
            .into_iter()
            .collect::<std::io::Result<Vec<_>>>()
            .ok()
        })
        .flatten()
        .filter(|f| 4 + 4 * f.len() + f.iter().map(Vec::len).sum::<usize>() < raw.len());
    let mut out = Vec::with_capacity(9 + raw.len());
    out.extend_from_slice(&(raw.len() as u64).to_le_bytes());
    match frames {
        Some(frames) => {
            out.push(1);
            out.extend_from_slice(&(frames.len() as u32).to_le_bytes());
            for f in &frames {
                out.extend_from_slice(&(f.len() as u32).to_le_bytes());
            }
            for f in &frames {
                out.extend_from_slice(f);
            }
        }
        None => {
            out.push(0);
            out.extend_from_slice(raw);
        }
    }
    out
}

/// The bytes [`pack`] packed (the pieces decompressed on the device's threads when one is
/// given).
pub(crate) fn unpack(bytes: &[u8], device: Option<&CpuDevice>) -> crate::Result<Vec<u8>> {
    let Some((len, rest)) = bytes.split_first_chunk::<8>() else {
        return refuse("packed bytes shorter than their header");
    };
    let len = u64::from_le_bytes(*len) as usize;
    let raw = match rest.split_first() {
        Some((0, raw)) => raw.to_vec(),
        Some((1, body)) => {
            let Some((count, body)) = body.split_first_chunk::<4>() else {
                return refuse("packed pieces without their count");
            };
            let count = u32::from_le_bytes(*count) as usize;
            if count != len.div_ceil(PIECE) || body.len() < 4 * count {
                return refuse("packed pieces of another count than their length says");
            }
            let (lens, mut frames) = body.split_at(4 * count);
            let mut parts = Vec::with_capacity(count);
            for l in lens.as_chunks::<4>().0 {
                let l = u32::from_le_bytes(*l) as usize;
                if frames.len() < l {
                    return refuse("packed pieces cut short");
                }
                let (f, rest) = frames.split_at(l);
                parts.push(f);
                frames = rest;
            }
            let pieces = each_on(count, device, |i| {
                let cap = PIECE.min(len - i * PIECE);
                frame::decompress(parts[i], cap)
            });
            let mut raw = Vec::with_capacity(len);
            for (i, p) in pieces.into_iter().enumerate() {
                let p = p.or_else(|e| refuse(format!("a zstd frame: {e}")))?;
                if p.len() != PIECE.min(len - i * PIECE) {
                    return refuse("a packed piece of another length");
                }
                raw.extend_from_slice(&p);
            }
            raw
        }
        _ => return refuse("packed bytes with an unknown flag"),
    };
    if raw.len() != len {
        return refuse("packed bytes of another length than their header says");
    }
    Ok(raw)
}

/// `f(base + b)` for every set bit `b` of `w`, rising.
fn each_bit(mut w: u64, base: usize, mut f: impl FnMut(u32)) {
    while w != 0 {
        f((base + w.trailing_zeros() as usize) as u32);
        w &= w - 1;
    }
}

/// What one machine found in one level: its new vertices and the edges it looked at. It is
/// what travels; every machine joins every machine's [`Found`] of the level.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Found {
    /// The vertices it reached that were open before the level (on a push, another machine
    /// may have found some of them too).
    pub nodes: NodeSet,
    /// The edges it looked at.
    pub examined: u64,
    /// The out-edges of the vertices it found (the next level's work when the machines'
    /// finds are apart, as a pull's are).
    pub edges: u64,
}

impl Found {
    /// As bytes: the edges looked at and the found vertices' out-edges (8 bytes each), then
    /// [`NodeSet::encode`].
    pub fn to_bytes(&self) -> Vec<u8> {
        self.bytes(None)
    }

    /// [`Found::to_bytes`] compressed on the device's threads (the same bytes).
    pub fn to_bytes_on(&self, device: &CpuDevice) -> Vec<u8> {
        self.bytes(Some(device))
    }

    fn bytes(&self, device: Option<&CpuDevice>) -> Vec<u8> {
        let mut out = self.examined.to_le_bytes().to_vec();
        out.extend_from_slice(&self.edges.to_le_bytes());
        out.extend_from_slice(&pack(&self.nodes.encode_raw(), device));
        out
    }

    /// From [`Found::to_bytes`].
    pub fn from_bytes(bytes: &[u8]) -> crate::Result<Self> {
        Self::read(bytes, None)
    }

    /// [`Found::from_bytes`], decompressed on the device's threads.
    pub fn from_bytes_on(bytes: &[u8], device: &CpuDevice) -> crate::Result<Self> {
        Self::read(bytes, Some(device))
    }

    fn read(bytes: &[u8], device: Option<&CpuDevice>) -> crate::Result<Self> {
        let Some((examined, rest)) = bytes.split_first_chunk::<8>() else {
            return refuse("a found set shorter than its header");
        };
        let Some((edges, rest)) = rest.split_first_chunk::<8>() else {
            return refuse("a found set shorter than its header");
        };
        Ok(Found {
            examined: u64::from_le_bytes(*examined),
            edges: u64::from_le_bytes(*edges),
            nodes: NodeSet::decode_raw(&unpack(rest, device)?, true)?,
        })
    }
}

/// The frontier as every machine holds it.
#[derive(Debug)]
enum Front {
    /// Rising, each once.
    List(Vec<u32>),
    /// A word per 64 vertices.
    Bits(Vec<u64>),
}

/// One thread's part of a machine's slice.
#[derive(Debug)]
struct Lane {
    examined: u64,
    edges: u64,
    /// The least and the largest word of the marks a push set (`usize::MAX`, 0: none).
    lo: usize,
    hi: usize,
}

impl Default for Lane {
    fn default() -> Self {
        Lane {
            examined: 0,
            edges: 0,
            lo: usize::MAX,
            hi: 0,
        }
    }
}

/// The set of the bits of `words` (word `i` at place `first + i`), as
/// [`NodeSet::from_words`] makes it (trimmed bit map or list), counted, scanned and listed
/// on the device's workers; the words are left zero.
fn take_words(words: &mut [u64], first: u32, device: &CpuDevice) -> NodeSet {
    let ws = &*words;
    let parts = device.split(ws.len(), |r| {
        let piece = &ws[r.clone()];
        let count = device.simd().popcount(piece);
        let lo = piece.iter().position(|&w| w != 0).map(|i| r.start + i);
        let hi = piece.iter().rposition(|&w| w != 0).map(|i| r.start + i);
        (r.start, count, lo, hi)
    });
    let count: usize = parts.iter().map(|p| p.1).sum();
    let (Some(lo), Some(hi)) = (
        parts.iter().find_map(|p| p.2),
        parts.iter().rev().find_map(|p| p.3),
    ) else {
        return NodeSet::default();
    };
    let set = if bits_smaller(count, hi - lo + 1) {
        NodeSet::Bits {
            first: first + lo as u32,
            words: ws[lo..=hi].to_vec(),
        }
    } else {
        // Each piece writes its places from the count of the pieces before it (the same
        // pieces: the same length cut the same way).
        let mut list = vec![0u32; count];
        {
            let out = atomic_u32s(&mut list);
            let parts = &parts;
            device.split(ws.len(), |r| {
                let i = parts.partition_point(|p| p.0 < r.start);
                let mut at: usize = parts[..i].iter().map(|p| p.1).sum();
                for (k, &w) in ws[r.clone()].iter().enumerate() {
                    each_bit(w, (first as usize + r.start + k) * 64, |v| {
                        out[at].store(v, Relaxed);
                        at += 1;
                    });
                }
            });
        }
        NodeSet::List(list)
    };
    let zero = atomic_words(&mut words[lo..=hi]);
    device.split(zero.len(), |r| {
        for w in &zero[r] {
            w.store(0, Relaxed);
        }
    });
    set
}

/// Clear bit `w` of `bits` if set; whether this call did.
fn take(bits: &[AtomicU64], w: u32) -> bool {
    let (at, bit) = (&bits[w as usize / 64], 1u64 << (w % 64));
    at.load(Relaxed) & bit != 0 && at.fetch_and(!bit, Relaxed) & bit != 0
}

/// One machine's side of a sliced search ([`slice_rounds`]): the whole graph, kept, and
/// the search's state, the same on every machine between levels. Per level, [`step`]
/// expands this machine's slice and gives its [`Found`]; [`take`] joins every machine's.
///
/// [`step`]: ReachSlice::step
/// [`take`]: ReachSlice::take
#[derive(Debug)]
pub struct ReachSlice {
    machine: usize,
    slices: Slices,
    graph: Arc<Graph<CpuBackend>>,
    opts: BfsOptions,
    /// One machine: today's kernel on kept buffers.
    state: Option<BfsState<CpuBackend>>,
    sources: Vec<u32>,
    /// The vertices that may still be reached.
    open: Vec<u64>,
    front: Front,
    /// The words of the last bit-map frontier, used again.
    spare: Vec<u64>,
    /// The places of the last list frontier, used again.
    spare_list: Vec<u32>,
    /// A word per 64 vertices, all zero between levels: a level's new vertices are marked
    /// here, then taken into its [`Found`].
    marks: Vec<u64>,
    nf: usize,
    mf: u64,
    explored: u64,
    last_pull: u64,
    pulling: bool,
    depth: u32,
    reached: usize,
    steps: Vec<Step>,
    live: bool,
    lanes: Vec<Lane>,
    local_below: u64,
    /// Kept buffers for this side's [`Found`] bytes, sent and received.
    coder: FoundCoder,
    /// The machines' [`Found`]s of a level read from bytes, their buffers kept.
    inbox: Vec<Found>,
}

impl ReachSlice {
    /// Machine `machine`'s side of searches over `graph` (the whole graph, the same on every
    /// machine) cut by `slices`.
    pub fn new(
        machine: usize,
        slices: Slices,
        graph: Arc<Graph<CpuBackend>>,
    ) -> crate::Result<Self> {
        if machine >= slices.machines() {
            return refuse(format!(
                "machine {machine} of {} machines",
                slices.machines()
            ));
        }
        Ok(ReachSlice {
            machine,
            slices,
            graph,
            opts: BfsOptions::default(),
            state: None,
            sources: Vec::new(),
            open: Vec::new(),
            front: Front::List(Vec::new()),
            spare: Vec::new(),
            spare_list: Vec::new(),
            marks: Vec::new(),
            nf: 0,
            mf: 0,
            explored: 0,
            last_pull: 0,
            pulling: false,
            depth: 0,
            reached: 0,
            steps: Vec::new(),
            live: false,
            lanes: Vec::new(),
            local_below: LOCAL_BELOW,
            coder: FoundCoder::new(),
            inbox: Vec::new(),
        })
    }

    /// Levels expected to look at fewer than `edges` edges run whole on every machine (the
    /// same work, the same answer, nothing sent); only the larger levels are cut into
    /// slices and joined. 0 cuts every level; [`LOCAL_BELOW`] by default. Every machine of
    /// a search must use the same bound.
    pub fn with_local_below(mut self, edges: u64) -> Self {
        self.local_below = edges;
        self
    }

    /// The machine this side is.
    pub fn machine(&self) -> usize {
        self.machine
    }

    /// The slices.
    pub fn slices(&self) -> &Slices {
        &self.slices
    }

    /// The graph.
    pub fn graph(&self) -> &Arc<Graph<CpuBackend>> {
        &self.graph
    }

    /// Start a search from `sources` with `opts` (as [`crate::bfs`] takes them; a vertex mask
    /// only on one machine). Every machine starts the same search.
    pub fn start(&mut self, sources: &[u32], opts: &BfsOptions) -> crate::Result<()> {
        self.start_with(sources, opts, None)
    }

    /// [`ReachSlice::start`], the open set filled on the device's workers.
    pub fn start_on(
        &mut self,
        sources: &[u32],
        opts: &BfsOptions,
        device: &CpuDevice,
    ) -> crate::Result<()> {
        self.start_with(sources, opts, Some(device))
    }

    fn start_with(
        &mut self,
        sources: &[u32],
        opts: &BfsOptions,
        device: Option<&CpuDevice>,
    ) -> crate::Result<()> {
        crate::bfs::check(&self.graph, sources, opts)?;
        self.opts = opts.clone();
        self.steps.clear();
        self.live = true;
        self.sources.clear();
        self.sources.extend_from_slice(sources);
        self.sources.sort_unstable();
        self.sources.dedup();
        if self.slices.machines() == 1 {
            return Ok(());
        }
        if opts.allowed.is_some() {
            self.live = false;
            return refuse("a vertex mask is not sliced (one machine takes it)");
        }
        let n = self.graph.vertices();
        let words = n.div_ceil(64);
        // Only a graph of another size changes the buffers; the marks stay zero.
        self.marks.resize(words, 0);
        if self.open.len() == words
            && let Some(d) = device
        {
            let open = atomic_words(&mut self.open);
            d.split(words, |r| {
                for w in &open[r] {
                    w.store(u64::MAX, Relaxed);
                }
            });
        } else {
            self.open.clear();
            self.open.resize(words, u64::MAX);
        }
        if !n.is_multiple_of(64) {
            self.open[words - 1] = u64::MAX >> (64 - n % 64);
        }
        for &s in &self.sources {
            self.open[s as usize / 64] &= !(1 << (s % 64));
        }
        let off = self.graph.out().pattern().offsets();
        self.nf = self.sources.len();
        self.reached = self.nf;
        self.mf = self
            .sources
            .iter()
            .map(|&s| off[s as usize + 1] - off[s as usize])
            .sum();
        let mut first = std::mem::take(&mut self.spare_list);
        first.clear();
        first.extend_from_slice(&self.sources);
        self.keep_front(Front::List(first));
        self.explored = 0;
        self.last_pull = 0;
        self.pulling = false;
        self.depth = 0;
        Ok(())
    }

    /// This machine's part of the next level that is cut into slices, or `None` when the
    /// search is over (on one machine: the whole search, today's kernel, and then `None`).
    /// The small levels before it run whole here, on every machine alike. Every machine
    /// gives `None`, or its part of the same level, at the same time.
    pub fn step(&mut self, device: &CpuDevice) -> crate::Result<Option<Found>> {
        if !self.live {
            return Ok(None);
        }
        if self.slices.machines() == 1 {
            self.live = false;
            let n = self.graph.vertices();
            let st = self.state.get_or_insert_with(|| BfsState::new(n, device));
            let sum = bfs_with(&self.graph, &self.sources, &self.opts, device, st)?;
            self.reached = sum.reached;
            self.depth = sum.depth;
            self.steps.clear();
            self.steps.extend_from_slice(st.steps());
            return Ok(None);
        }
        loop {
            if self.nf == 0 || self.opts.max_depth.is_some_and(|d| self.depth >= d) {
                self.live = false;
                return Ok(None);
            }
            let work = self.begin(device);
            let whole = work < self.local_below;
            let threads = if work < ONE_THREAD_BELOW {
                1
            } else {
                self.lanes.len()
            };
            let found = if self.pulling {
                self.pull(whole, threads, device)
            } else {
                self.push(whole, threads, device)
            };
            if !whole {
                return Ok(Some(found));
            }
            self.join(&[found], device)?;
            if !self.live {
                return Ok(None);
            }
        }
    }

    /// The next level's direction (Beamer's rule, the same on every machine) and the edges
    /// it is expected to look at (a push: the frontier's out-edges; a pull: the edges not
    /// yet looked at).
    fn begin(&mut self, device: &CpuDevice) -> u64 {
        let n = self.graph.vertices() as u64;
        let edges = self.graph.edges() as u64;
        let opts = &self.opts;
        self.pulling = match (opts.direction, self.graph.inn()) {
            (Direction::Push, _) | (Direction::Auto, None) => false,
            (Direction::Pull, _) => true,
            (Direction::Auto, Some(_)) => {
                if self.pulling {
                    (self.nf as u64) * opts.beta >= n && self.mf >= self.last_pull
                } else {
                    self.mf * opts.alpha > edges.saturating_sub(self.explored)
                        && (self.last_pull == 0 || self.mf > self.last_pull)
                }
            }
        };
        let work = if self.pulling {
            edges.saturating_sub(self.explored)
        } else {
            self.mf
        };
        self.explored += self.mf;
        let threads = device.threads().max(1);
        if self.lanes.len() != threads {
            self.lanes = (0..threads).map(|_| Lane::default()).collect();
        }
        work
    }

    fn push(&mut self, whole: bool, threads: usize, device: &CpuDevice) -> Found {
        let out = self.graph.out().pattern();
        let (off, idx): (&[u64], &[u32]) = (out.offsets(), out.indices());
        let degree = |v: u32| off[v as usize + 1] - off[v as usize];
        let open = atomic_words(&mut self.open);
        let marks = atomic_words(&mut self.marks);
        let expand = |lane: &mut Lane, v: u32| {
            let row = &idx[off[v as usize] as usize..off[v as usize + 1] as usize];
            lane.examined += row.len() as u64;
            for &w in row {
                if take(open, w) {
                    let k = w as usize / 64;
                    marks[k].fetch_or(1 << (w % 64), Relaxed);
                    lane.lo = lane.lo.min(k);
                    lane.hi = lane.hi.max(k);
                    lane.edges += degree(w);
                }
            }
        };
        let m = self.machine;
        let at = AtomicUsize::new(0);
        match &self.front {
            Front::List(list) => {
                let mine = if whole {
                    0..list.len()
                } else {
                    self.slices
                        .cut_by(m, list.len(), |i| degree(list[i]), device)
                };
                at.store(mine.start, Relaxed);
                device.each_block(&mut self.lanes[..threads], |_, lane| {
                    loop {
                        let a = at.fetch_add(PUSH_PIECE, Relaxed);
                        if a >= mine.end {
                            break;
                        }
                        for &v in &list[a..(a + PUSH_PIECE).min(mine.end)] {
                            expand(lane, v);
                        }
                    }
                });
            }
            Front::Bits(bits) => {
                let word_degree = |k: usize| {
                    let mut s = 0;
                    each_bit(bits[k], k * 64, |v| s += degree(v));
                    s
                };
                let mine = if whole {
                    0..bits.len()
                } else {
                    self.slices.cut_by(m, bits.len(), word_degree, device)
                };
                at.store(mine.start, Relaxed);
                device.each_block(&mut self.lanes[..threads], |_, lane| {
                    loop {
                        let a = at.fetch_add(PULL_WORDS, Relaxed);
                        if a >= mine.end {
                            break;
                        }
                        let end = (a + PULL_WORDS).min(mine.end);
                        for (k, &w) in bits.iter().enumerate().take(end).skip(a) {
                            each_bit(w, k * 64, |v| expand(lane, v));
                        }
                    }
                });
            }
        }
        let (mut examined, mut edges) = (0, 0);
        let (mut lo, mut hi) = (usize::MAX, 0);
        for lane in &mut self.lanes {
            examined += std::mem::take(&mut lane.examined);
            edges += std::mem::take(&mut lane.edges);
            lo = lo.min(std::mem::replace(&mut lane.lo, usize::MAX));
            hi = hi.max(std::mem::take(&mut lane.hi));
        }
        // The marked words only: the lanes saw where they wrote.
        let nodes = if lo > hi {
            NodeSet::default()
        } else {
            take_words(&mut self.marks[lo..=hi], lo as u32, device)
        };
        Found {
            nodes,
            examined,
            edges,
        }
    }

    fn pull(&mut self, whole: bool, threads: usize, device: &CpuDevice) -> Found {
        let words = self.open.len();
        if let Front::List(list) = &self.front {
            let mut bits = std::mem::take(&mut self.spare);
            bits.clear();
            bits.resize(words, 0);
            {
                let b = atomic_words(&mut bits);
                device.split(list.len(), |r| {
                    for &v in &list[r] {
                        b[v as usize / 64].fetch_or(1 << (v % 64), Relaxed);
                    }
                });
            }
            self.keep_front(Front::Bits(bits));
        }
        let Front::Bits(bits) = &self.front else {
            unreachable!("the frontier was made a bit map")
        };
        let inn = self
            .graph
            .inn()
            .expect("a pull has the transpose")
            .pattern();
        let (ioff, iidx): (&[u64], &[u32]) = (inn.offsets(), inn.indices());
        let off = self.graph.out().pattern().offsets();
        let open = atomic_words(&mut self.open);
        // a pull looks at an open vertex's in-edges until the first on the frontier: the
        // open vertices are the measure of its work
        let word_weight = |k: usize| u64::from(open[k].load(Relaxed).count_ones());
        let mine = if whole {
            0..words
        } else {
            self.slices.cut_by(self.machine, words, word_weight, device)
        };
        {
            let found = atomic_words(&mut self.marks[mine.clone()]);
            let at = AtomicUsize::new(mine.start);
            device.each_block(&mut self.lanes[..threads], |_, lane| {
                loop {
                    let a = at.fetch_add(PULL_WORDS, Relaxed);
                    if a >= mine.end {
                        break;
                    }
                    for k in a..(a + PULL_WORDS).min(mine.end) {
                        let mut o = open[k].load(Relaxed);
                        let mut got = 0u64;
                        let mut todo = o;
                        while todo != 0 {
                            let b = todo.trailing_zeros();
                            todo &= todo - 1;
                            let v = k * 64 + b as usize;
                            for &u in &iidx[ioff[v] as usize..ioff[v + 1] as usize] {
                                lane.examined += 1;
                                if bits[u as usize / 64] >> (u % 64) & 1 == 1 {
                                    o &= !(1 << b);
                                    got |= 1 << b;
                                    lane.edges += off[v + 1] - off[v];
                                    break;
                                }
                            }
                        }
                        open[k].store(o, Relaxed);
                        found[k - mine.start].store(got, Relaxed);
                    }
                }
            });
        }
        let (mut examined, mut edges) = (0, 0);
        for lane in &mut self.lanes {
            examined += std::mem::take(&mut lane.examined);
            edges += std::mem::take(&mut lane.edges);
        }
        Found {
            nodes: take_words(&mut self.marks[mine.clone()], mine.start as u32, device),
            examined,
            edges,
        }
    }

    /// Join every machine's [`Found`] of the level (this machine's included, any order):
    /// the next frontier, the same on every machine.
    pub fn take(&mut self, finds: &[Found], device: &CpuDevice) -> crate::Result<()> {
        if !self.live || self.slices.machines() == 1 {
            return refuse("a level joined with no level running");
        }
        let n = self.graph.vertices();
        if finds
            .iter()
            .any(|f| f.nodes.last().is_some_and(|v| v as usize >= n))
        {
            return refuse(format!("a vertex past the graph's {n}"));
        }
        self.join(finds, device)
    }

    /// The next frontier from every machine's finds of the level (checked).
    fn join(&mut self, finds: &[Found], device: &CpuDevice) -> crate::Result<()> {
        let n = self.graph.vertices();
        let off = self.graph.out().pattern().offsets();
        let degree = |v: u32| off[v as usize + 1] - off[v as usize];
        let total: usize = finds.iter().map(|f| f.nodes.len()).sum();
        let examined: u64 = finds.iter().map(|f| f.examined).sum();
        let lists = finds.iter().all(|f| matches!(f.nodes, NodeSet::List(_)));
        // the machines' finds are apart on a pull (each its own words) and when one machine
        // ran the level whole: their out-edges add up to the next level's
        let apart = self.pulling || finds.len() == 1;
        let summed: u64 = finds.iter().map(|f| f.edges).sum();
        let (got, mf) = if lists && total * 32 <= n {
            let mut next = std::mem::take(&mut self.spare_list);
            next.clear();
            for f in finds {
                if let NodeSet::List(l) = &f.nodes {
                    next.extend_from_slice(l);
                }
            }
            next.sort_unstable();
            next.dedup();
            for &v in &next {
                self.open[v as usize / 64] &= !(1 << (v % 64));
            }
            let mf = if apart {
                summed
            } else {
                next.iter().map(|&v| degree(v)).sum()
            };
            let got = next.len();
            self.keep_front(Front::List(next));
            (got, mf)
        } else {
            let words = self.open.len();
            let mut bits = match std::mem::replace(&mut self.front, Front::List(Vec::new())) {
                Front::Bits(b) => b,
                Front::List(l) => {
                    self.spare_list = l;
                    std::mem::take(&mut self.spare)
                }
            };
            bits.resize(words, 0);
            let mut maps: Vec<(usize, &[u64])> = Vec::new();
            for f in finds {
                if let NodeSet::Bits { first, words: w } = &f.nodes {
                    let first = *first as usize;
                    if first + w.len() > words {
                        return refuse("a bit map past the graph");
                    }
                    maps.push((first, w));
                }
            }
            {
                // the bit maps' words, every word written once (zero where none lies)
                let out = atomic_words(&mut bits);
                device.split(words, |r| {
                    for k in r {
                        let mut x = 0;
                        for &(first, w) in &maps {
                            if k >= first && k < first + w.len() {
                                x |= w[k - first];
                            }
                        }
                        out[k].store(x, Relaxed);
                    }
                });
                for f in finds {
                    if let NodeSet::List(l) = &f.nodes {
                        device.split(l.len(), |r| {
                            for &v in &l[r] {
                                out[v as usize / 64].fetch_or(1 << (v % 64), Relaxed);
                            }
                        });
                    }
                }
            }
            let open = atomic_words(&mut self.open);
            let front = &bits;
            let sums = device.split(words, |r| {
                let (mut got, mut mf) = (0usize, 0u64);
                for k in r {
                    let f = front[k];
                    if f == 0 {
                        continue;
                    }
                    open[k].store(open[k].load(Relaxed) & !f, Relaxed);
                    got += f.count_ones() as usize;
                    if !apart {
                        each_bit(f, k * 64, |v| mf += degree(v));
                    }
                }
                (got, mf)
            });
            self.front = Front::Bits(bits);
            let (got, mf) = sums
                .into_iter()
                .fold((0, 0), |(g, m), (a, b)| (g + a, m + b));
            (got, if apart { summed } else { mf })
        };
        let d = self.depth + 1;
        self.steps.push(Step {
            depth: d,
            direction: if self.pulling {
                Direction::Pull
            } else {
                Direction::Push
            },
            frontier: self.nf,
            reached: got,
            examined,
        });
        if self.pulling {
            self.last_pull = examined;
        }
        if got == 0 {
            self.live = false;
        } else {
            self.reached += got;
            self.nf = got;
            self.depth = d;
            self.mf = mf;
        }
        Ok(())
    }

    /// Make `front` the frontier; the buffer of the one before is kept for the next.
    fn keep_front(&mut self, front: Front) {
        match std::mem::replace(&mut self.front, front) {
            Front::Bits(b) => self.spare = b,
            Front::List(l) => self.spare_list = l,
        }
    }

    /// `found`'s bytes ([`Found::to_bytes`], the same format) on this side's kept
    /// compressors and scratch ([`Found::to_bytes_with`]).
    pub fn encode(&mut self, found: &Found, device: &CpuDevice) -> Vec<u8> {
        found.to_bytes_with(device, &mut self.coder)
    }

    /// [`ReachSlice::take`] of every machine's [`Found`] given as bytes, read into this
    /// side's kept buffers ([`Found::read_into`]): no set is copied before it is joined.
    pub fn take_bytes<'a>(
        &mut self,
        bytes: impl IntoIterator<Item = &'a [u8]>,
        device: &CpuDevice,
    ) -> crate::Result<()> {
        let mut inbox = std::mem::take(&mut self.inbox);
        let mut n = 0;
        let mut read = Ok(());
        for b in bytes {
            if inbox.len() == n {
                inbox.push(Found::default());
            }
            read = Found::read_into(b, device, &mut self.coder, &mut inbox[n]);
            if read.is_err() {
                break;
            }
            n += 1;
        }
        let r = read.and_then(|()| self.take(&inbox[..n], device));
        self.inbox = inbox;
        r
    }

    /// The vertices the last search reached (sources included).
    pub fn reached(&self) -> usize {
        self.reached
    }

    /// The deepest level the last search reached.
    pub fn depth(&self) -> u32 {
        self.depth
    }

    /// The last search's steps, in order.
    pub fn steps(&self) -> &[Step] {
        &self.steps
    }

    /// The vertices the last search reached, rising.
    pub fn vertices(&self) -> Vec<u32> {
        if self.slices.machines() == 1 {
            return self
                .state
                .as_ref()
                .map(|st| CpuBackend::indices(st.levels()))
                .unwrap_or_default();
        }
        let mut out = Vec::with_capacity(self.reached);
        let n = self.graph.vertices();
        for (k, &o) in self.open.iter().enumerate() {
            let mut w = !o;
            if (k + 1) * 64 > n {
                w &= u64::MAX >> ((k + 1) * 64 - n);
            }
            each_bit(w, k * 64, |v| out.push(v));
        }
        out
    }
}

/// What a sliced search did.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SliceRun {
    /// The vertices reached (sources included).
    pub reached: usize,
    /// The deepest level reached.
    pub depth: u32,
    /// The steps (the one-machine search's).
    pub steps: Vec<Step>,
    /// Levels cut into slices and joined over machines (0 on one machine, and for the
    /// levels every machine ran whole).
    pub exchanges: u32,
    /// Vertices handed over, summed over the machines and levels.
    pub sent: u64,
    /// Their bytes before compression ([`NodeSet::raw_bytes`]).
    pub raw_bytes: u64,
}

/// A sliced search in this process: every side (one per machine, in machine order, already
/// [`started`](ReachSlice::start) on the same search) steps on `device`, and every side
/// takes every side's [`Found`], until no side has a level left. A runner over machines
/// keeps the sides where the machines are and moves the [`Found`]s
/// ([`Found::to_bytes`]) between them.
pub fn slice_rounds(sides: &mut [ReachSlice], device: &CpuDevice) -> crate::Result<SliceRun> {
    let Some(first) = sides.first() else {
        return refuse("no side");
    };
    if first.slices.machines() != sides.len()
        || sides.iter().enumerate().any(|(m, s)| s.machine != m)
    {
        return refuse("a side per machine, in machine order");
    }
    let mut run = SliceRun::default();
    loop {
        let mut finds = Vec::with_capacity(sides.len());
        for side in sides.iter_mut() {
            finds.push(side.step(device)?);
        }
        if finds.iter().all(Option::is_none) {
            break;
        }
        let Some(finds) = finds.into_iter().collect::<Option<Vec<Found>>>() else {
            return refuse("the machines disagree on the level");
        };
        run.exchanges += 1;
        for f in &finds {
            run.sent += f.nodes.len() as u64;
            run.raw_bytes += f.nodes.raw_bytes() as u64;
        }
        for side in sides.iter_mut() {
            side.take(&finds, device)?;
        }
    }
    let last = &sides[0];
    run.reached = last.reached;
    run.depth = last.depth;
    run.steps = last.steps.clone();
    Ok(run)
}

/// A search from `sources` on `graph` cut by `slices`, every machine's side in this process
/// on `device` ([`slice_rounds`]), the levels below `local_below` edges run whole on every
/// side ([`ReachSlice::with_local_below`]); with [`Slices::one`] it is one call of today's
/// kernel.
pub fn search_slices(
    graph: &Arc<Graph<CpuBackend>>,
    slices: &Slices,
    local_below: u64,
    sources: &[u32],
    opts: &BfsOptions,
    device: &CpuDevice,
) -> crate::Result<SliceRun> {
    let mut sides = (0..slices.machines())
        .map(|m| {
            ReachSlice::new(m, slices.clone(), Arc::clone(graph))
                .map(|s| s.with_local_below(local_below))
        })
        .collect::<crate::Result<Vec<_>>>()?;
    for side in &mut sides {
        side.start(sources, opts)?;
    }
    slice_rounds(&mut sides, device)
}