Skip to main content

inference_engine/entailment/
matcher.rs

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