Skip to main content

tenferro_mpi/
error.rs

1//! Errors the transport adapter reports.
2
3use std::fmt;
4
5use tenferro_tensor::DType;
6
7/// Result alias for this crate.
8pub type Result<T> = std::result::Result<T, Error>;
9
10/// Why a receiver refused a tensor before its payload was sent.
11///
12/// The code travels in the ack frame, so the sender learns the reason instead of
13/// only observing that its send failed.
14#[non_exhaustive]
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum RejectReason {
17    /// The receiver's element type differs from the header's dtype.
18    DTypeMismatch,
19    /// The receiver's rank differs from the header's rank.
20    RankMismatch,
21    /// The receiver's shape differs from the header's shape.
22    ShapeMismatch,
23    /// The receiver does not implement the header's protocol version.
24    UnsupportedVersion,
25    /// The header frame could not be decoded.
26    MalformedHeader,
27    /// The declared element count exceeds one MPI message.
28    TooManyElements,
29    /// The destination buffer refuses host writes (device-only or non-compact).
30    DestinationNotWritable,
31    /// The peer's element byte order differs from the receiver's.
32    ByteOrderMismatch,
33    /// A reject code this version does not know.
34    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/// Why a sender aborted before offering a payload.
69///
70/// An abort is sent as a header frame with a non-zero status and no payload, so a
71/// receiver that is already blocking learns the outcome instead of hanging.
72#[non_exhaustive]
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub enum AbortReason {
75    /// The tensor's storage is not host-addressed memory.
76    NotHostResident,
77    /// The payload is not one compact column-major slice.
78    NonCompact,
79    /// The dtype has no wire encoding (a caller-owned external payload).
80    UnsupportedDType,
81    /// The element count exceeds one MPI message.
82    TooManyElements,
83    /// The rank exceeds [`crate::MAX_WIRE_RANK`].
84    RankTooLarge,
85    /// The host payload could not be borrowed.
86    HostAccess,
87    /// An abort code this version does not know.
88    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/// Failure of one transport call.
118///
119/// Variants split into three groups: local argument and payload checks (nothing is
120/// sent), receiver-side validation the sender is told about through the ack frame
121/// ([`Self::PeerRejected`]), and sender-side aborts the receiver is told about
122/// through an abort header ([`Self::PeerAborted`]).
123///
124/// # Examples
125///
126/// ```
127/// use tenferro_mpi::Error;
128///
129/// let error = Error::InvalidTag { tag: -1 };
130/// assert_eq!(error.to_string(), "tag -1 is negative");
131/// ```
132#[non_exhaustive]
133#[derive(Debug, thiserror::Error)]
134pub enum Error {
135    /// The tensor's storage is not host-addressed memory; nothing was sent.
136    ///
137    /// The adapter never transfers between host and device: download the tensor
138    /// explicitly (for a `Dynamic` owner, `TypedTensor::into_host`) first.
139    #[error("tensor is not host-resident; download it explicitly before sending")]
140    NotHostResident,
141    /// The payload is not one compact column-major host slice; nothing was sent.
142    #[error("tensor payload is not a compact column-major host slice")]
143    NonCompact,
144    /// The dtype has no wire encoding; nothing was sent.
145    #[error("dtype {dtype:?} has no MPI wire encoding")]
146    UnsupportedDType {
147        /// The dtype that could not be encoded.
148        dtype: DType,
149    },
150    /// More elements than one MPI message can carry; nothing was sent.
151    #[error("{elements} elements exceed the per-message limit {max}")]
152    TooManyElements {
153        /// Declared element count.
154        elements: u64,
155        /// Largest element count the wire protocol accepts.
156        max: u64,
157    },
158    /// The rank exceeds [`crate::MAX_WIRE_RANK`]; nothing was sent.
159    #[error("tensor rank {rank} exceeds the wire limit {max}")]
160    RankTooLarge {
161        /// Declared rank.
162        rank: usize,
163        /// Largest rank the header can carry.
164        max: usize,
165    },
166    /// The tag is negative; nothing was sent.
167    #[error("tag {tag} is negative")]
168    InvalidTag {
169        /// The rejected tag.
170        tag: i32,
171    },
172    /// A blocking send to the calling rank would deadlock; nothing was sent.
173    #[error("blocking self-send would deadlock; send to a different process")]
174    SelfMessage,
175    /// The receiver holds a different element type; the payload was not sent.
176    #[error("dtype mismatch: expected {expected:?}, received {received:?}")]
177    DTypeMismatch {
178        /// The receiver's element type.
179        expected: DType,
180        /// The dtype the header declared.
181        received: DType,
182    },
183    /// The receiver holds a different rank; the payload was not sent.
184    #[error("rank mismatch: expected {expected}, received {received}")]
185    RankMismatch {
186        /// The receiver's rank.
187        expected: usize,
188        /// The rank the header declared.
189        received: usize,
190    },
191    /// The receiver holds a different shape; the payload was not sent.
192    #[error("shape mismatch: expected {expected:?}, received {received:?}")]
193    ShapeMismatch {
194        /// The receiver's shape.
195        expected: Vec<usize>,
196        /// The shape the header declared.
197        received: Vec<usize>,
198    },
199    /// The frame's protocol version is not this crate's.
200    #[error("unsupported protocol version {received} (supported {supported})")]
201    UnsupportedVersion {
202        /// Version found in the frame.
203        received: u16,
204        /// Version this crate implements.
205        supported: u16,
206    },
207    /// A frame could not be decoded.
208    #[error("malformed frame: {reason}")]
209    MalformedHeader {
210        /// Which part of the frame failed.
211        reason: &'static str,
212    },
213    /// A frame arrived where the protocol expects a different one.
214    ///
215    /// Two ranks that send to each other on one tag at the same time each see the
216    /// other's header here, instead of hanging.
217    #[error("unexpected frame kind {kind}")]
218    UnexpectedFrame {
219        /// The frame kind that arrived.
220        kind: u8,
221    },
222    /// The peer's element byte order differs from the receiver's.
223    #[error("peer element byte order {received} differs from this host")]
224    ByteOrderMismatch {
225        /// The byte-order marker the header declared.
226        received: u8,
227    },
228    /// The receiver refused the tensor; it sent this reason in the ack frame.
229    #[error("peer rejected the tensor: {reason:?}")]
230    PeerRejected {
231        /// The receiver's reason.
232        reason: RejectReason,
233    },
234    /// The sender aborted before sending a payload.
235    #[error("peer aborted the send: {reason:?}")]
236    PeerAborted {
237        /// The sender's reason.
238        reason: AbortReason,
239    },
240    /// The received payload length disagrees with the header.
241    #[error("payload byte count mismatch: expected {expected}, received {received}")]
242    PayloadCountMismatch {
243        /// Byte count the header promised.
244        expected: i64,
245        /// Byte count the frame actually carried.
246        received: i64,
247    },
248    /// A `bool` payload carried a byte other than 0 or 1.
249    #[error("bool payload contained a byte other than 0 or 1")]
250    InvalidBoolPayload,
251    /// A tenferro tensor accessor failed.
252    #[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        // Zero and five both mean a malformed header; an unassigned code is
298        // preserved so a newer peer's reason is not silently relabelled.
299        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}