Skip to main content

inference_engine/entailment/
matcher.rs

1use super::{EntailmentError, EntailmentLimits, EntailmentReport, EntailmentTerms};
2use crate::reasoning::{TripleCursor, TripleSource};
3use std::future::{Future, Ready};
4
5type Unfiltered<T, E> = fn([T; 3]) -> Ready<Result<bool, EntailmentError<E>>>;
6
7/// Source-to-target simple entailment by consistent existential graph matching.
8pub struct SimpleEntailment {
9    limits: EntailmentLimits,
10}
11
12struct Frame<C> {
13    cursor: C,
14    checkpoint: usize,
15}
16pub(super) struct State {
17    pub(super) limits: EntailmentLimits,
18    pub(super) steps: u64,
19}
20
21impl SimpleEntailment {
22    /// Select finite target, binding, recursive-worklist and work budgets.
23    pub const fn new(limits: EntailmentLimits) -> Self {
24        Self { limits }
25    }
26
27    /// Decide whether the source graph contains one instance of the target.
28    ///
29    /// Source/target snapshots and term identity must be immutable for the whole
30    /// call. Source triples are streamed through indexed scans. Only explicitly
31    /// capped target patterns, bindings, owned cursors and term pairs are retained.
32    /// Triple terms are decomposed for substitution and never added as assertions.
33    ///
34    /// # Errors
35    /// Any read failure, cancellation or exhausted cap aborts the decision.
36    /// Resource exhaustion must never be interpreted as non-entailment.
37    pub async fn check<S, Q, A>(
38        &self,
39        source: &S,
40        target: &Q,
41        terms: &A,
42    ) -> Result<EntailmentReport, EntailmentError<S::Error>>
43    where
44        S: TripleSource,
45        Q: TripleSource<Term = S::Term, Error = S::Error>,
46        A: EntailmentTerms<Term = S::Term, Error = S::Error>,
47    {
48        self.check_selected(
49            source,
50            target,
51            terms,
52            None::<Unfiltered<S::Term, S::Error>>,
53            0,
54        )
55        .await
56    }
57
58    // Selection is internal to checked controllers. Meter every raw row and each
59    // metadata selection, even when no pattern will be retained. No second matcher.
60    pub(crate) async fn check_selected<S, Q, A, F, Fut>(
61        &self,
62        source: &S,
63        target: &Q,
64        terms: &A,
65        mut select: Option<F>,
66        initial_steps: u64,
67    ) -> Result<EntailmentReport, EntailmentError<S::Error>>
68    where
69        S: TripleSource,
70        Q: TripleSource<Term = S::Term, Error = S::Error>,
71        A: EntailmentTerms<Term = S::Term, Error = S::Error>,
72        F: FnMut([S::Term; 3]) -> Fut,
73        Fut: Future<Output = Result<bool, EntailmentError<S::Error>>>,
74    {
75        if initial_steps > self.limits.steps.get() {
76            return Err(EntailmentError::StepLimit);
77        }
78        let mut state = State {
79            limits: self.limits,
80            steps: initial_steps,
81        };
82        state.step(terms).await?;
83        let mut cursor = target
84            .scan([None, None, None])
85            .await
86            .map_err(EntailmentError::Storage)?;
87        // bounded: reject before retaining more than limits.patterns target tuples.
88        let mut patterns = Vec::new();
89        loop {
90            state.step(terms).await?;
91            let tuple = cursor.next().await.map_err(EntailmentError::Storage)?;
92            state.cancel(terms)?;
93            let Some(tuple) = tuple else {
94                break;
95            };
96            if let Some(select) = &mut select {
97                state.step(terms).await?;
98                let keep = select(tuple.clone()).await?;
99                state.cancel(terms)?;
100                if !keep {
101                    continue;
102                }
103            }
104            if patterns.len() == self.limits.patterns.get() as usize {
105                return Err(EntailmentError::TargetLimit);
106            }
107            patterns.push(tuple);
108        }
109        drop(cursor);
110        if patterns.is_empty() {
111            return Ok(state.report(true, 0));
112        }
113        // bounded: limits.bindings caps retained existential assignments before insertion.
114        let mut bindings = Vec::new();
115        // bounded: one owned cursor per capped target pattern; no source relation is collected.
116        let mut frames = Vec::new();
117        let probe = state.probe(&patterns[0], &bindings, terms).await?;
118        state.step(terms).await?;
119        frames.push(Frame {
120            cursor: source.scan(probe).await.map_err(EntailmentError::Storage)?,
121            checkpoint: 0,
122        });
123        while let Some(frame) = frames.last_mut() {
124            bindings.truncate(frame.checkpoint);
125            state.step(terms).await?;
126            let tuple = frame
127                .cursor
128                .next()
129                .await
130                .map_err(EntailmentError::Storage)?;
131            state.cancel(terms)?;
132            let Some(tuple) = tuple else {
133                frames.pop();
134                continue;
135            };
136            let index = frames.len() - 1;
137            if !state
138                .bind(&patterns[index], &tuple, &mut bindings, terms)
139                .await?
140            {
141                continue;
142            }
143            if index + 1 == patterns.len() {
144                return Ok(state.report(true, patterns.len() as u32));
145            }
146            let probe = state.probe(&patterns[index + 1], &bindings, terms).await?;
147            state.step(terms).await?;
148            frames.push(Frame {
149                cursor: source.scan(probe).await.map_err(EntailmentError::Storage)?,
150                checkpoint: bindings.len(),
151            });
152        }
153        state.cancel(terms)?;
154        Ok(state.report(false, patterns.len() as u32))
155    }
156}
157
158impl State {
159    fn report(&self, entailed: bool, target_triples: u32) -> EntailmentReport {
160        EntailmentReport {
161            entailed,
162            target_triples,
163            steps: self.steps,
164        }
165    }
166    fn cancel<A: EntailmentTerms>(&self, terms: &A) -> Result<(), EntailmentError<A::Error>> {
167        if terms.is_cancelled() {
168            Err(EntailmentError::Cancelled)
169        } else {
170            Ok(())
171        }
172    }
173    pub(super) async fn step<A: EntailmentTerms>(
174        &mut self,
175        terms: &A,
176    ) -> Result<(), EntailmentError<A::Error>> {
177        self.cancel(terms)?;
178        if self.steps == self.limits.steps.get() {
179            return Err(EntailmentError::StepLimit);
180        }
181        self.steps += 1;
182        crate::cooperative::checkpoint(self.steps).await;
183        self.cancel(terms)
184    }
185    pub(super) async fn probe<A: EntailmentTerms>(
186        &mut self,
187        pattern: &[A::Term; 3],
188        bindings: &[(A::Term, A::Term)],
189        terms: &A,
190    ) -> Result<[Option<A::Term>; 3], EntailmentError<A::Error>> {
191        let mut probe = [None, None, None];
192        for (index, term) in pattern.iter().enumerate() {
193            self.step(terms).await?;
194            if terms
195                .is_blank(term)
196                .await
197                .map_err(EntailmentError::Storage)?
198            {
199                probe[index] = bindings
200                    .iter()
201                    .find(|(key, _)| key == term)
202                    .map(|(_, value)| value.clone());
203            } else if terms
204                .triple_term(term)
205                .await
206                .map_err(EntailmentError::Storage)?
207                .is_none()
208            {
209                probe[index] = Some(term.clone());
210            }
211            self.cancel(terms)?;
212        }
213        Ok(probe)
214    }
215    pub(super) async fn bind<A: EntailmentTerms>(
216        &mut self,
217        pattern: &[A::Term; 3],
218        tuple: &[A::Term; 3],
219        bindings: &mut Vec<(A::Term, A::Term)>,
220        terms: &A,
221    ) -> Result<bool, EntailmentError<A::Error>> {
222        // bounded: limits.terms caps pending pairs, including the initial three slots.
223        let mut pending = Vec::new();
224        self.push_pairs(&mut pending, pattern, tuple)?;
225        while let Some((target, candidate)) = pending.pop() {
226            self.step(terms).await?;
227            if terms
228                .is_blank(&target)
229                .await
230                .map_err(EntailmentError::Storage)?
231            {
232                if let Some((_, value)) = bindings.iter().find(|(key, _)| key == &target) {
233                    if value != &candidate {
234                        return Ok(false);
235                    }
236                } else {
237                    if bindings.len() == self.limits.bindings.get() as usize {
238                        return Err(EntailmentError::BindingLimit);
239                    }
240                    bindings.push((target, candidate));
241                }
242            } else if let Some(target) = terms
243                .triple_term(&target)
244                .await
245                .map_err(EntailmentError::Storage)?
246            {
247                let Some(candidate) = terms
248                    .triple_term(&candidate)
249                    .await
250                    .map_err(EntailmentError::Storage)?
251                else {
252                    return Ok(false);
253                };
254                self.push_pairs(&mut pending, &target, &candidate)?;
255            } else if target != candidate {
256                return Ok(false);
257            }
258            self.cancel(terms)?;
259        }
260        Ok(true)
261    }
262    fn push_pairs<T: Clone, E>(
263        &self,
264        pending: &mut Vec<(T, T)>,
265        target: &[T; 3],
266        candidate: &[T; 3],
267    ) -> Result<(), EntailmentError<E>> {
268        if pending.len().saturating_add(3) > self.limits.terms.get() as usize {
269            return Err(EntailmentError::TermLimit);
270        }
271        for (target, candidate) in target.iter().zip(candidate).rev() {
272            pending.push((target.clone(), candidate.clone()));
273        }
274        Ok(())
275    }
276}