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