Skip to main content

switchyard_libsy/
error.rs

1// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Typed failures surfaced by libsy's orchestration APIs.
5
6use std::error::Error as StdError;
7
8use switchyard_protocol::{LlmClientError, ModelId};
9use thiserror::Error;
10
11/// Result type returned by libsy APIs.
12pub type Result<T> = std::result::Result<T, LibsyError>;
13
14/// Failures surfaced while selecting a route, driving an algorithm, or serving a model call.
15#[derive(Debug, Error)]
16pub enum LibsyError {
17    /// Request content violates the algorithm's input constraints.
18    #[error("{message}")]
19    InvalidRequest {
20        /// Description of the invalid input.
21        message: String,
22    },
23
24    /// A named target was not present in the configured target set.
25    #[error("target {target:?} was not found")]
26    TargetNotFound {
27        /// Missing target model id.
28        target: ModelId,
29    },
30
31    /// Routing was attempted without any configured targets.
32    #[error("no routing targets are configured")]
33    NoTargets,
34
35    /// An algorithm could not complete for an algorithm-specific reason.
36    #[error("{message}")]
37    AlgorithmError {
38        /// Description of the algorithm failure.
39        message: String,
40    },
41
42    /// The step-stream driver could not complete an operation.
43    #[error(transparent)]
44    Driver(#[from] DriverError),
45
46    /// An algorithm's step stream ended without a terminal routing outcome.
47    #[error("algorithm run ended without a routing outcome")]
48    MissingFinalResponse,
49
50    /// A target's protocol client failed while serving a routed request.
51    #[error("client call to target {target:?} failed: {source}")]
52    ClientCall {
53        /// Target whose client failed.
54        target: ModelId,
55        /// Typed error supplied by the protocol-owned client trait.
56        #[source]
57        source: LlmClientError,
58    },
59
60    /// A decision judge returned an unusable answer.
61    #[error("invalid decision from target {target:?}: {message}")]
62    InvalidDecision {
63        /// Judge that supplied the answer.
64        target: ModelId,
65        /// Description of the answer validation failure.
66        message: String,
67    },
68
69    /// A user extension or other foreign operation failed.
70    #[error("{operation} failed: {source}")]
71    External {
72        /// Short description of the operation that failed.
73        operation: &'static str,
74        /// Original failure.
75        #[source]
76        source: Box<dyn StdError + Send + Sync>,
77    },
78}
79
80impl LibsyError {
81    /// Wrap an error returned by the protocol-owned client trait.
82    pub fn client_call(target: impl Into<ModelId>, source: LlmClientError) -> Self {
83        Self::ClientCall {
84            target: target.into(),
85            source,
86        }
87    }
88
89    /// Describe an invalid answer returned by a decision judge.
90    pub fn invalid_decision(target: impl Into<ModelId>, message: impl Into<String>) -> Self {
91        Self::InvalidDecision {
92            target: target.into(),
93            message: message.into(),
94        }
95    }
96
97    /// Preserve a concrete foreign error with a description of the failed operation.
98    pub fn external(
99        operation: &'static str,
100        source: impl StdError + Send + Sync + 'static,
101    ) -> Self {
102        Self::External {
103            operation,
104            source: Box::new(source),
105        }
106    }
107}
108
109/// Failures in the step-stream driver.
110#[derive(Debug, Error)]
111pub enum DriverError {
112    /// The consumer side of the step channel was dropped.
113    #[error("driver stream is closed")]
114    StreamClosed,
115
116    /// One side of a response promise was dropped before delivery.
117    #[error("driver response promise was dropped")]
118    ResponseDropped,
119}
120
121#[cfg(test)]
122mod tests {
123    use super::*;
124
125    #[test]
126    fn client_call_preserves_target_and_source() {
127        let error = LibsyError::client_call(
128            "strong",
129            LlmClientError::General("upstream down".to_string()),
130        );
131        match &error {
132            LibsyError::ClientCall { target, source } => {
133                assert_eq!(target, "strong");
134                assert_eq!(source.to_string(), "upstream down");
135            }
136            other => panic!("expected ClientCall, got {other:?}"),
137        }
138        assert_eq!(
139            StdError::source(&error).map(ToString::to_string),
140            Some("upstream down".to_string())
141        );
142    }
143
144    #[test]
145    fn external_preserves_operation_and_source() {
146        let error = LibsyError::external(
147            "loading extension",
148            std::io::Error::other("bad configuration"),
149        );
150        assert!(matches!(
151            &error,
152            LibsyError::External { operation, .. } if *operation == "loading extension"
153        ));
154        assert_eq!(
155            StdError::source(&error).map(ToString::to_string),
156            Some("bad configuration".to_string())
157        );
158    }
159}