Skip to main content

inference_engine/reasoning/context/
engine.rs

1use super::{Rdfs12ContextConfig, Rdfs12ContextError, Rdfs12ContextOutcome, Rdfs12TargetReport};
2use crate::reasoning::{
3    ExecutionProfile, LiteralRole, LiteralTermAccess, Rdf12AxiomSeeder, Rdf12ContainerAccess,
4    Rdf12LiteralOccurrences, Rdf12LiteralTyper, Rdf12OccurrenceCursor, Rdf12OccurrenceTyper,
5    Rdf12SourceDiagnosticSink, Rdf12TripleTermStore, Rdf12WitnessStore, Rdfs12Source,
6    Rdfs12SourceOutcome, Reasoner, ReasoningError, ReasoningStore, TripleSource,
7};
8
9/// Complete selected source phases before augmenting original-target context.
10///
11/// This controller neither asserts target triples nor executes source predicate
12/// typing on target terms. It does not construct adequately substituted target
13/// propositions or decide full RDFS entailment/consistency. Missing matches stay
14/// undecided outside a complete semantic procedure.
15pub struct Rdfs12Context {
16    config: Rdfs12ContextConfig,
17}
18impl Rdfs12Context {
19    /// Configure source and target budgets separately, without implicit defaults.
20    pub const fn new(config: Rdfs12ContextConfig) -> Self {
21        Self { config }
22    }
23
24    /// Prepare a fresh selected source and then isolated original-target context.
25    ///
26    /// The immutable target and selected source must have independent blank scopes
27    /// and share the accessor/store's exact append-only term dictionary. All reads
28    /// must use authoritative persisted input; cache misses reload or fail. Caller
29    /// owns freshness, attempt-wide storage/I/O bounds, provenance and promotion.
30    /// Source diagnostics finish before the first target scan; supported source
31    /// conflicts return immediately. Target facts are never reclassified as source
32    /// input or fed into source consistency. Preserve target-role proof roots/paths.
33    ///
34    /// # Errors
35    /// Any source or target read, lexical, identity, cancellation or budget failure
36    /// invalidates all scratch. A known-invalid target literal remains a target
37    /// error, never a source-conflict or negative-entailment verdict.
38    pub async fn run<S, A, T, D>(
39        &self,
40        store: &mut S,
41        access: &A,
42        target: &T,
43        sink: &mut D,
44    ) -> Result<Rdfs12ContextOutcome, Rdfs12ContextError<S::Term, S::Error>>
45    where
46        S: Rdf12WitnessStore + Rdf12TripleTermStore,
47        A: LiteralTermAccess<Term = S::Term, Error = S::Error> + Rdf12ContainerAccess,
48        T: TripleSource<Term = S::Term, Error = S::Error>,
49        D: Rdf12SourceDiagnosticSink<Term = S::Term, Error = S::Error>,
50    {
51        let source = match Rdfs12Source::new(self.config.source)
52            .run(store, access, sink)
53            .await
54            .map_err(Rdfs12ContextError::Source)?
55        {
56            Rdfs12SourceOutcome::Prepared(report) => report,
57            Rdfs12SourceOutcome::Conflicting(report) => {
58                return Ok(Rdfs12ContextOutcome::SourceConflicting(report));
59            }
60        };
61        let mut seeds = Rdf12AxiomSeeder::new(self.config.target.axioms);
62        self.vocabulary(store, access, target, &mut seeds).await?;
63        let roots = target
64            .scan([None, None, None])
65            .await
66            .map_err(ReasoningError::Storage)?;
67        let mut literals = Rdf12LiteralOccurrences::new(
68            roots,
69            access,
70            LiteralRole::TargetContext,
71            self.config.target.traversal,
72        );
73        let literals =
74            Rdf12LiteralTyper::new(self.config.target.literals, LiteralRole::TargetContext)
75                .run(store, &mut literals)
76                .await
77                .map_err(Rdfs12ContextError::Literals)?;
78        let roots = target
79            .scan([None, None, None])
80            .await
81            .map_err(ReasoningError::Storage)?;
82        let mut terms = Rdf12OccurrenceCursor::new(
83            roots,
84            access,
85            LiteralRole::TargetContext,
86            self.config.target.traversal,
87        );
88        let terms = Rdf12OccurrenceTyper::new(
89            self.config.target.structural.inferred,
90            LiteralRole::TargetContext,
91        )
92        .run(store, &mut terms)
93        .await
94        .map_err(Rdfs12ContextError::Occurrences)?;
95        let core = Reasoner::new(ExecutionProfile::RdfsCore, self.config.target.structural)
96            .run(store)
97            .await?;
98        let inferred = seeds
99            .inferred()
100            .checked_add(literals.inferred)
101            .and_then(|value| value.checked_add(terms.inferred))
102            .and_then(|value| value.checked_add(core.inferred))
103            .ok_or(Rdfs12ContextError::CounterOverflow)?;
104        Ok(Rdfs12ContextOutcome::Prepared {
105            source,
106            target: Rdfs12TargetReport {
107                seeded: seeds.inferred(),
108                inferred,
109                occurrences: terms.occurrences,
110                deferred_triple_terms: terms.deferred_triple_terms,
111                literals: literals.occurrences,
112                lexical_bytes: literals.bytes,
113                core,
114            },
115        })
116    }
117    async fn vocabulary<S, A, T>(
118        &self,
119        store: &mut S,
120        access: &A,
121        target: &T,
122        seeds: &mut Rdf12AxiomSeeder,
123    ) -> Result<(), Rdfs12ContextError<S::Term, S::Error>>
124    where
125        S: ReasoningStore,
126        A: Rdf12ContainerAccess<Term = S::Term, Error = S::Error>,
127        T: TripleSource<Term = S::Term, Error = S::Error>,
128    {
129        let roots = target
130            .scan([None, None, None])
131            .await
132            .map_err(ReasoningError::Storage)?;
133        let mut cursor = Rdf12OccurrenceCursor::new(
134            roots,
135            access,
136            LiteralRole::TargetContext,
137            self.config.target.traversal,
138        );
139        while let Some(occurrence) = cursor.next().await.map_err(Rdfs12ContextError::Traversal)? {
140            let descriptor = access
141                .container_property(&occurrence.term, self.config.target.iri_bytes)
142                .await
143                .map_err(|error| Rdfs12ContextError::Vocabulary {
144                    occurrence: occurrence.clone(),
145                    error,
146                })?;
147            let Some(descriptor) = descriptor else {
148                continue;
149            };
150            if descriptor.iri().len() > self.config.target.iri_bytes.get() as usize {
151                return Err(Rdfs12ContextError::VocabularyLimit);
152            }
153            let resolved = store
154                .resolve_iri(descriptor.iri())
155                .await
156                .map_err(ReasoningError::Storage)?;
157            if resolved != occurrence.term {
158                return Err(Rdfs12ContextError::VocabularyIdentity);
159            }
160            seeds.seed_container(store, &descriptor).await?;
161        }
162        Ok(())
163    }
164}