Skip to main content

engram_parser/
error.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! Hand-rolled error types for `engram-parser`.
4//!
5//! Zero external dependencies: no `thiserror`, no `anyhow`. Callers may
6//! match on [`ParserError`] variants or rely on the `std::error::Error`
7//! trait for type-erased propagation.
8
9use std::fmt;
10use std::io;
11
12/// Which [`crate::ParseLimits`] field was exhausted.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14pub enum ParseLimitKind {
15    /// [`crate::ParseLimits::max_kv_count`].
16    KvCount,
17    /// [`crate::ParseLimits::max_tensor_count`].
18    TensorCount,
19    /// [`crate::ParseLimits::max_string_bytes`].
20    StringBytes,
21    /// [`crate::ParseLimits::max_array_work_items`].
22    ArrayWorkItems,
23    /// [`crate::ParseLimits::max_tensor_rank`].
24    TensorRank,
25    /// [`crate::ParseLimits::max_metadata_bytes`].
26    MetadataBytes,
27}
28
29impl ParseLimitKind {
30    /// Stable name used in parser errors and tests.
31    pub const fn as_str(self) -> &'static str {
32        match self {
33            Self::KvCount => "max_kv_count",
34            Self::TensorCount => "max_tensor_count",
35            Self::StringBytes => "max_string_bytes",
36            Self::ArrayWorkItems => "max_array_work_items",
37            Self::TensorRank => "max_tensor_rank",
38            Self::MetadataBytes => "max_metadata_bytes",
39        }
40    }
41}
42
43impl fmt::Display for ParseLimitKind {
44    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45        f.write_str(self.as_str())
46    }
47}
48
49/// File-declared field that failed `u64 -> usize` conversion.
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
51pub enum HostSizeField {
52    /// Length prefix of a GGUF string (KV key, string value, or tensor name).
53    StringLen,
54    /// Header `kv_count`.
55    KvCount,
56    /// Header `tensor_count`.
57    TensorCount,
58    /// Tensor directory `n_dims`.
59    TensorRank,
60    /// One tensor dimension.
61    TensorDim,
62    /// Tensor `relative_offset` in the data region.
63    RelativeOffset,
64    /// `general.alignment` layout field.
65    Alignment,
66    /// GGUF array element count.
67    ArrayLen,
68}
69
70impl HostSizeField {
71    /// Stable name used in parser errors and tests.
72    pub const fn as_str(self) -> &'static str {
73        match self {
74            Self::StringLen => "string_len",
75            Self::KvCount => "kv_count",
76            Self::TensorCount => "tensor_count",
77            Self::TensorRank => "tensor_rank",
78            Self::TensorDim => "tensor_dim",
79            Self::RelativeOffset => "relative_offset",
80            Self::Alignment => "general.alignment",
81            Self::ArrayLen => "array_len",
82        }
83    }
84}
85
86impl fmt::Display for HostSizeField {
87    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88        f.write_str(self.as_str())
89    }
90}
91
92/// Unified error type for checkpoint parsing and MoE weight extraction.
93#[derive(Debug)]
94pub enum ParserError {
95    /// The underlying file could not be read.
96    Io {
97        /// Path of the checkpoint being opened.
98        path: String,
99        /// Upstream `std::io::Error`.
100        source: io::Error,
101    },
102    /// The file is not a valid checkpoint (bad magic, unsupported
103    /// version, unknown value type, unexpected Safetensors layout, …).
104    UnsupportedFormat {
105        /// Path of the offending checkpoint.
106        path: String,
107        /// Human-readable explanation.
108        reason: String,
109    },
110    /// A required tensor was not found in the checkpoint.
111    MissingTensor {
112        /// Tensor name (or suffix) that was looked up.
113        name: String,
114        /// Path of the checkpoint.
115        path: String,
116    },
117    /// The checkpoint's on-disk layout is internally inconsistent
118    /// (tensor extends past EOF, element-count overflow, etc.).
119    InvalidLayout {
120        /// Path of the checkpoint.
121        path: String,
122        /// Human-readable explanation.
123        reason: String,
124    },
125    /// An expert index was out of range for the requested block or
126    /// stacked tensor.
127    ExpertOutOfRange {
128        /// Block index that was queried.
129        block: usize,
130        /// Expert index that was queried.
131        expert: usize,
132        /// Number of experts actually available.
133        available: usize,
134    },
135    /// A [`crate::ParseLimits`] budget was exhausted by a file-declared value.
136    LimitExceeded {
137        /// Path of the checkpoint.
138        path: String,
139        /// Budget that was exhausted.
140        limit: ParseLimitKind,
141        /// Declared or accumulated value that exceeded the budget.
142        declared: u64,
143        /// Configured budget for `limit`.
144        budget: u64,
145    },
146    /// A file-declared `u64` could not be represented as a host `usize`.
147    HostSizeOverflow {
148        /// Path of the checkpoint.
149        path: String,
150        /// On-wire field that overflowed.
151        field: HostSizeField,
152        /// Declared value that does not fit in `usize`.
153        value: u64,
154    },
155    /// A tensor name is claimed by more than one Safetensors shard.
156    DuplicateTensorOwnership {
157        /// Tensor name with conflicting owners.
158        name: String,
159        /// Checkpoint-relative shard paths that declare the tensor, sorted.
160        shards: Vec<String>,
161        /// Path of the checkpoint or index being inspected.
162        path: String,
163    },
164    /// An index-referenced Safetensors shard is missing on disk.
165    MissingShard {
166        /// Shard path as declared in the index (checkpoint-relative).
167        shard: String,
168        /// Path of the index or checkpoint that referenced the shard.
169        path: String,
170    },
171    /// The input needs a backend whose cargo feature is not enabled
172    /// (for example Safetensors input without `--features safetensors`).
173    FeatureDisabled {
174        /// Path of the checkpoint.
175        path: String,
176        /// Cargo feature that would enable the backend.
177        feature: &'static str,
178    },
179}
180
181impl ParserError {
182    pub(crate) fn limit_exceeded(
183        path: impl Into<String>,
184        limit: ParseLimitKind,
185        declared: u64,
186        budget: u64,
187    ) -> Self {
188        Self::LimitExceeded {
189            path: path.into(),
190            limit,
191            declared,
192            budget,
193        }
194    }
195
196    pub(crate) fn host_size(path: impl Into<String>, field: HostSizeField, value: u64) -> Self {
197        Self::HostSizeOverflow {
198            path: path.into(),
199            field,
200            value,
201        }
202    }
203}
204
205impl fmt::Display for ParserError {
206    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
207        match self {
208            Self::Io { path, source } => write!(f, "I/O error reading '{path}': {source}"),
209            Self::UnsupportedFormat { path, reason } => {
210                write!(f, "unsupported format in '{path}': {reason}")
211            }
212            Self::MissingTensor { name, path } => {
213                write!(f, "missing tensor '{name}' in '{path}'")
214            }
215            Self::InvalidLayout { path, reason } => {
216                write!(f, "invalid layout in '{path}': {reason}")
217            }
218            Self::ExpertOutOfRange {
219                block,
220                expert,
221                available,
222            } => write!(
223                f,
224                "expert index out of range: block={block}, expert={expert}, available={available}"
225            ),
226            Self::LimitExceeded {
227                path,
228                limit,
229                declared,
230                budget,
231            } => write!(
232                f,
233                "parse limit {limit} exceeded in '{path}': declared {declared}, budget {budget}"
234            ),
235            Self::HostSizeOverflow { path, field, value } => write!(
236                f,
237                "host-size conversion failed in '{path}': field {field} value {value} does not fit usize"
238            ),
239            Self::DuplicateTensorOwnership { name, shards, path } => {
240                write!(
241                    f,
242                    "duplicate tensor ownership for '{name}' across shards {} in '{path}'",
243                    shards.join(", ")
244                )
245            }
246            Self::MissingShard { shard, path } => {
247                write!(f, "missing shard '{shard}' referenced by '{path}'")
248            }
249            Self::FeatureDisabled { path, feature } => write!(
250                f,
251                "'{path}' requires the `{feature}` cargo feature, which is not enabled"
252            ),
253        }
254    }
255}
256
257impl std::error::Error for ParserError {
258    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
259        match self {
260            Self::Io { source, .. } => Some(source),
261            Self::UnsupportedFormat { .. }
262            | Self::MissingTensor { .. }
263            | Self::InvalidLayout { .. }
264            | Self::ExpertOutOfRange { .. }
265            | Self::LimitExceeded { .. }
266            | Self::HostSizeOverflow { .. }
267            | Self::DuplicateTensorOwnership { .. }
268            | Self::MissingShard { .. }
269            | Self::FeatureDisabled { .. } => None,
270        }
271    }
272}
273
274/// Convenience alias used throughout the crate.
275pub type Result<T> = std::result::Result<T, ParserError>;
276
277#[cfg(test)]
278mod tests {
279    use super::*;
280
281    #[test]
282    fn limit_and_host_errors_name_the_field() {
283        let limit = ParserError::limit_exceeded("mem://e", ParseLimitKind::StringBytes, 17, 16);
284        let host = ParserError::host_size("mem://e", HostSizeField::RelativeOffset, u64::MAX);
285        assert!(limit.to_string().contains("max_string_bytes"));
286        assert!(host.to_string().contains("relative_offset"));
287        assert!(std::error::Error::source(&limit).is_none());
288        assert!(std::error::Error::source(&host).is_none());
289    }
290
291    #[test]
292    fn limit_kind_match_is_exhaustive() {
293        let kinds = [
294            ParseLimitKind::KvCount,
295            ParseLimitKind::TensorCount,
296            ParseLimitKind::StringBytes,
297            ParseLimitKind::ArrayWorkItems,
298            ParseLimitKind::TensorRank,
299            ParseLimitKind::MetadataBytes,
300        ];
301        for kind in kinds {
302            let name = match kind {
303                ParseLimitKind::KvCount => "max_kv_count",
304                ParseLimitKind::TensorCount => "max_tensor_count",
305                ParseLimitKind::StringBytes => "max_string_bytes",
306                ParseLimitKind::ArrayWorkItems => "max_array_work_items",
307                ParseLimitKind::TensorRank => "max_tensor_rank",
308                ParseLimitKind::MetadataBytes => "max_metadata_bytes",
309            };
310            assert_eq!(kind.as_str(), name);
311        }
312    }
313
314    #[test]
315    fn host_field_match_is_exhaustive() {
316        let fields = [
317            HostSizeField::StringLen,
318            HostSizeField::KvCount,
319            HostSizeField::TensorCount,
320            HostSizeField::TensorRank,
321            HostSizeField::TensorDim,
322            HostSizeField::RelativeOffset,
323            HostSizeField::Alignment,
324            HostSizeField::ArrayLen,
325        ];
326        for field in fields {
327            let name = match field {
328                HostSizeField::StringLen => "string_len",
329                HostSizeField::KvCount => "kv_count",
330                HostSizeField::TensorCount => "tensor_count",
331                HostSizeField::TensorRank => "tensor_rank",
332                HostSizeField::TensorDim => "tensor_dim",
333                HostSizeField::RelativeOffset => "relative_offset",
334                HostSizeField::Alignment => "general.alignment",
335                HostSizeField::ArrayLen => "array_len",
336            };
337            assert_eq!(field.as_str(), name);
338        }
339    }
340}