Skip to main content

inference_engine/reasoning/source/
engine.rs

1use super::{
2    Rdf12ContainerAccess, Rdfs12SourceConfig, Rdfs12SourceError, Rdfs12SourceOutcome,
3    Rdfs12SourceReport,
4};
5use crate::reasoning::{
6    ExecutionProfile, LiteralRole, LiteralTermAccess, Rdf12AxiomSeeder,
7    Rdf12DatatypeConflictChecker, Rdf12LiteralOccurrences, Rdf12LiteralTyper,
8    Rdf12OccurrenceCursor, Rdf12OccurrenceTyper, Rdf12PropositionConstructor,
9    Rdf12SourceDiagnosticSink, Rdf12TripleTermStore, Rdf12WitnessStore, Reasoner, ReasoningError,
10    ReasoningStore, TripleCursor, TripleSource,
11};
12use rdf_reasoning::{Rdf12AxiomId, Rdf12ContainerProperty, Rdf12ExistentialAxiomId};
13use std::marker::PhantomData;
14
15/// Compose bounded source-only RDF/RDFS default-map preparation phases.
16///
17/// Start a fresh selected asserted snapshot; never expose prior closure or target
18/// context as source input. All scratch remains caller-owned and unpublished.
19/// Existing appearing triple terms are typed through the shared constructor;
20/// arbitrary resource/property combinations are not generated. Target-relative
21/// candidate completeness, goal scheduling and entailment decisions stay separate.
22pub struct Rdfs12Source {
23    pub(super) config: Rdfs12SourceConfig,
24}
25impl Rdfs12Source {
26    /// Configure every phase explicitly; the serialized config has no defaults.
27    pub const fn new(config: Rdfs12SourceConfig) -> Self {
28        Self { config }
29    }
30
31    /// Prepare source axioms, inspected literals, occurrences, existing terms and core.
32    ///
33    /// First inspect every original source literal through successful EOF. Retain
34    /// recognized lexical violations separately and return `Conflicting` without
35    /// seeding or inference. Read/metadata/UTF-8/resource failures remain errors.
36    /// Otherwise repeat bounded source rounds until no phase adds facts. Classify canonical
37    /// container IRIs from actual direct/nested source appearances, not literal
38    /// metadata. Seed distinct nonempty-class blanks through the caller's scope.
39    /// Only then scan supported default-map conflicts into the separate sink.
40    ///
41    /// `Prepared` is not a source-to-target decision or a full consistency
42    /// certificate. Check input currentness and the complete requested semantic
43    /// contract before atomic promotion; `Conflicting` forbids promotion.
44    ///
45    /// # Errors
46    /// Any compile/read/write/metadata/UTF-8/cancellation or resource failure
47    /// invalidates the attempt. Discard scratch and retain diagnostics with scope.
48    pub async fn run<S, A, D>(
49        &self,
50        store: &mut S,
51        access: &A,
52        sink: &mut D,
53    ) -> Result<Rdfs12SourceOutcome, Rdfs12SourceError<S::Term, S::Error>>
54    where
55        S: Rdf12WitnessStore + Rdf12TripleTermStore,
56        A: LiteralTermAccess<Term = S::Term, Error = S::Error> + Rdf12ContainerAccess,
57        D: Rdf12SourceDiagnosticSink<Term = S::Term, Error = S::Error>,
58    {
59        let mut report = self.inspect_source(store, access, sink).await?;
60        if report.diagnostics != 0 {
61            return Ok(Rdfs12SourceOutcome::Conflicting(report));
62        }
63        let mut seeds = Rdf12AxiomSeeder::new(self.config.axioms);
64        for family in [
65            Rdf12AxiomId::Rdf,
66            Rdf12AxiomId::Rdfs,
67            Rdf12AxiomId::DefaultDatatypes,
68        ] {
69            seeds.seed_family(store, family).await?;
70        }
71        for &id in Rdf12ExistentialAxiomId::ALL {
72            seeds.seed_existential(store, id).await?;
73        }
74        let first =
75            Rdf12ContainerProperty::try_new("http://www.w3.org/1999/02/22-rdf-syntax-ns#_1")
76                .expect("canonical standard container IRI");
77        seeds.seed_container(store, &first).await?;
78        report.seeded = seeds.inferred();
79        report.inferred = seeds.inferred();
80        loop {
81            if report.rounds == self.config.rounds.get() {
82                return Err(Rdfs12SourceError::Rounds);
83            }
84            report.rounds += 1;
85            let before = report.inferred;
86            self.vocabulary(store, access, &mut seeds).await?;
87            Rdfs12SourceReport::add(&mut report.inferred, seeds.inferred() - report.seeded)?;
88            report.seeded = seeds.inferred();
89            self.literals(store, access, &mut report).await?;
90            let roots = store
91                .snapshot()
92                .await
93                .map_err(ReasoningError::Storage)?
94                .scan([None, None, None])
95                .await
96                .map_err(ReasoningError::Storage)?;
97            let mut cursor = Rdf12OccurrenceCursor::new(
98                roots,
99                access,
100                LiteralRole::Source,
101                self.config.traversal,
102            );
103            let typed =
104                Rdf12OccurrenceTyper::new(self.config.structural.inferred, LiteralRole::Source)
105                    .run(store, &mut cursor)
106                    .await
107                    .map_err(Rdfs12SourceError::Occurrences)?;
108            Rdfs12SourceReport::add(&mut report.inferred, typed.inferred)?;
109            self.propositions(store, access, &mut report).await?;
110            let core = Reasoner::new(ExecutionProfile::RdfsCore, self.config.structural)
111                .run(store)
112                .await?;
113            Rdfs12SourceReport::add(&mut report.inferred, core.inferred)?;
114            if report.inferred == before {
115                break;
116            }
117        }
118        let conflicts = Rdf12DatatypeConflictChecker::new(self.config.conflicts)
119            .run(
120                store,
121                LiteralRole::Source,
122                &mut super::diagnostic::ConflictSink(sink),
123            )
124            .await
125            .map_err(Rdfs12SourceError::Conflicts)?;
126        report.diagnostics = conflicts.diagnostics;
127        Ok(if report.diagnostics == 0 {
128            Rdfs12SourceOutcome::Prepared(report)
129        } else {
130            Rdfs12SourceOutcome::Conflicting(report)
131        })
132    }
133    async fn vocabulary<S, A>(
134        &self,
135        store: &mut S,
136        access: &A,
137        seeds: &mut Rdf12AxiomSeeder,
138    ) -> Result<(), Rdfs12SourceError<S::Term, S::Error>>
139    where
140        S: ReasoningStore,
141        A: Rdf12ContainerAccess<Term = S::Term, Error = S::Error>,
142    {
143        let roots = store
144            .snapshot()
145            .await
146            .map_err(ReasoningError::Storage)?
147            .scan([None, None, None])
148            .await
149            .map_err(ReasoningError::Storage)?;
150        let mut cursor =
151            Rdf12OccurrenceCursor::new(roots, access, LiteralRole::Source, self.config.traversal);
152        while let Some(occurrence) = cursor.next().await.map_err(Rdfs12SourceError::Traversal)? {
153            let descriptor = access
154                .container_property(&occurrence.term, self.config.iri_bytes)
155                .await
156                .map_err(|error| Rdfs12SourceError::Vocabulary {
157                    occurrence: occurrence.clone(),
158                    error,
159                })?;
160            let Some(descriptor) = descriptor else {
161                continue;
162            };
163            if descriptor.iri().len() > self.config.iri_bytes.get() as usize {
164                return Err(Rdfs12SourceError::VocabularyLimit);
165            }
166            let resolved = store
167                .resolve_iri(descriptor.iri())
168                .await
169                .map_err(ReasoningError::Storage)?;
170            if resolved != occurrence.term {
171                return Err(Rdfs12SourceError::VocabularyIdentity);
172            }
173            seeds.seed_container(store, &descriptor).await?;
174        }
175        Ok(())
176    }
177    async fn literals<S, A>(
178        &self,
179        store: &mut S,
180        access: &A,
181        report: &mut Rdfs12SourceReport,
182    ) -> Result<(), Rdfs12SourceError<S::Term, S::Error>>
183    where
184        S: ReasoningStore,
185        A: LiteralTermAccess<Term = S::Term, Error = S::Error>,
186    {
187        let roots = store
188            .snapshot()
189            .await
190            .map_err(ReasoningError::Storage)?
191            .scan([None, None, None])
192            .await
193            .map_err(ReasoningError::Storage)?;
194        let mut cursor =
195            Rdf12LiteralOccurrences::new(roots, access, LiteralRole::Source, self.config.traversal);
196        let typed = Rdf12LiteralTyper::new(self.config.literals, LiteralRole::Source)
197            .run(store, &mut cursor)
198            .await
199            .map_err(Rdfs12SourceError::Literals)?;
200        Rdfs12SourceReport::add(&mut report.inferred, typed.inferred)?;
201        Rdfs12SourceReport::add(&mut report.literals, typed.occurrences)?;
202        Rdfs12SourceReport::add(&mut report.lexical_bytes, typed.bytes)
203    }
204    async fn propositions<S, A>(
205        &self,
206        store: &mut S,
207        access: &A,
208        report: &mut Rdfs12SourceReport,
209    ) -> Result<(), Rdfs12SourceError<S::Term, S::Error>>
210    where
211        S: Rdf12TripleTermStore,
212        A: crate::entailment::EntailmentTerms<Term = S::Term, Error = S::Error>,
213    {
214        let roots = store
215            .snapshot()
216            .await
217            .map_err(ReasoningError::Storage)?
218            .scan([None, None, None])
219            .await
220            .map_err(ReasoningError::Storage)?;
221        let mut cursor =
222            Rdf12OccurrenceCursor::new(roots, access, LiteralRole::Source, self.config.traversal);
223        while let Some(occurrence) = cursor.next().await.map_err(Rdfs12SourceError::Traversal)? {
224            let Some(triple) = access
225                .triple_term(&occurrence.term)
226                .await
227                .map_err(ReasoningError::Storage)?
228            else {
229                continue;
230            };
231            let canonical = store
232                .resolve_triple_term(triple.clone())
233                .await
234                .map_err(ReasoningError::Storage)?;
235            if canonical != occurrence.term {
236                return Err(Rdfs12SourceError::PropositionIdentity);
237            }
238            let mut candidate = Candidate::<_, S::Error> {
239                triple: Some(triple),
240                error: PhantomData,
241            };
242            let typed = Rdf12PropositionConstructor::new(self.config.propositions)
243                .run_candidates(store, &mut candidate)
244                .await?;
245            Rdfs12SourceReport::add(&mut report.inferred, typed.inferred)?;
246        }
247        Ok(())
248    }
249}
250struct Candidate<T, E> {
251    triple: Option<[T; 3]>,
252    error: PhantomData<fn() -> E>,
253}
254impl<T: Clone + Eq + Send + Sync, E: std::error::Error + Send + Sync + 'static> TripleCursor
255    for Candidate<T, E>
256{
257    type Term = T;
258    type Error = E;
259    async fn next(&mut self) -> Result<Option<[T; 3]>, E> {
260        Ok(self.triple.take())
261    }
262}