Skip to main content

inference_engine/reasoning/literal_typing/
mod.rs

1mod cursor;
2mod engine;
3use super::{LiteralError, LiteralReader, OccurrencePath, ReasoningError};
4pub use cursor::{LiteralCursorError, LiteralTermAccess, Rdf12LiteralOccurrences};
5pub use engine::Rdf12LiteralTyper;
6use serde::{Deserialize, Serialize};
7use std::{error::Error, fmt, future::Future, num::NonZeroU64};
8
9/// Explicit semantic phase: selected source data or isolated target context.
10#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
11pub enum LiteralRole {
12    /// A literal appearing in the selected immutable source graph.
13    Source,
14    /// A literal in the target-relative entailment context, separate from source consistency.
15    TargetContext,
16}
17
18/// One selected literal occurrence, including literals nested inside triple terms.
19///
20/// Root term keys retain their complete structure in the adapter's immutable
21/// dictionary. Input snapshot and logical graph provenance remain caller-owned.
22#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
23#[serde(deny_unknown_fields)]
24pub struct LiteralOccurrence<T> {
25    /// Exact literal term key; do not normalize or reconstruct its lexical form.
26    pub literal: T,
27    /// Root triple in which the literal occurs directly or recursively.
28    pub root: [T; 3],
29    /// Semantic phase owning this occurrence.
30    pub role: LiteralRole,
31    /// Exact direct or nested position within the selected root.
32    pub path: OccurrencePath,
33}
34
35/// A fallible cursor step containing one occurrence and independently advanced reader.
36pub type LiteralOccurrenceRead<T, R, E> =
37    Result<Option<(LiteralOccurrence<T>, R)>, LiteralCursorError<T, E>>;
38
39/// Streaming capability over selected immutable literal occurrences and readers.
40///
41/// The adapter supplies every relevant direct/recursive occurrence for one phase.
42/// Each reader must describe its occurrence's exact literal. Preserve selection,
43/// blank scope, and root/graph provenance; never hydrate all literals or expose
44/// a previous closure as new input. This is separate from RDF assertion scans:
45/// an RDF predicate spelling cannot manufacture a semantic metadata premise.
46pub trait LiteralOccurrenceCursor: Send {
47    /// Exact term identities shared with inference scratch storage.
48    type Term: Clone + Eq + Send + Sync;
49    /// Cursor/read failure.
50    type Error: Error + Send + Sync + 'static;
51    /// Reader for one immutable literal, independent of scratch writes.
52    /// It may borrow the immutable accessor for the cursor's lifetime.
53    type Reader: LiteralReader<Error = Self::Error>;
54    /// Return one occurrence and reader; zero remaining rows must mean successful EOF.
55    fn next(
56        &mut self,
57    ) -> impl Future<Output = LiteralOccurrenceRead<Self::Term, Self::Reader, Self::Error>> + Send;
58}
59
60/// Aggregate resource budgets for one literal-typing phase.
61#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
62#[serde(deny_unknown_fields)]
63pub struct LiteralTypingLimits {
64    pub(super) occurrences: NonZeroU64,
65    pub(super) inferred: NonZeroU64,
66    pub(super) bytes: u64,
67}
68impl LiteralTypingLimits {
69    /// Bound examined occurrences, novel inferred tuples and total lexical bytes.
70    /// A zero byte budget admits only empty payloads. Limits never truncate output.
71    pub const fn new(occurrences: NonZeroU64, inferred: NonZeroU64, bytes: u64) -> Self {
72        Self {
73            occurrences,
74            inferred,
75            bytes,
76        }
77    }
78}
79
80/// Completed literal-typing counters, returned only after successful cursor EOF.
81#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
82#[serde(deny_unknown_fields)]
83pub struct LiteralTypingReport {
84    /// Examined selected occurrences, including duplicate literal keys.
85    pub occurrences: u64,
86    /// Exact total lexical byte count, including opaque datatypes and duplicates.
87    pub bytes: u64,
88    /// Valid encountered literals outside the recognized default datatype map.
89    pub opaque: u64,
90    /// Novel generalized typing tuples; asserted/inferred duplicates are excluded.
91    pub inferred: u64,
92}
93
94/// Aborted semantic phase; staged facts must remain unpublished.
95#[derive(Debug)]
96pub enum LiteralTypingError<T, E> {
97    /// Cursor traversal/opening failed, retaining structural evidence when known.
98    Cursor(LiteralCursorError<T, E>),
99    /// Shared clause compilation, storage, cancellation or output-budget failure.
100    Reasoning(ReasoningError<E>),
101    /// Examination of another literal would exceed the occurrence budget.
102    OccurrenceLimit,
103    /// Cursor supplied an occurrence from a different semantic phase.
104    RoleMismatch {
105        /// Configured phase.
106        expected: LiteralRole,
107        /// Rejected occurrence, retained without reading its payload.
108        occurrence: LiteralOccurrence<T>,
109    },
110    /// Literal inspection failed, retaining identity and source/target role.
111    Literal {
112        /// Exact selected occurrence whose inspection failed.
113        occurrence: LiteralOccurrence<T>,
114        /// Metadata, lexical, UTF-8, resource, cancellation or storage diagnostic.
115        error: LiteralError<E>,
116    },
117}
118impl<T, E: fmt::Display> fmt::Display for LiteralTypingError<T, E> {
119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120        match self {
121            Self::Cursor(error) => error.fmt(f),
122            Self::Reasoning(error) => error.fmt(f),
123            Self::OccurrenceLimit => f.write_str("literal occurrence limit exceeded"),
124            Self::RoleMismatch {
125                expected,
126                occurrence,
127            } => write!(
128                f,
129                "expected {expected:?} literal role, received {:?}",
130                occurrence.role
131            ),
132            Self::Literal { occurrence, error } => write!(
133                f,
134                "{:?} literal inspection failed: {error}",
135                occurrence.role
136            ),
137        }
138    }
139}
140impl<T: fmt::Debug, E: Error + 'static> Error for LiteralTypingError<T, E> {
141    fn source(&self) -> Option<&(dyn Error + 'static)> {
142        match self {
143            Self::Cursor(error) => error.source(),
144            Self::Reasoning(error) => Some(error),
145            Self::Literal { error, .. } => Some(error),
146            _ => None,
147        }
148    }
149}