Skip to main content

inference_engine/reasoning/
occurrence_typing.rs

1use super::{
2    Evidence, Inference, Limit, LiteralRole, OccurrenceError, Rdf12OccurrenceCursor,
3    ReasoningError, ReasoningStore, TripleCursor, plan::OccurrenceClause,
4};
5use crate::entailment::EntailmentTerms;
6use rdf_reasoning::Rdf12OccurrenceRuleId;
7use serde::{Deserialize, Serialize};
8use std::{error::Error, fmt, num::NonZeroU64};
9
10/// Completed counters for one immutable occurrence phase; not a closure claim.
11#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
12#[serde(deny_unknown_fields)]
13pub struct OccurrenceTypingReport {
14    /// Actual appearances inspected, including repeated keys at distinct paths.
15    pub occurrences: u64,
16    /// Novel RDF typing conclusions, excluding asserted/inferred duplicates.
17    pub inferred: u64,
18    /// Target triple-term appearances lacking an established resource fact.
19    /// Their denotation must be established through construction, never assumed.
20    pub deferred_triple_terms: u64,
21}
22
23/// Failure of the complete occurrence-typing phase; discard partial staging.
24#[derive(Debug)]
25pub enum OccurrenceTypingError<E> {
26    /// Explicit cursor role does not match the selected execution role.
27    RoleMismatch {
28        /// Phase's configured role.
29        expected: LiteralRole,
30        /// Cursor's configured role.
31        actual: LiteralRole,
32    },
33    /// Root/decomposition/cancellation or traversal budget failed.
34    Traversal(OccurrenceError<E>),
35    /// Shared compilation, store, cancellation or output budget failed.
36    Reasoning(ReasoningError<E>),
37}
38impl<E> From<ReasoningError<E>> for OccurrenceTypingError<E> {
39    fn from(error: ReasoningError<E>) -> Self {
40        Self::Reasoning(error)
41    }
42}
43impl<E: fmt::Display> fmt::Display for OccurrenceTypingError<E> {
44    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45        match self {
46            Self::RoleMismatch { expected, actual } => write!(
47                f,
48                "occurrence role mismatch: expected {expected:?}, got {actual:?}"
49            ),
50            Self::Traversal(error) => error.fmt(f),
51            Self::Reasoning(error) => error.fmt(f),
52        }
53    }
54}
55impl<E: Error + 'static> Error for OccurrenceTypingError<E> {
56    fn source(&self) -> Option<&(dyn Error + 'static)> {
57        match self {
58            Self::Traversal(error) => Some(error),
59            Self::Reasoning(error) => Some(error),
60            _ => None,
61        }
62    }
63}
64
65/// Execute shared rdfD2/rdfs4 over authoritative recursive appearances.
66///
67/// Source admits both clauses. Target context admits rdfs4 only, never predicate
68/// typing, and defers new whole triple-term resource facts until construction
69/// establishes their denotation. Atomic components are still traversed and typed.
70/// The caller validates target literals before this phase, selects snapshots and schedules source
71/// consistency before target augmentation. This phase does not close newly staged
72/// triples recursively, inspect lexical payloads or construct proposition terms.
73pub struct Rdf12OccurrenceTyper {
74    inferred: NonZeroU64,
75    role: LiteralRole,
76}
77impl Rdf12OccurrenceTyper {
78    /// Select strict novel-output cap and one explicit source/target-context role.
79    /// The cursor independently bounds traversal, depth and inspected work.
80    pub const fn new(inferred: NonZeroU64, role: LiteralRole) -> Self {
81        Self { inferred, role }
82    }
83
84    /// Stage typing facts with exact structural occurrence evidence.
85    ///
86    /// The cursor role is checked before any source read or compilation. RDF
87    /// assertions spelling an auxiliary relation cannot bind that capability.
88    /// Nested parents remain structural evidence, never asserted RDF premises.
89    /// Keep scope/snapshot/source-graph origin alongside every retained proof.
90    ///
91    /// # Errors
92    /// Role mismatch, traversal, compilation, cancellation, storage and output
93    /// budget failures invalidate all partial output for the enclosing attempt.
94    pub async fn run<S, A, C>(
95        &self,
96        store: &mut S,
97        cursor: &mut Rdf12OccurrenceCursor<'_, A, C>,
98    ) -> Result<OccurrenceTypingReport, OccurrenceTypingError<S::Error>>
99    where
100        S: ReasoningStore,
101        A: EntailmentTerms<Term = S::Term, Error = S::Error>,
102        C: TripleCursor<Term = S::Term, Error = S::Error>,
103    {
104        if cursor.role() != self.role {
105            return Err(OccurrenceTypingError::RoleMismatch {
106                expected: self.role,
107                actual: cursor.role(),
108            });
109        }
110        Self::cancel(store)?;
111        // bounded: source selects two clauses; target context selects one.
112        let mut clauses = Vec::with_capacity(2);
113        for &id in Rdf12OccurrenceRuleId::ALL {
114            if self.role == LiteralRole::TargetContext && id == Rdf12OccurrenceRuleId::RdfD2 {
115                continue;
116            }
117            clauses.push(OccurrenceClause::compile(id, store).await?);
118        }
119        let mut report = OccurrenceTypingReport::default();
120        loop {
121            Self::cancel(store)?;
122            let next = cursor
123                .next()
124                .await
125                .map_err(OccurrenceTypingError::Traversal)?;
126            Self::cancel(store)?;
127            let Some(occurrence) = next else {
128                return Ok(report);
129            };
130            report.occurrences += 1;
131            for clause in &clauses {
132                let Some(bindings) = clause.bind(&occurrence) else {
133                    continue;
134                };
135                let triple = clause
136                    .head
137                    .ground(&bindings)
138                    .ok_or(ReasoningError::UnsupportedOccurrenceRule(clause.id))?;
139                if store
140                    .contains(&triple)
141                    .await
142                    .map_err(ReasoningError::Storage)?
143                {
144                    continue;
145                }
146                if self.role == LiteralRole::TargetContext && cursor.current_is_triple_term() {
147                    report.deferred_triple_terms += 1;
148                    continue;
149                }
150                Self::cancel(store)?;
151                if report.inferred == self.inferred.get() {
152                    return Err(ReasoningError::LimitExceeded(Limit::Inferred).into());
153                }
154                if store
155                    .insert_inferred(Inference {
156                        triple,
157                        evidence: Evidence::Occurrence {
158                            rule: clause.id,
159                            occurrence: occurrence.clone(),
160                        },
161                    })
162                    .await
163                    .map_err(ReasoningError::Storage)?
164                {
165                    report.inferred += 1;
166                }
167            }
168        }
169    }
170    fn cancel<S: ReasoningStore>(store: &S) -> Result<(), ReasoningError<S::Error>> {
171        if store.is_cancelled() {
172            Err(ReasoningError::Cancelled)
173        } else {
174            Ok(())
175        }
176    }
177}