inference-engine 0.1.0-alpha.14

Native Rust RDF inference engine with a shared command-line interface
Documentation
mod source;
mod vocabulary;
use inference_engine::entailment::{Rdfs12FragmentEntailment, Rdfs12FragmentOutcome};
use oxigraph::store::Store;
use source::Graph;
use std::{io, path::PathBuf, sync::Arc};
use tokio::{fs, task};
use vocabulary::{
    DATATYPES, FOREIGN, NEGATIVE, ORDINARY, POSITIVE, PROJECTION, PROPERTY, SOURCE, TRIPLE_TERM,
    Vocabulary,
};

pub struct DiskFixture {
    path: PathBuf,
}
type Decisions = (
    Rdfs12FragmentOutcome<u64>,
    Rdfs12FragmentOutcome<u64>,
    usize,
);
type BatchDecisions<const N: usize> = ([Rdfs12FragmentOutcome<u64>; N], usize);
impl DiskFixture {
    pub async fn try_new_triple_term(path: PathBuf) -> io::Result<Self> {
        fs::create_dir(&path).await?;
        let fixture = Self { path };
        fixture
            .write(|store, vocabulary| {
                // bounded: selected data, one target quote and a foreign declaration.
                for (row, graph) in [
                    ([4, 2, 3], SOURCE),
                    ([1, 18, 17], TRIPLE_TERM),
                    ([4, 10, 16], FOREIGN),
                ] {
                    store
                        .insert(&vocabulary.quad(row, graph)?)
                        .map_err(io::Error::other)?;
                }
                Ok(())
            })
            .await?;
        Ok(fixture)
    }
    pub async fn assert_property_declaration(&self, present: bool) -> io::Result<()> {
        self.write(move |store, vocabulary| {
            let quad = vocabulary.quad([4, 10, 16], SOURCE)?;
            if present {
                store.insert(&quad)
            } else {
                store.remove(&quad)
            }
            .map_err(io::Error::other)
        })
        .await
    }
    pub async fn check_triple_term(
        &self,
        checker: &Rdfs12FragmentEntailment,
    ) -> io::Result<BatchDecisions<1>> {
        self.check_graphs(checker, [TRIPLE_TERM]).await
    }

    pub async fn try_new_property(path: PathBuf) -> io::Result<Self> {
        fs::create_dir(&path).await?;
        let fixture = Self { path };
        fixture
            .write(|store, vocabulary| {
                // bounded: two candidate claims, selected data and a foreign predicate occurrence.
                for (row, graph) in [
                    ([4, 2, 3], SOURCE),
                    ([2, 10, 16], PROPERTY),
                    ([4, 10, 16], PROPERTY),
                    ([1, 4, 3], FOREIGN),
                ] {
                    store
                        .insert(&vocabulary.quad(row, graph)?)
                        .map_err(io::Error::other)?;
                }
                Ok(())
            })
            .await?;
        Ok(fixture)
    }
    pub async fn try_new_datatype(path: PathBuf) -> io::Result<Self> {
        fs::create_dir(&path).await?;
        let fixture = Self { path };
        fixture
            .write(|store, vocabulary| {
                // bounded: two fixed data quads plus three default class target graphs.
                for (row, graph) in [([1, 2, 3], SOURCE), ([1, 10, 13], FOREIGN)] {
                    store
                        .insert(&vocabulary.quad(row, graph)?)
                        .map_err(io::Error::other)?;
                }
                for (i, graph) in DATATYPES.iter().enumerate() {
                    store
                        .insert(&vocabulary.quad([1, 10, 13 + i as u64], graph)?)
                        .map_err(io::Error::other)?;
                }
                Ok(())
            })
            .await?;
        Ok(fixture)
    }
    pub async fn try_new_projection(path: PathBuf) -> io::Result<Self> {
        fs::create_dir(&path).await?;
        let fixture = Self { path };
        fixture
            .write(|store, vocabulary| {
                // bounded: nine quads, including the nonselected aligned assertion and schema.
                for (triple, graph) in [
                    ([4, 5, 6], SOURCE),
                    ([8, 5, 12], SOURCE),
                    ([4, 5, 9], PROJECTION),
                    ([8, 5, 9], PROJECTION),
                    ([9, 10, 11], PROJECTION),
                    ([4, 5, 9], ORDINARY),
                    ([8, 5, 9], ORDINARY),
                    ([8, 5, 6], FOREIGN),
                    ([2, 7, 1], FOREIGN),
                ] {
                    store
                        .insert(&vocabulary.quad(triple, graph)?)
                        .map_err(io::Error::other)?;
                }
                Ok(())
            })
            .await?;
        Ok(fixture)
    }
    pub async fn try_new(path: PathBuf) -> io::Result<Self> {
        fs::create_dir(&path).await?;
        let fixture = Self { path };
        fixture
            .write(|store, vocabulary| {
                // bounded: exactly five fixture quads, including two unselected facts.
                for (triple, graph) in [
                    ([4, 5, 6], SOURCE),
                    ([4, 5, 6], POSITIVE),
                    ([1, 2, 3], NEGATIVE),
                    ([1, 2, 3], FOREIGN),
                    ([2, 7, 1], FOREIGN),
                ] {
                    store
                        .insert(&vocabulary.quad(triple, graph)?)
                        .map_err(io::Error::other)?;
                }
                Ok(())
            })
            .await?;
        Ok(fixture)
    }
    async fn write(
        &self,
        change: impl FnOnce(&Store, &Vocabulary) -> io::Result<()> + Send + 'static,
    ) -> io::Result<()> {
        let path = self.path.clone();
        // Audited async boundary: all synchronous native open/write/flush/close I/O.
        task::spawn_blocking(move || {
            let store = Store::open(path).map_err(io::Error::other)?;
            change(&store, &Vocabulary::new())?;
            store.flush().map_err(io::Error::other)?;
            drop(store);
            Ok(())
        })
        .await
        .map_err(io::Error::other)?
    }
    pub async fn assert_content(&self, present: bool) -> io::Result<()> {
        self.write(move |store, vocabulary| {
            let quad = vocabulary.quad([1, 2, 3], SOURCE)?;
            if present {
                store.insert(&quad)
            } else {
                store.remove(&quad)
            }
            .map_err(io::Error::other)
        })
        .await
    }
    pub async fn assert_datatype_membership(&self, present: bool) -> io::Result<()> {
        self.write(move |store, vocabulary| {
            let quad = vocabulary.quad([1, 10, 13], SOURCE)?;
            if present {
                store.insert(&quad)
            } else {
                store.remove(&quad)
            }
            .map_err(io::Error::other)
        })
        .await
    }
    pub async fn assert_property_predicate(&self, present: bool) -> io::Result<()> {
        self.write(move |store, vocabulary| {
            // The second candidate is a predicate only INSIDE the selected triple term.
            let quad = vocabulary.quad([1, 2, 17], SOURCE)?;
            if present {
                store.insert(&quad)
            } else {
                store.remove(&quad)
            }
            .map_err(io::Error::other)
        })
        .await
    }
    pub async fn align_quotes(&self, aligned: bool) -> io::Result<()> {
        self.write(move |store, vocabulary| {
            let (remove, insert) = if aligned { (12, 6) } else { (6, 12) };
            store
                .remove(&vocabulary.quad([8, 5, remove], SOURCE)?)
                .map_err(io::Error::other)?;
            store
                .insert(&vocabulary.quad([8, 5, insert], SOURCE)?)
                .map_err(io::Error::other)
        })
        .await
    }
    pub async fn check(&self, checker: &Rdfs12FragmentEntailment) -> io::Result<Decisions> {
        let ([a, b], count) = self.check_graphs(checker, [NEGATIVE, POSITIVE]).await?;
        Ok((a, b, count))
    }
    pub async fn check_projection(
        &self,
        checker: &Rdfs12FragmentEntailment,
    ) -> io::Result<Decisions> {
        let ([a, b], count) = self.check_graphs(checker, [PROJECTION, ORDINARY]).await?;
        Ok((a, b, count))
    }
    pub async fn check_datatypes(
        &self,
        checker: &Rdfs12FragmentEntailment,
    ) -> io::Result<BatchDecisions<3>> {
        self.check_graphs(checker, DATATYPES).await
    }
    pub async fn check_property(
        &self,
        checker: &Rdfs12FragmentEntailment,
    ) -> io::Result<BatchDecisions<1>> {
        self.check_graphs(checker, [PROPERTY]).await
    }
    async fn check_graphs<const N: usize>(
        &self,
        checker: &Rdfs12FragmentEntailment,
        targets: [&str; N],
    ) -> io::Result<BatchDecisions<N>> {
        let path = self.path.clone();
        // No writer remains open. Selected graphs stay immutable across all scans.
        let store = task::spawn_blocking(move || Store::open_read_only(path))
            .await
            .map_err(io::Error::other)?
            .map_err(io::Error::other)?;
        let store = Arc::new(store);
        let vocabulary = Arc::new(Vocabulary::new());
        let result = async {
            let source = Graph::new(&store, &vocabulary, SOURCE)?;
            // bounded: private calls instantiate N=1, N=2 or N=3; verdicts only.
            let mut decisions = Vec::with_capacity(N);
            for target in targets {
                let target = Graph::new(&store, &vocabulary, target)?;
                decisions.push(
                    checker
                        .check(&source, &target, vocabulary.as_ref())
                        .await
                        .map_err(io::Error::other)?,
                );
            }
            let decisions: [Rdfs12FragmentOutcome<u64>; N] = decisions
                .try_into()
                .map_err(|_| io::Error::other("fixed fixture target inventory mismatch"))?;
            let count_store = store.clone();
            let count = task::spawn_blocking(move || count_store.len())
                .await
                .map_err(io::Error::other)?
                .map_err(io::Error::other)?;
            Ok((decisions, count))
        }
        .await;
        // Close even on a failed check, after all graph/cursor handles have dropped.
        task::spawn_blocking(move || {
            assert_eq!(Arc::strong_count(&store), 1);
            drop(store);
        })
        .await
        .map_err(io::Error::other)?;
        result
    }
    pub async fn remove(self) -> io::Result<()> {
        fs::remove_dir_all(self.path).await
    }
}