Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-plan/tests/no_spawn.rs

//! The column kernels run on the device's parked workers: once they are up, a call starts
//! no thread, whatever the number of cores. A thread is seen the first time it allocates
//! (a flag of its own, set by the allocator); a warm call must show no new one. Alone in its
//! own test binary, since the allocator is the whole program's.

#![allow(unsafe_code)]

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

use kleene_plan::{Atom, Engine, Facts, Inputs, Literal, Plan, Term};
use kleene_sparse::{CpuBackend, CpuDevice};

struct Seeing;

/// Threads that have allocated at least once.
static THREADS: AtomicUsize = AtomicUsize::new(0);

thread_local! {
    static SEEN: Cell<bool> = const { Cell::new(false) };
}

fn see() {
    // `try_with`: a thread being torn down has no flag left; it is not a new thread.
    let _ = SEEN.try_with(|s| {
        if !s.replace(true) {
            THREADS.fetch_add(1, Ordering::Relaxed);
        }
    });
}

// SAFETY: forwards to the system allocator; only marks the calling thread.
unsafe impl GlobalAlloc for Seeing {
    unsafe fn alloc(&self, l: Layout) -> *mut u8 {
        see();
        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 {
        see();
        unsafe { System.realloc(p, l, n) }
    }
}

#[global_allocator]
static A: Seeing = Seeing;

#[test]
fn a_warm_call_starts_no_thread() {
    let rt = tokio::runtime::Builder::new_current_thread()
        .build()
        .unwrap();
    // out(X, Z, Y) :- e(X, Y), e(Y, Z), !bad(Z).   from(X) :- out(X, Z, Y).
    // Large enough for many probe pieces and a parallel sort of the head.
    let mut p = Plan::new();
    let e = p.input("e", 2);
    let bad = p.input("bad", 1);
    let out = p.derived("out", 3);
    let from = p.derived("from", 1);
    let (x, y, z) = (p.var("X"), p.var("Y"), p.var("Z"));
    let at = |rel, vs: &[kleene_plan::Var]| Atom {
        rel,
        terms: vs.iter().map(|&v| Term::Var(v)).collect(),
    };
    p.rule(
        at(out, &[x, z, y]),
        [
            Literal::Pos(at(e, &[x, y])),
            Literal::Pos(at(e, &[y, z])),
            Literal::Neg(at(bad, &[z])),
        ],
    )
    .unwrap();
    p.rule(at(from, &[x]), [at(out, &[x, z, y])]).unwrap();
    let n = 200_000u32;
    let (mut src, mut dst) = (Vec::new(), Vec::new());
    for v in 0..n {
        for w in [(v + 1) % n, (v * 7 + 3) % n] {
            src.push(v);
            dst.push(w);
        }
    }
    let bads: Vec<u32> = (0..n).filter(|v| v % 5 == 0).collect();
    let mut inputs = Inputs::new();
    inputs
        .facts(e, Facts::from_columns(vec![src, dst]).unwrap())
        .facts(bad, Facts::from_columns(vec![bads]).unwrap());

    // Four threads on any host; each worker allocates once here, so all are seen.
    let device = CpuDevice::new(4);
    device.executor().run(4, &|t| {
        std::hint::black_box(vec![t as u8; 1]);
    });
    let engine: Engine<CpuBackend> = Engine::new(device);
    let first = rt.block_on(engine.run(&p, &inputs)).unwrap();
    let rows = first.get(out).unwrap().len();
    assert!(
        rows > 4 * (1 << 14),
        "{rows} rows: too few for several pieces"
    );
    for call in 0..3 {
        let before = THREADS.load(Ordering::Relaxed);
        let o = rt.block_on(engine.run(&p, &inputs)).unwrap();
        let new = THREADS.load(Ordering::Relaxed) - before;
        assert_eq!(o.get(out).unwrap().len(), rows);
        assert_eq!(new, 0, "warm call {call} started {new} threads");
    }
}