Skip to main content

inference_engine/reasoning/
engine.rs

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