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

//! The per-part step objects driven over a transport that is not the rounds' own loop: three
//! "machines" (threads) in one process, each keeping its parts' sides, the border sends moved
//! between them as Arrow batches over channels. The answers equal one machine's.

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

use arrow_array::RecordBatch;
use kleene_graph::{BfsState, Graph, ReachPart, Sends, Split, SplitIds, SplitKey, reach_rounds};
use kleene_sparse::{BoolOrAnd, CpuBackend, CpuDevice, Csr};

type B = CpuBackend;

/// A random graph of `n` nodes and `m` edges (a fixed generator: the same graph every run).
fn graph(n: u32, m: usize, seed: u64) -> Csr<u8> {
    let mut x = seed;
    let mut next = || {
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        (x % n as u64) as u32
    };
    let (mut src, mut dst) = (Vec::with_capacity(m), Vec::with_capacity(m));
    for _ in 0..m {
        src.push(next());
        dst.push(next());
    }
    Csr::from_edges(n as usize, n as usize, &src, &dst, None, BoolOrAnd).unwrap()
}

/// One machine's message in a round: the sends for the receiver's parts (an Arrow batch)
/// and how many entries the sender sent this round in all (for the end of the run).
struct Message {
    round: u32,
    batch: RecordBatch,
    sent: u64,
}

/// The `machines` messages of round `round`: a faster machine's later messages wait in
/// `early` (a channel does not keep rounds apart).
fn receive(
    from: &mpsc::Receiver<Message>,
    early: &mut Vec<Message>,
    round: u32,
    machines: 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() < machines {
        let m = from.recv().unwrap();
        if m.round == round {
            got.push(m);
        } else {
            early.push(m);
        }
    }
    got
}

/// One machine: keeps the sides of the parts `placement` gives it, runs them, and moves the
/// sends to the machines of their parts. Gives its parts' reached split ids and the rounds.
fn machine(
    me: usize,
    split: &Split<u8>,
    placement: &[usize],
    sources: &[u64],
    to: &[mpsc::Sender<Message>],
    from: &mpsc::Receiver<Message>,
) -> (Vec<u64>, u32) {
    let device = CpuDevice::default();
    let ids: &SplitIds = split.ids();
    let np = ids.parts();
    let machines = to.len();
    let mine: Vec<u32> = (0..np as u32)
        .filter(|&p| placement[p as usize] == me)
        .collect();
    let mut sides: Vec<ReachPart<B>> = mine
        .iter()
        .map(|&p| {
            let part = split.part(p);
            let g: Graph<B> = Graph::new(part.inner().clone(), &device).unwrap();
            let st = BfsState::new(g.vertices(), &device);
            ReachPart::new(part, np, g, st)
        })
        .collect();
    let mut arrivals: Vec<Vec<(u32, u8)>> = vec![Vec::new(); mine.len()];
    for &s in sources {
        let (p, l) = ids.locate(s).unwrap();
        if let Some(i) = mine.iter().position(|&q| q == p) {
            arrivals[i].push((l, 1));
        }
    }
    let mut rounds = 0;
    let mut early: Vec<Message> = Vec::new();
    loop {
        // Run my parts on what arrived; sort the sends by the machine of their part.
        let mut out: Vec<Sends<u8>> = (0..machines).map(|_| Sends::new()).collect();
        let mut sent = 0u64;
        for (i, &p) in mine.iter().enumerate() {
            let s = sides[i]
                .step(split.part(p), ids, &mut arrivals[i], &device)
                .unwrap();
            sent += s.len() as u64;
            for k in 0..s.len() {
                out[placement[s.part[k] as usize]].push(s.part[k], s.node[k], s.value[k]);
            }
        }
        for (m, s) in out.into_iter().enumerate() {
            let batch = s.to_batch().unwrap();
            to[m]
                .send(Message {
                    round: rounds,
                    batch,
                    sent,
                })
                .unwrap();
        }
        let mut total = 0;
        for msg in receive(from, &mut early, rounds, machines) {
            total += msg.sent;
            let s = Sends::<u8>::from_batch(&msg.batch).unwrap();
            for k in 0..s.len() {
                let i = mine.iter().position(|&q| q == s.part[k]).unwrap();
                arrivals[i].push((s.node[k], s.value[k]));
            }
        }
        if total == 0 {
            break;
        }
        rounds += 1;
    }
    let mut reached = Vec::new();
    for (i, &p) in mine.iter().enumerate() {
        reached.extend(sides[i].reached().iter().map(|&l| ids.base(p) + l as u64));
    }
    (reached, rounds)
}

/// Reach over three machines: each machine's thread, channels between every two.
fn over_three(split: &Split<u8>, placement: &[usize], sources: &[u64]) -> (Vec<u64>, u32) {
    let machines = 3;
    let (tx, rx): (Vec<_>, Vec<_>) = (0..machines).map(|_| mpsc::channel()).unzip();
    let got: Vec<(Vec<u64>, u32)> = thread::scope(|sc| {
        let handles: Vec<_> = rx
            .into_iter()
            .enumerate()
            .map(|(me, rx)| {
                let tx = tx.clone();
                sc.spawn(move || machine(me, split, placement, sources, &tx, &rx))
            })
            .collect();
        handles.into_iter().map(|h| h.join().unwrap()).collect()
    });
    let rounds = got[0].1;
    assert!(
        got.iter().all(|g| g.1 == rounds),
        "every machine ends in the same round"
    );
    let mut all: Vec<u64> = got.into_iter().flat_map(|g| g.0).collect();
    all.sort_unstable();
    (all, rounds)
}

#[test]
fn reach_over_three_machines_equals_one_machine() {
    let device = CpuDevice::default();
    let a = graph(3000, 7000, 0x5eed);
    let n = a.nrows() as u64;
    for key in [
        SplitKey::Hash(3),
        SplitKey::Hash(8),
        SplitKey::Blocks(vec![0, 700, 1500, 2200]),
    ] {
        let split = Split::from_csr(&a, &key, BoolOrAnd).unwrap();
        let np = split.ids().parts();
        // Parts to machines: round robin (with 8 parts some machines hold three).
        let placement: Vec<usize> = (0..np).map(|p| p % 3).collect();
        for sources in [vec![0u64], vec![5, 1777, 2999], vec![]] {
            let starts: Vec<u64> = sources
                .iter()
                .map(|&v| split.ids().from_original(v as u32).unwrap())
                .collect();
            let (got, rounds) = over_three(&split, &placement, &starts);
            // The same split run by the rounds' own loop in one process.
            let mut gs: Vec<Graph<B>> = split
                .parts()
                .iter()
                .map(|p| Graph::new(p.inner().clone(), &device).unwrap())
                .collect();
            let mut st: Vec<BfsState<B>> = gs
                .iter()
                .map(|g| BfsState::new(g.vertices(), &device))
                .collect();
            let r = reach_rounds(&split, &mut gs, &starts, &mut st, &device).unwrap();
            assert_eq!(got, r.ids(split.ids()), "{key:?} from {sources:?}");
            assert_eq!(rounds, r.exchanges.exchanges, "{key:?} from {sources:?}");
            // And one machine, one part.
            let whole = Split::whole(a.clone()).unwrap();
            let mut g1: Vec<Graph<B>> = vec![Graph::new(a.clone(), &device).unwrap()];
            let mut s1 = vec![BfsState::new(n as usize, &device)];
            let one = reach_rounds(&whole, &mut g1, &sources, &mut s1, &device).unwrap();
            let mut want: Vec<u64> = one
                .ids(whole.ids())
                .into_iter()
                .map(|i| split.ids().from_original(i as u32).unwrap())
                .collect();
            want.sort_unstable();
            assert_eq!(got, want, "{key:?} from {sources:?}");
        }
    }
}

#[test]
fn sends_go_through_an_arrow_batch_unchanged() {
    let mut s: Sends<u32> = Sends::new();
    s.push(2, 7, 40);
    s.push(0, 1, u32::MAX);
    s.push(2, 7, 3);
    let b = s.clone().to_batch().unwrap();
    assert_eq!(b.num_rows(), 3);
    assert_eq!(b.schema(), Sends::<u32>::schema());
    assert_eq!(Sends::<u32>::from_batch(&b).unwrap(), s);
    // A value too wide for the side's type is refused.
    let mut w: Sends<u64> = Sends::new();
    w.push(0, 0, u64::from(u32::MAX) + 1);
    let b = w.to_batch().unwrap();
    assert!(Sends::<u32>::from_batch(&b).is_err());
}

#[test]
fn a_part_side_folds_unsorted_repeated_arrivals_and_refuses_another_part() {
    let device = CpuDevice::default();
    let a = graph(400, 900, 7);
    let split = Split::from_csr(&a, &SplitKey::Hash(2), BoolOrAnd).unwrap();
    let part = split.part(0);
    let g: Graph<B> = Graph::new(part.inner().clone(), &device).unwrap();
    let st = BfsState::new(g.vertices(), &device);
    let mut side = ReachPart::new(part, 2, g, st);
    let mut arrivals = vec![(5, 1), (2, 1), (5, 1), (2, 1)];
    let sends = side
        .step(part, split.ids(), &mut arrivals, &device)
        .unwrap();
    assert!(arrivals.is_empty());
    assert!(side.reached().contains(&2) && side.reached().contains(&5));
    assert!(side.reached().windows(2).all(|w| w[0] < w[1]));
    assert!(
        sends.part.iter().all(|&q| q == 1),
        "a border send leaves the part"
    );
    assert_eq!(side.runs(), 1);
    // The same nodes again: nothing new, no search, no sends.
    let mut again = vec![(2, 1), (5, 1)];
    let none = side.step(part, split.ids(), &mut again, &device).unwrap();
    assert!(none.is_empty());
    assert_eq!(side.runs(), 1);
    // Another part's side is refused.
    assert!(
        side.step(split.part(1), split.ids(), &mut vec![], &device)
            .is_err()
    );
}