inference_engine/reasoning/
proposition.rs1use super::{
2 Evidence, Inference, Limit, Rdf12TripleTermStore, ReasoningError, ReasoningStore, TripleCursor,
3 TripleSource,
4 plan::{Bindings, PropositionClause},
5};
6use rdf_reasoning::Rdf12PropositionRuleId;
7use serde::{Deserialize, Serialize};
8use std::num::NonZeroU64;
9
10#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
12#[serde(deny_unknown_fields)]
13pub struct PropositionLimits {
14 inferred: NonZeroU64,
15 matches: NonZeroU64,
16}
17impl PropositionLimits {
18 pub const fn new(inferred: NonZeroU64, matches: NonZeroU64) -> Self {
20 Self { inferred, matches }
21 }
22}
23
24#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
26#[serde(deny_unknown_fields)]
27pub struct PropositionReport {
28 pub matches: u64,
30 pub inferred: u64,
32}
33
34pub struct Rdf12PropositionConstructor {
41 limits: PropositionLimits,
42}
43impl Rdf12PropositionConstructor {
44 pub const fn new(limits: PropositionLimits) -> Self {
46 Self { limits }
47 }
48
49 pub async fn run<S: Rdf12TripleTermStore>(
60 &self,
61 store: &mut S,
62 ) -> Result<PropositionReport, ReasoningError<S::Error>> {
63 Self::cancel(store)?;
64 let clause = PropositionClause::compile(Rdf12PropositionRuleId::Grdfs14, store).await?;
65 let source = store.snapshot().await.map_err(ReasoningError::Storage)?;
66 let mut report = PropositionReport::default();
67 let empty = std::array::from_fn(|_| None);
68 let mut first = source
69 .scan(clause.body[0].probe(&empty))
70 .await
71 .map_err(ReasoningError::Storage)?;
72 while let Some(a) = self.next(&mut first, store, &mut report).await? {
73 let Some(bindings) = clause.body[0].bind(&a, empty.clone()) else {
74 continue;
75 };
76 let mut second = source
77 .scan(clause.body[1].probe(&bindings))
78 .await
79 .map_err(ReasoningError::Storage)?;
80 while let Some(b) = self.next(&mut second, store, &mut report).await? {
81 let Some(bindings) = clause.body[1].bind(&b, bindings.clone()) else {
82 continue;
83 };
84 let mut third = source
85 .scan(clause.body[2].probe(&bindings))
86 .await
87 .map_err(ReasoningError::Storage)?;
88 while let Some(c) = self.next(&mut third, store, &mut report).await? {
89 let Some(bindings) = clause.body[2].bind(&c, bindings.clone()) else {
90 continue;
91 };
92 self.emit(
93 &clause,
94 &bindings,
95 [a.clone(), b.clone(), c],
96 store,
97 &mut report,
98 )
99 .await?;
100 }
101 }
102 }
103 Self::cancel(store)?;
104 Ok(report)
105 }
106 pub async fn run_candidates<S, C>(
124 &self,
125 store: &mut S,
126 candidates: &mut C,
127 ) -> Result<PropositionReport, ReasoningError<S::Error>>
128 where
129 S: Rdf12TripleTermStore,
130 C: TripleCursor<Term = S::Term, Error = S::Error>,
131 {
132 let mut phase = self.begin(store).await?;
133 while let Some(candidate) = self.next(candidates, store, &mut phase.report).await? {
134 phase.candidate(store, candidate).await?;
135 }
136 Self::cancel(store)?;
137 Ok(phase.report)
138 }
139 pub(super) async fn begin<S: Rdf12TripleTermStore>(
140 &self,
141 store: &mut S,
142 ) -> Result<PropositionPhase<S::Snapshot>, ReasoningError<S::Error>> {
143 Self::cancel(store)?;
144 let clause = PropositionClause::compile(Rdf12PropositionRuleId::Grdfs14, store).await?;
145 let source = store.snapshot().await.map_err(ReasoningError::Storage)?;
146 Ok(PropositionPhase {
147 constructor: Self::new(self.limits),
148 clause,
149 source,
150 report: PropositionReport::default(),
151 })
152 }
153 async fn emit<S: Rdf12TripleTermStore>(
154 &self,
155 clause: &PropositionClause<S::Term>,
156 bindings: &Bindings<S::Term>,
157 premises: [[S::Term; 3]; 3],
158 store: &mut S,
159 report: &mut PropositionReport,
160 ) -> Result<(), ReasoningError<S::Error>> {
161 Self::cancel(store)?;
162 let quoted = clause
163 .triple
164 .ground(bindings)
165 .ok_or(ReasoningError::UnsupportedPropositionRule(clause.id))?;
166 let term = store
167 .resolve_triple_term(quoted)
168 .await
169 .map_err(ReasoningError::Storage)?;
170 let triple = [term, clause.predicate.clone(), clause.object.clone()];
171 if store
172 .contains(&triple)
173 .await
174 .map_err(ReasoningError::Storage)?
175 {
176 return Ok(());
177 }
178 Self::cancel(store)?;
179 if report.inferred == self.limits.inferred.get() {
180 return Err(ReasoningError::LimitExceeded(Limit::Inferred));
181 }
182 if store
183 .insert_inferred(Inference {
184 triple,
185 evidence: Evidence::Proposition {
186 rule: clause.id,
187 premises,
188 },
189 })
190 .await
191 .map_err(ReasoningError::Storage)?
192 {
193 report.inferred += 1;
194 }
195 Ok(())
196 }
197 async fn next<S: ReasoningStore, C: TripleCursor<Term = S::Term, Error = S::Error>>(
198 &self,
199 cursor: &mut C,
200 store: &mut S,
201 report: &mut PropositionReport,
202 ) -> Result<Option<[S::Term; 3]>, ReasoningError<S::Error>> {
203 Self::cancel(store)?;
204 let row = cursor.next().await.map_err(ReasoningError::Storage)?;
205 if row.is_some() {
206 self.charge(store, report).await?;
207 }
208 Ok(row)
209 }
210 async fn charge<S: ReasoningStore>(
211 &self,
212 store: &mut S,
213 report: &mut PropositionReport,
214 ) -> Result<(), ReasoningError<S::Error>> {
215 Self::cancel(store)?;
216 if report.matches == self.limits.matches.get() {
217 return Err(ReasoningError::LimitExceeded(Limit::Matches));
218 }
219 report.matches += 1;
220 crate::cooperative::checkpoint(report.matches).await;
221 Self::cancel(store)
222 }
223 fn cancel<S: ReasoningStore>(store: &S) -> Result<(), ReasoningError<S::Error>> {
224 if store.is_cancelled() {
225 Err(ReasoningError::Cancelled)
226 } else {
227 Ok(())
228 }
229 }
230}
231
232pub(super) struct PropositionPhase<P: TripleSource> {
234 constructor: Rdf12PropositionConstructor,
235 clause: PropositionClause<P::Term>,
236 source: P,
237 pub(super) report: PropositionReport,
238}
239impl<P: TripleSource> PropositionPhase<P> {
240 pub(super) fn source(&self) -> &P {
241 &self.source
242 }
243 pub(super) async fn candidate<S>(
244 &mut self,
245 store: &mut S,
246 candidate: [P::Term; 3],
247 ) -> Result<(), ReasoningError<P::Error>>
248 where
249 S: Rdf12TripleTermStore<Term = P::Term, Error = P::Error>,
250 {
251 Rdf12PropositionConstructor::cancel(store)?;
252 let clause = &self.clause;
253 let bindings = clause
254 .triple
255 .bind(&candidate, std::array::from_fn(|_| None))
256 .ok_or(ReasoningError::UnsupportedPropositionRule(clause.id))?;
257 let mut premises = std::array::from_fn(|_| candidate.clone());
259 for (index, pattern) in clause.body.iter().enumerate() {
260 let premise = pattern
261 .ground(&bindings)
262 .ok_or(ReasoningError::UnsupportedPropositionRule(clause.id))?;
263 let mut probe = self
264 .source
265 .scan(premise.clone().map(Some))
266 .await
267 .map_err(ReasoningError::Storage)?;
268 let mut found = false;
269 while let Some(row) = self
270 .constructor
271 .next(&mut probe, store, &mut self.report)
272 .await?
273 {
274 if row != premise {
275 return Err(ReasoningError::InvalidProbe);
276 }
277 found = true;
278 }
279 if !found {
280 return Ok(());
281 }
282 premises[index] = premise;
283 }
284 self.constructor
285 .emit(clause, &bindings, premises, store, &mut self.report)
286 .await
287 }
288 pub(super) async fn selected<S>(
289 &mut self,
290 store: &mut S,
291 candidate: [P::Term; 3],
292 ) -> Result<(), ReasoningError<P::Error>>
293 where
294 S: Rdf12TripleTermStore<Term = P::Term, Error = P::Error>,
295 {
296 self.constructor.charge(store, &mut self.report).await?;
297 self.candidate(store, candidate).await
298 }
299}