diff --git a/crates/hx-core/src/agent.rs b/crates/hx-core/src/agent.rs index b90e1c2..a8fd7e4 100644 --- a/crates/hx-core/src/agent.rs +++ b/crates/hx-core/src/agent.rs @@ -62,6 +62,10 @@ impl Snap { } } +fn transient(status: u16) -> bool { + matches!(status, 408 | 429 | 500 | 502 | 503 | 529) +} + #[derive(Debug, thiserror::Error)] pub enum Error { #[error(transparent)] @@ -93,6 +97,8 @@ pub struct Agent { max_tokens: u32, effort: hx_ai::Effort, max_turns: u32, + /// First wait before retrying a transient API error; x4 per attempt. + retry_ms: u64, usage: Usage, session: Session, window: ContextWindow, @@ -141,6 +147,7 @@ impl Agent { max_tokens: 16_384, effort: hx_ai::Effort::Off, max_turns: 200, + retry_ms: 1000, usage: Usage::default(), session, window: { @@ -340,6 +347,33 @@ impl Agent { self.bus.emit(ev).await } + /// `provider.stream` with up to 3 retries on transient API errors (before any event was emitted). + // ponytail: ignores `retry-after` (Error::Api carries no headers) and mid-stream failures; add if seen. + async fn stream_retry( + &self, + req: Request, + ) -> Result>, Error> { + let mut wait = self.retry_ms; + for attempt in 1..=4 { + match self.provider.stream(req.clone()).await { + Err(hx_ai::Error::Api { status, .. }) if attempt < 4 && transient(status) => { + self.emit(Event::Info(format!( + "api error {status}; retry {attempt}/3 in {wait}ms" + ))) + .await; + let mut abort = self.abort.clone(); + tokio::select! { + _ = tokio::time::sleep(std::time::Duration::from_millis(wait)) => {} + _ = async { abort.wait_for(|a| *a).await.is_ok() } => return Err(Error::Aborted), + } + wait *= 4; + } + r => return Ok(r?), + } + } + unreachable!() + } + fn aborted(&self) -> bool { *self.abort.borrow() } @@ -375,7 +409,7 @@ impl Agent { max_tokens: self.max_tokens, effort: self.effort, }; - let mut s = self.provider.stream(req).await?; + let mut s = self.stream_retry(req).await?; let mut done = None; let mut abort = self.abort.clone(); loop { @@ -744,6 +778,73 @@ mod tests { ); } + /// Fails with `status` `n` times, then delegates to the script. + struct Flaky(Script, Mutex, u16); + #[async_trait] + impl Provider for Flaky { + async fn stream( + &self, + req: Request, + ) -> hx_ai::Result>> { + let fail = { + let mut n = self.1.lock().unwrap(); + let f = *n > 0; + *n = n.saturating_sub(1); + f + }; + if fail { + self.0.1.lock().unwrap().push(req); + return Err(hx_ai::Error::Api { + status: self.2, + body: "x".into(), + }); + } + self.0.stream(req).await + } + } + + async fn flaky_run(fails: u32, status: u16) -> (Result, usize) { + let p = Arc::new(Flaky( + Script( + Mutex::new(vec![asst(vec![ContentBlock::Text { text: "ok".into() }])]), + Mutex::new(vec![]), + ), + Mutex::new(fails), + status, + )); + let dir = tempfile::tempdir().unwrap(); + let cx = ToolCtx { + cwd: dir.path().into(), + state: Default::default(), + }; + let (mut a, _h) = Agent::new( + p.clone(), + Registry::default(), + Session::open(dir.path().join("s.jsonl")).unwrap(), + cx, + ); + a.retry_ms = 1; + let r = a.run("go").await; + let n = p.0.1.lock().unwrap().len(); + (r, n) + } + + #[tokio::test] + async fn transient_api_errors_are_retried() { + let (r, n) = flaky_run(1, 529).await; + assert!(r.is_ok()); + assert_eq!(n, 2); + let (r, n) = flaky_run(9, 503).await; + assert!(matches!( + r, + Err(Error::Ai(hx_ai::Error::Api { status: 503, .. })) + )); + assert_eq!(n, 4, "1 try + 3 retries"); + let (r, n) = flaky_run(1, 400).await; + assert!(r.is_err()); + assert_eq!(n, 1, "400 is not retried"); + } + #[tokio::test] async fn abort_and_max_turns() { let loop_forever = Arc::new(Script(