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(source, target, terms, None::<Unfiltered<S::Term, S::Error>>)
49            .await
50    }
51
52    // Selection is internal to checked controllers. Meter every raw row and each
53    // metadata selection, even when no pattern will be retained. No second matcher.
54    pub(crate) async fn check_selected<S, Q, A, F, Fut>(
55        &self,
56        source: &S,
57        target: &Q,
58        terms: &A,
59        mut select: Option<F>,
60    ) -> Result<EntailmentReport, EntailmentError<S::Error>>
61    where
62        S: TripleSource,
63        Q: TripleSource<Term = S::Term, Error = S::Error>,
64        A: EntailmentTerms<Term = S::Term, Error = S::Error>,
65        F: FnMut([S::Term; 3]) -> Fut,
66        Fut: Future<Output = Result<bool, EntailmentError<S::Error>>>,
67    {
68        let mut state = State {
69            limits: self.limits,
70            steps: 0,
71        };
72        state.step(terms).await?;
73        let mut cursor = target
74            .scan([None, None, None])
75            .await
76            .map_err(EntailmentError::Storage)?;
77        // bounded: reject before retaining more than limits.patterns target tuples.
78        let mut patterns = Vec::new();
79        loop {
80            state.step(terms).await?;
81            let tuple = cursor.next().await.map_err(EntailmentError::Storage)?;
82            state.cancel(terms)?;
83            let Some(tuple) = tuple else {
84                break;
85            };
86            if let Some(select) = &mut select {
87                state.step(terms).await?;
88                let keep = select(tuple.clone()).await?;
89                state.cancel(terms)?;
90                if !keep {
91                    continue;
92                }
93            }
94            if patterns.len() == self.limits.patterns.get() as usize {
95                return Err(EntailmentError::TargetLimit);
96            }
97            patterns.push(tuple);
98        }
99        drop(cursor);
100        if patterns.is_empty() {
101            return Ok(state.report(true, 0));
102        }
103        // bounded: limits.bindings caps retained existential assignments before insertion.
104        let mut bindings = Vec::new();
105        // bounded: one owned cursor per capped target pattern; no source relation is collected.
106        let mut frames = Vec::new();
107        let probe = state.probe(&patterns[0], &bindings, terms).await?;
108        state.step(terms).await?;
109        frames.push(Frame {
110            cursor: source.scan(probe).await.map_err(EntailmentError::Storage)?,
111            checkpoint: 0,
112        });
113        while let Some(frame) = frames.last_mut() {
114            bindings.truncate(frame.checkpoint);
115            state.step(terms).await?;
116            let tuple = frame
117                .cursor
118                .next()
119                .await
120                .map_err(EntailmentError::Storage)?;
121            state.cancel(terms)?;
122            let Some(tuple) = tuple else {
123                frames.pop();
124                continue;
125            };
126            let index = frames.len() - 1;
127            if !state
128                .bind(&patterns[index], &tuple, &mut bindings, terms)
129                .await?
130            {
131                continue;
132            }
133            if index + 1 == patterns.len() {
134                return Ok(state.report(true, patterns.len() as u32));
135            }
136            let probe = state.probe(&patterns[index + 1], &bindings, terms).await?;
137            state.step(terms).await?;
138            frames.push(Frame {
139                cursor: source.scan(probe).await.map_err(EntailmentError::Storage)?,
140                checkpoint: bindings.len(),
141            });
142        }
143        state.cancel(terms)?;
144        Ok(state.report(false, patterns.len() as u32))
145    }
146}
147
148impl State {
149    fn report(&self, entailed: bool, target_triples: u32) -> EntailmentReport {
150        EntailmentReport {
151            entailed,
152            target_triples,
153            steps: self.steps,
154        }
155    }
156    fn cancel<A: EntailmentTerms>(&self, terms: &A) -> Result<(), EntailmentError<A::Error>> {
157        if terms.is_cancelled() {
158            Err(EntailmentError::Cancelled)
159        } else {
160            Ok(())
161        }
162    }
163    pub(super) async fn step<A: EntailmentTerms>(
164        &mut self,
165        terms: &A,
166    ) -> Result<(), EntailmentError<A::Error>> {
167        self.cancel(terms)?;
168        if self.steps == self.limits.steps.get() {
169            return Err(EntailmentError::StepLimit);
170        }
171        self.steps += 1;
172        crate::cooperative::checkpoint(self.steps).await;
173        self.cancel(terms)
174    }
175    pub(super) async fn probe<A: EntailmentTerms>(
176        &mut self,
177        pattern: &[A::Term; 3],
178        bindings: &[(A::Term, A::Term)],
179        terms: &A,
180    ) -> Result<[Option<A::Term>; 3], EntailmentError<A::Error>> {
181        let mut probe = [None, None, None];
182        for (index, term) in pattern.iter().enumerate() {
183            self.step(terms).await?;
184            if terms
185                .is_blank(term)
186                .await
187                .map_err(EntailmentError::Storage)?
188            {
189                probe[index] = bindings
190                    .iter()
191                    .find(|(key, _)| key == term)
192                    .map(|(_, value)| value.clone());
193            } else if terms
194                .triple_term(term)
195                .await
196                .map_err(EntailmentError::Storage)?
197                .is_none()
198            {
199                probe[index] = Some(term.clone());
200            }
201            self.cancel(terms)?;
202        }
203        Ok(probe)
204    }
205    pub(super) async fn bind<A: EntailmentTerms>(
206        &mut self,
207        pattern: &[A::Term; 3],
208        tuple: &[A::Term; 3],
209        bindings: &mut Vec<(A::Term, A::Term)>,
210        terms: &A,
211    ) -> Result<bool, EntailmentError<A::Error>> {
212        // bounded: limits.terms caps pending pairs, including the initial three slots.
213        let mut pending = Vec::new();
214        self.push_pairs(&mut pending, pattern, tuple)?;
215        while let Some((target, candidate)) = pending.pop() {
216            self.step(terms).await?;
217            if terms
218                .is_blank(&target)
219                .await
220                .map_err(EntailmentError::Storage)?
221            {
222                if let Some((_, value)) = bindings.iter().find(|(key, _)| key == &target) {
223                    if value != &candidate {
224                        return Ok(false);
225                    }
226                } else {
227                    if bindings.len() == self.limits.bindings.get() as usize {
228                        return Err(EntailmentError::BindingLimit);
229                    }
230                    bindings.push((target, candidate));
231                }
232            } else if let Some(target) = terms
233                .triple_term(&target)
234                .await
235                .map_err(EntailmentError::Storage)?
236            {
237                let Some(candidate) = terms
238                    .triple_term(&candidate)
239                    .await
240                    .map_err(EntailmentError::Storage)?
241                else {
242                    return Ok(false);
243                };
244                self.push_pairs(&mut pending, &target, &candidate)?;
245            } else if target != candidate {
246                return Ok(false);
247            }
248            self.cancel(terms)?;
249        }
250        Ok(true)
251    }
252    fn push_pairs<T: Clone, E>(
253        &self,
254        pending: &mut Vec<(T, T)>,
255        target: &[T; 3],
256        candidate: &[T; 3],
257    ) -> Result<(), EntailmentError<E>> {
258        if pending.len().saturating_add(3) > self.limits.terms.get() as usize {
259            return Err(EntailmentError::TermLimit);
260        }
261        for (target, candidate) in target.iter().zip(candidate).rev() {
262            pending.push((target.clone(), candidate.clone()));
263        }
264        Ok(())
265    }
266}