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

nordisk/kleene

crates/kleene-ballista/tests/cluster.rs

//! A Ballista cluster in one process (a scheduler with kleene's rules and codec, three
//! executors) gives the one-machine answers at 1, 2, 3 and 8 parts, split by id blocks and
//! by hash, a first run (graphs loaded) and a warm one (graphs kept) alike; a query wakes
//! only the parts the central index says its sources can reach (one task per woken part
//! and stage, none for the others); the weak components equal a plain union-find's and the k-hop neighbourhoods a
//! depth-limited queue walk's.

use std::collections::VecDeque;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;

use ballista::prelude::SessionConfigExt;
use ballista_core::config::TaskSchedulingPolicy;
use ballista_core::serde::BallistaCodec;
use ballista_core::serde::protobuf::scheduler_grpc_client::SchedulerGrpcClient;
use ballista_scheduler::config::SchedulerConfig;
use datafusion::execution::SessionStateBuilder;
use datafusion::prelude::SessionConfig;
use graphar::mapped::{IntEdges, IntGraphWriter};
use kleene_ballista::{Cluster, GraphSpec, Key, KleeneRules, WholeGraph};

const N: u32 = 300;

/// A graph of `N` nodes: rings of 50 with chords, a few links between rings (one way), and
/// nodes nothing reaches.
fn edges() -> Vec<(u32, u32)> {
    let mut e = Vec::new();
    for v in 0..250u32 {
        let ring = v / 50;
        e.push((v, ring * 50 + (v + 1) % 50));
        e.push((v, ring * 50 + (v * 7 + 3) % 50));
    }
    for (a, b) in [(10, 60), (70, 120), (130, 180), (199, 5)] {
        e.push((a, b));
    }
    e.sort_unstable();
    e.dedup();
    e
}

/// Per node its hops from `s` (`u32::MAX`: not reached).
fn depths(s: u32) -> Vec<u32> {
    let mut adj = vec![Vec::new(); N as usize];
    for (a, b) in edges() {
        adj[a as usize].push(b);
    }
    let mut depth = vec![u32::MAX; N as usize];
    depth[s as usize] = 0;
    let mut q = VecDeque::from([s]);
    while let Some(v) = q.pop_front() {
        for &w in &adj[v as usize] {
            if depth[w as usize] == u32::MAX {
                depth[w as usize] = depth[v as usize] + 1;
                q.push_back(w);
            }
        }
    }
    depth
}

/// The nodes a plain breadth-first search from `s` reaches, rising.
fn reference(s: u32) -> Vec<u64> {
    within(s, u32::MAX)
}

/// The nodes within `k` hops of `s` (itself included), rising.
fn within(s: u32, k: u32) -> Vec<u64> {
    let mut adj = vec![Vec::new(); N as usize];
    for (a, b) in edges() {
        adj[a as usize].push(b);
    }
    let mut depth = vec![u32::MAX; N as usize];
    depth[s as usize] = 0;
    let mut q = VecDeque::from([s]);
    while let Some(v) = q.pop_front() {
        if depth[v as usize] == k {
            continue;
        }
        for &w in &adj[v as usize] {
            if depth[w as usize] == u32::MAX {
                depth[w as usize] = depth[v as usize] + 1;
                q.push_back(w);
            }
        }
    }
    let seen: Vec<bool> = depth.iter().map(|&d| d != u32::MAX).collect();
    (0..N as u64).filter(|&v| seen[v as usize]).collect()
}

/// Each weak component's least node, rising.
fn components() -> Vec<u64> {
    let mut up: Vec<u32> = (0..N).collect();
    fn root(up: &mut [u32], mut v: u32) -> u32 {
        while up[v as usize] != v {
            up[v as usize] = up[up[v as usize] as usize];
            v = up[v as usize];
        }
        v
    }
    for (a, b) in edges() {
        let (ra, rb) = (root(&mut up, a), root(&mut up, b));
        // The smaller root wins, so a root is its component's least node.
        let (lo, hi) = (ra.min(rb), ra.max(rb));
        up[hi as usize] = lo;
    }
    (0..N)
        .filter(|&v| root(&mut up, v) == v)
        .map(u64::from)
        .collect()
}

struct Dir(PathBuf);

impl Drop for Dir {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

/// The graph in a directory of its own per test (`name`): the tests run at once.
fn write_graph(name: &str) -> Dir {
    let d = std::env::temp_dir().join(format!("kleene-ballista-{}-{name}", std::process::id()));
    let _ = std::fs::remove_dir_all(&d);
    std::fs::create_dir_all(&d).unwrap();
    let e = edges();
    let src: Vec<u32> = e.iter().map(|p| p.0).collect();
    let dst: Vec<u32> = e.iter().map(|p| p.1).collect();
    let mut w = IntGraphWriter::new(&d, "X").unwrap();
    w.vertices("v", N, vec![]).unwrap();
    w.edges(IntEdges::from_pairs(("v", "link", "v"), (N, N), &src, &dst, vec![]).unwrap())
        .unwrap();
    w.finish().unwrap();
    Dir(d)
}

async fn cluster(executors: usize) -> Cluster {
    let config = Cluster::session(1);
    let state = SessionStateBuilder::new()
        .with_config(config.clone())
        .with_default_features()
        .build();
    let logical = config.ballista_logical_extension_codec();
    let physical = config.ballista_physical_extension_codec();
    let session_state = state.clone();
    let session_config = config.clone();
    let addr = ballista_scheduler::standalone::new_standalone_scheduler_with_config(
        Arc::new(move |_: SessionConfig| Ok(session_state.clone())),
        Arc::new(move || session_config.clone()),
        BallistaCodec::new(logical, physical),
        // The standalone executors poll for work.
        SchedulerConfig::default()
            .with_scheduler_policy(TaskSchedulingPolicy::PullStaged)
            .with_adaptive_rules(Arc::new(KleeneRules)),
    )
    .await
    .expect("a scheduler");
    let url = format!("http://localhost:{}", addr.port());
    for _ in 0..executors {
        let mut client = None;
        for _ in 0..50 {
            if let Ok(c) = SchedulerGrpcClient::connect(url.clone()).await {
                client = Some(c);
                break;
            }
            tokio::time::sleep(Duration::from_millis(100)).await;
        }
        ballista_executor::new_standalone_executor_from_state(
            client.expect("the scheduler"),
            2,
            &state,
        )
        .await
        .expect("an executor");
    }
    Cluster::new(url)
}

fn blocks(k: u64) -> Key {
    let n = N as u64;
    Key::Blocks((0..k).map(|i| i * n.div_ceil(k)).collect())
}

/// Checks the answers from `sources` and returns the parts the query woke.
async fn check(c: &Cluster, dir: &Path, key: Key, sources: &[u32]) -> Vec<u32> {
    let parts = key.parts();
    let spec = GraphSpec::new(dir.to_str().unwrap(), "v_link_v", key.clone()).unwrap();
    let g = c.prepare(spec, vec![0; parts], None).await.unwrap();
    let mut want: Vec<u64> = sources.iter().flat_map(|&s| reference(s)).collect();
    want.sort_unstable();
    want.dedup();
    let mut woken = Vec::new();
    for run in ["first", "warm"] {
        let r = tokio::time::timeout(Duration::from_secs(120), c.reach(&g, sources))
            .await
            .expect("the query ends in 120 s")
            .unwrap();
        assert_eq!(r.ids, want, "{key:?} {run} run from {sources:?}");
        if parts == 1 {
            assert_eq!(r.sent, 0, "one part sends nothing");
        }
        // Every part holding a reached node was woken.
        for &v in &want {
            let sid = g.ids.from_original(v as u32).unwrap();
            let (p, _) = g.ids.locate(sid).unwrap();
            assert!(
                r.woken.contains(&p),
                "{key:?}: part {p} of node {v} not woken"
            );
        }
        woken = r.woken;
    }
    woken
}

/// Checks the k-hop neighbourhoods from `s` for the hop counts PuppyGraph's queries ask.
async fn check_khop(c: &Cluster, dir: &Path, key: Key, s: u32) {
    let spec = GraphSpec::new(dir.to_str().unwrap(), "v_link_v", key.clone()).unwrap();
    let g = c.prepare(spec, vec![0; key.parts()], None).await.unwrap();
    for k in [1, 2, 3, 6, 10] {
        let r = tokio::time::timeout(Duration::from_secs(120), c.khop(&g, s, k))
            .await
            .expect("the query ends in 120 s")
            .unwrap();
        assert_eq!(r.ids, within(s, k), "{key:?} {k} hops from {s}");
    }
}

/// Checks the weak components (each component's name, its least node).
async fn check_wcc(c: &Cluster, dir: &Path, key: Key) {
    let spec = GraphSpec::new(dir.to_str().unwrap(), "v_link_v", key.clone()).unwrap();
    let g = c.prepare(spec, vec![0; key.parts()], None).await.unwrap();
    for run in ["first", "warm"] {
        let r = tokio::time::timeout(Duration::from_secs(120), c.wcc(&g))
            .await
            .expect("the query ends in 120 s")
            .unwrap();
        assert_eq!(r.ids, components(), "{key:?} {run} components");
        assert_eq!(r.woken.len(), key.parts(), "the components wake every part");
    }
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn the_cluster_gives_the_one_machine_answers() {
    let _ = tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .try_init();
    let d = write_graph("split");
    let c = cluster(3).await;
    for k in [1, 2, 3, 8] {
        check(&c, &d.0, blocks(k), &[0]).await;
        check(&c, &d.0, Key::Hash(k as u32), &[0]).await;
        check_wcc(&c, &d.0, blocks(k)).await;
        check_wcc(&c, &d.0, Key::Hash(k as u32)).await;
        check_khop(&c, &d.0, blocks(k), 3).await;
        check_khop(&c, &d.0, Key::Hash(k as u32), 3).await;
    }
    // In part order: blocks of 100 make parts 0 and 1 a circle and part 2 alone; blocks of
    // 38 and hash parts other orders.
    for key in [blocks(3), blocks(8), Key::Hash(3), blocks(1)] {
        let spec = GraphSpec::new(d.0.to_str().unwrap(), "v_link_v", key.clone()).unwrap();
        let g = c.prepare(spec, vec![0; key.parts()], None).await.unwrap();
        c.load_parts(&g).await.unwrap();
        for s in [0u32, 120, 290] {
            for run in ["first", "warm"] {
                let r = tokio::time::timeout(Duration::from_secs(120), c.sweep(&g, &[s]))
                    .await
                    .expect("the sweep ends in 120 s")
                    .unwrap();
                assert_eq!(r.ids, reference(s), "{key:?} sweep from {s}, {run}");
            }
        }
    }
    // Two sources, one that reaches nothing past itself.
    check(&c, &d.0, Key::Hash(3), &[120, 290]).await;
    // Blocks of 100: rings 0-199 link parts 0 and 1 both ways, ring 200-249 and the lone
    // nodes past it are part 2, which nothing outside reaches and which reaches nothing
    // outside: the central index wakes only what the sources can reach.
    assert_eq!(check(&c, &d.0, blocks(3), &[290]).await, vec![2]);
    assert_eq!(check(&c, &d.0, blocks(3), &[200]).await, vec![2]);
    assert_eq!(check(&c, &d.0, blocks(3), &[0]).await, vec![0, 1]);
    // Blocks of 38: part 7 (266-299) holds lone nodes only.
    assert_eq!(check(&c, &d.0, blocks(8), &[270]).await, vec![7]);
}

/// Every machine holds the whole graph (Distributed v1.1): one search cut in slices (every
/// level cut, and small levels whole), many searches handed out whole, weak components whole
/// on one machine, and loading ahead give the one-machine answers on 1 to 4 machines.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn the_whole_graph_on_every_machine_gives_the_one_machine_answers() {
    let d = write_graph("whole");
    let c = cluster(3).await;
    let path = d.0.to_str().unwrap();
    for weights in [vec![1], vec![2, 1], vec![1, 1, 1], vec![3, 1, 2, 1]] {
        let m = weights.len();
        let mut g = WholeGraph::new(path, "v_link_v", weights.clone(), None);
        let load = c.load(&g).await.unwrap();
        assert_eq!(load.counts, vec![u64::from(N); m], "{weights:?} load");
        for local_below in [0, kleene_graph::LOCAL_BELOW] {
            g.local_below = local_below;
            for s in [0, 120, 290] {
                for k in [Some(1), Some(2), Some(3), Some(6), Some(10), None] {
                    let r = tokio::time::timeout(Duration::from_secs(120), c.sliced(&g, &[s], k))
                        .await
                        .expect("the query ends in 120 s")
                        .unwrap();
                    let want = within(s, k.unwrap_or(u32::MAX)).len() as u64;
                    assert_eq!(
                        r.counts,
                        vec![want],
                        "{weights:?} {local_below} from {s} {k:?}"
                    );
                }
            }
        }
        let sources = [0, 120, 290, 3, 60, 199, 250];
        for k in [Some(2), None] {
            let r = c.many(&g, &sources, k).await.unwrap();
            let want: Vec<u64> = sources
                .iter()
                .map(|&s| within(s, k.unwrap_or(u32::MAX)).len() as u64)
                .collect();
            assert_eq!(r.counts, want, "{weights:?} many {k:?}");
        }
        let r = c.components(&g).await.unwrap();
        assert_eq!(
            r.counts,
            vec![components().len() as u64],
            "{weights:?} components"
        );
    }
}

/// Sliced searches on the same graph at the same time keep apart: each answer equals one
/// machine's (every level cut, so every search runs several rounds side by side).
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn sliced_searches_at_the_same_time_give_the_one_machine_answers() {
    let d = write_graph("together");
    let c = cluster(3).await;
    let path = d.0.to_str().unwrap();
    let mut g = WholeGraph::new(path, "v_link_v", vec![1, 1, 1], None);
    g.local_below = 0;
    c.load(&g).await.unwrap();
    let asks: Vec<(u32, Option<u32>)> = vec![
        (0, None),
        (120, Some(2)),
        (290, None),
        (60, Some(6)),
        (199, None),
        (3, Some(3)),
    ];
    for round in 0..4 {
        let runs = asks.iter().map(|&(s, k)| {
            let (c, g) = (&c, &g);
            async move {
                let r = tokio::time::timeout(Duration::from_secs(120), c.sliced(g, &[s], k))
                    .await
                    .expect("the query ends in 120 s");
                (s, k, r)
            }
        });
        for (s, k, r) in futures::future::join_all(runs).await {
            let want = within(s, k.unwrap_or(u32::MAX)).len() as u64;
            let r = r.unwrap_or_else(|e| panic!("round {round} from {s} {k:?}: {e}"));
            assert_eq!(r.counts, vec![want], "round {round} from {s} {k:?}");
        }
    }
}

/// A computed split, made once and saved beside the set (`kleene_index::save_computed_split`,
/// as `kleene split-report --save` does), is read by the client and by every executor: the
/// answers equal one machine's. With none saved, the spec is refused with a clear error.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_saved_computed_split_gives_the_one_machine_answers() {
    let d = write_graph("computed");
    let path = d.0.to_str().unwrap();
    let c = cluster(3).await;
    let spec = GraphSpec::new(path, "v_link_v", Key::Computed(3)).unwrap();
    let err = c
        .prepare(spec, vec![0; 3], None)
        .await
        .unwrap_err()
        .to_string();
    assert!(err.contains("no saved computed split"), "{err}");
    let out = kleene_ballista::state::read_graph(path, "v_link_v").unwrap();
    let inn = out.transpose();
    let dev = kleene_sparse::CpuDevice::new(2);
    let kix = PathBuf::from(format!("{path}.kix"));
    let store = kleene_index::Store::keyed(&kix, b"test set".to_vec()).unwrap();
    for k in [2u32, 3] {
        let how = kleene_graph::SplitCompute::new(k);
        let split =
            kleene_graph::computed_split::<kleene_sparse::CpuBackend>(&out, &inn, &how, &dev)
                .unwrap();
        kleene_index::save_computed_split(&store, "v_link_v", 0, &how, &split).unwrap();
        check(&c, &d.0, Key::Computed(k), &[0]).await;
        check(&c, &d.0, Key::Computed(k), &[120, 290]).await;
        check_wcc(&c, &d.0, Key::Computed(k)).await;
        check_khop(&c, &d.0, Key::Computed(k), 3).await;
    }
}

/// An executor reads a saved computed split once and keeps its key: a query's rounds (and
/// the next job) do not read the saved list again, so on one executor a list removed after
/// the first query leaves the next queries answering.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn an_executor_reads_the_saved_computed_split_once() {
    let d = write_graph("computed-once");
    let path = d.0.to_str().unwrap();
    let c = cluster(1).await;
    let out = kleene_ballista::state::read_graph(path, "v_link_v").unwrap();
    let inn = out.transpose();
    let dev = kleene_sparse::CpuDevice::new(2);
    let kix = PathBuf::from(format!("{path}.kix"));
    let store = kleene_index::Store::keyed(&kix, b"test set".to_vec()).unwrap();
    let how = kleene_graph::SplitCompute::new(3);
    let split =
        kleene_graph::computed_split::<kleene_sparse::CpuBackend>(&out, &inn, &how, &dev).unwrap();
    kleene_index::save_computed_split(&store, "v_link_v", 0, &how, &split).unwrap();
    let spec = GraphSpec::new(path, "v_link_v", Key::Computed(3)).unwrap();
    let g = c.prepare(spec, vec![0, 0, 0], None).await.unwrap();
    let first = c.khop(&g, 0, 6).await.unwrap();
    assert_eq!(first.ids, within(0, 6));
    std::fs::remove_dir_all(&kix).unwrap();
    for k in [3, 6] {
        let r = tokio::time::timeout(Duration::from_secs(120), c.khop(&g, 0, k))
            .await
            .expect("the query ends in 120 s")
            .unwrap();
        assert_eq!(r.ids, within(0, k), "{k} hops after the list is gone");
    }
    let r = c.wcc(&g).await.unwrap();
    assert_eq!(r.ids, components(), "components after the list is gone");
}

/// Shortest paths and the closure (the Datalog recursion) over the cluster give the
/// one-machine answers at 1, 2, 3 and 8 parts; the central index the client builds from the
/// executors' summaries is the one built from the whole split.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn shortest_paths_and_the_closure_over_machines_give_the_one_machine_answers() {
    let d = write_graph("paths");
    let c = cluster(3).await;
    let path = d.0.to_str().unwrap();
    let all: Vec<(u32, u32)> = edges();
    let (src, dst): (Vec<u32>, Vec<u32>) = all.iter().copied().unzip();
    for k in [1u32, 2, 3, 8] {
        for key in [blocks(u64::from(k)), Key::Hash(k)] {
            let spec = GraphSpec::new(path, "v_link_v", key.clone()).unwrap();
            let g = c
                .prepare(spec, (0..key.parts() as u32).map(|p| p % 3).collect(), None)
                .await
                .unwrap();
            // The summaries and ids are the whole split's.
            let whole = kleene_graph::Split::<u8>::new(
                N as usize,
                &src,
                &dst,
                None,
                &g.spec.split_key().unwrap(),
                kleene_sparse::BoolOrAnd,
            )
            .unwrap();
            assert_eq!(g.summaries, whole.summaries(), "{key:?} summaries");
            assert_eq!(&g.ids, whole.ids(), "{key:?} ids");
            for s in [0u32, 120, 290] {
                for run in ["first", "warm"] {
                    let r = tokio::time::timeout(Duration::from_secs(120), c.sssp(&g, s))
                        .await
                        .expect("the search ends in 120 s")
                        .unwrap();
                    let want: Vec<(u64, u64)> = depths(s)
                        .into_iter()
                        .enumerate()
                        .filter(|d| d.1 != u32::MAX)
                        .map(|(v, d)| (v as u64, u64::from(d)))
                        .collect();
                    assert_eq!(r.values, want, "{key:?} sssp from {s}, {run}");
                }
            }
            // 70 starts (two jobs of 64 and 6), each with one or two pair ends.
            let mut base: Vec<(u32, u32)> = (0..70u32).map(|i| (i * 4, (i * 4 + 9) % N)).collect();
            base.push((0, 290));
            base.push((8, 205));
            let r = tokio::time::timeout(Duration::from_secs(240), c.closure(&g, &base))
                .await
                .expect("the closure ends in 240 s")
                .unwrap();
            let mut want: Vec<(u32, u32)> = base
                .iter()
                .flat_map(|&(x, y)| reference(y).into_iter().map(move |z| (x, z as u32)))
                .collect();
            want.sort_unstable();
            want.dedup();
            assert_eq!(r.pairs, want, "{key:?} closure");
            assert_eq!(r.jobs, 2, "64 starts a job");
        }
    }
}