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

nordisk/kleene

crates/kleene-datalog/tests/external.rs

//! E5: external relations (index lookups and Rust fact producers) read as relations in
//! rules, each run against the same question asked with plain facts or a plain loop.

use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

use kleene_datalog::{
    Aggregate, DatalogError, Engine, External, Facts, How, Inputs, Producer, Program, Proof,
    RelKind, Result, Stratum, Value, plan, within,
};
use kleene_sparse::{CpuBackend, CpuDevice};

type E = Engine<CpuBackend>;

fn engine() -> E {
    Engine::new(CpuDevice::new(2)).explain(true)
}

fn rows(f: &Facts) -> BTreeSet<Vec<u64>> {
    f.rows().collect()
}

const BASE: u64 = 0x5555_0000_0000;

/// Ranges `(id, lo, hi)`, sorted and disjoint, with gaps.
fn ranges() -> Vec<(u32, u64, u64)> {
    let mut out = Vec::new();
    let mut at = BASE;
    for id in 0..50u32 {
        at += (id as u64 * 7) % 13;
        let len = 3 + (id as u64 * 31) % 40;
        out.push((id, at, at + len));
        at += len;
    }
    out
}

fn addrs(rs: &[(u32, u64, u64)]) -> Vec<u64> {
    let end = rs.last().unwrap().2;
    (BASE - 5..end + 5).step_by(3).collect()
}

/// `(addr, id)`: the range holding `addr`, by binary search; answers when `addr` is bound.
/// Counts its batch calls.
#[derive(Debug)]
struct RangeIndex {
    rs: Vec<(u32, u64, u64)>,
    calls: AtomicUsize,
}

impl RangeIndex {
    fn find(&self, a: u64) -> Option<u32> {
        let i = self.rs.partition_point(|r| r.1 <= a).checked_sub(1)?;
        let (id, _, hi) = self.rs[i];
        (a < hi).then_some(id)
    }
}

impl External for RangeIndex {
    fn arity(&self) -> usize {
        2
    }
    fn can(&self, bound: u64) -> bool {
        bound & 1 != 0
    }
    fn lookup(
        &self,
        bound: u64,
        keys: &[&[Value]],
        n: usize,
        out: &mut dyn FnMut(usize, &[Value]),
    ) -> Result<()> {
        self.calls.fetch_add(1, Ordering::Relaxed);
        assert_eq!(keys[0].len(), n);
        for (k, &a) in keys[0].iter().enumerate() {
            if let Some(id) = self.find(a)
                && (bound & 2 == 0 || keys[1][k] == id as u64)
            {
                out(k, &[a, id as u64]);
            }
        }
        Ok(())
    }
}

/// `(id, h)`: a hash of an id; answers when `id` is bound.
#[derive(Debug)]
struct Hash;

fn hash(x: u64) -> u64 {
    x.wrapping_mul(0x9e37_79b9_7f4a_7c15) >> 40
}

impl External for Hash {
    fn arity(&self) -> usize {
        2
    }
    fn can(&self, bound: u64) -> bool {
        bound & 1 != 0
    }
    fn lookup(
        &self,
        bound: u64,
        keys: &[&[Value]],
        n: usize,
        out: &mut dyn FnMut(usize, &[Value]),
    ) -> Result<()> {
        for (k, &x) in keys[0].iter().enumerate().take(n) {
            let h = hash(x);
            if bound & 2 == 0 || keys[1][k] == h {
                out(k, &[x, h]);
            }
        }
        Ok(())
    }
}

fn index() -> Arc<RangeIndex> {
    Arc::new(RangeIndex {
        rs: ranges(),
        calls: AtomicUsize::new(0),
    })
}

#[tokio::test]
async fn a_lookup_bound_by_facts_equals_the_range_join_and_a_loop() {
    let rs = ranges();
    let xs = addrs(&rs);
    let mut p = Program::new();
    let addr = p.input::<1>("addr");
    let func = p.input::<3>("func");
    let fn_of = p.external::<2>("fn_of");
    let by_index = p.derived::<2>("by_index");
    let by_join = p.derived::<2>("by_join");
    let (a, f, lo, hi) = (p.var("A"), p.var("F"), p.var("Lo"), p.var("Hi"));
    p.rule(by_index.at([a, f]), [addr.at([a]), fn_of.at([a, f])])
        .unwrap();
    p.rule(
        by_join.at([a, f]),
        [
            addr.at([a]).into(),
            func.at([f, lo, hi]).into(),
            within(a, lo, hi),
        ],
    )
    .unwrap();
    let ix = index();
    let mut inputs = Inputs::new();
    inputs
        .facts(&addr, Facts::from_rows(1, xs.iter().map(|&x| [x])).unwrap())
        .unwrap();
    inputs
        .facts(
            &func,
            Facts::from_rows(3, rs.iter().map(|&(i, l, h)| [i as u64, l, h])).unwrap(),
        )
        .unwrap();
    inputs.external(&fn_of, ix.clone()).unwrap();
    let out = engine().run(&p, &inputs).await.unwrap();
    let want: BTreeSet<Vec<u64>> = xs
        .iter()
        .filter_map(|&x| {
            rs.iter()
                .find(|r| r.1 <= x && x < r.2)
                .map(|r| vec![x, r.0 as u64])
        })
        .collect();
    assert!(want.len() > 200);
    assert_eq!(rows(out.get(&by_index).unwrap()), want);
    assert_eq!(rows(out.get(&by_join).unwrap()), want);
    // asked once, for the whole batch of addresses
    assert_eq!(ix.calls.load(Ordering::Relaxed), 1);
    // its proofs end in the index
    let w = want.iter().next().unwrap();
    let q = out.why(&p, &by_index, [w[0], w[1]]).unwrap();
    let How::Rule { premises, .. } = &q.how else {
        panic!("a rule proof")
    };
    assert_eq!(premises[1].how, How::External);
    assert!(q.render(&p).contains("[external]"), "{}", q.render(&p));
}

#[tokio::test]
async fn chained_lookups_constants_and_repeated_variables() {
    let rs = ranges();
    let xs = addrs(&rs);
    let mut p = Program::new();
    let addr = p.input::<1>("addr");
    let fn_of = p.external::<2>("fn_of");
    let h = p.external::<2>("hash");
    let tagged = p.derived::<3>("tagged");
    let in7 = p.derived::<1>("in7");
    let fixed = p.derived::<1>("fixed");
    let (a, f, x) = (p.var("A"), p.var("F"), p.var("X"));
    // the second external is bound only by the first one's answer
    p.rule(
        tagged.at([a, f, x]),
        [addr.at([a]), fn_of.at([a, f]), h.at([f, x])],
    )
    .unwrap();
    // a constant in the answered column
    p.rule(
        in7.at([a]),
        [addr.at([a]), fn_of.atom([a.into(), 7u32.into()])],
    )
    .unwrap();
    // a body of externals alone: constants bind the lookup
    p.rule(
        fixed.at([f]),
        [fn_of.atom([(rs[3].1 + 1).into(), f.into()])],
    )
    .unwrap();
    let mut inputs = Inputs::new();
    inputs
        .facts(&addr, Facts::from_rows(1, xs.iter().map(|&x| [x])).unwrap())
        .unwrap();
    inputs.external(&fn_of, index()).unwrap();
    inputs.external(&h, Arc::new(Hash)).unwrap();
    let out = engine().run(&p, &inputs).await.unwrap();
    let ix = index();
    let want: BTreeSet<Vec<u64>> = xs
        .iter()
        .filter_map(|&x| ix.find(x).map(|f| vec![x, f as u64, hash(f as u64)]))
        .collect();
    assert_eq!(rows(out.get(&tagged).unwrap()), want);
    let want7: BTreeSet<Vec<u64>> = xs
        .iter()
        .filter(|&&x| ix.find(x) == Some(7))
        .map(|&x| vec![x])
        .collect();
    assert!(!want7.is_empty());
    assert_eq!(rows(out.get(&in7).unwrap()), want7);
    assert_eq!(rows(out.get(&fixed).unwrap()), BTreeSet::from([vec![3]]));
}

/// The edges of a small graph listed by a producer.
fn edge_producer(es: Vec<(u64, u64)>) -> Arc<dyn External> {
    Arc::new(Producer::new(2, move |out: &mut dyn FnMut(&[Value])| {
        for &(a, b) in &es {
            out(&[a, b]);
        }
        Ok(())
    }))
}

fn graph() -> Vec<(u64, u64)> {
    vec![
        (0, 1),
        (1, 2),
        (2, 0),
        (2, 3),
        (3, 4),
        (5, 6),
        (7, 3),
        (4, 8),
    ]
}

#[tokio::test]
async fn producers_are_listed_once_and_joined_anywhere() {
    let es = graph();
    let mut p = Program::new();
    let entry = p.input::<1>("entry");
    let edge = p.external::<2>("edge");
    let reach = p.derived::<1>("reach");
    let succ = p.derived::<2>("succ");
    let all = p.derived::<2>("all");
    let (f, g) = (p.var("F"), p.var("G"));
    p.rule(reach.at([f]), [entry.at([f])]).unwrap();
    p.rule(reach.at([g]), [reach.at([f]), edge.at([f, g])])
        .unwrap();
    // bound by facts, but the producer answers only the empty pattern: a hash join
    p.rule(succ.at([f, g]), [entry.at([f]), edge.at([f, g])])
        .unwrap();
    // a producer alone
    p.rule(all.at([f, g]), [edge.at([f, g])]).unwrap();
    // an external edge is joined, never planned as a BFS
    assert!(matches!(
        plan(&p).unwrap()[..],
        [
            Stratum::Joins { .. },
            Stratum::Joins { .. },
            Stratum::Joins { .. }
        ]
    ));
    let mut inputs = Inputs::new();
    inputs
        .facts(&entry, Facts::from_rows(1, [[7u64], [5]]).unwrap())
        .unwrap();
    inputs.external(&edge, edge_producer(es.clone())).unwrap();
    let out = engine().run(&p, &inputs).await.unwrap();
    assert_eq!(
        rows(out.get(&reach).unwrap()),
        [7, 3, 4, 8, 5, 6].iter().map(|&v| vec![v]).collect()
    );
    assert_eq!(
        rows(out.get(&succ).unwrap()),
        BTreeSet::from([vec![7, 3], vec![5, 6]])
    );
    assert_eq!(
        rows(out.get(&all).unwrap()),
        es.iter().map(|&(a, b)| vec![a, b]).collect()
    );
}

/// `(addr)`: the address lies in some range; answers with `addr` bound.
#[derive(Debug)]
struct Covered(Arc<RangeIndex>);

impl External for Covered {
    fn arity(&self) -> usize {
        1
    }
    fn can(&self, bound: u64) -> bool {
        bound == 1
    }
    fn lookup(
        &self,
        _bound: u64,
        keys: &[&[Value]],
        n: usize,
        out: &mut dyn FnMut(usize, &[Value]),
    ) -> Result<()> {
        for (k, &x) in keys[0].iter().enumerate().take(n) {
            if self.0.find(x).is_some() {
                out(k, &[x]);
            }
        }
        Ok(())
    }
}

#[tokio::test]
async fn negated_lookups_and_aggregates_over_lookups() {
    let rs = ranges();
    let xs = addrs(&rs);
    let mut p = Program::new();
    let addr = p.input::<1>("addr");
    let covered = p.external::<1>("covered");
    let fn_of = p.external::<2>("fn_of");
    let gap = p.derived::<1>("gap");
    let size = p.derived::<2>("size");
    let first = p.derived::<2>("first");
    let (a, f, n) = (p.var("A"), p.var("F"), p.var("N"));
    p.rule(gap.at([a]), [addr.at([a]).into(), !covered.at([a])])
        .unwrap();
    p.aggregate(
        size.at([f, n]),
        Aggregate::count([f], [a], n),
        [addr.at([a]), fn_of.at([a, f])],
    )
    .unwrap();
    p.aggregate(
        first.at([f, a]),
        Aggregate::min_by([f], [a]),
        [addr.at([a]), fn_of.at([a, f])],
    )
    .unwrap();
    let ix = index();
    let mut inputs = Inputs::new();
    inputs
        .facts(&addr, Facts::from_rows(1, xs.iter().map(|&x| [x])).unwrap())
        .unwrap();
    inputs
        .external(&covered, Arc::new(Covered(ix.clone())))
        .unwrap();
    inputs.external(&fn_of, ix.clone()).unwrap();
    let out = engine().run(&p, &inputs).await.unwrap();
    let want_gap: BTreeSet<Vec<u64>> = xs
        .iter()
        .filter(|&&x| ix.find(x).is_none())
        .map(|&x| vec![x])
        .collect();
    assert!(!want_gap.is_empty());
    assert_eq!(rows(out.get(&gap).unwrap()), want_gap);
    let mut by: BTreeMap<u32, Vec<u64>> = BTreeMap::new();
    for &x in &xs {
        if let Some(f) = ix.find(x) {
            by.entry(f).or_default().push(x);
        }
    }
    let want_size: BTreeSet<Vec<u64>> = by
        .iter()
        .map(|(&f, v)| vec![f as u64, v.len() as u64])
        .collect();
    let want_first: BTreeSet<Vec<u64>> = by.iter().map(|(&f, v)| vec![f as u64, v[0]]).collect();
    assert_eq!(rows(out.get(&size).unwrap()), want_size);
    assert_eq!(rows(out.get(&first).unwrap()), want_first);
    // every proof checks: premises that are external are answered by the index again
    let ext_holds = |rel, t: &[u64]| -> bool {
        if rel == covered.id() {
            ix.find(t[0]).is_some()
        } else {
            ix.find(t[0]) == Some(t[1] as u32)
        }
    };
    fn walk(p: &Program, q: &Proof, ext: &dyn Fn(kleene_datalog::RelId, &[u64]) -> bool) {
        match &q.how {
            How::External => assert!(ext(q.rel, &q.tuple)),
            How::Input => assert_eq!(p.relation_info(q.rel).kind, RelKind::Input),
            How::Rule {
                premises, absent, ..
            } => {
                premises.iter().for_each(|s| walk(p, s, ext));
                for (rel, t) in absent {
                    assert!(!ext(*rel, t));
                }
            }
            How::Aggregate { members, .. } => {
                for m in members {
                    m.premises.iter().for_each(|s| walk(p, s, ext));
                }
            }
            other => panic!("a proof the walk does not know: {other:?}"),
        }
    }
    for rel in [gap.id(), size.id(), first.id()] {
        for t in rows(out.get_id(rel).unwrap()) {
            walk(&p, &out.why_id(&p, rel, &t).unwrap(), &ext_holds);
        }
    }
}

#[tokio::test]
async fn a_lookup_nothing_binds_is_refused_and_arity_is_checked() {
    let mut p = Program::new();
    let fn_of = p.external::<2>("fn_of");
    let r = p.derived::<2>("r");
    let (a, f) = (p.var("A"), p.var("F"));
    p.rule(r.at([a, f]), [fn_of.at([a, f])]).unwrap();
    let mut inputs = Inputs::new();
    inputs.external(&fn_of, index()).unwrap();
    let err = engine().run(&p, &inputs).await.unwrap_err();
    assert!(matches!(err, DatalogError::Program(_)), "{err}");
    let mut wrong = Inputs::new();
    let one = p.external::<1>("one");
    assert!(wrong.external(&one, index()).is_err());
    // a rule cannot derive an external
    assert!(matches!(
        p.rule(fn_of.at([a, f]), [r.at([a, f])]),
        Err(DatalogError::Program(_))
    ));
}