Skip to main content

inference_engine/reasoning/
occurrence.rs

1use super::{LiteralRole, TripleCursor};
2use crate::entailment::EntailmentTerms;
3use serde::{Deserialize, Serialize};
4use std::{
5    error::Error,
6    fmt,
7    num::{NonZeroU32, NonZeroU64},
8};
9
10/// One position in an asserted or nested subject/predicate/object triple.
11#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
12pub enum TermPosition {
13    /// Subject position.
14    Subject,
15    /// Predicate position, including predicates inside triple terms.
16    Predicate,
17    /// Object position.
18    Object,
19}
20impl TermPosition {
21    fn at(index: u8) -> Self {
22        match index {
23            0 => Self::Subject,
24            1 => Self::Predicate,
25            2 => Self::Object,
26            _ => unreachable!("triple position"),
27        }
28    }
29}
30
31/// Nonempty structural path from a selected root triple to an appearing term.
32#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
33#[serde(deny_unknown_fields)]
34pub struct OccurrencePath {
35    root: TermPosition,
36    nested: Vec<TermPosition>,
37}
38impl OccurrencePath {
39    /// A direct term position in the selected root triple.
40    pub const fn root(position: TermPosition) -> Self {
41        Self {
42            root: position,
43            nested: Vec::new(),
44        }
45    }
46    /// Iterate the root position followed by zero or more nested positions.
47    pub fn positions(&self) -> impl DoubleEndedIterator<Item = &TermPosition> {
48        std::iter::once(&self.root).chain(self.nested.iter())
49    }
50    fn is_predicate(&self) -> bool {
51        self.nested.last().unwrap_or(&self.root) == &TermPosition::Predicate
52    }
53}
54
55/// An actual term appearance, retaining its selected root, path and semantic role.
56#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
57#[serde(deny_unknown_fields)]
58pub struct TermOccurrence<T> {
59    /// Exact term key, including scoped blanks and triple terms themselves.
60    pub term: T,
61    /// Original selected root; nested triple contents are not asserted roots.
62    pub root: [T; 3],
63    /// Actual enclosing triple; a nested parent is not an asserted RDF premise.
64    pub parent: [T; 3],
65    /// Source and target appearances must remain separate capabilities.
66    pub role: LiteralRole,
67    /// Nonempty path through actual triple structure, never literal metadata.
68    pub path: OccurrencePath,
69}
70impl<T> TermOccurrence<T> {
71    /// Whether this occurrence occupies a root or nested predicate position.
72    pub fn is_predicate(&self) -> bool {
73        self.path.is_predicate()
74    }
75}
76
77/// Explicit bounds on traversal depth, emitted appearances and total read work.
78#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
79#[serde(deny_unknown_fields)]
80pub struct OccurrenceLimits {
81    depth: NonZeroU32,
82    occurrences: NonZeroU64,
83    steps: NonZeroU64,
84}
85impl OccurrenceLimits {
86    /// Depth counts path positions, so one permits only non-triple root terms.
87    /// Steps count root-cursor reads and authoritative term decompositions.
88    pub const fn new(depth: NonZeroU32, occurrences: NonZeroU64, steps: NonZeroU64) -> Self {
89        Self {
90            depth,
91            occurrences,
92            steps,
93        }
94    }
95}
96
97/// Incomplete traversal; never interpret errors as absent terms or end of stream.
98#[derive(Debug)]
99pub enum OccurrenceError<E> {
100    /// Root scan or authoritative term access failed.
101    Storage(E),
102    /// Attempt cancelled or superseded.
103    Cancelled,
104    /// Another nested frame would exceed the explicit path-depth budget.
105    DepthLimit,
106    /// Another emitted appearance would exceed its budget.
107    OccurrenceLimit,
108    /// Another root read or term lookup would exceed its work budget.
109    StepLimit,
110}
111impl<E: fmt::Display> fmt::Display for OccurrenceError<E> {
112    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113        match self {
114            Self::Storage(error) => write!(f, "occurrence access failed: {error}"),
115            Self::Cancelled => f.write_str("occurrence traversal cancelled"),
116            Self::DepthLimit => f.write_str("occurrence path depth limit exceeded"),
117            Self::OccurrenceLimit => f.write_str("occurrence count limit exceeded"),
118            Self::StepLimit => f.write_str("occurrence work limit exceeded"),
119        }
120    }
121}
122impl<E: Error + 'static> Error for OccurrenceError<E> {
123    fn source(&self) -> Option<&(dyn Error + 'static)> {
124        match self {
125            Self::Storage(error) => Some(error),
126            _ => None,
127        }
128    }
129}
130
131struct Frame<T> {
132    triple: [T; 3],
133    next: u8,
134}
135
136/// Stream actual RDF term/predicate appearances with bounded iterative traversal.
137///
138/// Reuses the asynchronous structural accessor used by simple entailment. A
139/// backend cache miss must load authoritative structure or fail; `None` means
140/// a supported atomic term, never an evicted or unsupported triple term.
141/// Literal datatype/language/direction metadata are not traversed as RDF terms.
142///
143/// Supply an immutable root cursor for one selected scope and role. Source
144/// assertions/derived facts and target context are separately scheduled by the
145/// controller. This cursor performs no entailment, datatype typing, property
146/// typing, constructor execution or graph writes. After any error discard the
147/// traversal and all semantic output based on its incomplete appearances.
148pub struct Rdf12OccurrenceCursor<'a, A: EntailmentTerms, C: TripleCursor> {
149    roots: C,
150    terms: &'a A,
151    role: LiteralRole,
152    limits: OccurrenceLimits,
153    root: Option<[A::Term; 3]>,
154    // bounded: one three-key frame per explicitly capped path depth.
155    frames: Vec<Frame<A::Term>>,
156    occurrences: u64,
157    steps: u64,
158    finished: bool,
159    current_triple_term: bool,
160}
161impl<'a, A, C> Rdf12OccurrenceCursor<'a, A, C>
162where
163    A: EntailmentTerms,
164    C: TripleCursor<Term = A::Term, Error = A::Error>,
165{
166    /// Bind one immutable selected root cursor and exact shared term dictionary.
167    /// Keep snapshot/source-graph provenance alongside returned root/path records.
168    pub fn new(roots: C, terms: &'a A, role: LiteralRole, limits: OccurrenceLimits) -> Self {
169        Self {
170            roots,
171            terms,
172            role,
173            limits,
174            root: None,
175            frames: Vec::new(),
176            occurrences: 0,
177            steps: 0,
178            finished: false,
179            current_triple_term: false,
180        }
181    }
182    /// Explicit source/target role selected before any traversal I/O.
183    pub const fn role(&self) -> LiteralRole {
184        self.role
185    }
186
187    // The structural lookup performed by next() classifies its last emitted term.
188    // This reuses authoritative metadata without another read or unmetered lookup.
189    pub(super) const fn current_is_triple_term(&self) -> bool {
190        self.current_triple_term
191    }
192
193    /// Emit one actual appearance, revisiting repeated keys at distinct paths.
194    ///
195    /// # Errors
196    /// Backend, cancellation and explicit traversal budgets abort the attempt.
197    /// Nested cycles cannot exhaust the call stack: depth/work caps fail first.
198    pub async fn next(
199        &mut self,
200    ) -> Result<Option<TermOccurrence<A::Term>>, OccurrenceError<A::Error>> {
201        self.cancel()?;
202        if self.finished {
203            return Ok(None);
204        }
205        loop {
206            if self.frames.is_empty() {
207                self.step().await?;
208                let Some(root) = self.roots.next().await.map_err(OccurrenceError::Storage)? else {
209                    self.cancel()?;
210                    self.finished = true;
211                    return Ok(None);
212                };
213                self.root = Some(root.clone());
214                self.frames.push(Frame {
215                    triple: root,
216                    next: 0,
217                });
218            }
219            let frame = self.frames.last_mut().expect("root frame exists");
220            if frame.next == 3 {
221                self.frames.pop();
222                continue;
223            }
224            let parent = frame.triple.clone();
225            let term = frame.triple[usize::from(frame.next)].clone();
226            frame.next += 1;
227            if self.occurrences == self.limits.occurrences.get() {
228                return Err(OccurrenceError::OccurrenceLimit);
229            }
230            self.step().await?;
231            let nested = self
232                .terms
233                .triple_term(&term)
234                .await
235                .map_err(OccurrenceError::Storage)?;
236            self.cancel()?;
237            // bounded: path is at most the configured number of retained frames.
238            let path = OccurrencePath {
239                root: TermPosition::at(self.frames[0].next - 1),
240                nested: self
241                    .frames
242                    .iter()
243                    .skip(1)
244                    .map(|frame| TermPosition::at(frame.next - 1))
245                    .collect(),
246            };
247            self.current_triple_term = nested.is_some();
248            if let Some(triple) = nested {
249                if self.frames.len() == self.limits.depth.get() as usize {
250                    return Err(OccurrenceError::DepthLimit);
251                }
252                self.frames.push(Frame { triple, next: 0 });
253            }
254            self.occurrences += 1;
255            return Ok(Some(TermOccurrence {
256                term,
257                parent,
258                root: self.root.clone().expect("selected root exists"),
259                role: self.role,
260                path,
261            }));
262        }
263    }
264    async fn step(&mut self) -> Result<(), OccurrenceError<A::Error>> {
265        self.cancel()?;
266        if self.steps == self.limits.steps.get() {
267            return Err(OccurrenceError::StepLimit);
268        }
269        self.steps += 1;
270        crate::cooperative::checkpoint(self.steps).await;
271        self.cancel()
272    }
273    fn cancel(&self) -> Result<(), OccurrenceError<A::Error>> {
274        if self.terms.is_cancelled() {
275            Err(OccurrenceError::Cancelled)
276        } else {
277            Ok(())
278        }
279    }
280}