Skip to main content

switchyard_runner/
failure.rs

1// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Safe, structured summaries of route-execution failures for telemetry.
5
6use libsy::LibsyError;
7use strum_macros::IntoStaticStr;
8use switchyard_protocol::{LlmClientError, ModelId};
9
10use crate::RunnerError;
11
12/// Stable class of a terminal route-execution failure.
13///
14/// This deliberately carries no provider message, response body, or source
15/// error. It is suitable for logs and telemetry, not client-facing rendering.
16#[non_exhaustive]
17#[derive(Clone, Copy, Debug, IntoStaticStr)]
18#[strum(serialize_all = "snake_case")]
19pub enum RouteErrorKind {
20    /// The upstream returned a non-success HTTP response.
21    UpstreamHttp,
22    /// The selected target rejected the request because its context window was exceeded.
23    ContextWindowExceeded,
24    /// The upstream request timed out.
25    Timeout,
26    /// The upstream could not be reached or the request could not be sent.
27    Transport,
28    /// The upstream response could not be decoded or validated.
29    InvalidResponse,
30    /// Decoding the inbound request failed in translation.
31    RequestTranslation,
32    /// Encoding the request for the upstream failed in translation.
33    RequestEncoding,
34    /// Decoding or encoding the response failed in translation.
35    ResponseTranslation,
36    /// The request cannot be served as supplied.
37    InvalidRequest,
38    /// The configured route or client cannot serve the request.
39    Configuration,
40    /// The routing algorithm or driver could not produce an outcome.
41    Algorithm,
42    /// A failure without a safe, more specific kind.
43    Other,
44}
45
46impl RouteErrorKind {
47    /// Returns the stable telemetry value for this kind.
48    pub fn as_str(self) -> &'static str {
49        self.into()
50    }
51}
52
53/// When a terminal failure occurred relative to response delivery.
54#[non_exhaustive]
55#[derive(Clone, Copy, Debug, IntoStaticStr)]
56#[strum(serialize_all = "snake_case")]
57pub enum RouteErrorPhase {
58    /// The route failed before returning a response to its caller.
59    BeforeResponse,
60    /// A previously returned streaming response failed while it was consumed.
61    DuringStream,
62}
63
64impl RouteErrorPhase {
65    /// Returns the stable telemetry value for this phase.
66    pub fn as_str(self) -> &'static str {
67        self.into()
68    }
69}
70
71/// Safe, structured terminal-failure data for routing telemetry.
72#[non_exhaustive]
73#[derive(Clone, Debug)]
74pub struct RouteErrorSummary {
75    /// Stable failure classification.
76    pub kind: RouteErrorKind,
77    /// Whether the error preceded response delivery or occurred while streaming.
78    pub phase: RouteErrorPhase,
79    /// Upstream HTTP status, when directly available.
80    pub upstream_status: Option<u16>,
81    /// Selected target that failed, when the runner knows it.
82    pub target: Option<ModelId>,
83}
84
85impl RunnerError {
86    /// Returns a safe telemetry summary for a failure before response delivery.
87    pub fn execution_error_summary(&self) -> RouteErrorSummary {
88        match self {
89            Self::Algorithm(LibsyError::ClientCall { target, source }) => {
90                client_error_summary(source, RouteErrorPhase::BeforeResponse, Some(target))
91            }
92            Self::Client(source) => {
93                client_error_summary(source, RouteErrorPhase::BeforeResponse, None)
94            }
95            Self::Configuration { .. } => summary(
96                RouteErrorKind::Configuration,
97                RouteErrorPhase::BeforeResponse,
98                None,
99                None,
100            ),
101            Self::UnknownRouteModel(_)
102            | Self::IncompatibleCallerFormat(_)
103            | Self::AuxiliaryUnsupported => summary(
104                RouteErrorKind::InvalidRequest,
105                RouteErrorPhase::BeforeResponse,
106                None,
107                None,
108            ),
109            Self::Algorithm(_) => summary(
110                RouteErrorKind::Algorithm,
111                RouteErrorPhase::BeforeResponse,
112                None,
113                None,
114            ),
115        }
116    }
117}
118
119/// Returns a safe telemetry summary for an error yielded by an active response stream.
120///
121/// `served_model` should be the target recorded on the response before its stream was returned.
122pub fn stream_error_summary(
123    error: &LlmClientError,
124    served_model: Option<&ModelId>,
125) -> RouteErrorSummary {
126    client_error_summary(error, RouteErrorPhase::DuringStream, served_model)
127}
128
129fn client_error_summary(
130    error: &LlmClientError,
131    phase: RouteErrorPhase,
132    target: Option<&ModelId>,
133) -> RouteErrorSummary {
134    let target = target.or(match error {
135        // Context-window errors carry the resolved target model when a caller has not
136        // already supplied the route's selected or served target.
137        LlmClientError::ContextWindowExceeded { model, .. } => Some(model),
138        _ => None,
139    });
140    let (kind, upstream_status) = match error {
141        LlmClientError::UpstreamHttp { status, .. } => {
142            (RouteErrorKind::UpstreamHttp, Some(status.as_u16()))
143        }
144        LlmClientError::ContextWindowExceeded { .. } => {
145            (RouteErrorKind::ContextWindowExceeded, None)
146        }
147        LlmClientError::Timeout { .. } => (RouteErrorKind::Timeout, None),
148        LlmClientError::Transport { .. } => (RouteErrorKind::Transport, None),
149        LlmClientError::InvalidResponse { .. } => (RouteErrorKind::InvalidResponse, None),
150        LlmClientError::RequestTranslation(_) => (RouteErrorKind::RequestTranslation, None),
151        LlmClientError::RequestEncoding(_) => (RouteErrorKind::RequestEncoding, None),
152        LlmClientError::ResponseTranslation(_) => (RouteErrorKind::ResponseTranslation, None),
153        LlmClientError::InvalidRequest { .. } => (RouteErrorKind::InvalidRequest, None),
154        LlmClientError::Configuration { .. } => (RouteErrorKind::Configuration, None),
155        LlmClientError::Ffi { .. } | LlmClientError::General(_) => (RouteErrorKind::Other, None),
156        _ => (RouteErrorKind::Other, None),
157    };
158    summary(kind, phase, upstream_status, target)
159}
160
161fn summary(
162    kind: RouteErrorKind,
163    phase: RouteErrorPhase,
164    upstream_status: Option<u16>,
165    target: Option<&ModelId>,
166) -> RouteErrorSummary {
167    RouteErrorSummary {
168        kind,
169        phase,
170        upstream_status,
171        target: target.cloned(),
172    }
173}
174
175#[cfg(test)]
176mod tests {
177    use super::*;
178
179    const SECRET: &str = "patient name is Jane Doe";
180
181    #[test]
182    fn execution_error_summary_keeps_http_status_and_target_without_body() {
183        let error = RunnerError::Algorithm(LibsyError::ClientCall {
184            target: ModelId::from("strong"),
185            source: LlmClientError::UpstreamHttp {
186                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
187                body: format!("upstream response: {SECRET}"),
188            },
189        });
190
191        let summary = error.execution_error_summary();
192
193        assert!(matches!(summary.kind, RouteErrorKind::UpstreamHttp));
194        assert!(matches!(summary.phase, RouteErrorPhase::BeforeResponse));
195        assert_eq!(summary.upstream_status, Some(503));
196        assert_eq!(summary.target.as_ref().map(ModelId::as_str), Some("strong"));
197        assert!(!format!("{summary:?}").contains(SECRET));
198    }
199
200    #[test]
201    fn execution_error_summary_reduces_untrusted_messages_to_kinds() {
202        let error = RunnerError::Algorithm(LibsyError::AlgorithmError {
203            message: SECRET.to_string(),
204        });
205
206        let summary = error.execution_error_summary();
207
208        assert!(matches!(summary.kind, RouteErrorKind::Algorithm));
209        assert_eq!(summary.target, None);
210        assert!(!format!("{summary:?}").contains(SECRET));
211    }
212
213    #[test]
214    fn stream_error_summary_preserves_served_target_without_source_text() {
215        let error = LlmClientError::Timeout {
216            source: std::io::Error::other(SECRET).into(),
217        };
218
219        let summary = stream_error_summary(&error, Some(&ModelId::from("fallback")));
220
221        assert!(matches!(summary.kind, RouteErrorKind::Timeout));
222        assert!(matches!(summary.phase, RouteErrorPhase::DuringStream));
223        assert_eq!(
224            summary.target.as_ref().map(ModelId::as_str),
225            Some("fallback")
226        );
227        assert!(!format!("{summary:?}").contains(SECRET));
228    }
229
230    #[test]
231    fn stream_error_summary_uses_context_window_model_without_a_served_target() {
232        let error = LlmClientError::ContextWindowExceeded {
233            model: ModelId::from("weak"),
234            message: SECRET.to_string(),
235        };
236
237        let summary = stream_error_summary(&error, None);
238
239        assert!(matches!(
240            summary.kind,
241            RouteErrorKind::ContextWindowExceeded
242        ));
243        assert!(matches!(summary.phase, RouteErrorPhase::DuringStream));
244        assert_eq!(summary.target.as_ref().map(ModelId::as_str), Some("weak"));
245        assert!(!format!("{summary:?}").contains(SECRET));
246    }
247
248    #[test]
249    fn client_error_kinds_have_stable_telemetry_values() {
250        let cases = vec![
251            (
252                LlmClientError::ContextWindowExceeded {
253                    model: ModelId::from("weak"),
254                    message: SECRET.to_string(),
255                },
256                "context_window_exceeded",
257            ),
258            (
259                LlmClientError::Transport {
260                    source: std::io::Error::other(SECRET).into(),
261                },
262                "transport",
263            ),
264            (
265                LlmClientError::InvalidResponse {
266                    source: std::io::Error::other(SECRET).into(),
267                },
268                "invalid_response",
269            ),
270            (
271                LlmClientError::RequestTranslation(SECRET.to_string()),
272                "request_translation",
273            ),
274            (
275                LlmClientError::RequestEncoding(SECRET.to_string()),
276                "request_encoding",
277            ),
278            (
279                LlmClientError::ResponseTranslation(SECRET.to_string()),
280                "response_translation",
281            ),
282            (
283                LlmClientError::Configuration {
284                    message: SECRET.to_string(),
285                },
286                "configuration",
287            ),
288            (
289                LlmClientError::InvalidRequest {
290                    message: SECRET.to_string(),
291                },
292                "invalid_request",
293            ),
294            (LlmClientError::General(SECRET.to_string()), "other"),
295        ];
296
297        for (error, value) in cases {
298            let summary = stream_error_summary(&error, None);
299            assert_eq!(summary.kind.as_str(), value);
300            assert!(!format!("{summary:?}").contains(SECRET));
301        }
302    }
303
304    #[test]
305    fn route_error_phases_have_stable_telemetry_values() {
306        assert_eq!(RouteErrorPhase::BeforeResponse.as_str(), "before_response");
307        assert_eq!(RouteErrorPhase::DuringStream.as_str(), "during_stream");
308    }
309
310    #[test]
311    fn direct_client_errors_do_not_claim_a_target() {
312        let error = RunnerError::Client(LlmClientError::Timeout {
313            source: std::io::Error::other(SECRET).into(),
314        });
315
316        let summary = error.execution_error_summary();
317
318        assert!(matches!(summary.kind, RouteErrorKind::Timeout));
319        assert!(matches!(summary.phase, RouteErrorPhase::BeforeResponse));
320        assert_eq!(summary.target, None);
321        assert!(!format!("{summary:?}").contains(SECRET));
322    }
323
324    #[test]
325    fn runner_request_and_configuration_errors_are_classified() {
326        let configuration = RunnerError::configuration(SECRET);
327        assert!(matches!(
328            configuration.execution_error_summary().kind,
329            RouteErrorKind::Configuration
330        ));
331
332        let unsupported = RunnerError::AuxiliaryUnsupported;
333        assert!(matches!(
334            unsupported.execution_error_summary().kind,
335            RouteErrorKind::InvalidRequest
336        ));
337    }
338}