inference-engine 0.1.0-alpha.14

Native Rust RDF inference engine with a shared command-line interface
Documentation
use crate::{
    entailment::{EntailmentError, EntailmentLimits},
    reasoning::{LiteralRole, OccurrenceError, OccurrenceLimits, TermOccurrence},
};
use rdf_reasoning::Rdf12Datatype;
use serde::{Deserialize, Serialize};
use std::{error::Error, fmt, num::NonZeroU32};

/// Explicit admission, cumulative search and per-IRI metadata budgets; no defaults.
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Rdfs12FragmentLimits {
    pub(super) traversal: OccurrenceLimits,
    pub(super) search: EntailmentLimits,
    pub(super) iri_bytes: NonZeroU32,
}
impl Rdfs12FragmentLimits {
    /// Bound admission/probe traversals and total property/denotation-probe plus matching work.
    /// IRI reads and blank checks occur at most once per admitted appearance.
    pub const fn new(
        traversal: OccurrenceLimits,
        search: EntailmentLimits,
        iri_bytes: NonZeroU32,
    ) -> Self {
        Self {
            traversal,
            search,
            iri_bytes,
        }
    }
}

/// Completed work for a decision within the checked RDFS source fragment.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Rdfs12FragmentReport {
    /// Fully examined source appearances, including recursive/repeated paths.
    pub source_occurrences: u64,
    /// Fully examined target appearances, including recursive/repeated paths.
    pub target_occurrences: u64,
    /// Ordinary-predicate patterns retained; zero when matching was not invoked.
    pub projected_target_triples: u32,
    /// Cumulative charged property/denotation-probe and matching work; zero before search.
    pub search_steps: u64,
}

/// A condition outside this proven fragment, not a non-entailment witness.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub enum Rdfs12FragmentRestriction {
    /// An asserted standard-predicate root is outside the three admitted schema forms.
    UnsupportedSourceSchema,
    /// A literal appears in either graph; no lexical payload was inspected.
    Literal,
    /// Ordinary constraints matched, but a standard-predicate constraint remains unproved.
    UnresolvedStandardConstraint,
    /// A generalized position occurs: blank predicate or non-object triple term.
    GeneralizedPosition,
}

/// A complete decision only after both graphs satisfy all admission conditions.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub enum Rdfs12FragmentOutcome<T> {
    /// One consistent instance of the entire target proves RDFS 1.2 entailment.
    Entailed(Rdfs12FragmentReport),
    /// The free-constructor standard completion supplies a countermodel.
    /// This is not failure to find a proof within a construction/pass budget.
    NotEntailed {
        /// Completed admission/search work; search counters are zero if not invoked.
        report: Rdfs12FragmentReport,
        /// The explicit countermodel condition used for this negative decision.
        refutation: Rdfs12FragmentRefutation<T>,
    },
    /// This fragment has no decision for the rejected source/target appearance.
    Unsupported {
        /// Specific failed admission condition.
        restriction: Rdfs12FragmentRestriction,
        /// Exact original root, term, phase and recursive path.
        occurrence: TermOccurrence<T>,
    },
}

/// A refutation condition in the checked source's fresh-atom standard completion.
///
/// This records an observation about a pinned input, not an independently trusted
/// proof object. Keep source/target graph and snapshot identities with the report.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub enum Rdfs12FragmentRefutation<T> {
    /// This nested triple term has no value in the selective-property source model.
    /// Its fixed predicate is neither a source predicate nor declared a property.
    TripleTermPredicate {
        /// Exact nested target predicate appearance, including its parent triple term.
        occurrence: TermOccurrence<T>,
    },
    /// No consistent substitution satisfies the ordinary-predicate projection.
    OrdinaryProjection,
    /// In a selective-property completion, this fixed ordinary name is not a property.
    /// All scoped source predicates and asserted property declarations were inspected.
    NamedPropertyMembership {
        /// Exact original root-subject appearance of the unforced property claim.
        occurrence: TermOccurrence<T>,
    },
    /// A fixed ordinary named subject can denote a fresh atom outside this value space.
    /// This is one chosen model, not a rule that IRIs cannot denote literal values.
    DefaultDatatypeMembership {
        /// Exact shared mandatory default-map datatype.
        datatype: Rdf12Datatype,
        /// Exact original root-subject appearance with target role and path.
        occurrence: TermOccurrence<T>,
    },
}

/// Incomplete admission/search; never convert these failures into `NotEntailed`.
#[derive(Debug)]
pub enum Rdfs12FragmentError<T, E> {
    /// Opening the selected immutable graph failed.
    Graph {
        /// Owning semantic phase.
        role: LiteralRole,
        /// Backend failure.
        error: E,
    },
    /// Bounded structural traversal failed, including late cursor errors.
    Traversal(OccurrenceError<E>),
    /// Authoritative IRI or blank classification failed for this appearance.
    Metadata {
        /// Exact failed appearance.
        occurrence: TermOccurrence<T>,
        /// Backend failure.
        error: E,
    },
    /// An adapter returned IRI metadata larger than its explicit cap.
    IriLimit {
        /// Exact over-budget appearance.
        occurrence: TermOccurrence<T>,
    },
    /// Property/denotation candidate search or shared matching did not complete.
    Search(EntailmentError<E>),
    /// The attempt was cancelled/superseded.
    Cancelled,
    /// Work counters cannot represent a completed traversal.
    CounterOverflow,
}
impl<T, E: fmt::Display> fmt::Display for Rdfs12FragmentError<T, E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Graph { error, .. } => write!(f, "RDFS fragment graph access failed: {error}"),
            Self::Traversal(error) => error.fmt(f),
            Self::Metadata { error, .. } => write!(f, "RDFS fragment metadata failed: {error}"),
            Self::IriLimit { .. } => f.write_str("RDFS fragment IRI metadata limit exceeded"),
            Self::Search(error) => error.fmt(f),
            Self::Cancelled => f.write_str("RDFS fragment decision cancelled"),
            Self::CounterOverflow => f.write_str("RDFS fragment work counter overflow"),
        }
    }
}
impl<T: fmt::Debug, E: Error + 'static> Error for Rdfs12FragmentError<T, E> {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Graph { error, .. } | Self::Metadata { error, .. } => Some(error),
            Self::Traversal(error) => Some(error),
            Self::Search(error) => Some(error),
            _ => None,
        }
    }
}