repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

ai(SMH-PLAN-AIAG0001): route streams with bounded retry and failover

3717b991c4eb82e9d44706ecec7e9a9f0323558d

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Routing walks the catalog's ordered plan: rate limits and overloaded
endpoints fail over immediately, transient faults get a bounded retry
budget per endpoint with injected backoff, and invalid or
authentication faults fail without touching the next endpoint.
Exhausting the plan surfaces the last fault.

Changed files (4)

+360 / −0 text lines

Diff layout

Cargo.lock

Modified

+1 / −0 text lines

513513name = "smith-ai"
514514version = "0.1.0"
515515dependencies = [
516 "futures",
516517 "serde",
517518 "serde_json",
518519 "smith",

smith-ai/Cargo.toml

Modified

+1 / −0 text lines

1010[dependencies]
1111smith = { path = "../smith" }
12futures = { workspace = true }
1213serde = { workspace = true }
1314serde_json = { workspace = true }

smith-ai/src/lib.rs

Modified

+3 / −0 text lines

1717pub mod gemini;
1818/// Offline model catalog, capabilities, and resolution.
1919pub mod models;
20/// Endpoint routing with bounded retry and failover.
21pub mod mux;
2022/// OpenAI-compatible chat-completions adapter.
2123pub mod openai;
2224/// Cancellable, generation-checked catalog refresh.
2729pub use conformance::{Expected, Fixture, StreamDecoder};
2830pub use gemini::GeminiDecoder;
2931pub use models::{Catalog, ModelCapabilities, ModelEntry, ProviderKind};
32pub use mux::{Endpoint, Router};
3033pub use openai::OpenAiDecoder;
3134pub use refresh::{CatalogSnapshot, CatalogState, RefreshOutcome, refresh};

smith-ai/src/mux.rs

Added
new file mode 100644

+355 / −0 text lines

1//! Endpoint routing with bounded retry and failover.
2//!
3//! Resolution produces an ordered plan; routing walks it. Rate limits and
4//! overloaded endpoints fail over immediately, transient faults get a bounded
5//! retry budget per endpoint, invalid requests and authentication faults fail
6//! without trying anything else, and exhausting the plan surfaces the last
7//! fault instead of looping.
8
9use crate::models::Catalog;
10use futures::StreamExt;
11use smith::error::{ProviderFault, Result, SmithError};
12use smith::provider::{ProviderRequest, ProviderStream, StreamFn};
13use smith::tool::CancelHandle;
14use std::collections::HashMap;
15use std::sync::Arc;
17/// One endpoint in a failover plan: a model id and its stream.
18#[derive(Clone)]
19pub struct Endpoint {
20 /// Model id used in requests to this endpoint.
21 pub model: String,
22 /// The endpoint's stream function.
23 pub stream: StreamFn,
24}
26/// Routes requests through a resolved failover plan.
27#[derive(Clone)]
28pub struct Router {
29 catalog: Catalog,
30 endpoints: Arc<HashMap<String, Endpoint>>,
31 /// Transient retries per endpoint before failing over.
32 transient_retries: u32,
33 /// Injected delay for retry backoff; tests pass a no-op.
34 sleeper: Arc<dyn Fn(u64) + Send + Sync>,
35}
37impl Router {
38 /// Build a router over a catalog and named endpoints.
39 ///
40 /// # Errors
41 ///
42 /// Returns a [`SmithError::Config`] fault when an endpoint model is not
43 /// in the catalog.
44 pub fn new(
45 catalog: Catalog,
46 endpoints: HashMap<String, Endpoint>,
47 transient_retries: u32,
48 ) -> Result<Self> {
49 for model in endpoints.keys() {
50 catalog.resolve_plan(model)?;
51 }
52 Ok(Self {
53 catalog,
54 endpoints: Arc::new(endpoints),
55 transient_retries,
56 sleeper: Arc::new(|_| {}),
57 })
58 }
60 /// Replace the retry delay function; returns the router for chaining.
61 #[must_use]
62 pub fn with_sleeper(mut self, sleeper: Arc<dyn Fn(u64) + Send + Sync>) -> Self {
63 self.sleeper = sleeper;
64 self
65 }
67 /// Send `request` through the failover plan for its target.
68 ///
69 /// The returned stream carries the first endpoint's normalized events;
70 /// faults that occur after a stream starts are terminal for the caller,
71 /// because a partially consumed response cannot be retried honestly.
72 ///
73 /// # Errors
74 ///
75 /// Returns the last provider fault when every endpoint failed, or the
76 /// first non-failover fault (invalid request, authentication).
77 pub fn route(
78 &self,
79 target: &str,
80 request: &ProviderRequest,
81 cancel: &CancelHandle,
82 ) -> Result<ProviderStream> {
83 let plan = self.catalog.resolve_plan(target)?;
84 let mut last_fault: Option<SmithError> = None;
85 for entry in plan {
86 let Some(endpoint) = self.endpoints.get(&entry.id) else {
87 continue;
88 };
89 let mut attempt: u32 = 0;
90 let mut endpoint_failed = false;
91 while !endpoint_failed {
92 if cancel.is_cancelled() {
93 return Err(SmithError::Cancelled);
94 }
95 self.catalog.validate_request(&entry.id, request)?;
96 let mut routed = request.clone();
97 routed.model.clone_from(&endpoint.model);
98 let stream = (endpoint.stream)(routed, cancel.clone());
99 // Establishment faults surface as the first stream item;
100 // classify them before the caller consumes anything.
101 match first_item(stream) {
102 Ok(events) => return Ok(events),
103 Err(err) => match &err {
104 SmithError::Provider { fault }
105 if fault.may_fail_over()
106 && !matches!(
107 fault,
108 ProviderFault::Transient { .. } if attempt < self.transient_retries
109 ) =>
110 {
111 last_fault = Some(err);
112 endpoint_failed = true;
113 }
114 SmithError::Provider {
115 fault: ProviderFault::Transient { .. },
116 } if attempt < self.transient_retries => {
117 attempt += 1;
118 (self.sleeper)(50 * u64::from(attempt));
119 }
120 _ => return Err(err),
121 },
122 }
123 }
124 }
125 Err(last_fault.unwrap_or_else(|| SmithError::Provider {
126 fault: ProviderFault::Protocol {
127 message: format!("no endpoint serves '{target}'"),
128 },
129 }))
130 }
131}
133/// Split off the first stream item so establishment faults classify before
134/// the caller consumes anything.
135fn first_item(stream: ProviderStream) -> std::result::Result<ProviderStream, SmithError> {
136 let mut stream = stream;
137 let mut buffer: Vec<smith::provider::StreamItem> = Vec::new();
138 match futures::executor::block_on(stream.next()) {
139 Some(item) => {
140 if let Err(err) = &item {
141 return Err(err.clone());
142 }
143 buffer.push(item);
144 Ok(Box::pin(
145 futures::stream::iter(buffer).chain(ProviderStreamRest(stream)),
146 ))
147 }
148 None => Ok(Box::pin(futures::stream::iter(buffer))),
149 }
150}
152/// Adapter that yields the remainder of a partially consumed stream.
153struct ProviderStreamRest(ProviderStream);
155impl futures::Stream for ProviderStreamRest {
156 type Item = smith::provider::StreamItem;
158 fn poll_next(
159 mut self: std::pin::Pin<&mut Self>,
160 cx: &mut std::task::Context<'_>,
161 ) -> std::task::Poll<Option<Self::Item>> {
162 std::pin::Pin::new(&mut self.0).poll_next(cx)
163 }
164}
166#[cfg(test)]
167#[expect(clippy::unwrap_used, reason = "router tests script fault streams")]
168mod tests {
169 use super::*;
170 use futures::StreamExt;
171 use smith::id::MessageId;
172 use smith::message::{Message, Role};
173 use smith::stream::{StopReason, StreamEvent, Usage};
174 use std::sync::atomic::{AtomicUsize, Ordering};
176 fn catalog() -> Catalog {
177 Catalog::from_json(
178 r#"{
179 "models": {
180 "primary": {"id": "primary", "provider": "OpenAiCompatible", "capabilities": {
181 "context_window": 8192, "max_output_tokens": 1024, "input_images": false,
182 "tool_use": true, "thinking": false, "strict_tool_input": false, "cache_control": false}},
183 "backup": {"id": "backup", "provider": "OpenAiCompatible", "capabilities": {
184 "context_window": 8192, "max_output_tokens": 1024, "input_images": false,
185 "tool_use": true, "thinking": false, "strict_tool_input": false, "cache_control": false}}
186 },
187 "aliases": {},
188 "groups": { "plan": ["primary", "backup"] }
189 }"#,
190 )
191 .unwrap()
192 }
194 fn scripted(outcome: std::sync::Arc<std::sync::Mutex<Vec<Result<StreamEvent>>>>) -> StreamFn {
195 Arc::new(move |_request, _cancel| {
196 let item = { outcome.lock().unwrap().remove(0) };
197 futures::stream::iter(vec![item]).boxed()
198 })
199 }
201 fn request() -> ProviderRequest {
202 ProviderRequest::new("plan", vec![Message::with_text(Role::User, "hi")])
203 }
205 fn rate_limit() -> SmithError {
206 SmithError::Provider {
207 fault: ProviderFault::RateLimit {
208 retry_after_ms: None,
209 },
210 }
211 }
213 fn ok_stream() -> Vec<Result<StreamEvent>> {
214 vec![Ok(StreamEvent::stop(
215 StopReason::EndTurn,
216 Some(Usage::new()),
217 ))]
218 }
220 fn drain(mut stream: ProviderStream) -> Result<StreamEvent> {
221 let _ = MessageId::new();
222 futures::executor::block_on(stream.next()).unwrap()
223 }
225 fn route_err(
226 router: &Router,
227 target: &str,
228 request: &ProviderRequest,
229 cancel: &CancelHandle,
230 ) -> SmithError {
231 match router.route(target, request, cancel) {
232 Err(err) => err,
233 Ok(_) => unreachable!("routing must fail in this scenario"),
234 }
235 }
237 #[test]
238 fn rate_limits_fail_over_immediately() {
239 let primary_calls = Arc::new(AtomicUsize::new(0));
240 let primary_seen = Arc::clone(&primary_calls);
241 let primary: StreamFn = Arc::new(move |_request, _cancel| {
242 primary_seen.fetch_add(1, Ordering::SeqCst);
243 futures::stream::iter(vec![Err(rate_limit())]).boxed()
244 });
245 let backup: StreamFn = {
246 let events = Arc::new(std::sync::Mutex::new(vec![Ok(StreamEvent::text_delta(
247 MessageId::new(),
248 "backup",
249 ))]));
250 scripted(events)
251 };
252 let endpoints = HashMap::from([
253 (
254 "primary".to_string(),
255 Endpoint {
256 model: "primary".to_string(),
257 stream: primary,
258 },
259 ),
260 (
261 "backup".to_string(),
262 Endpoint {
263 model: "backup".to_string(),
264 stream: backup,
265 },
266 ),
267 ]);
268 let router = Router::new(catalog(), endpoints, 2).unwrap();
269 let stream = router
270 .route("plan", &request(), &CancelHandle::new())
271 .unwrap();
272 assert!(matches!(drain(stream), Ok(StreamEvent::TextDelta { .. })));
273 // Rate limit fails over without retrying the same endpoint.
274 assert_eq!(primary_calls.load(Ordering::SeqCst), 1);
275 }
277 #[test]
278 fn transient_faults_retry_bounded_then_fail_over() {
279 let primary_attempts = Arc::new(AtomicUsize::new(0));
280 let seen = Arc::clone(&primary_attempts);
281 let primary: StreamFn = Arc::new(move |_request, _cancel| {
282 let count = seen.fetch_add(1, Ordering::SeqCst);
283 let item = if count < 2 {
284 Err(SmithError::Provider {
285 fault: ProviderFault::Transient {
286 message: "reset".to_string(),
287 },
288 })
289 } else {
290 Ok(StreamEvent::stop(StopReason::EndTurn, None))
291 };
292 futures::stream::iter(vec![item]).boxed()
293 });
294 let endpoints = HashMap::from([(
295 "primary".to_string(),
296 Endpoint {
297 model: "primary".to_string(),
298 stream: primary,
299 },
300 )]);
301 let router = Router::new(catalog(), endpoints, 2).unwrap();
302 let stream = router
303 .route("primary", &request(), &CancelHandle::new())
304 .unwrap();
305 assert!(matches!(drain(stream), Ok(StreamEvent::Stop { .. })));
306 }
308 #[test]
309 fn invalid_requests_fail_without_failover() {
310 let endpoints = HashMap::from([
311 (
312 "primary".to_string(),
313 Endpoint {
314 model: "primary".to_string(),
315 stream: scripted(Arc::new(std::sync::Mutex::new(ok_stream()))),
316 },
317 ),
318 (
319 "backup".to_string(),
320 Endpoint {
321 model: "backup".to_string(),
322 stream: scripted(Arc::new(std::sync::Mutex::new(ok_stream()))),
323 },
324 ),
325 ]);
326 let router = Router::new(catalog(), endpoints, 2).unwrap();
327 let mut invalid = request();
328 invalid.params.thinking = true;
329 let err = route_err(&router, "plan", &invalid, &CancelHandle::new());
330 assert_eq!(err.code(), "PROVIDER_INVALID");
331 }
333 #[test]
334 fn exhausting_the_plan_surfaces_the_last_fault() {
335 let endpoints = HashMap::from([
336 (
337 "primary".to_string(),
338 Endpoint {
339 model: "primary".to_string(),
340 stream: scripted(Arc::new(std::sync::Mutex::new(vec![Err(rate_limit())]))),
341 },
342 ),
343 (
344 "backup".to_string(),
345 Endpoint {
346 model: "backup".to_string(),
347 stream: scripted(Arc::new(std::sync::Mutex::new(vec![Err(rate_limit())]))),
348 },
349 ),
350 ]);
351 let router = Router::new(catalog(), endpoints, 2).unwrap();
352 let err = route_err(&router, "plan", &request(), &CancelHandle::new());
353 assert_eq!(err.code(), "PROVIDER_RATE_LIMIT");
354 }
355}