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

//! A search run again on its kept state allocates nothing: every level's frontier, the
//! visited mask, the levels and the step log reuse the buffers of the first search, and
//! parallel steps run on the device's parked workers. Weak components (Afforest) run again
//! on their kept buffers allocate nothing either, and count on the workers; many searches side
//! by side on kept searchers ([`BfsMany`]) allocate nothing, whichever searcher takes which
//! source. One test: the counting allocator sees every thread of this binary.

// A counting allocator needs `unsafe impl GlobalAlloc`: allowed in this test only.
#![allow(unsafe_code)]

use std::alloc::{GlobalAlloc, Layout, System};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

use kleene_graph::{
    AfforestState, BfsMany, BfsOptions, BfsState, Direction, Graph, afforest, afforest_with, bfs,
    bfs_with,
};
use kleene_sparse::{BoolOrAnd, CpuBackend, CpuDevice, Csr, Executor, Mask};

struct Counting;

static ALLOCS: AtomicUsize = AtomicUsize::new(0);

// SAFETY: every call is passed straight to the system allocator.
unsafe impl GlobalAlloc for Counting {
    unsafe fn alloc(&self, l: Layout) -> *mut u8 {
        ALLOCS.fetch_add(1, Ordering::Relaxed);
        unsafe { System.alloc(l) }
    }
    unsafe fn dealloc(&self, p: *mut u8, l: Layout) {
        unsafe { System.dealloc(p, l) }
    }
    unsafe fn realloc(&self, p: *mut u8, l: Layout, n: usize) -> *mut u8 {
        ALLOCS.fetch_add(1, Ordering::Relaxed);
        unsafe { System.realloc(p, l, n) }
    }
}

#[global_allocator]
static GLOBAL: Counting = Counting;

/// Runs a job's shares in turn on the caller, the last first if `last_first`: the share
/// that runs first takes every source of many searches.
struct InTurn {
    last_first: bool,
}

// SAFETY: `run` calls each `t` in `0..n` exactly once and returns after the last one.
unsafe impl Executor for InTurn {
    fn threads(&self) -> usize {
        4
    }

    fn run(&self, n: usize, job: &(dyn Fn(usize) + Sync)) {
        let n = n.min(4);
        for t in 0..n {
            job(if self.last_first { n - 1 - t } else { t });
        }
    }
}

type B = CpuBackend;

fn rmat_like(scale: u32, factor: usize, seed: u64) -> (usize, Vec<u32>, Vec<u32>) {
    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 {
        // Skewed ends: hubs and a long tail.
        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);
    }
    (n, src, dst)
}

#[test]
fn a_search_on_kept_state_allocates_nothing() {
    let (n, src, dst) = rmat_like(15, 8, 3);
    let a = Csr::from_edges(n, n, &src, &dst, None, BoolOrAnd).unwrap();
    let sources = [1u32, 77, 300];
    let allowed = Mask::from_indices(
        n,
        &(0..n as u32).filter(|v| v % 13 != 5).collect::<Vec<_>>(),
    );
    for device in [
        CpuDevice::new(1),
        CpuDevice::new(4).with_grain(64),
        CpuDevice::default().with_grain(512),
    ] {
        let g: Graph<B> = Graph::new(a.clone(), &device).unwrap();
        for direction in [Direction::Auto, Direction::Push, Direction::Pull] {
            for mask in [None, Some(allowed.clone())] {
                let opts = BfsOptions {
                    direction,
                    allowed: mask,
                    ..BfsOptions::default()
                };
                let want = bfs(&g, &sources, &opts, &device).unwrap();
                let mut st = BfsState::<B>::new(n, &device);
                bfs_with(&g, &sources, &opts, &device, &mut st).unwrap();
                let before = ALLOCS.load(Ordering::SeqCst);
                let got = bfs_with(&g, &sources, &opts, &device, &mut st).unwrap();
                let allocs = ALLOCS.load(Ordering::SeqCst) - before;
                assert_eq!(
                    allocs,
                    0,
                    "{direction:?}, mask {}, {} threads",
                    opts.allowed.is_some(),
                    device.threads()
                );
                assert_eq!((got.reached, got.depth), (want.reached, want.depth));
                assert_eq!(
                    st.levels().iter().collect::<Vec<_>>(),
                    want.levels.iter().collect::<Vec<_>>()
                );
                assert_eq!(st.steps(), &want.steps[..]);
                assert!(want.reached > n / 4, "reached {}", want.reached);
            }
        }
        // Weak components on kept buffers: the labels and the count equal a fresh run's.
        let (out, inn) = (g.out(), g.inn().expect("the transpose"));
        let want = afforest(out, inn, &device).unwrap();
        let want_count = want.count();
        let mut st = AfforestState::new();
        afforest_with(out, inn, &device, &mut st).unwrap();
        let before = ALLOCS.load(Ordering::SeqCst);
        let rounds = afforest_with(out, inn, &device, &mut st).unwrap();
        let count = st.count(&device);
        let allocs = ALLOCS.load(Ordering::SeqCst) - before;
        assert_eq!(allocs, 0, "components, {} threads", device.threads());
        assert_eq!(rounds, want.rounds);
        assert_eq!(count, want_count, "{} threads", device.threads());
        assert!((0..n).all(|v| st.label(v) == want.of[v]));
        assert!(want_count > 1);
        // Many searches side by side on kept searchers: the answers of searches alone.
        let opts = BfsOptions {
            max_depth: Some(3),
            ..BfsOptions::default()
        };
        let mut st = BfsState::<B>::new(n, &device);
        let want: Vec<u64> = sources
            .iter()
            .map(|&s| bfs_with(&g, &[s], &opts, &device, &mut st).unwrap().reached as u64)
            .collect();
        let mut many = BfsMany::new();
        let mut got = vec![0u64; sources.len()];
        many.run(&g, &sources, &opts, &device, &mut got).unwrap();
        let before = ALLOCS.load(Ordering::SeqCst);
        many.run(&g, &sources, &opts, &device, &mut got).unwrap();
        let allocs = ALLOCS.load(Ordering::SeqCst) - before;
        assert_eq!(allocs, 0, "many searches, {} threads", device.threads());
        assert_eq!(got, want);
    }
    // The first searcher takes every source in the first call and the last one in the
    // next: a searcher that has searched nothing yet allocates nothing either.
    let first = CpuDevice::with_executor(Arc::new(InTurn { last_first: false }));
    let last = CpuDevice::with_executor(Arc::new(InTurn { last_first: true }));
    let g: Graph<B> = Graph::new(a, &first).unwrap();
    let opts = BfsOptions {
        max_depth: Some(3),
        ..BfsOptions::default()
    };
    let mut want = vec![0u64; sources.len()];
    let mut many = BfsMany::new();
    many.run(&g, &sources, &opts, &first, &mut want).unwrap();
    let mut got = vec![0u64; sources.len()];
    let before = ALLOCS.load(Ordering::SeqCst);
    many.run(&g, &sources, &opts, &last, &mut got).unwrap();
    let allocs = ALLOCS.load(Ordering::SeqCst) - before;
    assert_eq!(allocs, 0, "many searches, the last searcher first");
    assert_eq!(got, want);
}