crates/kleene-graph/tests/machines_kinds.rs
//! The step objects of components, shortest paths and closure over three "machines"
//! (and the level-by-level k hops) (threads) in one process, the border sends moved as Arrow batches over channels: the
//! answers equal the rounds' own loop and one machine's, and so do the exchange counts.
use std::sync::mpsc;
use std::thread;
use arrow_array::RecordBatch;
use std::collections::VecDeque;
use kleene_graph::{
ClosurePart, ComponentsPart, Graph, KhopPart, Sends, Split, SplitKey, SsspOptions, SsspPart,
closure_rounds, components_rounds, khop_rounds, sssp_rounds,
};
use kleene_sparse::{BoolOrAnd, CpuBackend, CpuDevice, MinPlus, Value};
type B = CpuBackend;
/// A random edge list of `n` nodes and `m` edges with weights 1..=9 (a fixed generator).
fn edges(n: u32, m: usize, seed: u64) -> (Vec<u32>, Vec<u32>, Vec<u32>) {
let mut x = seed;
let mut next = || {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
x
};
let (mut s, mut d, mut w) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..m {
s.push((next() % n as u64) as u32);
d.push((next() % n as u64) as u32);
w.push((next() % 9 + 1) as u32);
}
(s, d, w)
}
fn keys() -> Vec<SplitKey> {
vec![
SplitKey::Hash(3),
SplitKey::Hash(8),
SplitKey::Blocks(vec![0, 300, 650, 1000]),
]
}
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
}
/// Three machines, part `p` on machine `p % 3`. Each machine makes its parts' sides with
/// `make(p)` (the side, its first sends, its first arrivals) and steps them with `step` on
/// what arrived; the sends travel as Arrow batches. Gives every part's side (by part) and
/// the exchanges that carried something.
fn over_three<S, T, M, F>(np: usize, make: M, step: F) -> (Vec<S>, u32)
where
S: Send,
T: Value + Into<u64> + TryFrom<u64> + Send,
M: Fn(u32) -> (S, Sends<T>, Vec<(u32, T)>) + Sync,
F: Fn(&mut S, u32, &mut Vec<(u32, T)>) -> Sends<T> + Sync,
{
let machines = 3;
let (tx, rx): (Vec<_>, Vec<_>) = (0..machines).map(|_| mpsc::channel::<Message>()).unzip();
let (make, step) = (&make, &step);
let got: Vec<(Vec<(u32, S)>, u32)> = thread::scope(|sc| {
let hs: Vec<_> = rx
.into_iter()
.enumerate()
.map(|(me, rx)| {
let tx = tx.clone();
sc.spawn(move || {
let mine: Vec<u32> = (0..np as u32).filter(|p| *p as usize % 3 == me).collect();
let mut sides = Vec::new();
let mut first = Sends::new();
let mut arrivals = Vec::new();
for &p in &mine {
let (s, mut f, a) = make(p);
sides.push(s);
first.append(&mut f);
arrivals.push(a);
}
let mut rounds = 0;
let mut early: Vec<Message> = Vec::new();
let mut pending = Some(first);
loop {
let mut all = pending.take().unwrap_or_default();
for (i, &p) in mine.iter().enumerate() {
let mut s = step(&mut sides[i], p, &mut arrivals[i]);
all.append(&mut s);
}
let sent = all.len() as u64;
let mut out: Vec<Sends<T>> = (0..machines).map(|_| Sends::new()).collect();
for k in 0..all.len() {
let q = all.part[k];
out[q as usize % 3].push(q, all.node[k], all.value[k]);
}
for (m, s) in out.into_iter().enumerate() {
let batch = s.to_batch().unwrap();
tx[m]
.send(Message {
round: rounds,
batch,
sent,
})
.unwrap();
}
let mut total = 0;
for msg in receive(&rx, &mut early, rounds, machines) {
total += msg.sent;
let s = Sends::<T>::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;
}
(mine.into_iter().zip(sides).collect(), rounds)
})
})
.collect();
hs.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<(u32, S)> = got.into_iter().flat_map(|g| g.0).collect();
all.sort_by_key(|e| e.0);
(all.into_iter().map(|e| e.1).collect(), rounds)
}
#[test]
fn components_over_three_machines_equal_one_machine() {
let device = CpuDevice::new(2);
let n = 1000;
let (src, dst, _) = edges(n, 900, 3);
let wo = Split::<u8>::new(n as usize, &src, &dst, None, &SplitKey::Hash(1), BoolOrAnd).unwrap();
let wi = Split::<u8>::new(n as usize, &dst, &src, None, &SplitKey::Hash(1), BoolOrAnd).unwrap();
let one = components_rounds::<B>(&wo, &wi, &device).unwrap();
for key in keys() {
let out = Split::<u8>::new(n as usize, &src, &dst, None, &key, BoolOrAnd).unwrap();
let inn = Split::<u8>::new(n as usize, &dst, &src, None, &key, BoolOrAnd).unwrap();
let ids = out.ids();
let (sides, rounds) = over_three(
ids.parts(),
|p| {
let (s, f) =
ComponentsPart::new::<B>(out.part(p), inn.part(p), ids, &device).unwrap();
(s, f, Vec::new())
},
|s, p, a| s.step(out.part(p), inn.part(p), ids, a).unwrap(),
);
let of: Vec<u32> = sides.iter().flat_map(|s| s.names()).collect();
let r = components_rounds::<B>(&out, &inn, &device).unwrap();
assert_eq!(of, r.of, "{key:?}");
assert_eq!(rounds, r.exchanges.exchanges, "{key:?}");
// By original node, the one-machine answer.
let by_node: Vec<u32> = (0..n)
.map(|v| of[ids.from_original(v).unwrap() as usize])
.collect();
let one_by_node: Vec<u32> = (0..n)
.map(|v| one.of[wo.ids().from_original(v).unwrap() as usize])
.collect();
assert_eq!(by_node, one_by_node, "{key:?}");
}
}
#[test]
fn shortest_paths_over_three_machines_equal_one_machine() {
let device = CpuDevice::new(2);
let n = 1000;
let (src, dst, w) = edges(n, 4000, 5);
let s = MinPlus::<u32>::new();
let opts = SsspOptions::default();
for weighted in [false, true] {
let wv = weighted.then_some(w.as_slice());
let whole = Split::new(n as usize, &src, &dst, wv, &SplitKey::Hash(1), s).unwrap();
for source in [0u32, 444] {
let one = sssp_rounds::<B>(
&whole,
whole.ids().from_original(source).unwrap(),
&opts,
&device,
)
.unwrap();
let mut want: Vec<(u32, u64)> = one
.ids(whole.ids())
.into_iter()
.map(|(i, d)| (whole.ids().original(i).unwrap(), d))
.collect();
want.sort_unstable();
for key in keys() {
let split = Split::new(n as usize, &src, &dst, wv, &key, s).unwrap();
let ids = split.ids();
let (sp, sl) = ids.locate(ids.from_original(source).unwrap()).unwrap();
let (sides, rounds) = over_three(
ids.parts(),
|p| {
let mut side = SsspPart::<B>::new(split.part(p));
let first = if p == sp {
side.start(split.part(p), ids, sl, &opts, &device).unwrap()
} else {
Sends::new()
};
(side, first, Vec::new())
},
|side, p, a| side.step(split.part(p), ids, a, &device).unwrap(),
);
let mut got: Vec<(u32, u64)> = Vec::new();
for (p, side) in sides.iter().enumerate() {
let base = ids.base(p as u32);
for &(l, d) in side.distances() {
got.push((ids.original(base + l as u64).unwrap(), d));
}
}
got.sort_unstable();
assert_eq!(got, want, "{key:?} from {source}, weighted {weighted}");
let r =
sssp_rounds::<B>(&split, ids.from_original(source).unwrap(), &opts, &device)
.unwrap();
assert_eq!(rounds, r.exchanges.exchanges, "{key:?} from {source}");
}
}
}
}
#[test]
fn closure_over_three_machines_equals_one_machine() {
let device = CpuDevice::new(2);
let n = 1000;
let (src, dst, _) = edges(n, 1300, 9);
let whole =
Split::<u8>::new(n as usize, &src, &dst, None, &SplitKey::Hash(1), BoolOrAnd).unwrap();
// Base pairs: 70 of the edges (two batches of starts).
let base_orig: Vec<(u32, u32)> = (0..70).map(|k| (src[k * 7], dst[k * 7])).collect();
let on = |split: &Split<u8>| -> Vec<(u64, u64)> {
base_orig
.iter()
.map(|&(a, b)| {
(
split.ids().from_original(a).unwrap(),
split.ids().from_original(b).unwrap(),
)
})
.collect()
};
let orig = |split: &Split<u8>, pairs: Vec<(u64, u64)>| -> Vec<(u32, u32)> {
let mut v: Vec<(u32, u32)> = pairs
.into_iter()
.map(|(a, b)| {
(
split.ids().original(a).unwrap(),
split.ids().original(b).unwrap(),
)
})
.collect();
v.sort_unstable();
v
};
let want = orig(
&whole,
closure_rounds::<B>(&whole, &on(&whole), &device)
.unwrap()
.pairs,
);
for key in keys() {
let split = Split::<u8>::new(n as usize, &src, &dst, None, &key, BoolOrAnd).unwrap();
let ids = split.ids();
let base = on(&split);
let mut starts: Vec<u64> = base.iter().map(|e| e.0).collect();
starts.sort_unstable();
starts.dedup();
let mut pairs: Vec<(u64, u64)> = Vec::new();
let mut exchanges = 0;
// One run over the machines per batch of 64 starts (the caller picks the batch).
for batch in starts.chunks(64) {
let (sides, rounds) = over_three(
ids.parts(),
|p| {
let mut first = Vec::new();
for &(a, y) in &base {
if let Ok(k) = batch.binary_search(&a) {
let (q, l) = ids.locate(y).unwrap();
if q == p {
first.push((l, 1u64 << k));
}
}
}
(
ClosurePart::<B>::new(split.part(p), &device),
Sends::new(),
first,
)
},
|side, p, a| side.step(split.part(p), ids, a, &device).unwrap(),
);
exchanges += rounds;
for (p, side) in sides.iter().enumerate() {
for (l, mut word) in side.words() {
while word != 0 {
let k = word.trailing_zeros() as usize;
word &= word - 1;
pairs.push((batch[k], ids.base(p as u32) + l as u64));
}
}
}
}
assert_eq!(orig(&split, pairs), want, "{key:?}");
let r = closure_rounds::<B>(&split, &base, &device).unwrap();
assert_eq!(exchanges, r.exchanges.exchanges, "{key:?}");
}
}
/// The nodes other than `source` within `k` hops, by a queue.
fn plain_khop(n: u32, src: &[u32], dst: &[u32], source: u32, k: u32) -> Vec<u32> {
let mut d = vec![u32::MAX; n as usize];
d[source as usize] = 0;
let mut q = VecDeque::from([source]);
while let Some(v) = q.pop_front() {
if d[v as usize] == k {
continue;
}
for e in 0..src.len() {
if src[e] == v && d[dst[e] as usize] == u32::MAX {
d[dst[e] as usize] = d[v as usize] + 1;
q.push_back(dst[e]);
}
}
}
(0..n)
.filter(|&v| v != source && d[v as usize] <= k)
.collect()
}
#[test]
fn k_hops_level_by_level_equal_a_queue_one_part_and_over_three_machines() {
let device = CpuDevice::new(2);
let n = 1000;
let (src, dst, _) = edges(n, 1800, 13);
let mut all_keys = keys();
all_keys.push(SplitKey::Hash(1));
for key in all_keys {
let split = Split::<u8>::new(n as usize, &src, &dst, None, &key, BoolOrAnd).unwrap();
let ids = split.ids();
for (source, k) in [(0u32, 1u32), (0, 2), (17, 3), (17, 6), (444, 10)] {
let want = plain_khop(n, &src, &dst, source, k);
let from = ids.from_original(source).unwrap();
let mut gs: Vec<Graph<B>> = split
.parts()
.iter()
.map(|p| Graph::new(p.inner().clone(), &device).unwrap())
.collect();
let r = khop_rounds(&split, &mut gs, from, k, &device).unwrap();
let mut got: Vec<u32> = r
.ids(ids)
.into_iter()
.map(|i| ids.original(i).unwrap())
.filter(|&v| v != source)
.collect();
got.sort_unstable();
assert_eq!(got, want, "{key:?} from {source}, k {k}");
assert!(r.exchanges.exchanges <= k, "{key:?}: one hop a round");
// Over three machines.
let (sp, sl) = ids.locate(from).unwrap();
let (sides, rounds) = over_three(
ids.parts(),
|p| {
let part = split.part(p);
let g = Graph::new(part.inner().clone(), &device).unwrap();
let first = if p == sp {
vec![(sl, 0u32)]
} else {
Vec::new()
};
(KhopPart::<B>::new(part, g, k), Sends::new(), first)
},
|side, p, a| side.step(split.part(p), ids, a, &device).unwrap(),
);
let mut over: Vec<u32> = Vec::new();
for (p, side) in sides.iter().enumerate() {
for &l in side.reached() {
let v = ids.original(ids.base(p as u32) + l as u64).unwrap();
if v != source {
over.push(v);
}
}
}
over.sort_unstable();
assert_eq!(over, want, "{key:?} from {source}, k {k}, three machines");
assert_eq!(
rounds, r.exchanges.exchanges,
"{key:?} from {source}, k {k}"
);
}
}
}