1use std::fmt;
4
5use tenferro_tensor::DType;
6
7pub type Result<T> = std::result::Result<T, Error>;
9
10#[non_exhaustive]
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum RejectReason {
17 DTypeMismatch,
19 RankMismatch,
21 ShapeMismatch,
23 UnsupportedVersion,
25 MalformedHeader,
27 TooManyElements,
29 DestinationNotWritable,
31 ByteOrderMismatch,
33 Unknown(u8),
35}
36
37impl RejectReason {
38 pub(crate) fn code(self) -> u8 {
39 match self {
40 Self::DTypeMismatch => 1,
41 Self::RankMismatch => 2,
42 Self::ShapeMismatch => 3,
43 Self::UnsupportedVersion => 4,
44 Self::MalformedHeader => 5,
45 Self::TooManyElements => 6,
46 Self::DestinationNotWritable => 7,
47 Self::ByteOrderMismatch => 8,
48 Self::Unknown(code) => code,
49 }
50 }
51
52 pub(crate) fn from_code(code: u8) -> Self {
53 match code {
54 0 => Self::MalformedHeader,
55 1 => Self::DTypeMismatch,
56 2 => Self::RankMismatch,
57 3 => Self::ShapeMismatch,
58 4 => Self::UnsupportedVersion,
59 5 => Self::MalformedHeader,
60 6 => Self::TooManyElements,
61 7 => Self::DestinationNotWritable,
62 8 => Self::ByteOrderMismatch,
63 other => Self::Unknown(other),
64 }
65 }
66}
67
68#[non_exhaustive]
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub enum AbortReason {
75 NotHostResident,
77 NonCompact,
79 UnsupportedDType,
81 TooManyElements,
83 RankTooLarge,
85 HostAccess,
87 Unknown(u8),
89}
90
91impl AbortReason {
92 pub(crate) fn code(self) -> u8 {
93 match self {
94 Self::NotHostResident => 1,
95 Self::NonCompact => 2,
96 Self::UnsupportedDType => 3,
97 Self::TooManyElements => 4,
98 Self::RankTooLarge => 5,
99 Self::HostAccess => 6,
100 Self::Unknown(code) => code,
101 }
102 }
103
104 pub(crate) fn from_code(code: u8) -> Self {
105 match code {
106 1 => Self::NotHostResident,
107 2 => Self::NonCompact,
108 3 => Self::UnsupportedDType,
109 4 => Self::TooManyElements,
110 5 => Self::RankTooLarge,
111 6 => Self::HostAccess,
112 other => Self::Unknown(other),
113 }
114 }
115}
116
117#[non_exhaustive]
133#[derive(Debug, thiserror::Error)]
134pub enum Error {
135 #[error("tensor is not host-resident; download it explicitly before sending")]
140 NotHostResident,
141 #[error("tensor payload is not a compact column-major host slice")]
143 NonCompact,
144 #[error("dtype {dtype:?} has no MPI wire encoding")]
146 UnsupportedDType {
147 dtype: DType,
149 },
150 #[error("{elements} elements exceed the per-message limit {max}")]
152 TooManyElements {
153 elements: u64,
155 max: u64,
157 },
158 #[error("tensor rank {rank} exceeds the wire limit {max}")]
160 RankTooLarge {
161 rank: usize,
163 max: usize,
165 },
166 #[error("tag {tag} is negative")]
168 InvalidTag {
169 tag: i32,
171 },
172 #[error("blocking self-send would deadlock; send to a different process")]
174 SelfMessage,
175 #[error("dtype mismatch: expected {expected:?}, received {received:?}")]
177 DTypeMismatch {
178 expected: DType,
180 received: DType,
182 },
183 #[error("rank mismatch: expected {expected}, received {received}")]
185 RankMismatch {
186 expected: usize,
188 received: usize,
190 },
191 #[error("shape mismatch: expected {expected:?}, received {received:?}")]
193 ShapeMismatch {
194 expected: Vec<usize>,
196 received: Vec<usize>,
198 },
199 #[error("unsupported protocol version {received} (supported {supported})")]
201 UnsupportedVersion {
202 received: u16,
204 supported: u16,
206 },
207 #[error("malformed frame: {reason}")]
209 MalformedHeader {
210 reason: &'static str,
212 },
213 #[error("unexpected frame kind {kind}")]
218 UnexpectedFrame {
219 kind: u8,
221 },
222 #[error("peer element byte order {received} differs from this host")]
224 ByteOrderMismatch {
225 received: u8,
227 },
228 #[error("peer rejected the tensor: {reason:?}")]
230 PeerRejected {
231 reason: RejectReason,
233 },
234 #[error("peer aborted the send: {reason:?}")]
236 PeerAborted {
237 reason: AbortReason,
239 },
240 #[error("payload byte count mismatch: expected {expected}, received {received}")]
242 PayloadCountMismatch {
243 expected: i64,
245 received: i64,
247 },
248 #[error("bool payload contained a byte other than 0 or 1")]
250 InvalidBoolPayload,
251 #[error(transparent)]
253 Tensor(#[from] tenferro_tensor::Error),
254}
255
256impl Error {
257 pub(crate) fn abort_reason(&self) -> AbortReason {
258 match self {
259 Self::NotHostResident => AbortReason::NotHostResident,
260 Self::NonCompact => AbortReason::NonCompact,
261 Self::UnsupportedDType { .. } => AbortReason::UnsupportedDType,
262 Self::TooManyElements { .. } => AbortReason::TooManyElements,
263 Self::RankTooLarge { .. } => AbortReason::RankTooLarge,
264 Self::Tensor(_) => AbortReason::HostAccess,
265 _ => AbortReason::HostAccess,
266 }
267 }
268}
269
270impl fmt::Display for AbortReason {
271 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
272 write!(formatter, "{self:?}")
273 }
274}
275
276#[cfg(test)]
277mod tests {
278 use super::*;
279
280 #[test]
281 fn reject_codes_round_trip_and_unknown_codes_stay_unknown() {
282 let cases = [
283 (RejectReason::DTypeMismatch, 1),
284 (RejectReason::RankMismatch, 2),
285 (RejectReason::ShapeMismatch, 3),
286 (RejectReason::UnsupportedVersion, 4),
287 (RejectReason::MalformedHeader, 5),
288 (RejectReason::TooManyElements, 6),
289 (RejectReason::DestinationNotWritable, 7),
290 (RejectReason::ByteOrderMismatch, 8),
291 (RejectReason::Unknown(42), 42),
292 ];
293 for (reason, code) in cases {
294 assert_eq!(reason.code(), code);
295 assert_eq!(RejectReason::from_code(code), reason);
296 }
297 assert_eq!(RejectReason::from_code(0), RejectReason::MalformedHeader);
300 assert_eq!(RejectReason::from_code(9), RejectReason::Unknown(9));
301 }
302
303 #[test]
304 fn abort_codes_round_trip_and_unknown_codes_stay_unknown() {
305 let cases = [
306 (AbortReason::NotHostResident, 1),
307 (AbortReason::NonCompact, 2),
308 (AbortReason::UnsupportedDType, 3),
309 (AbortReason::TooManyElements, 4),
310 (AbortReason::RankTooLarge, 5),
311 (AbortReason::HostAccess, 6),
312 (AbortReason::Unknown(42), 42),
313 ];
314 for (reason, code) in cases {
315 assert_eq!(reason.code(), code);
316 assert_eq!(AbortReason::from_code(code), reason);
317 }
318 assert_eq!(AbortReason::from_code(0), AbortReason::Unknown(0));
319 assert_eq!(
320 AbortReason::HostAccess.to_string(),
321 "HostAccess",
322 "the wire ack is human-readable through Debug"
323 );
324 }
325
326 #[test]
327 fn error_display_covers_local_checks_and_receiver_failures() {
328 let cases = [
329 (
330 Error::NotHostResident,
331 "tensor is not host-resident; download it explicitly before sending",
332 ),
333 (
334 Error::NonCompact,
335 "tensor payload is not a compact column-major host slice",
336 ),
337 (
338 Error::UnsupportedDType { dtype: DType::F64 },
339 "dtype F64 has no MPI wire encoding",
340 ),
341 (
342 Error::TooManyElements {
343 elements: 10,
344 max: 5,
345 },
346 "10 elements exceed the per-message limit 5",
347 ),
348 (
349 Error::RankTooLarge { rank: 65, max: 64 },
350 "tensor rank 65 exceeds the wire limit 64",
351 ),
352 (Error::InvalidTag { tag: -1 }, "tag -1 is negative"),
353 (
354 Error::SelfMessage,
355 "blocking self-send would deadlock; send to a different process",
356 ),
357 (
358 Error::DTypeMismatch {
359 expected: DType::F64,
360 received: DType::F32,
361 },
362 "dtype mismatch: expected F64, received F32",
363 ),
364 (
365 Error::RankMismatch {
366 expected: 2,
367 received: 3,
368 },
369 "rank mismatch: expected 2, received 3",
370 ),
371 (
372 Error::ShapeMismatch {
373 expected: vec![2, 3],
374 received: vec![3, 2],
375 },
376 "shape mismatch: expected [2, 3], received [3, 2]",
377 ),
378 (
379 Error::UnsupportedVersion {
380 received: 2,
381 supported: 1,
382 },
383 "unsupported protocol version 2 (supported 1)",
384 ),
385 (
386 Error::MalformedHeader {
387 reason: "bad magic",
388 },
389 "malformed frame: bad magic",
390 ),
391 (
392 Error::UnexpectedFrame { kind: 9 },
393 "unexpected frame kind 9",
394 ),
395 (
396 Error::ByteOrderMismatch { received: 1 },
397 "peer element byte order 1 differs from this host",
398 ),
399 (
400 Error::PeerRejected {
401 reason: RejectReason::DTypeMismatch,
402 },
403 "peer rejected the tensor: DTypeMismatch",
404 ),
405 (
406 Error::PeerAborted {
407 reason: AbortReason::NotHostResident,
408 },
409 "peer aborted the send: NotHostResident",
410 ),
411 (
412 Error::PayloadCountMismatch {
413 expected: 10,
414 received: 8,
415 },
416 "payload byte count mismatch: expected 10, received 8",
417 ),
418 (
419 Error::InvalidBoolPayload,
420 "bool payload contained a byte other than 0 or 1",
421 ),
422 ];
423 for (error, expected) in cases {
424 assert_eq!(error.to_string(), expected);
425 }
426 }
427
428 #[test]
429 fn tensor_failure_is_transparent_and_keeps_its_source() {
430 use std::error::Error as _;
431
432 let inner = tenferro_tensor::Error::BackendSource {
433 op: "send",
434 source: Box::new(std::io::Error::other("backend down")),
435 };
436 let error = Error::from(inner);
437 assert!(matches!(error, Error::Tensor(_)));
438 assert_eq!(error.to_string(), "send: backend failure: backend down");
439 assert!(
440 error.source().is_some(),
441 "a transparent wrapper forwards the inner error's source"
442 );
443
444 let leaf = Error::from(tenferro_tensor::Error::Internal("inner failure".into()));
445 assert_eq!(leaf.to_string(), "internal tensor error: inner failure");
446 assert!(leaf.source().is_none());
447 assert!(Error::InvalidTag { tag: -1 }.source().is_none());
448 }
449
450 #[cfg(not(any(feature = "system", feature = "runtime", feature = "engine")))]
451 #[test]
452 fn error_type_is_usable_in_the_no_feature_protocol_shell() {
453 let error = Error::TooManyElements {
454 elements: 2,
455 max: 1,
456 };
457 assert_eq!(error.abort_reason(), AbortReason::TooManyElements);
458 assert!(error.to_string().contains("per-message limit"));
459 }
460
461 #[test]
462 fn abort_reason_classifies_every_send_failure() {
463 assert_eq!(
464 Error::NotHostResident.abort_reason(),
465 AbortReason::NotHostResident
466 );
467 assert_eq!(Error::NonCompact.abort_reason(), AbortReason::NonCompact);
468 assert_eq!(
469 Error::UnsupportedDType { dtype: DType::F64 }.abort_reason(),
470 AbortReason::UnsupportedDType
471 );
472 assert_eq!(
473 Error::TooManyElements {
474 elements: 2,
475 max: 1
476 }
477 .abort_reason(),
478 AbortReason::TooManyElements
479 );
480 assert_eq!(
481 Error::RankTooLarge { rank: 2, max: 1 }.abort_reason(),
482 AbortReason::RankTooLarge
483 );
484 assert_eq!(
485 Error::Tensor(tenferro_tensor::Error::Internal("access".into())).abort_reason(),
486 AbortReason::HostAccess
487 );
488 assert_eq!(
489 Error::InvalidTag { tag: -1 }.abort_reason(),
490 AbortReason::HostAccess,
491 "receiver-side failures are not abort headers"
492 );
493 }
494}