Skip to main content

inference_engine/reasoning/
engine.rs

1use super::{
2    Evidence, ExecutionProfile, Inference, Limit, Premises, ReasoningError, ReasoningStore,
3    RunLimits, RunReport, TripleCursor, TripleSource,
4    plan::{Bindings, Body, Clause},
5};
6
7/// One native, storage-independent executor for the named RDF/RDFS profiles.
8pub struct Reasoner {
9    profile: ExecutionProfile,
10    limits: RunLimits,
11}
12
13impl Reasoner {
14    /// Select an exact supported profile and explicit resource limits.
15    pub const fn new(profile: ExecutionProfile, limits: RunLimits) -> Self {
16        Self { profile, limits }
17    }
18    /// Exact selected execution contract.
19    pub const fn profile(&self) -> ExecutionProfile {
20        self.profile
21    }
22    /// Implementation package version to record alongside input/profile identity.
23    pub const fn implementation_version(&self) -> &'static str {
24        env!("CARGO_PKG_VERSION")
25    }
26    /// Pinned semantic rule catalogue identity for inference provenance.
27    pub const fn rule_catalogue(&self) -> &'static str {
28        env!("INFERENCE_ENGINE_RULE_CATALOGUE")
29    }
30
31    /// Derive into caller-owned scratch until a fixpoint, retaining bounded state.
32    ///
33    /// Memory is at most fourteen clauses, fixed-size bindings and two active cursors
34    /// per join. Each round reads an immutable view; inserted tuples become
35    /// join inputs next round. Stores must implement indexed probes and disk spill.
36    ///
37    /// # Errors
38    /// Cancellation, resource exhaustion, unsupported shared rule shapes or any
39    /// storage failure abort the run. Staged output must then be discarded.
40    pub async fn run<S: ReasoningStore>(
41        &self,
42        store: &mut S,
43    ) -> Result<RunReport, ReasoningError<S::Error>> {
44        Self::check_cancelled(store)?;
45        // bounded: the executable shared selections contain at most fourteen clauses.
46        let mut clauses = Vec::with_capacity(self.profile.rules().len());
47        for &rule in self.profile.rules() {
48            clauses.push(Clause::compile(rule, store).await?);
49        }
50        let mut report = RunReport::default();
51        loop {
52            Self::check_cancelled(store)?;
53            if report.rounds == self.limits.rounds.get() {
54                return Err(ReasoningError::LimitExceeded(Limit::Rounds));
55            }
56            report.rounds += 1;
57            let snapshot = store.snapshot().await.map_err(ReasoningError::Storage)?;
58            let before = report.inferred;
59            for clause in &clauses {
60                self.evaluate(clause, &snapshot, store, &mut report).await?;
61            }
62            Self::check_cancelled(store)?;
63            if report.inferred == before {
64                return Ok(report);
65            }
66        }
67    }
68
69    async fn evaluate<S: ReasoningStore>(
70        &self,
71        clause: &Clause<S::Term>,
72        source: &S::Snapshot,
73        store: &mut S,
74        report: &mut RunReport,
75    ) -> Result<(), ReasoningError<S::Error>> {
76        let empty = std::array::from_fn(|_| None);
77        let mut outer = source
78            .scan(clause.body.first().probe(&empty))
79            .await
80            .map_err(ReasoningError::Storage)?;
81        while let Some(first) = self.next(&mut outer, store, report).await? {
82            let Some(bindings) = clause.body.first().bind(&first, empty.clone()) else {
83                continue;
84            };
85            let Body::Two([_, second_pattern]) = &clause.body else {
86                self.emit(clause, &bindings, Premises::One(first), store, report)
87                    .await?;
88                continue;
89            };
90            let mut inner = source
91                .scan(second_pattern.probe(&bindings))
92                .await
93                .map_err(ReasoningError::Storage)?;
94            while let Some(second) = self.next(&mut inner, store, report).await? {
95                let Some(bindings) = second_pattern.bind(&second, bindings.clone()) else {
96                    continue;
97                };
98                self.emit(
99                    clause,
100                    &bindings,
101                    Premises::Two([first.clone(), second]),
102                    store,
103                    report,
104                )
105                .await?;
106            }
107        }
108        Ok(())
109    }
110
111    async fn emit<S: ReasoningStore>(
112        &self,
113        clause: &Clause<S::Term>,
114        bindings: &Bindings<S::Term>,
115        premises: Premises<S::Term>,
116        store: &mut S,
117        report: &mut RunReport,
118    ) -> Result<(), ReasoningError<S::Error>> {
119        let triple = clause
120            .head
121            .ground(bindings)
122            .ok_or(ReasoningError::UnsupportedRule(clause.id))?;
123        if store
124            .contains(&triple)
125            .await
126            .map_err(ReasoningError::Storage)?
127        {
128            return Ok(());
129        }
130        Self::check_cancelled(store)?;
131        if report.inferred == self.limits.inferred.get() {
132            return Err(ReasoningError::LimitExceeded(Limit::Inferred));
133        }
134        let inference = Inference {
135            triple,
136            evidence: Evidence::Rule {
137                rule: clause.id,
138                premises,
139            },
140        };
141        if store
142            .insert_inferred(inference)
143            .await
144            .map_err(ReasoningError::Storage)?
145        {
146            report.inferred += 1;
147        }
148        Ok(())
149    }
150
151    async fn next<S: ReasoningStore, C: TripleCursor<Term = S::Term, Error = S::Error>>(
152        &self,
153        cursor: &mut C,
154        store: &mut S,
155        report: &mut RunReport,
156    ) -> Result<Option<[S::Term; 3]>, ReasoningError<S::Error>> {
157        Self::check_cancelled(store)?;
158        let tuple = cursor.next().await.map_err(ReasoningError::Storage)?;
159        if tuple.is_some() {
160            if report.matches == self.limits.matches.get() {
161                return Err(ReasoningError::LimitExceeded(Limit::Matches));
162            }
163            report.matches += 1;
164            crate::cooperative::checkpoint(report.matches).await;
165            Self::check_cancelled(store)?;
166        }
167        Ok(tuple)
168    }
169
170    fn check_cancelled<S: ReasoningStore>(store: &S) -> Result<(), ReasoningError<S::Error>> {
171        if store.is_cancelled() {
172            Err(ReasoningError::Cancelled)
173        } else {
174            Ok(())
175        }
176    }
177}