Skip to main content

causa_protocol/translation/
error_envelope.rs

1//! The provider error envelope, read one way wherever it arrives.
2//!
3//! All three protocols report a failure as an object with a `message` and a
4//! `code` or `type`: in the body of a non-success HTTP response under
5//! `error`, and inside a successful stream as an error event. Both places go
6//! through [`ErrorDetail::read`], so a host sees the same text for the same
7//! envelope. An envelope that arrives inside a successful response has no
8//! status to classify it, so [`provider_error`] reads the kind from the
9//! envelope's `code` and `type`.
10//!
11//! Only two things leave the envelope. The message is cut to 200 characters
12//! and loses its control characters, so it is safe to print on one line. The
13//! code is kept only when it is a short identifier. Nothing else in the
14//! envelope, and nothing outside it, is echoed.
15
16use causa_kernel::{ModelInvokeError, ModelInvokeErrorKind};
17use serde_json::Value;
18
19/// Longest provider message kept, in characters.
20const MAX_MESSAGE_CHARS: usize = 200;
21
22/// What an error envelope says, reduced to what is safe to show.
23#[derive(Debug, Clone, Default, PartialEq, Eq)]
24#[non_exhaustive]
25pub struct ErrorDetail {
26    /// The provider's `code` when it is a short identifier, otherwise its
27    /// `type` under the same condition.
28    pub code: Option<String>,
29    /// The provider's `message`, on one line and at most 200 characters
30    /// (longer text ends with an ellipsis). `None` when absent or empty.
31    pub message: Option<String>,
32}
33
34impl ErrorDetail {
35    /// Reads an error object: the value under `error` in an HTTP error body,
36    /// or the error carried by a stream event. Only an object is read: an
37    /// error given as a bare string is not the envelope, and its text is not
38    /// echoed.
39    pub fn read(error: &Value) -> Self {
40        let code = name(error, "code")
41            .or_else(|| name(error, "type"))
42            .map(str::to_owned);
43        let message = error
44            .get("message")
45            .and_then(Value::as_str)
46            .and_then(snippet);
47        Self { code, message }
48    }
49
50    /// Reads the body of a non-success HTTP response. A body that is not
51    /// JSON with an `error` object yields an empty detail; there is no
52    /// fallback to the raw text.
53    pub fn read_body(body: &str) -> Self {
54        serde_json::from_str::<Value>(body)
55            .ok()
56            .and_then(|envelope| envelope.get("error").map(Self::read))
57            .unwrap_or_default()
58    }
59}
60
61/// The string under `key`, when it is a short identifier.
62fn name<'a>(error: &'a Value, key: &str) -> Option<&'a str> {
63    error
64        .get(key)
65        .and_then(Value::as_str)
66        .filter(|text| is_identifier(text))
67}
68
69/// The error a successful response body reports about itself: an `error`
70/// that is an object. `None` for a body that reports no error, including one
71/// whose `error` is `null` or any other value that is not the envelope.
72pub fn reported_error(body: &Value) -> Option<ModelInvokeError> {
73    body.get("error")
74        .filter(|error| error.is_object())
75        .map(provider_error)
76}
77
78/// An error the provider reported inside a successful response: a stream
79/// event, or a 2xx body that is an error envelope. There is no status, so
80/// the kind comes from the envelope: `code` is looked up first and `type`
81/// second, and the first one the table knows decides. The text is the
82/// envelope's code and message, read by the rule an HTTP error body goes
83/// through.
84///
85/// | `code` or `type` | Kind |
86/// |---|---|
87/// | `rate_limit_exceeded`, `rate_limit_error`, `overloaded_error`, `server_error`, `api_error`, `internal_server_error`, `timeout_error` | `Transient` |
88/// | `invalid_request_error`, `invalid_request` | `InvalidRequest` |
89/// | anything else, or neither present | `Permanent` |
90pub fn provider_error(error: &Value) -> ModelInvokeError {
91    let detail = ErrorDetail::read(error);
92    let kind = [name(error, "code"), name(error, "type")]
93        .into_iter()
94        .flatten()
95        .find_map(named_kind)
96        .unwrap_or(ModelInvokeErrorKind::Permanent);
97    let label = detail.code.as_deref().unwrap_or("unknown");
98    let message = match &detail.message {
99        Some(message) => format!("provider error ({label}): {message}"),
100        None => format!("provider error ({label})"),
101    };
102    let error = ModelInvokeError::new(kind, message);
103    match detail.code {
104        Some(code) => error.with_code(code),
105        None => error,
106    }
107}
108
109fn named_kind(name: &str) -> Option<ModelInvokeErrorKind> {
110    match name {
111        "rate_limit_exceeded"
112        | "rate_limit_error"
113        | "overloaded_error"
114        | "server_error"
115        | "api_error"
116        | "internal_server_error"
117        | "timeout_error" => Some(ModelInvokeErrorKind::Transient),
118        "invalid_request_error" | "invalid_request" => Some(ModelInvokeErrorKind::InvalidRequest),
119        _ => None,
120    }
121}
122
123/// Whether provider text is short and plain enough to echo as a name: 1 to
124/// 64 ASCII letters, digits, dots, underscores or hyphens.
125pub(crate) fn is_identifier(text: &str) -> bool {
126    (1..=64).contains(&text.len())
127        && text
128            .bytes()
129            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
130}
131
132/// Characters that break a line or reorder the text around them without
133/// being control characters: the Unicode line and paragraph separators and
134/// the bidirectional marks, embeddings, overrides and isolates.
135fn breaks_line(c: char) -> bool {
136    c.is_control()
137        || matches!(
138            c,
139            '\u{2028}' | '\u{2029}' | '\u{061C}' | '\u{200E}' | '\u{200F}'
140                | '\u{202A}'..='\u{202E}'
141                | '\u{2066}'..='\u{2069}'
142        )
143}
144
145/// One printable line: each run of control, line-separator or bidirectional
146/// formatting characters becomes a space, then the text is cut to
147/// [`MAX_MESSAGE_CHARS`].
148fn snippet(message: &str) -> Option<String> {
149    let line = message
150        .split(breaks_line)
151        .map(str::trim)
152        .filter(|part| !part.is_empty())
153        .collect::<Vec<_>>()
154        .join(" ");
155    if line.is_empty() {
156        return None;
157    }
158    let mut chars = line.chars();
159    let mut kept: String = chars.by_ref().take(MAX_MESSAGE_CHARS).collect();
160    if chars.next().is_some() {
161        kept.push('…');
162    }
163    Some(kept)
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169    use serde_json::json;
170
171    #[test]
172    fn code_falls_back_to_type_and_must_be_an_identifier() {
173        let detail = ErrorDetail::read(&json!({"type": "rate_limit_error", "message": "slow"}));
174        assert_eq!(detail.code.as_deref(), Some("rate_limit_error"));
175        let detail = ErrorDetail::read(&json!({"code": "model_not_found", "type": "x"}));
176        assert_eq!(detail.code.as_deref(), Some("model_not_found"));
177        // A null or numeric code is not a name; the type is used instead.
178        let detail = ErrorDetail::read(&json!({"code": null, "type": "invalid_request_error"}));
179        assert_eq!(detail.code.as_deref(), Some("invalid_request_error"));
180        for code in ["", "two words", "a\nb", &"x".repeat(65)] {
181            assert_eq!(
182                ErrorDetail::read(&json!({"code": code})).code,
183                None,
184                "{code:?}"
185            );
186            // A code that is not a name does not hide a type that is.
187            assert_eq!(
188                ErrorDetail::read(&json!({"code": code, "type": "api_error"}))
189                    .code
190                    .as_deref(),
191                Some("api_error"),
192                "{code:?}"
193            );
194        }
195    }
196
197    #[test]
198    fn kind_is_read_from_code_then_type() {
199        use ModelInvokeErrorKind::{InvalidRequest, Permanent, Transient};
200        for (envelope, kind, code) in [
201            (
202                json!({"type": "invalid_request_error", "code": "context_length_exceeded"}),
203                InvalidRequest,
204                Some("context_length_exceeded"),
205            ),
206            (
207                json!({"type": "server_error", "code": "model_overloaded"}),
208                Transient,
209                Some("model_overloaded"),
210            ),
211            (
212                json!({"type": "rate_limit_error", "code": ""}),
213                Transient,
214                Some("rate_limit_error"),
215            ),
216            (
217                json!({"type": "timeout_error"}),
218                Transient,
219                Some("timeout_error"),
220            ),
221            (
222                json!({"type": "authentication_error", "code": "invalid_api_key"}),
223                Permanent,
224                Some("invalid_api_key"),
225            ),
226            (json!({"message": "no name"}), Permanent, None),
227        ] {
228            let error = provider_error(&envelope);
229            assert_eq!(error.kind, kind, "{envelope}");
230            assert_eq!(error.code.as_deref(), code, "{envelope}");
231        }
232    }
233
234    #[test]
235    fn a_body_reports_an_error_only_through_an_object() {
236        for body in [
237            json!({"error": null}),
238            json!({"choices": []}),
239            json!({"error": 7}),
240            json!({"error": "quota used up"}),
241        ] {
242            assert!(reported_error(&body).is_none(), "{body}");
243        }
244        let error =
245            reported_error(&json!({"error": {"type": "overloaded_error", "message": "busy"}}))
246                .expect("object error");
247        assert_eq!(error.kind, ModelInvokeErrorKind::Transient);
248        assert_eq!(error.message, "provider error (overloaded_error): busy");
249        // A bare string is not the envelope; its text is never echoed.
250        assert_eq!(
251            ErrorDetail::read(&json!("quota used up")),
252            ErrorDetail::default()
253        );
254    }
255
256    #[test]
257    fn message_is_one_line_without_control_characters() {
258        let detail = ErrorDetail::read(&json!({"message": "bad\r\nkey\u{1b}[31m red \u{7}"}));
259        assert_eq!(detail.message.as_deref(), Some("bad key [31m red"));
260        let detail = ErrorDetail::read(
261            &json!({"message": "one\u{2028}two\u{2029}three \u{202e}evil\u{2066}x\u{200f}"}),
262        );
263        assert_eq!(detail.message.as_deref(), Some("one two three evil x"));
264        assert_eq!(ErrorDetail::read(&json!({"message": "\n\t"})).message, None);
265        assert_eq!(ErrorDetail::read(&json!({"message": 7})).message, None);
266    }
267
268    #[test]
269    fn message_is_cut_at_two_hundred_characters() {
270        let detail = ErrorDetail::read(&json!({"message": "é".repeat(201)}));
271        let message = detail.message.expect("message");
272        assert_eq!(message.chars().count(), 201);
273        assert!(message.ends_with('…'));
274        let detail = ErrorDetail::read(&json!({"message": "é".repeat(200)}));
275        assert_eq!(detail.message.expect("message").chars().count(), 200);
276    }
277
278    #[test]
279    fn body_without_an_error_object_yields_nothing() {
280        assert_eq!(
281            ErrorDetail::read_body("<html>502</html>"),
282            ErrorDetail::default()
283        );
284        assert_eq!(
285            ErrorDetail::read_body("{\"status\":\"fail\"}"),
286            ErrorDetail::default()
287        );
288        let detail =
289            ErrorDetail::read_body("{\"error\":{\"message\":\"no\",\"type\":\"api_error\"}}");
290        assert_eq!(detail.message.as_deref(), Some("no"));
291        assert_eq!(detail.code.as_deref(), Some("api_error"));
292    }
293}