Skip to main content

inference_engine/entailment/
mod.rs

1//! Bounded RDF 1.2 simple-entailment matching over caller-owned immutable graphs.
2//!
3//! This checks one consistent target blank-node substitution, including inside
4//! nested triple terms. RDFS closure, datatype value equivalence, inconsistency
5//! detection and target-relevant vocabulary seeding are separate prerequisites
6//! for the stronger entailment regimes. A simple match is not full RDFS support.
7
8mod ground;
9mod iri;
10mod matcher;
11mod partial;
12pub use ground::{
13    SchemaFreeGroundEntailment, SchemaFreeGroundError, SchemaFreeGroundLimits,
14    SchemaFreeGroundOutcome, SchemaFreeGroundReport, SchemaFreeGroundRestriction,
15};
16pub use iri::IriTermAccess;
17pub use matcher::SimpleEntailment;
18pub(crate) use partial::PartialMatches;
19
20use serde::{Deserialize, Serialize};
21use std::{
22    error::Error,
23    fmt,
24    future::Future,
25    num::{NonZeroU32, NonZeroU64},
26};
27
28/// Asynchronous structural access to exact source/target term identities.
29///
30/// Both graphs and this accessor must share a term-identity domain. Preserve
31/// scoped blanks and exact RDF literal identity, including case-insensitive
32/// language-tag identity and direction. Use bounded-clone IDs or shared handles;
33/// no method may hydrate a graph or a dictionary. Reject unsupported extensions
34/// at the adapter's standard-RDF admission boundary, never erase or coerce them.
35pub trait EntailmentTerms: Send + Sync {
36    /// Exact RDF term key, including recursive triple-term identity.
37    type Term: Clone + Eq + Send + Sync;
38    /// Backend term-access failure.
39    type Error: Error + Send + Sync + 'static;
40    /// Whether this term is a blank node. Target blanks are existential variables.
41    fn is_blank(&self, term: &Self::Term)
42    -> impl Future<Output = Result<bool, Self::Error>> + Send;
43    /// Decompose a triple term into exact subject/predicate/object keys.
44    /// Return `None` only for a supported non-triple term; never assert its contents.
45    fn triple_term(
46        &self,
47        term: &Self::Term,
48    ) -> impl Future<Output = Result<Option<[Self::Term; 3]>, Self::Error>> + Send;
49    /// Whether the enclosing immutable attempt is cancelled or superseded.
50    fn is_cancelled(&self) -> bool;
51}
52
53/// Explicit bounds on target size, existential bindings, term worklist and work.
54#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
55#[serde(deny_unknown_fields)]
56pub struct EntailmentLimits {
57    patterns: NonZeroU32,
58    bindings: NonZeroU32,
59    terms: NonZeroU32,
60    steps: NonZeroU64,
61}
62impl EntailmentLimits {
63    /// Bound retained target triples/active cursors, blank bindings, pending term
64    /// pairs and total read/unification/probe steps. Source graphs remain streamed.
65    /// Exceeding any cap is an error, never a negative entailment answer.
66    pub const fn new(
67        patterns: NonZeroU32,
68        bindings: NonZeroU32,
69        terms: NonZeroU32,
70        steps: NonZeroU64,
71    ) -> Self {
72        Self {
73            patterns,
74            bindings,
75            terms,
76            steps,
77        }
78    }
79}
80
81/// Completed simple-entailment decision with bounded-work counters.
82#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
83#[serde(deny_unknown_fields)]
84pub struct EntailmentReport {
85    /// Whether the source contains an instance of the entire target graph.
86    pub entailed: bool,
87    /// Target triples read before matching.
88    pub target_triples: u32,
89    /// Cursor reads, structural probes and term-pair unifications performed.
90    pub steps: u64,
91}
92
93/// Incomplete entailment inspection; callers must not report `false` on error.
94#[derive(Debug)]
95pub enum EntailmentError<E> {
96    /// Graph or term access failed.
97    Storage(E),
98    /// Caller cancelled or superseded the attempt.
99    Cancelled,
100    /// Retaining another target triple would exceed its explicit cap.
101    TargetLimit,
102    /// Another existential binding would exceed its explicit cap.
103    BindingLimit,
104    /// Pending recursive term pairs would exceed their explicit cap.
105    TermLimit,
106    /// The explicit total work-step budget was exhausted.
107    StepLimit,
108}
109impl<E: fmt::Display> fmt::Display for EntailmentError<E> {
110    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111        match self {
112            Self::Storage(error) => write!(f, "entailment storage failed: {error}"),
113            Self::Cancelled => f.write_str("entailment cancelled"),
114            Self::TargetLimit => f.write_str("entailment target limit exceeded"),
115            Self::BindingLimit => f.write_str("entailment bindings limit exceeded"),
116            Self::TermLimit => f.write_str("entailment term worklist limit exceeded"),
117            Self::StepLimit => f.write_str("entailment steps limit exceeded"),
118        }
119    }
120}
121impl<E: Error + 'static> Error for EntailmentError<E> {
122    fn source(&self) -> Option<&(dyn Error + 'static)> {
123        match self {
124            Self::Storage(error) => Some(error),
125            _ => None,
126        }
127    }
128}