Skip to main content

inference_engine/reasoning/literal_typing/
engine.rs

1use super::{
2    LiteralOccurrenceCursor, LiteralRole, LiteralTypingError, LiteralTypingLimits,
3    LiteralTypingReport,
4};
5use crate::reasoning::{
6    Evidence, Inference, Limit, Rdf12LiteralValidator, ReasoningError, ReasoningStore,
7    plan::LiteralClause,
8};
9use rdf_reasoning::Rdf12LiteralRuleId;
10
11/// Execute shared default-map GrdfD1 clauses over inspected semantic occurrences.
12///
13/// This adds generalized literal typing; it does not certify complete source
14/// consistency, enumerate occurrences or implement the entire RDFS procedure.
15pub struct Rdf12LiteralTyper {
16    limits: LiteralTypingLimits,
17    role: LiteralRole,
18}
19impl Rdf12LiteralTyper {
20    /// Select explicit aggregate budgets and one source/target-context phase.
21    pub const fn new(limits: LiteralTypingLimits, role: LiteralRole) -> Self {
22        Self { limits, role }
23    }
24
25    /// Inspect selected literals and stage conclusions from shared GrdfD1 patterns.
26    ///
27    /// The cursor owns immutable occurrence selection and readers. Reader metadata
28    /// and UTF-8 payloads are checked before creating virtual metadata premises.
29    /// Unknown encountered datatypes remain opaque even when graph assertions
30    /// declare them datatypes. RDF scans cannot satisfy this auxiliary relation.
31    ///
32    /// Source and target context must use separate attempts/phases; callers must
33    /// never infer source inconsistency from invalid target-context metadata.
34    ///
35    /// # Errors
36    /// On any storage/inspection failure, role mismatch or budget exhaustion,
37    /// abort the whole attempt, including earlier staged conclusions. A lexical
38    /// diagnostic is retained for later role-aware consistency/entailment policy;
39    /// no error is silently converted into an entailment answer.
40    pub async fn run<S, C>(
41        &self,
42        store: &mut S,
43        cursor: &mut C,
44    ) -> Result<LiteralTypingReport, LiteralTypingError<S::Term, S::Error>>
45    where
46        S: ReasoningStore,
47        C: LiteralOccurrenceCursor<Term = S::Term, Error = S::Error>,
48    {
49        Self::check_cancelled(store)?;
50        // bounded: exactly three default-map clauses, independent of graph size.
51        let mut clauses = Vec::with_capacity(3);
52        for &id in Rdf12LiteralRuleId::ALL {
53            clauses.push(
54                LiteralClause::compile(id, store)
55                    .await
56                    .map_err(LiteralTypingError::Reasoning)?,
57            );
58        }
59        let mut report = LiteralTypingReport::default();
60        loop {
61            Self::check_cancelled(store)?;
62            let next = cursor.next().await.map_err(LiteralTypingError::Cursor)?;
63            Self::check_cancelled(store)?;
64            let Some((occurrence, mut reader)) = next else {
65                return Ok(report);
66            };
67            if occurrence.role != self.role {
68                return Err(LiteralTypingError::RoleMismatch {
69                    expected: self.role,
70                    occurrence,
71                });
72            }
73            if report.occurrences == self.limits.occurrences.get() {
74                return Err(LiteralTypingError::OccurrenceLimit);
75            }
76            report.occurrences += 1;
77            crate::cooperative::checkpoint(report.occurrences).await;
78            Self::check_cancelled(store)?;
79            let inspection = Rdf12LiteralValidator::new(self.limits.bytes - report.bytes)
80                .validate(&mut reader)
81                .await
82                .map_err(|error| LiteralTypingError::Literal {
83                    occurrence: occurrence.clone(),
84                    error,
85                })?;
86            Self::check_cancelled(store)?;
87            report.bytes += inspection.bytes;
88            let Some(datatype) = inspection.datatype else {
89                report.opaque += 1;
90                continue;
91            };
92            let id = Rdf12LiteralRuleId::GrdfD1(datatype);
93            let clause = clauses
94                .iter()
95                .find(|clause| clause.id == id)
96                .ok_or_else(|| {
97                    LiteralTypingError::Reasoning(ReasoningError::UnsupportedLiteralRule(id))
98                })?;
99            let metadata = [occurrence.literal.clone(), clause.datatype.clone()];
100            let bindings = clause
101                .body
102                .bind(&metadata, std::array::from_fn(|_| None))
103                .ok_or_else(|| {
104                    LiteralTypingError::Reasoning(ReasoningError::UnsupportedLiteralRule(id))
105                })?;
106            let triple = clause.head.ground(&bindings).ok_or_else(|| {
107                LiteralTypingError::Reasoning(ReasoningError::UnsupportedLiteralRule(id))
108            })?;
109            if store
110                .contains(&triple)
111                .await
112                .map_err(|error| LiteralTypingError::Reasoning(ReasoningError::Storage(error)))?
113            {
114                continue;
115            }
116            Self::check_cancelled(store)?;
117            if report.inferred == self.limits.inferred.get() {
118                return Err(LiteralTypingError::Reasoning(
119                    ReasoningError::LimitExceeded(Limit::Inferred),
120                ));
121            }
122            let inference = Inference {
123                triple,
124                evidence: Evidence::Literal {
125                    rule: id,
126                    occurrence,
127                    lexical_bytes: inspection.bytes,
128                },
129            };
130            if store
131                .insert_inferred(inference)
132                .await
133                .map_err(|error| LiteralTypingError::Reasoning(ReasoningError::Storage(error)))?
134            {
135                report.inferred += 1;
136            }
137        }
138    }
139    fn check_cancelled<S: ReasoningStore>(
140        store: &S,
141    ) -> Result<(), LiteralTypingError<S::Term, S::Error>> {
142        if store.is_cancelled() {
143            Err(LiteralTypingError::Reasoning(ReasoningError::Cancelled))
144        } else {
145            Ok(())
146        }
147    }
148}