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

//! One search over machines that all hold the same whole graph, each level cut by edge count
//! into slices weighted by the machines' cores: the answers and the steps equal one machine's
//! direction-optimizing search, in one process and over three machines faked by threads
//! and channels; many searches handed out whole by the same weights; the frontiers as they
//! travel (a list or a bit map, whichever is smaller, compressed).

use std::sync::Arc;
use std::sync::mpsc;
use std::thread;

use kleene_graph::{
    Bfs, BfsOptions, Direction, Found, FoundCoder, Graph, NodeSet, ReachSlice, Slices, bfs,
    search_slices,
};
use kleene_sparse::{BoolOrAnd, CpuBackend, CpuDevice, Csr};

type B = CpuBackend;

/// A skewed graph of `2^scale` vertices and `factor` edges a vertex (hubs and a long tail,
/// R-MAT's shape; a fixed generator: the same graph every run).
fn rmat(scale: u32, factor: usize, seed: u64) -> Csr<u8> {
    let n = 1usize << scale;
    let mut x = seed;
    let mut step = || {
        x = x
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);
        (x >> 33) as u32
    };
    let (mut src, mut dst) = (Vec::new(), Vec::new());
    for _ in 0..n * factor {
        let (mut s, mut d) = (0u32, 0u32);
        for _ in 0..scale {
            let r = step() % 100;
            s = (s << 1) | u32::from((57..76).contains(&r) || r >= 95);
            d = (d << 1) | u32::from(r >= 76);
        }
        src.push(s);
        dst.push(d);
    }
    Csr::from_edges(n, n, &src, &dst, None, BoolOrAnd).unwrap()
}

/// A `side` x `side` grid, both ways along each edge: a deep search with thin levels.
fn grid(side: u32) -> Csr<u8> {
    let n = side * side;
    let (mut src, mut dst) = (Vec::new(), Vec::new());
    for v in 0..n {
        let (r, c) = (v / side, v % side);
        let mut edge = |w: u32| {
            src.push(v);
            dst.push(w);
        };
        if c + 1 < side {
            edge(v + 1);
        }
        if c > 0 {
            edge(v - 1);
        }
        if r + 1 < side {
            edge(v + side);
        }
        if r > 0 {
            edge(v - side);
        }
    }
    Csr::from_edges(n as usize, n as usize, &src, &dst, None, BoolOrAnd).unwrap()
}

fn built(a: &Csr<u8>, dev: &CpuDevice) -> Arc<Graph<B>> {
    Arc::new(Graph::<B>::new(a.clone(), dev).unwrap())
}

fn opts(direction: Direction, k: Option<u32>) -> BfsOptions {
    BfsOptions {
        direction,
        max_depth: k,
        ..BfsOptions::default()
    }
}

/// The one-machine search's reached count, depth, steps and vertices.
fn check(what: &str, got: (usize, u32, &[kleene_graph::Step], Vec<u32>), want: &Bfs<B>) {
    assert_eq!(got.0, want.reached, "{what}: reached");
    assert_eq!(got.1, want.depth, "{what}: depth");
    assert_eq!(got.2, &want.steps[..], "{what}: steps");
    assert_eq!(got.3, want.vertices(), "{what}: vertices");
}

#[test]
fn cuts_by_weight_cover_every_item_once() {
    let s = Slices::new(&[32, 12, 12]).unwrap();
    assert_eq!(s.machines(), 3);
    assert_eq!((s.weight(0), s.weight(1), s.weight(2)), (32, 12, 12));
    for n in [0usize, 1, 2, 7, 56, 1000, 12345] {
        let parts: Vec<_> = (0..3).map(|m| s.portion(m, n)).collect();
        assert_eq!(parts[0].start, 0);
        assert_eq!(parts[2].end, n);
        assert!(parts.windows(2).all(|w| w[0].end == w[1].start), "{n}");
    }
    assert_eq!(s.portion(0, 56), 0..32);
    assert_eq!(s.portion(1, 56), 32..44);
    assert_eq!(s.portion(2, 56), 44..56);
    // a weighted cut: the running sum before an item decides; one device or another
    let w: Vec<u64> = (0..5000u64)
        .map(|i| (i * 7919) % 97 + u64::from(i % 13 == 0) * 900)
        .collect();
    let mut prefix = vec![0u64];
    for &x in &w {
        prefix.push(prefix.last().unwrap() + x);
    }
    let total = *prefix.last().unwrap();
    for dev in [CpuDevice::new(1), CpuDevice::new(4).with_grain(64)] {
        let mut end = 0;
        for m in 0..3 {
            let r = s.cut(m, &prefix);
            assert_eq!(r, s.cut_by(m, w.len(), |i| w[i], &dev), "machine {m}");
            assert_eq!(r.start, end);
            end = r.end;
            let share = s.share(m, total);
            if r.start < w.len() && m > 0 {
                assert!(prefix[r.start] >= share.start);
            }
            if r.start > 0 {
                assert!(prefix[r.start - 1] < share.start);
            }
        }
        assert_eq!(end, w.len());
    }
    // one machine takes all; a machine of weight 0 nothing
    assert_eq!(Slices::one().cut(0, &prefix), 0..w.len());
    let z = Slices::new(&[3, 0, 1]).unwrap();
    assert!(z.cut(1, &prefix).is_empty());
    assert!(Slices::new(&[]).is_err());
    assert!(Slices::new(&[0, 0]).is_err());
}

#[test]
fn node_sets_travel_as_the_smaller_form_and_come_back() {
    let sparse: Vec<u32> = (0..100).map(|i| i * 1000 + 7).collect();
    let dense: Vec<u32> = (5000..9000).filter(|v| v % 3 != 0).collect();
    let s = NodeSet::from_sorted(sparse.clone());
    assert!(matches!(s, NodeSet::List(_)));
    let d = NodeSet::from_sorted(dense.clone());
    assert!(matches!(d, NodeSet::Bits { .. }));
    assert_eq!(d.nodes(), dense);
    assert_eq!(d.len(), dense.len());
    assert!(d.raw_bytes() < 4 * dense.len());
    for set in [
        s,
        d,
        NodeSet::default(),
        NodeSet::from_sorted(vec![0, u32::MAX]),
    ] {
        let bytes = set.encode();
        assert_eq!(NodeSet::decode(&bytes).unwrap(), set);
        let f = Found {
            nodes: set.clone(),
            examined: 77,
            edges: 5,
        };
        assert_eq!(Found::from_bytes(&f.to_bytes()).unwrap(), f);
        assert!(NodeSet::decode(&bytes[..bytes.len() / 2]).is_err());
    }
    // a large set travels in pieces, compressed on a device's threads: the same bytes
    let big: Vec<u32> = (0..3_000_000u32)
        .filter(|v| v % 7 == 0 || v % 11 == 0)
        .collect();
    let set = NodeSet::from_sorted(big.clone());
    let dev = CpuDevice::new(4);
    let (one, many) = (set.encode(), set.encode_on(&dev));
    assert_eq!(one, many);
    assert!(
        one.len() < set.raw_bytes() / 4,
        "{} of {}",
        one.len(),
        set.raw_bytes()
    );
    assert_eq!(NodeSet::decode_on(&one, &dev).unwrap().nodes(), big);
    let f = Found {
        nodes: set,
        examined: 1,
        edges: 2,
    };
    assert_eq!(f.to_bytes_on(&dev), f.to_bytes());
    assert_eq!(Found::from_bytes_on(&f.to_bytes(), &dev).unwrap(), f);
    let mut broken = one.clone();
    let k = broken.len() - 10;
    broken[k] ^= 0xff;
    assert!(NodeSet::decode(&broken).is_err() || NodeSet::decode(&broken).unwrap().nodes() != big);
    // the dense set compresses below its bit map
    let enc = NodeSet::from_sorted(dense.clone()).encode();
    println!(
        "{} vertices: list {} bytes, bit map {} bytes, sent {} bytes",
        dense.len(),
        4 * dense.len(),
        NodeSet::from_sorted(dense).raw_bytes(),
        enc.len()
    );
    // from words: trimmed, or a list when smaller
    let w = NodeSet::from_words(10, vec![0, 0, u64::MAX, 0b101, 0]);
    assert_eq!(
        w,
        NodeSet::Bits {
            first: 12,
            words: vec![u64::MAX, 0b101]
        }
    );
    // one vertex in 100 places: a bit map once compressed (above one in 256)
    let sparse_bits: Vec<u32> = (0..64u32).map(|i| i * 100 + 5).collect();
    assert!(matches!(
        NodeSet::from_sorted(sparse_bits.clone()),
        NodeSet::Bits { .. }
    ));
    assert_eq!(
        NodeSet::from_sorted(sparse_bits.clone()).nodes(),
        sparse_bits
    );
    let l = NodeSet::from_words(1, vec![0, 1 << 3, 0, 0, 0, 0, 0, 0, 0, 1]);
    assert_eq!(l, NodeSet::List(vec![2 * 64 + 3, 10 * 64]));
    assert!(NodeSet::from_words(0, vec![0, 0]).is_empty());
}

/// The bytes made and read on kept buffers ([`FoundCoder`]) are the plain ones: lists and
/// bit maps, small (sent whole) and large (compressed in pieces), one coder and one found
/// set used again across forms and sizes.
#[test]
fn found_bytes_on_kept_buffers_are_the_plain_bytes() {
    let sets = [
        NodeSet::default(),
        NodeSet::from_sorted(vec![3, 70, 900]),
        NodeSet::from_sorted((5000..9000).filter(|v| v % 3 != 0).collect()),
        NodeSet::from_sorted(vec![0, u32::MAX]),
        NodeSet::from_sorted(
            (0..3_000_000u32)
                .filter(|v| v % 7 == 0 || v % 11 == 0)
                .collect(),
        ),
        NodeSet::from_sorted((0..300_000u32).map(|v| v * 1000 + v % 7).collect()),
        NodeSet::from_sorted((0..40_000u32).map(|v| v * 3).collect()),
    ];
    assert!(matches!(sets[5], NodeSet::List(_)));
    assert!(matches!(sets[4], NodeSet::Bits { .. }));
    for dev in [CpuDevice::new(1), CpuDevice::new(4)] {
        let mut coder = FoundCoder::new();
        let mut into = Found::default();
        for round in 0..2 {
            for (i, set) in sets.iter().enumerate() {
                let f = Found {
                    nodes: set.clone(),
                    examined: 7 + i as u64,
                    edges: 11 * i as u64,
                };
                let plain = f.to_bytes();
                let kept = f.to_bytes_with(&dev, &mut coder);
                assert_eq!(
                    kept,
                    plain,
                    "set {i} round {round} {} threads",
                    dev.threads()
                );
                Found::read_into(&plain, &dev, &mut coder, &mut into).unwrap();
                assert_eq!(into, f, "set {i} round {round} {} threads", dev.threads());
                let mut broken = plain.clone();
                broken.truncate(plain.len() - 1);
                assert!(Found::read_into(&broken, &dev, &mut coder, &mut into).is_err());
            }
        }
    }
}

/// The bytes of a [`Found`] that travels, two pieces compressed, as kleene-graph wrote them
/// through the `zstd` shim (main 93007dd), before it called mzstd directly.
const SHIM_BYTES: &str = "05000000000000000900000000000000f5490200000000000102000000200000001900000028b52ffda000000200a50000600100000000814020100804020100f1ffca4b1228b52ffd60f5487d000038028140201008040100eb89f66204";

/// The wire does not change with the coder: a set compressed in two pieces is written to the
/// bytes the shim wrote, plainly and on kept buffers, and those bytes read back to the set.
#[test]
fn found_bytes_are_the_bytes_written_through_the_zstd_shim() {
    let want: Vec<u8> = SHIM_BYTES
        .as_bytes()
        .chunks(2)
        .map(|h| u8::from_str_radix(std::str::from_utf8(h).unwrap(), 16).unwrap())
        .collect();
    let f = Found {
        nodes: NodeSet::from_sorted((0..1_200_000u32).filter(|v| v % 7 == 0).collect()),
        examined: 5,
        edges: 9,
    };
    assert_eq!((want[24], &want[25..29]), (1, &[2u8, 0, 0, 0][..]));
    assert_eq!(f.to_bytes(), want);
    assert_eq!(Found::from_bytes(&want).unwrap(), f);
    for dev in [CpuDevice::new(1), CpuDevice::new(4)] {
        let mut coder = FoundCoder::new();
        let mut into = Found::default();
        assert_eq!(f.to_bytes_with(&dev, &mut coder), want);
        assert_eq!(Found::from_bytes_on(&want, &dev).unwrap(), f);
        Found::read_into(&want, &dev, &mut coder, &mut into).unwrap();
        assert_eq!(into, f);
    }
}

#[test]
fn a_sliced_search_equals_one_machine_steps_included() {
    let dev = CpuDevice::new(4).with_grain(256);
    let cases = [
        ("rmat 2^14", rmat(14, 8, 7), vec![0u32, 3]),
        ("grid 90", grid(90), vec![0u32]),
        ("rmat 2^12 sparse", rmat(12, 1, 11), vec![5u32, 900, 4000]),
    ];
    let weights: [&[u32]; 4] = [&[1], &[1, 1, 1], &[32, 12, 12], &[5, 0, 3, 1]];
    for (name, a, sources) in &cases {
        let g = built(a, &dev);
        for direction in [Direction::Auto, Direction::Push, Direction::Pull] {
            for k in [None, Some(1), Some(2), Some(3), Some(6), Some(10)] {
                let o = opts(direction, k);
                let want = bfs(&g, sources, &o, &dev).unwrap();
                for w in weights {
                    for local in [0, 3000, u64::MAX] {
                        let slices = Slices::new(w).unwrap();
                        let run = search_slices(&g, &slices, local, sources, &o, &dev).unwrap();
                        let what = format!(
                            "{name} {direction:?} k {k:?} weights {w:?} local below {local}"
                        );
                        assert_eq!(run.reached, want.reached, "{what}");
                        assert_eq!(run.depth, want.depth, "{what}");
                        assert_eq!(run.steps, want.steps, "{what}");
                        if w.len() == 1 || local == u64::MAX {
                            assert_eq!(run.exchanges, 0, "{what}: nothing sent");
                            assert_eq!(run.sent, 0, "{what}");
                        } else if local == 0 {
                            assert_eq!(run.exchanges as usize, want.steps.len(), "{what}");
                            // every machine found every vertex but the sources at most once
                            assert!(run.sent as usize >= want.reached - sources.len(), "{what}");
                        } else {
                            assert!(run.exchanges as usize <= want.steps.len(), "{what}");
                        }
                    }
                }
            }
        }
    }
    // a graph without its transpose pushes every level
    let a = rmat(12, 4, 3);
    let g = Arc::new(Graph::<B>::push_only(a, &dev).unwrap());
    let o = BfsOptions::default();
    let want = bfs(&g, &[1], &o, &dev).unwrap();
    let run = search_slices(&g, &Slices::new(&[2, 1]).unwrap(), 0, &[1], &o, &dev).unwrap();
    assert_eq!(run.steps, want.steps);
    assert!(run.steps.iter().all(|s| s.direction == Direction::Push));
}

#[test]
fn a_side_gives_the_reached_vertices_and_refuses_what_it_cannot_slice() {
    let dev = CpuDevice::new(2);
    let a = rmat(11, 6, 5);
    let g = built(&a, &dev);
    let o = opts(Direction::Auto, Some(3));
    let want = bfs(&g, &[2], &o, &dev).unwrap();
    for w in [&[1u32][..], &[2, 1, 1]] {
        let slices = Slices::new(w).unwrap();
        let mut sides: Vec<ReachSlice> = (0..slices.machines())
            .map(|m| {
                ReachSlice::new(m, slices.clone(), Arc::clone(&g))
                    .unwrap()
                    .with_local_below(0)
            })
            .collect();
        for s in &mut sides {
            s.start(&[2], &o).unwrap();
        }
        let run = kleene_graph::slice_rounds(&mut sides, &dev).unwrap();
        assert_eq!(run.reached, want.reached);
        for s in &sides {
            check(
                &format!("{w:?} machine {}", s.machine()),
                (s.reached(), s.depth(), s.steps(), s.vertices()),
                &want,
            );
        }
    }
    let slices = Slices::new(&[1, 1]).unwrap();
    assert!(ReachSlice::new(2, slices.clone(), Arc::clone(&g)).is_err());
    let mut side = ReachSlice::new(0, slices, Arc::clone(&g)).unwrap();
    let masked = BfsOptions {
        allowed: Some(kleene_sparse::Mask::all(a.nrows())),
        ..BfsOptions::default()
    };
    assert!(side.start(&[0], &masked).is_err());
    assert!(side.start(&[u32::MAX], &BfsOptions::default()).is_err());
    side.start(&[0], &BfsOptions::default()).unwrap();
    let past = Found {
        nodes: NodeSet::List(vec![a.nrows() as u32]),
        examined: 0,
        edges: 0,
    };
    assert!(side.take(&[past], &dev).is_err());
}

/// One machine's message of a level: its [`Found`] as bytes, or nothing when its search is
/// over.
struct Message {
    round: u32,
    from: usize,
    bytes: Option<Vec<u8>>,
}

/// The other machines' messages of round `round` (later rounds wait in `early`).
fn receive(
    from: &mpsc::Receiver<Message>,
    early: &mut Vec<Message>,
    round: u32,
    others: usize,
) -> Vec<Message> {
    let mut got: Vec<Message> = Vec::new();
    let mut k = 0;
    while k < early.len() {
        if early[k].round == round {
            got.push(early.swap_remove(k));
        } else {
            k += 1;
        }
    }
    while got.len() < others {
        let m = from.recv().unwrap();
        if m.round == round {
            got.push(m);
        } else {
            early.push(m);
        }
    }
    got.sort_by_key(|m| m.from);
    got
}

/// What one faked machine did: the search's answer and the bytes it sent per level.
struct Machine {
    reached: usize,
    depth: u32,
    steps: Vec<kleene_graph::Step>,
    vertices: Vec<u32>,
    bytes: Vec<usize>,
}

/// The search over `weights.len()` machines, a thread each with its own device of
/// `threads[m]` threads and its own side, every [`Found`] sent to every other machine as
/// bytes over a channel.
fn over_machines(
    g: &Arc<Graph<B>>,
    weights: &[u32],
    threads: &[usize],
    sources: &[u32],
    o: &BfsOptions,
    local: u64,
) -> Vec<Machine> {
    let slices = Slices::new(weights).unwrap();
    let k = slices.machines();
    let (txs, rxs): (Vec<_>, Vec<_>) = (0..k).map(|_| mpsc::channel::<Message>()).unzip();
    let handles: Vec<_> = rxs
        .into_iter()
        .enumerate()
        .map(|(m, rx)| {
            let txs = txs.clone();
            let (g, slices, sources, o) =
                (Arc::clone(g), slices.clone(), sources.to_vec(), o.clone());
            let dev = CpuDevice::new(threads[m]);
            thread::spawn(move || {
                let mut side = ReachSlice::new(m, slices, g)
                    .unwrap()
                    .with_local_below(local);
                side.start_on(&sources, &o, &dev).unwrap();
                let (mut early, mut bytes) = (Vec::new(), Vec::new());
                let mut round = 0u32;
                loop {
                    let mine = side.step(&dev).unwrap();
                    // On the side's kept buffers, both ways.
                    let out = mine.as_ref().map(|f| side.encode(f, &dev));
                    bytes.push(out.as_ref().map_or(0, Vec::len));
                    for (to, tx) in txs.iter().enumerate() {
                        if to != m {
                            tx.send(Message {
                                round,
                                from: m,
                                bytes: out.clone(),
                            })
                            .unwrap();
                        }
                    }
                    let got = receive(&rx, &mut early, round, k - 1);
                    if mine.is_none() && got.iter().all(|g| g.bytes.is_none()) {
                        bytes.pop();
                        break;
                    }
                    let own = out.expect("every machine has the level");
                    let theirs: Vec<Vec<u8>> = got
                        .into_iter()
                        .map(|g| g.bytes.expect("the level"))
                        .collect();
                    let all = std::iter::once(&own[..]).chain(theirs.iter().map(Vec::as_slice));
                    side.take_bytes(all, &dev).unwrap();
                    round += 1;
                }
                Machine {
                    reached: side.reached(),
                    depth: side.depth(),
                    steps: side.steps().to_vec(),
                    vertices: side.vertices(),
                    bytes,
                }
            })
        })
        .collect();
    drop(txs);
    handles.into_iter().map(|h| h.join().unwrap()).collect()
}

#[test]
fn over_three_machines_faked_in_one_process() {
    let dev = CpuDevice::new(4);
    for (name, a, source) in [
        ("rmat 2^15", rmat(15, 8, 9), 1u32),
        ("grid 120", grid(120), 0),
    ] {
        let g = built(&a, &dev);
        for k in [Some(1), Some(2), Some(3), Some(6), Some(10), None] {
            let o = opts(Direction::Auto, k);
            let want = bfs(&g, &[source], &o, &dev).unwrap();
            for local in [0, 5000] {
                let got = over_machines(&g, &[32, 12, 12], &[4, 2, 2], &[source], &o, local);
                for (m, x) in got.iter().enumerate() {
                    check(
                        &format!("{name} k {k:?} machine {m} local below {local}"),
                        (x.reached, x.depth, &x.steps, x.vertices.clone()),
                        &want,
                    );
                }
            }
            let got = over_machines(&g, &[32, 12, 12], &[4, 2, 2], &[source], &o, 0);
            let per_level: Vec<usize> = (0..got[0].bytes.len())
                .map(|l| got.iter().map(|x| x.bytes[l]).sum())
                .collect();
            println!(
                "{name} k {k:?}: {} levels, bytes sent per level (all machines) {per_level:?}, {} in all",
                per_level.len(),
                per_level.iter().sum::<usize>()
            );
        }
    }
}

#[test]
fn many_searches_handed_out_whole_equal_one_machine() {
    let dev = CpuDevice::new(2);
    let a = rmat(13, 6, 21);
    let g = built(&a, &dev);
    // the units: 40 k-hop queries, each answered by today's kernel on the machine it is given to
    let units: Vec<(u32, u32)> = (0..40u32)
        .map(|i| ((i * 211) % 8192, [1, 2, 3, 6, 10][i as usize % 5]))
        .collect();
    let answer = |&(s, k): &(u32, u32)| {
        bfs(&g, &[s], &opts(Direction::Auto, Some(k)), &dev)
            .unwrap()
            .reached
            - 1
    };
    let want: Vec<usize> = units.iter().map(answer).collect();
    for w in [&[1u32][..], &[32, 12, 12], &[1, 0, 1]] {
        let slices = Slices::new(w).unwrap();
        let joined: Vec<usize> = thread::scope(|sc| {
            let hs: Vec<_> = (0..slices.machines())
                .map(|m| {
                    let mine = &units[slices.portion(m, units.len())];
                    sc.spawn(move || mine.iter().map(answer).collect::<Vec<_>>())
                })
                .collect();
            hs.into_iter().flat_map(|h| h.join().unwrap()).collect()
        });
        assert_eq!(joined, want, "{w:?}");
    }
}

/// Combined at the sender, the sends give each part what it folds from the uncombined ones:
/// one entry per node, its values folded with the query's add (or, min), sorted; the same
/// with no device and on 1, 2 and 7 threads, for nodes packed (a dense fold) and spread (a
/// sorted fold); and coded compact on the device's threads, the same bytes.
#[test]
fn combined_sends_give_each_part_what_it_folds_from_the_sends() {
    use kleene_graph::Sends;
    let mut x = 0x9e37_79b9u64;
    let mut next = |m: u64| {
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        x % m
    };
    fn folded<T: kleene_sparse::Value + Ord>(
        s: &Sends<T>,
        part: u32,
        add: impl Fn(T, T) -> T,
    ) -> Vec<(u32, T)> {
        let mut e = s.for_part(part);
        e.sort_unstable_by_key(|e| e.0);
        let mut out: Vec<(u32, T)> = Vec::new();
        for (n, v) in e {
            match out.last_mut() {
                Some(l) if l.0 == n => l.1 = add(l.1, v),
                _ => out.push((n, v)),
            }
        }
        out
    }
    let devices = [
        None,
        Some(CpuDevice::new(1)),
        Some(CpuDevice::new(2)),
        Some(CpuDevice::new(7)),
    ];
    // Many border edges to few nodes (R-MAT's hubs), then few edges over a wide range.
    for (entries, range) in [(20000u64, 300u64), (300000, 40000), (50000, 1 << 26)] {
        let mut dist: Sends<u32> = Sends::new();
        let mut flags: Sends<u64> = Sends::new();
        for _ in 0..entries {
            let (p, v) = (next(5) as u32, next(range) as u32);
            dist.push(p, v, next(1 << 20) as u32);
            flags.push(p, v, 1 << next(64));
        }
        for dev in &devices {
            let d = dist.clone().combine(|a, b| a.min(b), dev.as_ref());
            let f = flags.clone().combine(|a, b| a | b, dev.as_ref());
            for p in 0..5 {
                let want = folded(&dist, p, |a, b| a.min(b));
                assert_eq!(d.for_part(p), want, "min, part {p}, {entries} in {range}");
                let want = folded(&flags, p, |a, b| a | b);
                assert_eq!(f.for_part(p), want, "or, part {p}, {entries} in {range}");
            }
            for s in [(&d.part, &d.node), (&f.part, &f.node)] {
                let keys: Vec<(u32, u32)> = s.0.iter().copied().zip(s.1.iter().copied()).collect();
                assert!(
                    keys.windows(2).all(|w| w[0] < w[1]),
                    "one entry per node, sorted"
                );
            }
            assert_eq!(d.to_compact_on(dev.as_ref()), d.to_compact());
            assert_eq!(f.to_compact_on(dev.as_ref()), f.to_compact());
            if range == 300 {
                assert!(d.len() < dist.len() / 2, "{} of {}", d.len(), dist.len());
                assert!(d.to_compact().len() < dist.to_compact().len());
            }
        }
    }
    let empty: Sends<u8> = Sends::new();
    assert!(empty.combine(|a, b| a | b, None).is_empty());
}

#[test]
fn border_sends_travel_compact_and_come_back_sorted() {
    use kleene_graph::Sends;
    let mut x = 0x1234_5678u64;
    let mut next = |m: u64| {
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        x % m
    };
    // reach's sends: value 1, distinct nodes, many to a few parts (bit maps)
    let mut reach: Sends<u8> = Sends::new();
    for p in 0..3u32 {
        for v in (0..20000u32).filter(|v| v % 3 != p) {
            reach.push(p, v, 1);
        }
    }
    // k-hop's and shortest paths' sends: repeats of a node with other values (lists)
    let mut dist: Sends<u32> = Sends::new();
    for _ in 0..5000 {
        dist.push(next(8) as u32, next(100_000) as u32, next(1 << 20) as u32);
    }
    dist.push(7, 5, 9);
    dist.push(7, 5, 3);
    fn sorted<T: Copy + Ord>(s: &Sends<T>) -> Vec<(u32, u32, T)> {
        let mut v: Vec<_> = (0..s.part.len())
            .map(|k| (s.part[k], s.node[k], s.value[k]))
            .collect();
        v.sort_unstable();
        v
    }
    let bytes = reach.to_compact();
    assert_eq!(
        sorted(&Sends::<u8>::from_compact(&bytes).unwrap()),
        sorted(&reach)
    );
    let arrow = reach.clone().to_batch().unwrap().get_array_memory_size();
    println!(
        "reach sends: {} entries, compact {} bytes, Arrow batch {arrow} bytes",
        reach.len(),
        bytes.len()
    );
    let d = dist.to_compact();
    assert_eq!(
        sorted(&Sends::<u32>::from_compact(&d).unwrap()),
        sorted(&dist)
    );
    println!(
        "distance sends: {} entries, compact {} bytes, raw {} bytes",
        dist.len(),
        d.len(),
        dist.len() * 12
    );
    let empty: Sends<u8> = Sends::new();
    assert!(
        Sends::<u8>::from_compact(&empty.to_compact())
            .unwrap()
            .is_empty()
    );
    assert!(Sends::<u8>::from_compact(&bytes[..bytes.len() - 3]).is_err());
    // a value too wide for the receiver's type
    let mut wide: Sends<u32> = Sends::new();
    wide.push(0, 0, 300);
    assert!(Sends::<u8>::from_compact(&wide.to_compact()).is_err());
}

/// The measurement behind `COMBINE_DENSE_RATIO` and the compact coding (run by hand:
/// `cargo test --release --test slices combine_costs -- --ignored --nocapture`).
#[test]
#[ignore]
fn combine_costs() {
    use kleene_graph::Sends;
    use std::time::Instant;
    let dev = CpuDevice::default();
    let mut x = 0x2545_f491u64;
    let mut next = |m: u64| {
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        x % m
    };
    // Three target parts of 5.6M nodes; sends per node from 1/64 to 16 on average.
    let nodes = 5_600_000u64;
    for per_node in [1.0 / 64.0, 1.0 / 16.0, 1.0 / 4.0, 1.0, 16.0] {
        let m = (3.0 * nodes as f64 * per_node) as u64;
        let mut s: Sends<u32> = Sends::new();
        for _ in 0..m {
            // Skewed: half the sends to a hundredth of the nodes, as R-MAT's hubs.
            let v = if next(2) == 0 {
                next(nodes / 100)
            } else {
                next(nodes)
            };
            s.push(next(3) as u32, v as u32, next(1 << 20) as u32);
        }
        let mut line = format!("{m} sends ({per_node} a node):");
        for (name, ratio) in [
            ("sort", 0),
            ("ratio 4", 4),
            ("ratio 16", 16),
            ("ratio 64", 64),
            ("dense", u64::MAX),
        ] {
            let t = Instant::now();
            let c = s
                .clone()
                .combine_dense_from(|a, b| a.min(b), Some(&dev), ratio);
            line += &format!(
                " {name} {:.1} ms ({});",
                t.elapsed().as_secs_f64() * 1e3,
                c.len()
            );
        }
        let mut order: Vec<usize> = (0..s.len()).collect();
        let t = Instant::now();
        order.sort_unstable_by_key(|&k| (s.part[k], s.node[k]));
        line += &format!(
            " one-thread sort of all {:.1} ms;",
            t.elapsed().as_secs_f64() * 1e3
        );
        let c = s.clone().combine(|a, b| a.min(b), Some(&dev));
        let t = Instant::now();
        let one = c.to_compact_on(None);
        let t1 = t.elapsed();
        let t = Instant::now();
        let many = c.to_compact_on(Some(&dev));
        let tn = t.elapsed();
        assert_eq!(one, many);
        line += &format!(
            " compact {} B of {} raw: one thread {:.1} ms, {} threads {:.1} ms",
            one.len(),
            c.len() * 8,
            t1.as_secs_f64() * 1e3,
            dev.threads(),
            tn.as_secs_f64() * 1e3
        );
        println!("{line}");
    }
}