Skip to main content

inference_engine/reasoning/
seeding.rs

1use super::{
2    AxiomFamily, Evidence, Inference, Limit, Rdf12WitnessStore, ReasoningError, ReasoningStore,
3};
4use datalog_structural_model::{Rule, Term};
5use rdf_reasoning::{
6    Rdf12AxiomId, Rdf12ContainerProperty, Rdf12ExistentialAxiomId, TRIPLE_RELATION,
7};
8use std::num::NonZeroU64;
9
10/// Explicit bounded seeding of shared RDF 1.2 axioms into fresh attempt storage.
11///
12/// This is independent of structural-rule profile selection and does not claim
13/// full RDFS entailment. The caller chooses source/target-relevant container
14/// vocabulary; this type never enumerates infinite `rdf:_n` IRIs or scans a graph.
15/// Select `_1` where required by the standard's target-entailment procedure.
16///
17/// One instance budgets all its seed calls cumulatively. Rule execution has its
18/// own output budget; callers must also enforce an attempt-wide scratch budget.
19/// On any failure discard the attempt, including all successfully staged seeds.
20pub struct Rdf12AxiomSeeder {
21    maximum: NonZeroU64,
22    inferred: u64,
23}
24
25impl Rdf12AxiomSeeder {
26    /// Set the maximum total novel axiom tuples across this seeder's calls.
27    pub const fn new(maximum: NonZeroU64) -> Self {
28        Self {
29            maximum,
30            inferred: 0,
31        }
32    }
33
34    /// Total newly staged axiom tuples; asserted/inferred duplicates are excluded.
35    pub const fn inferred(&self) -> u64 {
36        self.inferred
37    }
38
39    /// Stage one finite shared family, preserving exact family and ground tuple.
40    ///
41    /// # Errors
42    /// Storage failure, cancellation, unsupported definitions or exhausted output
43    /// budget abort the attempt. Successful prior writes remain unpublished scratch.
44    pub async fn seed_family<S: ReasoningStore>(
45        &mut self,
46        store: &mut S,
47        family: Rdf12AxiomId,
48    ) -> Result<(), ReasoningError<S::Error>> {
49        Self::check_cancelled(store)?;
50        // bounded: each fixed standard family has at most 41 ground definitions.
51        for rule in family.definitions() {
52            self.seed_rule(store, &rule, AxiomFamily::Rdf12(family))
53                .await?;
54        }
55        Self::check_cancelled(store)
56    }
57
58    /// Stage the four shared RDF/RDFS axioms for one already checked container IRI.
59    ///
60    /// The caller supplies relevant vocabulary incrementally, including target
61    /// vocabulary when checking entailment. Merely seeding observed input IRIs is
62    /// insufficient to implement arbitrary source-to-target entailment.
63    ///
64    /// # Errors
65    /// Storage failure, cancellation, unsupported definitions or exhausted output
66    /// budget abort the entire attempt; partial seeds must never be promoted.
67    pub async fn seed_container<S: ReasoningStore, I: AsRef<str>>(
68        &mut self,
69        store: &mut S,
70        container: &Rdf12ContainerProperty<I>,
71    ) -> Result<(), ReasoningError<S::Error>> {
72        Self::check_cancelled(store)?;
73        self.seed_rule(
74            store,
75            &container.rdf_definition(),
76            AxiomFamily::Rdf12Container,
77        )
78        .await?;
79        for rule in container.rdfs_definitions() {
80            self.seed_rule(store, &rule, AxiomFamily::Rdf12Container)
81                .await?;
82        }
83        Self::check_cancelled(store)
84    }
85
86    /// Stage one shared nonempty-class membership using a caller-owned blank.
87    ///
88    /// RDF uses the three `rdfD1a` descriptors; RDFS also uses `rdfs14a`.
89    /// Repeated calls reuse the attempt's stored witness. Distinct blank keys
90    /// imply neither unequal denotations nor a unique-name assumption. Preserve
91    /// attempt/snapshot identity alongside descriptor and ground membership.
92    ///
93    /// # Errors
94    /// Unsupported allocation, storage failure, cancellation or exhausted output
95    /// budget aborts the entire attempt; partial witnesses must not be promoted.
96    pub async fn seed_existential<S: Rdf12WitnessStore>(
97        &mut self,
98        store: &mut S,
99        id: Rdf12ExistentialAxiomId,
100    ) -> Result<(), ReasoningError<S::Error>> {
101        Self::check_cancelled(store)?;
102        let blank = store
103            .resolve_existential_blank(id)
104            .await
105            .map_err(ReasoningError::Storage)?;
106        let predicate = store
107            .resolve_iri("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")
108            .await
109            .map_err(ReasoningError::Storage)?;
110        let class = store
111            .resolve_iri(id.class_iri())
112            .await
113            .map_err(ReasoningError::Storage)?;
114        self.stage(
115            store,
116            [blank, predicate, class],
117            AxiomFamily::Rdf12Existential(id),
118        )
119        .await
120    }
121
122    async fn seed_rule<S: ReasoningStore>(
123        &mut self,
124        store: &mut S,
125        rule: &Rule,
126        family: AxiomFamily,
127    ) -> Result<(), ReasoningError<S::Error>> {
128        Self::check_cancelled(store)?;
129        let head = rule
130            .head
131            .as_atom()
132            .ok_or(ReasoningError::UnsupportedAxiom)?;
133        let [Term::Constant(s), Term::Constant(p), Term::Constant(o)] = head.terms.as_slice()
134        else {
135            return Err(ReasoningError::UnsupportedAxiom);
136        };
137        if !rule.body.is_empty() || head.predicate.as_str() != TRIPLE_RELATION {
138            return Err(ReasoningError::UnsupportedAxiom);
139        }
140        let triple = [
141            store
142                .resolve_iri(s.as_str())
143                .await
144                .map_err(ReasoningError::Storage)?,
145            store
146                .resolve_iri(p.as_str())
147                .await
148                .map_err(ReasoningError::Storage)?,
149            store
150                .resolve_iri(o.as_str())
151                .await
152                .map_err(ReasoningError::Storage)?,
153        ];
154        self.stage(store, triple, family).await
155    }
156
157    async fn stage<S: ReasoningStore>(
158        &mut self,
159        store: &mut S,
160        triple: [S::Term; 3],
161        family: AxiomFamily,
162    ) -> Result<(), ReasoningError<S::Error>> {
163        Self::check_cancelled(store)?;
164        if store
165            .contains(&triple)
166            .await
167            .map_err(ReasoningError::Storage)?
168        {
169            return Self::check_cancelled(store);
170        }
171        Self::check_cancelled(store)?;
172        if self.inferred == self.maximum.get() {
173            return Err(ReasoningError::LimitExceeded(Limit::Inferred));
174        }
175        if store
176            .insert_inferred(Inference {
177                triple,
178                evidence: Evidence::Axiom(family),
179            })
180            .await
181            .map_err(ReasoningError::Storage)?
182        {
183            self.inferred += 1;
184        }
185        Self::check_cancelled(store)
186    }
187
188    fn check_cancelled<S: ReasoningStore>(store: &S) -> Result<(), ReasoningError<S::Error>> {
189        if store.is_cancelled() {
190            Err(ReasoningError::Cancelled)
191        } else {
192            Ok(())
193        }
194    }
195}