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

//! Local-first rounds over a split: reachability, closure, weak components and shortest
//! paths equal the one-machine answers (a plain one-thread reference and the one-part run)
//! on graphs split 1, 2, 3 and 8 ways, with parts that feed each other in a circle and a
//! start that reaches nothing.

use std::collections::{BTreeMap, BTreeSet, BinaryHeap, VecDeque};

use kleene_graph::{
    BfsOptions, BfsState, Graph, GraphBackend, Split, SplitKey, SsspOptions, bfs_with,
    closure_rounds, components_rounds, reach_rounds, sssp_rounds,
};
use kleene_sparse::{BoolOrAnd, CpuBackend, CpuDevice, Csr, MinPlus, SparseBackend};

type B = CpuBackend;

struct G {
    n: usize,
    src: Vec<u32>,
    dst: Vec<u32>,
    w: Vec<u32>,
}

fn random(n: u32, m: usize, seed: u64) -> G {
    let mut x = seed;
    let mut next = || {
        x = x
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);
        (x >> 33) as u32
    };
    let (mut src, mut dst, mut w) = (Vec::new(), Vec::new(), Vec::new());
    for _ in 0..m {
        src.push(next() % n);
        dst.push(next() % n);
        w.push(1 + next() % 9);
    }
    G {
        n: n as usize,
        src,
        dst,
        w,
    }
}

/// A ring 0 -> 1 -> ... -> n-1 -> 0 plus a few chords, and node `n` alone: split in blocks,
/// each part feeds the next and the last the first (a circle of parts).
fn ring(n: u32) -> G {
    let (mut src, mut dst, mut w) = (Vec::new(), Vec::new(), Vec::new());
    for i in 0..n {
        src.push(i);
        dst.push((i + 1) % n);
        w.push(2);
        if i % 7 == 0 {
            src.push(i);
            dst.push((i + n / 2) % n);
            w.push(9);
        }
    }
    G {
        n: n as usize + 1,
        src,
        dst,
        w,
    }
}

fn keys(n: usize) -> Vec<SplitKey> {
    vec![
        SplitKey::Blocks(vec![0]),
        SplitKey::Hash(2),
        SplitKey::Blocks(vec![0, n as u64 / 3, 2 * n as u64 / 3]),
        SplitKey::Hash(3),
        SplitKey::Hash(8),
        SplitKey::Property((0..n as u32).map(|v| v % 8).collect()),
    ]
}

fn reference_reach(g: &G, starts: &[u32]) -> BTreeSet<u32> {
    let mut seen: BTreeSet<u32> = starts.iter().copied().collect();
    let mut q: VecDeque<u32> = starts.iter().copied().collect();
    while let Some(v) = q.pop_front() {
        for k in 0..g.src.len() {
            if g.src[k] == v && seen.insert(g.dst[k]) {
                q.push_back(g.dst[k]);
            }
        }
    }
    seen
}

fn graphs(split: &Split<u8>, device: &CpuDevice) -> (Vec<Graph<B>>, Vec<BfsState<B>>) {
    let g: Vec<Graph<B>> = split
        .parts()
        .iter()
        .map(|p| Graph::new(p.inner().clone(), device).unwrap())
        .collect();
    let st = g
        .iter()
        .map(|g| BfsState::new(g.vertices(), device))
        .collect();
    (g, st)
}

#[test]
fn reachability_equals_the_one_machine_answer() {
    let device = CpuDevice::new(4);
    for g in [random(300, 700, 1), random(300, 300, 2), ring(60)] {
        for starts in [
            vec![0u32],
            vec![5, 77 % g.n as u32, 200 % g.n as u32],
            vec![(g.n - 1) as u32],
        ] {
            let want = reference_reach(&g, &starts);
            for key in keys(g.n) {
                let split = Split::<u8>::new(g.n, &g.src, &g.dst, None, &key, BoolOrAnd).unwrap();
                let (mut gs, mut st) = graphs(&split, &device);
                let ids = split.ids();
                let s: Vec<u64> = starts
                    .iter()
                    .map(|&v| ids.from_original(v).unwrap())
                    .collect();
                let r = reach_rounds(&split, &mut gs, &s, &mut st, &device).unwrap();
                let got: BTreeSet<u32> = r
                    .ids(ids)
                    .iter()
                    .map(|&i| ids.original(i).unwrap())
                    .collect();
                assert_eq!(got, want, "{key:?} from {starts:?}");
                if split.parts().len() == 1 {
                    assert_eq!(r.exchanges.exchanges, 0);
                    assert_eq!(r.exchanges.runs, vec![1]);
                }
            }
        }
    }
}

#[test]
fn one_part_is_one_search_of_the_whole_graph() {
    let device = CpuDevice::new(4);
    let g = random(500, 2000, 3);
    let a = Csr::<u8>::from_edges(g.n, g.n, &g.src, &g.dst, None, BoolOrAnd).unwrap();
    let whole = Split::whole(a.clone()).unwrap();
    let (mut gs, mut st) = graphs(&whole, &device);
    let r = reach_rounds(&whole, &mut gs, &[3, 9], &mut st, &device).unwrap();
    // The same search on the same graph: the same levels, the same steps.
    let direct = Graph::<B>::new(a, &device).unwrap();
    let mut mine = BfsState::new(g.n, &device);
    bfs_with(&direct, &[3, 9], &BfsOptions::default(), &device, &mut mine).unwrap();
    assert_eq!(
        B::vector_to_host(st[0].levels()).iter().collect::<Vec<_>>(),
        B::vector_to_host(mine.levels()).iter().collect::<Vec<_>>()
    );
    assert_eq!(st[0].steps(), mine.steps());
    assert_eq!(r.reached[0], B::indices(mine.levels()));
    assert_eq!(r.exchanges.exchanges, 0);
}

#[test]
fn a_circle_of_parts_exchanges_until_nothing_is_new_and_a_lone_start_wakes_nothing() {
    let device = CpuDevice::new(2);
    let g = ring(60);
    let key = SplitKey::Blocks(vec![0, 20, 40]);
    let split = Split::<u8>::new(g.n, &g.src, &g.dst, None, &key, BoolOrAnd).unwrap();
    let (mut gs, mut st) = graphs(&split, &device);
    let r = reach_rounds(&split, &mut gs, &[0], &mut st, &device).unwrap();
    assert_eq!(r.ids(split.ids()).len(), 60);
    // Part 0 reaches 1 and (by a chord) 2 at once, part 1 reaches 2; part 2 leads back to 0,
    // which has nothing new: the rounds end when no part receives anything new.
    assert!(r.exchanges.exchanges >= 2, "{:?}", r.exchanges);
    assert!(r.exchanges.exchanges <= 4, "{:?}", r.exchanges);
    assert_eq!(r.exchanges.woken(), 3);
    // Node 60 has no edge: it reaches only itself; no exchange, one part woken.
    let (mut gs, mut st) = graphs(&split, &device);
    let lone = reach_rounds(&split, &mut gs, &[60], &mut st, &device).unwrap();
    assert_eq!(lone.ids(split.ids()), vec![60]);
    assert_eq!(lone.exchanges.exchanges, 0);
    assert_eq!(lone.exchanges.runs, vec![0, 0, 1]);
    // A part nothing reaches is never woken: from 45 within part 2... the ring reaches all,
    // so cut the ring's way back: a chain 0 -> 1 -> ... (no edge into part 0 from others).
    let chain = G {
        n: 30,
        src: (0..29).collect(),
        dst: (1..30).collect(),
        w: vec![1; 29],
    };
    let split = Split::<u8>::new(
        30,
        &chain.src,
        &chain.dst,
        None,
        &SplitKey::Blocks(vec![0, 10, 20]),
        BoolOrAnd,
    )
    .unwrap();
    let (mut gs, mut st) = graphs(&split, &device);
    let r = reach_rounds(&split, &mut gs, &[12], &mut st, &device).unwrap();
    assert_eq!(r.exchanges.runs, vec![0, 1, 1]);
    assert_eq!(r.exchanges.exchanges, 1);
}

#[test]
fn closure_equals_the_one_machine_answer() {
    let device = CpuDevice::new(4);
    for g in [random(120, 260, 4), ring(40)] {
        // tc(X, Z) :- edge(X, Z).  tc(X, Z) :- tc(X, Y), edge(Y, Z).  for every X.
        let mut want = BTreeSet::new();
        for x in 0..g.n as u32 {
            let firsts: Vec<u32> = (0..g.src.len())
                .filter(|&k| g.src[k] == x)
                .map(|k| g.dst[k])
                .collect();
            for z in reference_reach(&g, &firsts) {
                want.insert((x, z));
            }
        }
        let mut one = None;
        for key in keys(g.n) {
            let split = Split::<u8>::new(g.n, &g.src, &g.dst, None, &key, BoolOrAnd).unwrap();
            let ids = split.ids();
            let base: Vec<(u64, u64)> = (0..g.src.len())
                .map(|k| {
                    (
                        ids.from_original(g.src[k]).unwrap(),
                        ids.from_original(g.dst[k]).unwrap(),
                    )
                })
                .collect();
            let r = closure_rounds::<B>(&split, &base, &device).unwrap();
            let got: BTreeSet<(u32, u32)> = r
                .pairs
                .iter()
                .map(|&(a, b)| (ids.original(a).unwrap(), ids.original(b).unwrap()))
                .collect();
            assert_eq!(got.len(), r.pairs.len());
            assert_eq!(got, want, "{key:?}");
            if split.parts().len() == 1 {
                assert_eq!(r.exchanges.exchanges, 0);
                one = Some(got);
            }
        }
        assert_eq!(one.unwrap(), want);
    }
}

/// Weak components: each node named by the least node of its component.
fn reference_components(g: &G) -> Vec<u32> {
    let mut of: Vec<u32> = (0..g.n as u32).collect();
    loop {
        let mut changed = false;
        for k in 0..g.src.len() {
            let (a, b) = (g.src[k] as usize, g.dst[k] as usize);
            let m = of[a].min(of[b]);
            if of[a] != m || of[b] != m {
                of[a] = m;
                of[b] = m;
                changed = true;
            }
        }
        if !changed {
            return of;
        }
    }
}

#[test]
fn weak_components_equal_the_one_machine_answer() {
    let device = CpuDevice::new(4);
    for g in [random(300, 200, 5), random(300, 500, 6), ring(50)] {
        let want = reference_components(&g);
        for key in keys(g.n) {
            let out = Split::<u8>::new(g.n, &g.src, &g.dst, None, &key, BoolOrAnd).unwrap();
            let inn = Split::<u8>::new(g.n, &g.dst, &g.src, None, &key, BoolOrAnd).unwrap();
            let r = components_rounds::<B>(&out, &inn, &device).unwrap();
            let ids = out.ids();
            let got: Vec<u32> = (0..g.n as u32)
                .map(|v| r.of[ids.from_original(v).unwrap() as usize])
                .collect();
            assert_eq!(got, want, "{key:?}");
            if out.parts().len() == 1 {
                // One part: the kernel's own answer, no exchange.
                let a = Csr::<u8>::from_edges(g.n, g.n, &g.src, &g.dst, None, BoolOrAnd).unwrap();
                let c = B::components_of(&a, &a.transpose(), &device).unwrap();
                assert_eq!(r.of, c.of);
                assert_eq!(r.exchanges.exchanges, 0);
            }
        }
    }
}

fn dijkstra(g: &G, source: u32, weighted: bool) -> BTreeMap<u32, u64> {
    let mut best: BTreeMap<(u32, u32), u64> = BTreeMap::new();
    for k in 0..g.src.len() {
        let w = if weighted { g.w[k] as u64 } else { 1 };
        let e = best.entry((g.src[k], g.dst[k])).or_insert(w);
        *e = (*e).min(w);
    }
    let mut dist = BTreeMap::from([(source, 0u64)]);
    let mut heap = BinaryHeap::from([std::cmp::Reverse((0u64, source))]);
    while let Some(std::cmp::Reverse((d, v))) = heap.pop() {
        if dist.get(&v).is_some_and(|&x| x < d) {
            continue;
        }
        for (&(a, b), &w) in best.range((v, 0)..=(v, u32::MAX)) {
            debug_assert_eq!(a, v);
            let nd = d + w;
            if dist.get(&b).is_none_or(|&x| nd < x) {
                dist.insert(b, nd);
                heap.push(std::cmp::Reverse((nd, b)));
            }
        }
    }
    dist
}

#[test]
fn shortest_paths_equal_the_one_machine_answer() {
    let device = CpuDevice::new(4);
    let s = MinPlus::<u32>::new();
    for g in [random(300, 900, 7), ring(60)] {
        for source in [0u32, 17, (g.n - 1) as u32] {
            for weighted in [false, true] {
                let want = dijkstra(&g, source, weighted);
                for key in keys(g.n) {
                    let w = weighted.then_some(g.w.as_slice());
                    let split = Split::new(g.n, &g.src, &g.dst, w, &key, s).unwrap();
                    let ids = split.ids();
                    let r = sssp_rounds::<B>(
                        &split,
                        ids.from_original(source).unwrap(),
                        &SsspOptions::default(),
                        &device,
                    )
                    .unwrap();
                    let got: BTreeMap<u32, u64> = r
                        .ids(ids)
                        .into_iter()
                        .map(|(i, d)| (ids.original(i).unwrap(), d))
                        .collect();
                    assert_eq!(got, want, "{key:?} from {source}, weighted {weighted}");
                }
            }
        }
    }
}

/// Exchanges and time of a reach split 1, 2, 3 and 8 ways, in one process: a random graph
/// (2^20 nodes, 16M edges, split by hash) and a grid road network (1024 x 1024, each node to
/// its right and lower neighbour and back, split into blocks of rows as regions). Run with
/// `cargo test --release -p kleene-graph --test rounds -- --ignored --nocapture`.
#[test]
#[ignore]
fn exchange_counts() {
    let device = CpuDevice::default();
    let random = random(1 << 20, 16 << 20, 11);
    let side = 1024u32;
    let (mut src, mut dst) = (Vec::new(), Vec::new());
    for r in 0..side {
        for c in 0..side {
            let v = r * side + c;
            for w in [
                (c + 1 < side).then_some(v + 1),
                (r + 1 < side).then_some(v + side),
            ]
            .into_iter()
            .flatten()
            {
                src.extend([v, w]);
                dst.extend([w, v]);
            }
        }
    }
    let n = (side * side) as usize;
    let grid = G {
        n,
        w: vec![1; src.len()],
        src,
        dst,
    };
    for (name, g, region) in [("random", &random, false), ("grid", &grid, true)] {
        for parts in [1u32, 2, 3, 8] {
            let key = if parts == 1 {
                SplitKey::Blocks(vec![0])
            } else if region {
                SplitKey::Blocks(
                    (0..parts as u64)
                        .map(|k| k * g.n as u64 / parts as u64)
                        .collect(),
                )
            } else {
                SplitKey::Hash(parts)
            };
            let split = Split::<u8>::new(g.n, &g.src, &g.dst, None, &key, BoolOrAnd).unwrap();
            let border: usize = split.parts().iter().map(|p| p.border().len()).sum();
            let (mut gs, mut st) = graphs(&split, &device);
            let mut times = Vec::new();
            let mut last = None;
            for _ in 0..5 {
                let t = std::time::Instant::now();
                let r = reach_rounds(&split, &mut gs, &[0], &mut st, &device).unwrap();
                times.push(t.elapsed().as_secs_f64() * 1e3);
                last = Some(r);
            }
            times.sort_by(f64::total_cmp);
            let r = last.unwrap();
            println!(
                "{name} parts {parts}: border edges {border}, reached {}, exchanges {}, sent {}, runs {:?}, median {:.1} ms",
                r.ids(split.ids()).len(),
                r.exchanges.exchanges,
                r.exchanges.sent,
                r.exchanges.runs,
                times[2]
            );
        }
    }
}

/// Row 17's measurement: a closure on one machine by today's masked products
/// ([`kleene_graph::closure`]) and by the rounds' set propagation on one part
/// ([`closure_rounds`] over [`Split::whole`]); the same pairs, and the time of each. Run
/// with `cargo test --release -p kleene-graph --test rounds -- --ignored --nocapture
/// closure_on_one_machine`.
#[test]
#[ignore]
fn closure_on_one_machine_masked_products_against_the_rounds() {
    use std::time::Instant;
    let device = CpuDevice::default();
    let median = |mut v: Vec<f64>| {
        v.sort_by(f64::total_cmp);
        v[v.len() / 2]
    };
    // (name, graph, base pairs)
    type Case = (String, G, Vec<(u32, u32)>);
    let mut cases: Vec<Case> = Vec::new();
    let g = random(1 << 18, 1 << 20, 21);
    let base: Vec<(u32, u32)> = (0..256).map(|k| (g.src[k * 97], g.dst[k * 97])).collect();
    cases.push(("random 2^18 / 2^20, 256 base pairs".into(), g, base));
    let g = random(1 << 18, 1 << 20, 22);
    let base: Vec<(u32, u32)> = (0..4096).map(|k| (g.src[k * 13], g.dst[k * 13])).collect();
    cases.push(("random 2^18 / 2^20, 4096 base pairs".into(), g, base));
    // A tree (each node to its parent): the whole closure (base = the edges).
    let n = 1u32 << 16;
    let (src, dst): (Vec<u32>, Vec<u32>) = (1..n).map(|v| (v, v / 2)).unzip();
    let t = G {
        n: n as usize,
        w: vec![1; src.len()],
        src,
        dst,
    };
    let base: Vec<(u32, u32)> = t.src.iter().copied().zip(t.dst.iter().copied()).collect();
    cases.push(("tree 2^16, base = every edge".into(), t, base));
    // A grid road network 256 x 256 (right and down), base: the first row's edges.
    let side = 256u32;
    let (mut src, mut dst) = (Vec::new(), Vec::new());
    for r in 0..side {
        for c in 0..side {
            let v = r * side + c;
            if c + 1 < side {
                src.push(v);
                dst.push(v + 1);
            }
            if r + 1 < side {
                src.push(v);
                dst.push(v + side);
            }
        }
    }
    let base: Vec<(u32, u32)> = (0..side - 1).map(|c| (c, c + 1)).collect();
    let grid = G {
        n: (side * side) as usize,
        w: vec![1; src.len()],
        src,
        dst,
    };
    cases.push(("grid 256 x 256, base = the first row".into(), grid, base));
    for (name, g, base) in cases {
        let e = Csr::from_edges(g.n, g.n, &g.src, &g.dst, None, BoolOrAnd).unwrap();
        let (b0, b1): (Vec<u32>, Vec<u32>) = base.iter().copied().unzip();
        let bm = Csr::from_edges(g.n, g.n, &b0, &b1, None, BoolOrAnd).unwrap();
        let whole = Split::whole(e.clone()).unwrap();
        let based: Vec<(u64, u64)> = base.iter().map(|&(a, b)| (a as u64, b as u64)).collect();
        let (mut tm, mut tr) = (Vec::new(), Vec::new());
        let (mut pm, mut pr) = (0usize, 0usize);
        for _ in 0..5 {
            let t = Instant::now();
            let c =
                kleene_graph::closure::<B>(&bm, &e, kleene_graph::Side::Right, &device).unwrap();
            tm.push(t.elapsed().as_secs_f64() * 1e3);
            pm = c.pairs.nnz();
            let t = Instant::now();
            let r = closure_rounds::<B>(&whole, &based, &device).unwrap();
            tr.push(t.elapsed().as_secs_f64() * 1e3);
            pr = r.pairs.len();
        }
        assert_eq!(pm, pr, "{name}: the same pairs");
        println!(
            "{name}: {pm} pairs; masked products {:.2} ms, rounds (one part) {:.2} ms (medians of 5)",
            median(tm),
            median(tr)
        );
    }
}