Skip to main content

causa_runtime/retry/
gateway.rs

1//! Retrying `ModelGateway` wrapper: attempt loop, backoff and control.
2
3use std::future::Future;
4use std::time::Instant;
5
6use async_trait::async_trait;
7use causa_kernel::{
8    CallControl, ControlError, ModelGateway, ModelInvokeError, ModelInvokeErrorKind, ModelOutput,
9    ModelRequest, ModelStream, StreamDelta,
10};
11use futures_util::StreamExt;
12
13use super::RetryPolicy;
14
15/// A [`ModelGateway`] that retries an inner gateway under a [`RetryPolicy`].
16///
17/// The wrapper is an ordinary gateway — no new trait, no runner option, off
18/// unless the host builds one — and every attempt sends the same
19/// [`ModelRequest`].
20///
21/// - Only [`ModelInvokeErrorKind::Transient`] and
22///   [`ModelInvokeErrorKind::TimedOut`] failures are retried. `Permanent`,
23///   `Undecodable`, `InvalidRequest`, `Cancelled` and `UnknownOutcome` are
24///   never retried,
25///   and there is no setting for that.
26/// - `invoke` and `stream` share the policy; each logical call counts its
27///   own attempts.
28/// - `stream` reads the inner stream's first item before returning. An inner
29///   error, or a first item that is a [`StreamDelta::Error`] with a retryable
30///   kind, starts another attempt. Any other first item is handed on followed
31///   by the rest of the stream, and the call is never retried from then on —
32///   a failure after the first delta reaches the caller unchanged. An inner
33///   stream that ends before yielding any item is classified `UnknownOutcome`
34///   and never retried.
35/// - A wait is raced against the caller's [`CallControl`]: cancellation during
36///   a wait returns `Cancelled`, and a wait that would reach the parent
37///   deadline returns the last error instead of waiting. The wrapper never
38///   extends the parent deadline and never cancels the parent token.
39/// - A server-requested delay ([`ModelInvokeError::retry_delay`]) is waited as
40///   given while it is at or below `max_server_delay`; above the ceiling the
41///   call fails at once. Without one, the wrapper uses its own jittered
42///   exponential backoff.
43/// - One `tracing` event per retry records the attempt, the failure kind and
44///   the wait.
45#[derive(Clone)]
46pub struct RetryingGateway<G: ModelGateway> {
47    inner: G,
48    policy: RetryPolicy,
49}
50
51impl<G: ModelGateway> std::fmt::Debug for RetryingGateway<G> {
52    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        f.debug_struct("RetryingGateway")
54            .field("policy", &self.policy)
55            .finish_non_exhaustive()
56    }
57}
58
59impl<G: ModelGateway> RetryingGateway<G> {
60    /// Wraps `inner` with `policy`. The wrapped value stays reachable
61    /// through [`RetryingGateway::inner`]; a host that wants a shared trait
62    /// object builds the wrapper around the concrete gateway and coerces
63    /// `Arc::new(RetryingGateway::new(gateway, policy))` to
64    /// `Arc<dyn ModelGateway>`.
65    pub fn new(inner: G, policy: RetryPolicy) -> Self {
66        Self { inner, policy }
67    }
68
69    /// The retry policy in force.
70    pub fn policy(&self) -> &RetryPolicy {
71        &self.policy
72    }
73
74    /// The wrapped gateway.
75    pub fn inner(&self) -> &G {
76        &self.inner
77    }
78
79    /// Whether `error` may start another attempt after `attempt` calls.
80    fn retryable(&self, error: &ModelInvokeError, attempt: u32) -> bool {
81        attempt < self.policy.max_attempts
82            && matches!(
83                error.kind,
84                ModelInvokeErrorKind::Transient | ModelInvokeErrorKind::TimedOut
85            )
86    }
87
88    /// Wait before the next attempt. `Err` means the call gives up and
89    /// reports that error instead: a server delay above the ceiling, or a
90    /// wait that would reach the parent deadline.
91    async fn wait(
92        &self,
93        attempt: u32,
94        error: &ModelInvokeError,
95        control: &CallControl,
96    ) -> Result<(), ModelInvokeError> {
97        let delay = match error.retry_delay {
98            Some(server) if server <= self.policy.max_server_delay => server,
99            // The provider asked for longer than the host allows: do not wait.
100            Some(_) => return Err(error.clone()),
101            None => self.policy.backoff(attempt),
102        };
103        if let Some(deadline) = control.deadline()
104            && Instant::now()
105                .checked_add(delay)
106                .is_none_or(|end| end >= deadline)
107        {
108            // The wait would reach or pass the parent deadline: report the
109            // last error now rather than extend the call.
110            return Err(error.clone());
111        }
112        tracing::debug!(
113            target: "causa_runtime::retry",
114            attempt,
115            max_attempts = self.policy.max_attempts,
116            kind = ?error.kind,
117            wait_ms = u64::try_from(delay.as_millis()).unwrap_or(u64::MAX),
118            "retrying model invocation"
119        );
120        tokio::select! {
121            biased;
122            _ = control.cancellation_token().cancelled() => {
123                Err(control_error(ControlError::Cancelled))
124            }
125            _ = tokio::time::sleep(delay) => match control.check() {
126                Ok(()) => Ok(()),
127                Err(ControlError::Cancelled) => Err(control_error(ControlError::Cancelled)),
128                // The deadline arrived while waiting: the last error stands
129                // and no further attempt starts.
130                Err(ControlError::TimedOut) => Err(error.clone()),
131            },
132        }
133    }
134}
135
136#[async_trait]
137impl<G: ModelGateway> ModelGateway for RetryingGateway<G> {
138    async fn invoke(
139        &self,
140        request: &ModelRequest,
141        control: &CallControl,
142    ) -> Result<ModelOutput, ModelInvokeError> {
143        let mut attempt = 1;
144        loop {
145            check_control(control)?;
146            match under_control(control, self.inner.invoke(request, control)).await {
147                Attempt::Stopped(error) => return Err(error),
148                Attempt::Ran(Ok(output)) => return Ok(output),
149                Attempt::Ran(Err(error)) => {
150                    if !self.retryable(&error, attempt) {
151                        return Err(error);
152                    }
153                    self.wait(attempt, &error, control).await?;
154                    attempt += 1;
155                }
156            }
157        }
158    }
159
160    async fn stream(
161        &self,
162        request: &ModelRequest,
163        control: &CallControl,
164    ) -> Result<ModelStream, ModelInvokeError> {
165        let mut attempt = 1;
166        loop {
167            check_control(control)?;
168            let first = under_control(control, async {
169                let mut source = self.inner.stream(request, control).await?;
170                Ok(source.next().await.map(|delta| (delta, source)))
171            })
172            .await;
173            match first {
174                Attempt::Stopped(error) => return Err(error),
175                Attempt::Ran(Err(error)) => {
176                    if !self.retryable(&error, attempt) {
177                        return Err(error);
178                    }
179                    self.wait(attempt, &error, control).await?;
180                    attempt += 1;
181                }
182                // No item means no Done either: the wrapper classifies the
183                // empty stream itself and never retries UnknownOutcome.
184                Attempt::Ran(Ok(None)) => {
185                    return Err(ModelInvokeError::new(
186                        ModelInvokeErrorKind::UnknownOutcome,
187                        "model stream ended without Done before yielding any item",
188                    ));
189                }
190                Attempt::Ran(Ok(Some((first, source)))) => {
191                    if let StreamDelta::Error { error } = &first
192                        && self.retryable(error, attempt)
193                    {
194                        let error = error.clone();
195                        // The failed attempt never reached the caller, so the
196                        // policy applies exactly as before establishment.
197                        self.wait(attempt, &error, control).await?;
198                        attempt += 1;
199                        continue;
200                    }
201                    // Returning this stream is the irrevocable visibility
202                    // boundary: nothing after the first item is retried.
203                    return Ok(Box::pin(
204                        futures_util::stream::once(async move { first }).chain(source),
205                    ));
206                }
207            }
208        }
209    }
210}
211
212/// One attempt's outcome, or the control stop that ended the call.
213enum Attempt<T> {
214    /// The attempt ran; its result applies.
215    Ran(Result<T, ModelInvokeError>),
216    /// The caller's control stopped the call first; never retried.
217    Stopped(ModelInvokeError),
218}
219
220/// Race one attempt against the caller's cancellation and deadline. Racing
221/// here keeps the wrapper's own waits and attempts bounded even around an
222/// inner gateway that does not check the control plane itself.
223async fn under_control<T>(
224    control: &CallControl,
225    work: impl Future<Output = Result<T, ModelInvokeError>>,
226) -> Attempt<T> {
227    tokio::select! {
228        biased;
229        cause = stop(control) => Attempt::Stopped(control_error(cause)),
230        result = work => Attempt::Ran(result),
231    }
232}
233
234/// The caller's cancellation or deadline, whichever arrives first.
235async fn stop(control: &CallControl) -> ControlError {
236    tokio::select! {
237        biased;
238        _ = control.cancellation_token().cancelled() => ControlError::Cancelled,
239        _ = async {
240            match control.deadline() {
241                Some(deadline) => tokio::time::sleep_until(deadline.into()).await,
242                None => std::future::pending::<()>().await,
243            }
244        } => ControlError::TimedOut,
245    }
246}
247
248fn check_control(control: &CallControl) -> Result<(), ModelInvokeError> {
249    control.check().map_err(control_error)
250}
251
252fn control_error(cause: ControlError) -> ModelInvokeError {
253    match cause {
254        ControlError::Cancelled => ModelInvokeError::new(
255            ModelInvokeErrorKind::Cancelled,
256            "model invocation cancelled",
257        ),
258        ControlError::TimedOut => ModelInvokeError::new(
259            ModelInvokeErrorKind::TimedOut,
260            "model invocation deadline exceeded",
261        ),
262    }
263}