1use std::fmt;
10use std::io;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14pub enum ParseLimitKind {
15 KvCount,
17 TensorCount,
19 StringBytes,
21 ArrayWorkItems,
23 TensorRank,
25 MetadataBytes,
27}
28
29impl ParseLimitKind {
30 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
51pub enum HostSizeField {
52 StringLen,
54 KvCount,
56 TensorCount,
58 TensorRank,
60 TensorDim,
62 RelativeOffset,
64 Alignment,
66 ArrayLen,
68}
69
70impl HostSizeField {
71 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#[derive(Debug)]
94pub enum ParserError {
95 Io {
97 path: String,
99 source: io::Error,
101 },
102 UnsupportedFormat {
105 path: String,
107 reason: String,
109 },
110 MissingTensor {
112 name: String,
114 path: String,
116 },
117 InvalidLayout {
120 path: String,
122 reason: String,
124 },
125 ExpertOutOfRange {
128 block: usize,
130 expert: usize,
132 available: usize,
134 },
135 LimitExceeded {
137 path: String,
139 limit: ParseLimitKind,
141 declared: u64,
143 budget: u64,
145 },
146 HostSizeOverflow {
148 path: String,
150 field: HostSizeField,
152 value: u64,
154 },
155 DuplicateTensorOwnership {
157 name: String,
159 shards: Vec<String>,
161 path: String,
163 },
164 MissingShard {
166 shard: String,
168 path: String,
170 },
171 FeatureDisabled {
174 path: String,
176 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
274pub 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}