Skip to main content

transcribe_cpp/
error.rs

1//! Error type mapped from `transcribe_status`.
2//!
3//! The C API reports failures as a `transcribe_status` int; this module maps
4//! each one to a distinct [`Error`] variant (requirements §3: "distinct
5//! failures stay distinct"). The grouping mirrors the Python binding's
6//! exception hierarchy — the conformance precedent — and the raw status is
7//! preserved via [`Error::raw_status`].
8
9use transcribe_cpp_sys as sys;
10use transcribe_cpp_types::{ErrorKind, ErrorReport, Transcript};
11
12/// Convenience alias for results from this crate.
13pub type Result<T> = std::result::Result<T, Error>;
14
15/// Everything that can go wrong talking to the native library.
16///
17/// Match on the variant for typed handling; [`Error::raw_status`] recovers the
18/// underlying `transcribe_status` code (0 for errors raised purely on the Rust
19/// side, e.g. the load-time version gate or a `NUL` in a caller string).
20#[derive(Debug, thiserror::Error)]
21#[non_exhaustive]
22pub enum Error {
23    /// `TRANSCRIBE_ERR_INVALID_ARG` (or `_SAMPLE_RATE`).
24    #[error("invalid argument: {0}")]
25    InvalidArgument(String),
26    /// `TRANSCRIBE_ERR_NOT_IMPLEMENTED` — the model has no path for this call.
27    #[error("not implemented by this model: {0}")]
28    NotImplemented(String),
29    /// `TRANSCRIBE_ERR_FILE_NOT_FOUND` — the GGUF path does not exist.
30    #[error("model file not found: {0}")]
31    ModelFileNotFound(String),
32    /// `TRANSCRIBE_ERR_GGUF` / `_UNSUPPORTED_ARCH` / `_UNSUPPORTED_VARIANT`.
33    #[error("model load failed: {0}")]
34    ModelLoad(String),
35    /// `TRANSCRIBE_ERR_OOM`.
36    #[error("out of memory: {0}")]
37    OutOfMemory(String),
38    /// `TRANSCRIBE_ERR_BACKEND` — the requested backend could not be satisfied.
39    #[error("backend error: {0}")]
40    Backend(String),
41    /// `TRANSCRIBE_ERR_UNSUPPORTED_{TASK,LANGUAGE,TIMESTAMPS,PNC,ITN}` — the
42    /// model cannot satisfy this request shape.
43    #[error("unsupported request: {0}")]
44    Unsupported(String),
45    /// `TRANSCRIBE_ERR_BAD_STRUCT_SIZE` — an ABI/struct-size fault. With the
46    /// generated FFI this indicates a header/library skew, not caller error.
47    #[error("ABI struct-size mismatch: {0}")]
48    BadStructSize(String),
49    /// `TRANSCRIBE_ERR_INPUT_TOO_LONG` — audio longer than the model can decode.
50    #[error("input too long: {0}")]
51    InputTooLong(String),
52    /// `TRANSCRIBE_ERR_ABORTED` — the abort callback returned true. The
53    /// transcript of chunks that completed before the abort is preserved.
54    #[error("operation aborted: {message}")]
55    Aborted {
56        message: String,
57        /// Partial transcript from chunks that completed before the abort.
58        partial: Option<Box<Transcript>>,
59    },
60    /// `TRANSCRIBE_ERR_OUTPUT_TRUNCATED` — the decode hit the generation budget
61    /// before end-of-stream; the transcript is incomplete by contract. The
62    /// partial transcript is always preserved.
63    #[error("output truncated before end-of-stream: {message}")]
64    OutputTruncated {
65        message: String,
66        /// The (incomplete) transcript produced before truncation.
67        partial: Option<Box<Transcript>>,
68    },
69    /// `TRANSCRIBE_ERR_OUTPUT_REPETITION` — the decode was stopped because the
70    /// output began repeating itself; the transcript is incomplete by contract.
71    /// The partial transcript, with the repeats dropped, is always preserved.
72    #[error("output began repeating before end-of-stream: {message}")]
73    OutputRepetition {
74        message: String,
75        /// The (incomplete) transcript produced before the loop, one copy kept.
76        partial: Option<Box<Transcript>>,
77    },
78    /// `TRANSCRIBE_ERR_UNSUPPORTED_ROLE` — see [`Model::roles`](crate::Model::roles).
79    #[error("unsupported role: {0}")]
80    UnsupportedRole(String),
81    /// `TRANSCRIBE_ERR_INPUT_TOO_SHORT` — the audio is shorter than the role's
82    /// minimum (e.g. [`LangIdInfo::min_audio_ms`](crate::LangIdInfo)).
83    #[error("input too short: {0}")]
84    InputTooShort(String),
85    /// The loaded library's base version disagrees with the headers this crate
86    /// was generated against (the pre-1.0 version lock). Raised on first use.
87    #[error("native library version mismatch: {0}")]
88    VersionMismatch(String),
89    /// A caller-supplied string contained an interior NUL byte.
90    #[error("string contains an interior NUL byte: {0}")]
91    Nul(#[from] std::ffi::NulError),
92    /// Another session of the same model already has a compute operation in
93    /// flight. The C library serializes compute per model (the 0.x limitation):
94    /// at most one run / batch / active stream across ALL of a model's sessions
95    /// at a time. Finish or drop the in-flight stream (one-shot runs/batches
96    /// just queue) before starting another, or give each concurrent worker its
97    /// own model. Raised purely on the Rust side, so [`Error::raw_status`] is 0.
98    #[error("model busy: {0}")]
99    Busy(String),
100    /// A non-OK status with no more specific mapping.
101    #[error("{0}")]
102    Other(String),
103}
104
105impl From<&Error> for ErrorReport {
106    fn from(err: &Error) -> Self {
107        let mut report = ErrorReport::new(err.kind(), err.to_string());
108        report.status = err.raw_status();
109        report.partial = err.partial().cloned();
110        report
111    }
112}
113
114/// Moves the partial transcript out instead of cloning it.
115impl From<Error> for ErrorReport {
116    fn from(err: Error) -> Self {
117        let (kind, message, status) = (err.kind(), err.to_string(), err.raw_status());
118        let mut report = ErrorReport::new(kind, message);
119        report.status = status;
120        report.partial = match err {
121            Error::Aborted { partial, .. }
122            | Error::OutputTruncated { partial, .. }
123            | Error::OutputRepetition { partial, .. } => partial.map(|p| *p),
124            _ => None,
125        };
126        report
127    }
128}
129
130/// Serializes as an [`ErrorReport`] (see there for the shape), without
131/// cloning the partial transcript.
132#[cfg(feature = "serde")]
133impl serde::Serialize for Error {
134    fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
135        #[derive(serde::Serialize)]
136        struct Report<'a> {
137            kind: ErrorKind,
138            message: String,
139            status: i32,
140            partial: Option<&'a Transcript>,
141        }
142        Report {
143            kind: self.kind(),
144            message: self.to_string(),
145            status: self.raw_status(),
146            partial: self.partial(),
147        }
148        .serialize(s)
149    }
150}
151
152impl Error {
153    /// This error's [`ErrorKind`].
154    pub fn kind(&self) -> ErrorKind {
155        // Exhaustive on purpose: a new variant must pick a kind to compile.
156        match self {
157            Error::InvalidArgument(_) => ErrorKind::InvalidArgument,
158            Error::NotImplemented(_) => ErrorKind::NotImplemented,
159            Error::ModelFileNotFound(_) => ErrorKind::ModelFileNotFound,
160            Error::ModelLoad(_) => ErrorKind::ModelLoad,
161            Error::OutOfMemory(_) => ErrorKind::OutOfMemory,
162            Error::Backend(_) => ErrorKind::Backend,
163            Error::Unsupported(_) => ErrorKind::Unsupported,
164            Error::BadStructSize(_) => ErrorKind::BadStructSize,
165            Error::InputTooLong(_) => ErrorKind::InputTooLong,
166            Error::Aborted { .. } => ErrorKind::Aborted,
167            Error::OutputTruncated { .. } => ErrorKind::OutputTruncated,
168            Error::OutputRepetition { .. } => ErrorKind::OutputRepetition,
169            Error::UnsupportedRole(_) => ErrorKind::UnsupportedRole,
170            Error::InputTooShort(_) => ErrorKind::InputTooShort,
171            Error::VersionMismatch(_) => ErrorKind::VersionMismatch,
172            Error::Nul(_) => ErrorKind::Nul,
173            Error::Busy(_) => ErrorKind::Busy,
174            Error::Other(_) => ErrorKind::Other,
175        }
176    }
177
178    /// The `transcribe_status` this error was mapped from, or `0` for errors
179    /// raised on the Rust side (version gate, NUL in a string, …).
180    pub fn raw_status(&self) -> i32 {
181        use sys::transcribe_status as S;
182        let s = match self {
183            Error::InvalidArgument(_) => S::TRANSCRIBE_ERR_INVALID_ARG,
184            Error::NotImplemented(_) => S::TRANSCRIBE_ERR_NOT_IMPLEMENTED,
185            Error::ModelFileNotFound(_) => S::TRANSCRIBE_ERR_FILE_NOT_FOUND,
186            Error::ModelLoad(_) => S::TRANSCRIBE_ERR_GGUF,
187            Error::OutOfMemory(_) => S::TRANSCRIBE_ERR_OOM,
188            Error::Backend(_) => S::TRANSCRIBE_ERR_BACKEND,
189            Error::Unsupported(_) => S::TRANSCRIBE_ERR_UNSUPPORTED_TASK,
190            Error::BadStructSize(_) => S::TRANSCRIBE_ERR_BAD_STRUCT_SIZE,
191            Error::InputTooLong(_) => S::TRANSCRIBE_ERR_INPUT_TOO_LONG,
192            Error::Aborted { .. } => S::TRANSCRIBE_ERR_ABORTED,
193            Error::OutputTruncated { .. } => S::TRANSCRIBE_ERR_OUTPUT_TRUNCATED,
194            Error::OutputRepetition { .. } => S::TRANSCRIBE_ERR_OUTPUT_REPETITION,
195            Error::UnsupportedRole(_) => S::TRANSCRIBE_ERR_UNSUPPORTED_ROLE,
196            Error::InputTooShort(_) => S::TRANSCRIBE_ERR_INPUT_TOO_SHORT,
197            _ => S::TRANSCRIBE_OK,
198        };
199        s.0 as i32
200    }
201
202    /// The partial transcript carried by [`Error::Aborted`] /
203    /// [`Error::OutputTruncated`] / [`Error::OutputRepetition`], if any. `None`
204    /// for every other variant.
205    pub fn partial(&self) -> Option<&Transcript> {
206        match self {
207            Error::Aborted { partial, .. }
208            | Error::OutputTruncated { partial, .. }
209            | Error::OutputRepetition { partial, .. } => partial.as_deref(),
210            _ => None,
211        }
212    }
213}
214
215/// Human-readable text for a `transcribe_status` (from the C side).
216pub(crate) fn status_string(status: i32) -> String {
217    // Borrowed pointer into static storage; copy at the boundary.
218    let ptr = unsafe { sys::transcribe_status_string(status) };
219    if ptr.is_null() {
220        return format!("status {status}");
221    }
222    unsafe { std::ffi::CStr::from_ptr(ptr) }
223        .to_string_lossy()
224        .into_owned()
225}
226
227/// Build the mapped error for a non-OK status (without a partial transcript).
228/// The run path re-attaches partials for the two result-bearing statuses.
229pub(crate) fn error_for_status(status: sys::transcribe_status, context: &str) -> Error {
230    use sys::transcribe_status as S;
231    let code = status.0 as i32;
232    let msg = {
233        let s = status_string(code);
234        if context.is_empty() {
235            format!("{s} (status {code})")
236        } else {
237            format!("{context}: {s} (status {code})")
238        }
239    };
240    match status {
241        S::TRANSCRIBE_ERR_INVALID_ARG | S::TRANSCRIBE_ERR_SAMPLE_RATE => {
242            Error::InvalidArgument(msg)
243        }
244        S::TRANSCRIBE_ERR_NOT_IMPLEMENTED => Error::NotImplemented(msg),
245        S::TRANSCRIBE_ERR_FILE_NOT_FOUND => Error::ModelFileNotFound(msg),
246        S::TRANSCRIBE_ERR_GGUF
247        | S::TRANSCRIBE_ERR_UNSUPPORTED_ARCH
248        | S::TRANSCRIBE_ERR_UNSUPPORTED_VARIANT => Error::ModelLoad(msg),
249        S::TRANSCRIBE_ERR_OOM => Error::OutOfMemory(msg),
250        S::TRANSCRIBE_ERR_BACKEND => Error::Backend(msg),
251        S::TRANSCRIBE_ERR_UNSUPPORTED_LANGUAGE
252        | S::TRANSCRIBE_ERR_UNSUPPORTED_TASK
253        | S::TRANSCRIBE_ERR_UNSUPPORTED_TIMESTAMPS
254        | S::TRANSCRIBE_ERR_UNSUPPORTED_PNC
255        | S::TRANSCRIBE_ERR_UNSUPPORTED_ITN => Error::Unsupported(msg),
256        S::TRANSCRIBE_ERR_BAD_STRUCT_SIZE => Error::BadStructSize(msg),
257        S::TRANSCRIBE_ERR_INPUT_TOO_LONG => Error::InputTooLong(msg),
258        S::TRANSCRIBE_ERR_ABORTED => Error::Aborted {
259            message: msg,
260            partial: None,
261        },
262        S::TRANSCRIBE_ERR_OUTPUT_TRUNCATED => Error::OutputTruncated {
263            message: msg,
264            partial: None,
265        },
266        S::TRANSCRIBE_ERR_OUTPUT_REPETITION => Error::OutputRepetition {
267            message: msg,
268            partial: None,
269        },
270        S::TRANSCRIBE_ERR_UNSUPPORTED_ROLE => Error::UnsupportedRole(msg),
271        S::TRANSCRIBE_ERR_INPUT_TOO_SHORT => Error::InputTooShort(msg),
272        _ => Error::Other(msg),
273    }
274}
275
276/// `Ok(())` for `TRANSCRIBE_OK`, otherwise the mapped error.
277pub(crate) fn check(status: sys::transcribe_status, context: &str) -> Result<()> {
278    if status == sys::transcribe_status::TRANSCRIBE_OK {
279        Ok(())
280    } else {
281        Err(error_for_status(status, context))
282    }
283}
284
285#[cfg(test)]
286mod tests {
287    use super::*;
288    use std::mem::discriminant;
289    use sys::transcribe_status as S;
290
291    #[test]
292    fn every_status_maps_to_a_typed_variant() {
293        // Every non-OK status the linked library knows, found by walking codes
294        // upward until `transcribe_status_string` falls back to its "unknown"
295        // text, so a status appended to the header without a mapping fails here.
296        let unknown = status_string(-1);
297        let codes: Vec<S> = (1..256u32)
298            .take_while(|&c| status_string(c as i32) != unknown)
299            .map(S)
300            .collect();
301        assert!(
302            codes.len() >= S::TRANSCRIBE_ERR_UNSUPPORTED_ROLE.0 as usize,
303            "status walk stopped early at {} codes",
304            codes.len()
305        );
306        for status in codes {
307            let code = status.0;
308            let err = error_for_status(status, "ctx");
309            assert!(
310                !matches!(err, Error::Other(_)),
311                "status {code} falls through to Error::Other: {err:?}"
312            );
313            // raw_status must name a status that maps back to the same
314            // variant (grouped codes like SAMPLE_RATE report their group's
315            // primary status, never 0).
316            let raw = err.raw_status();
317            assert_ne!(raw, 0, "status {code} reports raw_status 0: {err:?}");
318            let back = error_for_status(S(raw as u32), "ctx");
319            assert_eq!(
320                discriminant(&back),
321                discriminant(&err),
322                "status {code} -> {err:?} -> raw {raw} -> {back:?}"
323            );
324            assert_eq!(back.kind(), err.kind(), "status {code}");
325            assert_ne!(err.kind(), ErrorKind::Other, "status {code}");
326        }
327        let role = error_for_status(S::TRANSCRIBE_ERR_UNSUPPORTED_ROLE, "ctx");
328        assert!(matches!(role, Error::UnsupportedRole(_)), "{role:?}");
329    }
330}