Skip to main content

inference_engine/reasoning/
literal.rs

1use rdf_reasoning::{Rdf12Datatype, Rdf12LexicalError};
2use rdf_structural_model::{LiteralMetadata, ModelError};
3use serde::{Deserialize, Serialize};
4use std::{error::Error, fmt, future::Future};
5
6const CHUNK: usize = 4096;
7
8/// One immutable literal's metadata and independently streamed UTF-8 payload.
9///
10/// Opening this reader is adapter-owned: retain exact source term identity and
11/// graph occurrence separately. Metadata access is pure and must not read the
12/// lexical payload. Implementations may borrow metadata without allocating it.
13pub trait LiteralReader: Send {
14    /// Backend payload-read failure.
15    type Error: Error + Send + Sync + 'static;
16    /// Borrow standard metadata, including original language spelling/direction.
17    fn metadata(&self) -> LiteralMetadata<&str>;
18    /// Fill at most the supplied buffer, returning zero only at successful EOF.
19    ///
20    /// UTF-8 scalars may straddle reads. Errors and cancellation must never be
21    /// disguised as EOF; drop must release/cancel the underlying read.
22    fn read(
23        &mut self,
24        output: &mut [u8],
25    ) -> impl Future<Output = Result<usize, Self::Error>> + Send;
26    /// Whether the enclosing inference attempt was cancelled or superseded.
27    fn is_cancelled(&self) -> bool;
28}
29
30/// Successful lexical inspection, without allocating or normalizing the literal.
31#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
32#[serde(deny_unknown_fields)]
33pub struct LiteralReport {
34    /// Recognized default datatype; `None` means an encountered opaque datatype.
35    /// Opaque does not mean ill-typed, nor does it extend the recognized map.
36    pub datatype: Option<Rdf12Datatype>,
37    /// Exact lexical UTF-8 byte count, after verifying successful EOF.
38    pub bytes: u64,
39}
40
41/// One shared lexical violation found in a fully inspected payload.
42#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
43#[serde(deny_unknown_fields)]
44pub struct LexicalViolation {
45    /// Global start of the fragment containing the first violation.
46    pub fragment_offset: u64,
47    /// Shared invalid character and fragment-relative byte offset.
48    pub error: Rdf12LexicalError,
49}
50
51/// Complete payload inspection, including a possible semantic lexical violation.
52/// Transport, UTF-8, metadata, cancellation and budget failures are errors instead.
53#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
54#[serde(deny_unknown_fields)]
55pub struct LiteralInspection {
56    /// Exact datatype recognition and byte count after successful EOF.
57    pub report: LiteralReport,
58    /// First recognized lexical violation; unknown datatypes remain opaque.
59    pub violation: Option<LexicalViolation>,
60}
61
62/// Bounded lexical inspection under the three mandatory RDF 1.2 datatypes.
63///
64/// Uses shared structural metadata checks and `rdf-reasoning` lexical semantics.
65/// Unknown encountered datatypes remain opaque. This does not implement datatype
66/// value comparison or graph-wide consistency and never rewrites a source term.
67pub struct Rdf12LiteralValidator {
68    maximum: u64,
69}
70
71impl Rdf12LiteralValidator {
72    /// Set a strict byte budget, including opaque datatype payloads. A zero
73    /// budget permits only an empty lexical form, verified through an EOF probe.
74    pub const fn new(maximum: u64) -> Self {
75        Self { maximum }
76    }
77
78    /// Validate metadata, then stream the lexical form using 4099 bytes of scratch.
79    ///
80    /// No whole literal is retained. At most three incomplete UTF-8 bytes carry
81    /// between reads. An exact byte budget permits the final EOF probe; exceeding
82    /// it fails. Callers separately budget total attempt work across literals.
83    ///
84    /// # Errors
85    /// Invalid standard metadata, invalid UTF-8, a recognized lexical violation,
86    /// cancellation, resource exhaustion or a backend error abort inspection.
87    /// A lexical violation is semantic evidence about this literal; it does not
88    /// certify graph inconsistency or authorize publishing a partial inference.
89    pub async fn validate<R: LiteralReader>(
90        &self,
91        reader: &mut R,
92    ) -> Result<LiteralReport, LiteralError<R::Error>> {
93        let inspection = self.inspect(reader).await?;
94        if let Some(violation) = inspection.violation {
95            return Err(LiteralError::Lexical {
96                fragment_offset: violation.fragment_offset,
97                error: violation.error,
98            });
99        }
100        Ok(inspection.report)
101    }
102
103    /// Inspect the entire payload, retaining only its first shared lexical violation.
104    ///
105    /// A semantic diagnostic is returned only after successful UTF-8 inspection
106    /// through EOF. Later transport/cancellation/resource errors invalidate it.
107    /// Scratch stays fixed at 4099 bytes plus one violation, even for huge values.
108    ///
109    /// # Errors
110    /// Invalid metadata/UTF-8, storage, cancellation or byte/reader limits abort.
111    pub async fn inspect<R: LiteralReader>(
112        &self,
113        reader: &mut R,
114    ) -> Result<LiteralInspection, LiteralError<R::Error>> {
115        Self::check_cancelled(reader)?;
116        let datatype = {
117            let metadata = reader.metadata();
118            metadata
119                .validate_standard()
120                .map_err(LiteralError::Metadata)?;
121            Rdf12Datatype::recognize_iri(metadata.datatype().as_str())
122        };
123        // bounded: one 4096-byte read plus at most three incomplete UTF-8 bytes.
124        let mut buffer = [0_u8; CHUNK + 3];
125        let mut pending = 0;
126        let mut bytes = 0_u64;
127        let mut offset = 0_u64;
128        let mut read_steps = 0_u64;
129        let mut violation = None;
130        loop {
131            Self::check_cancelled(reader)?;
132            let remaining = self.maximum - bytes;
133            let capacity = remaining.saturating_add(1).min(CHUNK as u64) as usize;
134            let count = reader
135                .read(&mut buffer[pending..pending + capacity])
136                .await
137                .map_err(LiteralError::Storage)?;
138            Self::check_cancelled(reader)?;
139            if count > capacity {
140                return Err(LiteralError::ReadContract);
141            }
142            // Bounded scheduling counter; aggregate byte accounting stays exact below.
143            read_steps = (read_steps + 1) % crate::cooperative::QUANTUM;
144            crate::cooperative::checkpoint(read_steps).await;
145            Self::check_cancelled(reader)?;
146            if count as u64 > remaining {
147                return Err(LiteralError::ByteLimit);
148            }
149            bytes = bytes
150                .checked_add(count as u64)
151                .ok_or(LiteralError::LengthOverflow)?;
152            if count == 0 {
153                return if pending == 0 {
154                    Ok(LiteralInspection {
155                        report: LiteralReport { datatype, bytes },
156                        violation,
157                    })
158                } else {
159                    Err(LiteralError::Utf8 {
160                        byte_offset: offset,
161                    })
162                };
163            }
164            let length = pending + count;
165            let valid = match std::str::from_utf8(&buffer[..length]) {
166                Ok(_) => length,
167                Err(error) if error.error_len().is_none() => error.valid_up_to(),
168                Err(error) => {
169                    let byte_offset = offset
170                        .checked_add(error.valid_up_to() as u64)
171                        .ok_or(LiteralError::LengthOverflow)?;
172                    return Err(LiteralError::Utf8 { byte_offset });
173                }
174            };
175            let fragment = std::str::from_utf8(&buffer[..valid])
176                .expect("UTF-8 decoder's valid prefix must be UTF-8");
177            if violation.is_none()
178                && let Some(datatype) = datatype
179                && let Err(error) = datatype.validate_lexical(fragment)
180            {
181                violation = Some(LexicalViolation {
182                    fragment_offset: offset,
183                    error,
184                });
185            }
186            offset = offset
187                .checked_add(valid as u64)
188                .ok_or(LiteralError::LengthOverflow)?;
189            buffer.copy_within(valid..length, 0);
190            pending = length - valid;
191        }
192    }
193
194    fn check_cancelled<R: LiteralReader>(reader: &R) -> Result<(), LiteralError<R::Error>> {
195        if reader.is_cancelled() {
196            Err(LiteralError::Cancelled)
197        } else {
198            Ok(())
199        }
200    }
201}
202
203/// Failed literal inspection; backend failures remain distinct from semantics.
204#[derive(Debug)]
205pub enum LiteralError<E> {
206    /// Payload access failed.
207    Storage(E),
208    /// Standard datatype/facet pairing is invalid or an extension is unsupported.
209    Metadata(ModelError),
210    /// Malformed UTF-8 or an incomplete scalar at EOF, at a global byte offset.
211    Utf8 {
212        /// Start of the malformed byte sequence in the lexical payload.
213        byte_offset: u64,
214    },
215    /// Shared recognized-datatype lexical violation, without changing its witness.
216    Lexical {
217        /// Global start of the fragment; add the shared error's relative offset.
218        fragment_offset: u64,
219        /// Shared semantics' invalid character and fragment-relative byte offset.
220        error: Rdf12LexicalError,
221    },
222    /// The literal exceeded its explicit lexical byte budget.
223    ByteLimit,
224    /// A reader reported more bytes than the supplied buffer could hold.
225    ReadContract,
226    /// Lexical byte accounting exceeded the supported u64 range.
227    LengthOverflow,
228    /// Caller cancelled or superseded the enclosing attempt.
229    Cancelled,
230}
231
232impl<E: fmt::Display> fmt::Display for LiteralError<E> {
233    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
234        match self {
235            Self::Storage(error) => write!(f, "literal storage failed: {error}"),
236            Self::Metadata(error) => write!(f, "unsupported standard literal metadata: {error}"),
237            Self::Utf8 { byte_offset } => write!(f, "invalid lexical UTF-8 at byte {byte_offset}"),
238            Self::Lexical {
239                fragment_offset,
240                error,
241            } => write!(
242                f,
243                "literal fragment starting at byte {fragment_offset}: {error}"
244            ),
245            Self::ByteLimit => f.write_str("literal lexical byte limit exceeded"),
246            Self::ReadContract => f.write_str("literal reader exceeded its supplied buffer"),
247            Self::LengthOverflow => f.write_str("literal byte count overflow"),
248            Self::Cancelled => f.write_str("literal inspection cancelled"),
249        }
250    }
251}
252
253impl<E: Error + 'static> Error for LiteralError<E> {
254    fn source(&self) -> Option<&(dyn Error + 'static)> {
255        match self {
256            Self::Storage(error) => Some(error),
257            Self::Metadata(error) => Some(error),
258            Self::Lexical { error, .. } => Some(error),
259            _ => None,
260        }
261    }
262}