inference-engine 0.1.0-alpha.13

Native Rust RDF inference engine with a shared command-line interface
Documentation
use super::db::{self, GRAPHS, INDEX, Id, Key, Shared, Work};
use crate::reasoning::{Inference, ReasoningStore, TripleCursor, TripleSource};
use redb::{ReadTransaction, ReadableDatabase, ReadableTable};
use std::{io, ops::Bound, sync::Arc};
pub(super) struct Store {
    pub state: Shared,
    pub graph: u64,
    pub work: Arc<Work>,
}
pub(super) struct Snapshot {
    read: Arc<ReadTransaction>,
    graph: u64,
    work: Arc<Work>,
}
pub(super) struct Cursor {
    read: Arc<ReadTransaction>,
    index: usize,
    low: Key,
    high: Key,
    after: Option<Key>,
    work: Arc<Work>,
}
impl ReasoningStore for Store {
    type Term = Id;
    type Error = io::Error;
    type Snapshot = Snapshot;
    async fn resolve_iri(&mut self, iri: &str) -> io::Result<Id> {
        self.work.step()?;
        let iri = oxrdf::NamedNode::new(iri)
            .map_err(io::Error::other)?
            .to_string();
        db::access(&self.state, move |s| s.resolve(&iri, 1)).await
    }
    async fn snapshot(&mut self) -> io::Result<Snapshot> {
        self.work.step()?;
        let read = db::access(&self.state, |s| {
            s.flush()?;
            s.db.begin_read().map_err(io::Error::other)
        })
        .await?;
        Ok(Snapshot {
            read: Arc::new(read),
            graph: self.graph,
            work: self.work.clone(),
        })
    }
    async fn contains(&mut self, t: &[Id; 3]) -> io::Result<bool> {
        self.work.step()?;
        let (g, t) = (self.graph, *t);
        db::access(&self.state, move |s| s.contains(g, t)).await
    }
    async fn insert_inferred(&mut self, proof: Inference<Id>) -> io::Result<bool> {
        self.work.step()?;
        let g = self.graph;
        db::access(&self.state, move |s| {
            s.insert(g, proof.triple, Some(&proof))
        })
        .await
    }
    fn is_cancelled(&self) -> bool {
        false
    }
}
impl TripleSource for Snapshot {
    type Term = Id;
    type Error = io::Error;
    type Cursor = Cursor;
    async fn scan(&self, pattern: [Option<Id>; 3]) -> io::Result<Cursor> {
        self.work.step()?;
        // Three cyclic indexes cover every fixed-field combination with one prefix range.
        let permutations = [[0, 1, 2], [1, 2, 0], [2, 0, 1]];
        let index = (0..3)
            .max_by_key(|&i| {
                permutations[i]
                    .iter()
                    .take_while(|&&j| pattern[j].is_some())
                    .count()
            })
            .expect("three indexes");
        let mut low = [0_u64; 3];
        let mut high = [u64::MAX; 3];
        for (i, &j) in permutations[index].iter().enumerate() {
            if let Some(id) = pattern[j] {
                low[i] = id.0;
                high[i] = id.0;
            } else {
                break;
            }
        }
        Ok(Cursor {
            read: self.read.clone(),
            index,
            low: (self.graph, low[0], low[1], low[2]),
            high: (self.graph, high[0], high[1], high[2]),
            after: None,
            work: self.work.clone(),
        })
    }
}
impl TripleCursor for Cursor {
    type Term = Id;
    type Error = io::Error;
    async fn next(&mut self) -> io::Result<Option<[Id; 3]>> {
        self.work.step()?;
        let read = self.read.clone();
        let (index, low, high, after) = (self.index, self.low, self.high, self.after);
        let row = tokio::task::spawn_blocking(move || -> io::Result<Option<Key>> {
            let table = read.open_table(INDEX[index]).map_err(io::Error::other)?;
            let start = after.map_or(Bound::Included(low), Bound::Excluded);
            let mut range = table
                .range((start, Bound::Included(high)))
                .map_err(io::Error::other)?;
            range
                .next()
                .transpose()
                .map_err(io::Error::other)
                .map(|r| r.map(|(k, _)| k.value()))
        })
        .await
        .map_err(io::Error::other)??;
        if let Some(row) = row {
            self.after = Some(row);
            Ok(Some(db::tuple(row, index)))
        } else {
            Ok(None)
        }
    }
}
pub(super) async fn next_graph(state: &Shared, after: Option<u64>) -> io::Result<Option<u64>> {
    db::access(state, move |s| {
        s.flush()?;
        let r = s.db.begin_read().map_err(io::Error::other)?;
        let table = r.open_table(GRAPHS).map_err(io::Error::other)?;
        let start = after.map_or(Bound::Unbounded, Bound::Excluded);
        let mut range = table
            .range((start, Bound::Unbounded))
            .map_err(io::Error::other)?;
        range
            .next()
            .transpose()
            .map_err(io::Error::other)
            .map(|r| r.map(|(k, _)| k.value()))
    })
    .await
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::{args::Args, db::State};
    use crate::reasoning::{ExecutionProfile, Reasoner, RunLimits};
    use clap::Parser;
    use std::{
        num::{NonZeroU32, NonZeroU64},
        sync::Mutex,
    };
    fn setup() -> (tempfile::TempDir, Store) {
        let args = Args::parse_from([
            "inference-engine",
            "--profile",
            "rdfs-subclass",
            "unused.ttl",
        ]);
        let directory = tempfile::tempdir().unwrap();
        let state = State::create(&directory.path().join("test.redb"), &args).unwrap();
        (
            directory,
            Store {
                state: Arc::new(Mutex::new(state)),
                graph: 0,
                work: Arc::new(Work::new(100000)),
            },
        )
    }
    #[tokio::test]
    async fn every_probe_shape_is_exact_and_graph_scoped() {
        let (_directory, mut store) = setup();
        let a = store.resolve_iri("urn:a").await.unwrap();
        let b = store.resolve_iri("urn:b").await.unwrap();
        let c = store.resolve_iri("urn:c").await.unwrap();
        let p = store.resolve_iri("urn:p").await.unwrap();
        let q = store.resolve_iri("urn:q").await.unwrap();
        let rows = [[a, p, b], [a, q, c], [c, p, b]];
        db::access(&store.state, move |s| {
            for row in rows {
                s.insert(0, row, None)?;
            }
            s.insert(a.0, [a, p, b], None)?;
            Ok(())
        })
        .await
        .unwrap();
        let snapshot = store.snapshot().await.unwrap();
        for mask in 0..8 {
            let pattern = std::array::from_fn(|i| (mask & (1 << i) != 0).then_some(rows[0][i]));
            let expected = rows
                .iter()
                .filter(|r| (0..3).all(|i| pattern[i].is_none_or(|v| r[i] == v)))
                .count();
            let mut cursor = snapshot.scan(pattern).await.unwrap();
            let mut count = 0;
            while let Some(row) = cursor.next().await.unwrap() {
                assert!((0..3).all(|i| pattern[i].is_none_or(|v| row[i] == v)));
                count += 1;
            }
            assert_eq!(count, expected, "probe mask {mask}");
        }
    }
    #[tokio::test]
    async fn snapshots_stay_frozen_across_multiple_inference_commits() {
        let (_directory, mut store) = setup();
        let dog = store.resolve_iri("urn:Dog").await.unwrap();
        let animal = store.resolve_iri("urn:Animal").await.unwrap();
        let sub = store
            .resolve_iri("http://www.w3.org/2000/01/rdf-schema#subClassOf")
            .await
            .unwrap();
        let ty = store
            .resolve_iri("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")
            .await
            .unwrap();
        db::access(&store.state, move |s| s.insert(0, [dog, sub, animal], None))
            .await
            .unwrap();
        for i in 0..140 {
            let id = store.resolve_iri(&format!("urn:dog:{i}")).await.unwrap();
            db::access(&store.state, move |s| s.insert(0, [id, ty, dog], None))
                .await
                .unwrap();
        }
        let old = store.snapshot().await.unwrap();
        let pattern = [None, Some(ty), Some(animal)];
        assert!(
            old.scan(pattern)
                .await
                .unwrap()
                .next()
                .await
                .unwrap()
                .is_none()
        );
        let limits = RunLimits::new(
            NonZeroU32::new(10).unwrap(),
            NonZeroU64::new(1000).unwrap(),
            NonZeroU64::new(100000).unwrap(),
        );
        let report = Reasoner::new(ExecutionProfile::RdfsSubclass, limits)
            .run(&mut store)
            .await
            .unwrap();
        assert_eq!(report.inferred, 140);
        assert!(
            old.scan(pattern)
                .await
                .unwrap()
                .next()
                .await
                .unwrap()
                .is_none()
        );
        let fresh = store.snapshot().await.unwrap();
        let mut cursor = fresh.scan(pattern).await.unwrap();
        let mut count = 0;
        while cursor.next().await.unwrap().is_some() {
            count += 1;
        }
        assert_eq!(count, 140);
    }
}