inference-engine 0.1.0-alpha.13

Native Rust RDF inference engine with a shared command-line interface
Documentation
use super::{
    Rdfs12FragmentEntailment, Rdfs12FragmentError, Rdfs12FragmentRefutation, evidence::IriKind,
};
use crate::{
    entailment::{EntailmentError, IriTermAccess, matcher::State},
    reasoning::{
        LiteralRole, OccurrencePath, Rdf12OccurrenceCursor, TermOccurrence, TermPosition,
        TripleCursor, TripleSource,
    },
};
impl Rdfs12FragmentEntailment {
    pub(super) async fn property_refutation<S, E, A>(
        &self,
        source: &S,
        target: &E,
        access: &A,
        initial_steps: u64,
    ) -> Result<
        (Option<Rdfs12FragmentRefutation<S::Term>>, u64),
        Rdfs12FragmentError<S::Term, S::Error>,
    >
    where
        S: TripleSource,
        E: TripleSource<Term = S::Term, Error = S::Error>,
        A: IriTermAccess<Term = S::Term, Error = S::Error>,
    {
        let mut work = State {
            limits: self.limits.search,
            steps: initial_steps,
        };
        work.step(access)
            .await
            .map_err(Rdfs12FragmentError::Search)?;
        let mut cursor =
            target
                .scan([None, None, None])
                .await
                .map_err(|error| Rdfs12FragmentError::Graph {
                    role: LiteralRole::TargetContext,
                    error,
                })?;
        // bounded: one current root/candidate, source cursor and first certificate.
        let mut refutation = None;
        loop {
            work.step(access)
                .await
                .map_err(Rdfs12FragmentError::Search)?;
            let row = cursor
                .next()
                .await
                .map_err(|error| Rdfs12FragmentError::Search(EntailmentError::Storage(error)))?;
            Self::cancelled(access)?;
            let Some(root) = row else { break };
            // Still read through target EOF after evidence; do not issue more source probes.
            if refutation.is_some() {
                continue;
            }
            let predicate = self
                .root_iri(access, &root, TermPosition::Predicate, &mut work)
                .await?
                .ok_or(Rdfs12FragmentError::Search(
                    EntailmentError::TargetSelectionMetadata,
                ))?;
            if predicate != IriKind::Type {
                continue;
            }
            if self
                .root_iri(access, &root, TermPosition::Subject, &mut work)
                .await?
                != Some(IriKind::Ordinary)
            {
                continue;
            }
            if self
                .root_iri(access, &root, TermPosition::Object, &mut work)
                .await?
                != Some(IriKind::Property)
            {
                continue;
            }
            if !self
                .source_property_required(source, access, &root[0], &mut work)
                .await?
            {
                refutation = Some(Rdfs12FragmentRefutation::NamedPropertyMembership {
                    occurrence: root_occurrence(&root, TermPosition::Subject),
                });
            }
        }
        Self::cancelled(access)?;
        Ok((refutation, work.steps))
    }
    pub(super) async fn source_property_required<S, A>(
        &self,
        source: &S,
        access: &A,
        key: &S::Term,
        work: &mut State,
    ) -> Result<bool, Rdfs12FragmentError<S::Term, S::Error>>
    where
        S: TripleSource,
        A: IriTermAccess<Term = S::Term, Error = S::Error>,
    {
        work.step(access)
            .await
            .map_err(Rdfs12FragmentError::Search)?;
        let roots =
            source
                .scan([None, None, None])
                .await
                .map_err(|error| Rdfs12FragmentError::Graph {
                    role: LiteralRole::Source,
                    error,
                })?;
        let mut cursor =
            Rdf12OccurrenceCursor::new(roots, access, LiteralRole::Source, self.limits.traversal);
        let mut required = false;
        loop {
            // One next() performs at most one root read plus one structural lookup.
            // Charge both before entering it; traversal also enforces its own caps.
            work.step(access)
                .await
                .map_err(Rdfs12FragmentError::Search)?;
            work.step(access)
                .await
                .map_err(Rdfs12FragmentError::Search)?;
            let Some(occurrence) = cursor
                .next()
                .await
                .map_err(Rdfs12FragmentError::Traversal)?
            else {
                break;
            };
            if occurrence.is_predicate() && occurrence.term == *key {
                required = true;
            }
            if occurrence.root[0] == *key && occurrence.path.positions().eq([&TermPosition::Object])
            {
                let mut predicate = root_occurrence(&occurrence.root, TermPosition::Predicate);
                predicate.role = LiteralRole::Source;
                let mut object = occurrence.clone();
                object.role = LiteralRole::Source;
                let kind = self.occurrence_iri(access, &predicate, work).await?.ok_or(
                    Rdfs12FragmentError::Search(EntailmentError::TargetSelectionMetadata),
                )?;
                if kind == IriKind::Type {
                    let object_kind = self.occurrence_iri(access, &object, work).await?.ok_or(
                        Rdfs12FragmentError::Search(EntailmentError::TargetSelectionMetadata),
                    )?;
                    if object_kind == IriKind::Property {
                        required = true;
                    }
                }
            }
        }
        Self::cancelled(access)?;
        Ok(required)
    }
    async fn root_iri<A: IriTermAccess>(
        &self,
        access: &A,
        root: &[A::Term; 3],
        position: TermPosition,
        work: &mut State,
    ) -> Result<Option<IriKind>, Rdfs12FragmentError<A::Term, A::Error>> {
        self.occurrence_iri(access, &root_occurrence(root, position), work)
            .await
    }
    pub(super) async fn occurrence_iri<A: IriTermAccess>(
        &self,
        access: &A,
        occurrence: &TermOccurrence<A::Term>,
        work: &mut State,
    ) -> Result<Option<IriKind>, Rdfs12FragmentError<A::Term, A::Error>> {
        work.step(access)
            .await
            .map_err(Rdfs12FragmentError::Search)?;
        let iri = access
            .iri(&occurrence.term, self.limits.iri_bytes)
            .await
            .map_err(|error| Rdfs12FragmentError::Metadata {
                occurrence: occurrence.clone(),
                error,
            })?;
        Self::cancelled(access)?;
        let Some(iri) = iri else { return Ok(None) };
        if iri.as_ref().len() > self.limits.iri_bytes.get() as usize {
            return Err(Rdfs12FragmentError::IriLimit {
                occurrence: occurrence.clone(),
            });
        }
        Ok(Some(IriKind::inspect(iri.as_ref())))
    }
}
fn root_occurrence<T: Clone>(root: &[T; 3], position: TermPosition) -> TermOccurrence<T> {
    let index = match position {
        TermPosition::Subject => 0,
        TermPosition::Predicate => 1,
        TermPosition::Object => 2,
    };
    TermOccurrence {
        term: root[index].clone(),
        root: root.clone(),
        parent: root.clone(),
        role: LiteralRole::TargetContext,
        path: OccurrencePath::root(position),
    }
}