Skip to main content

base/interface/
recovery_policy.rs

1//! `RecoveryPolicy` — what to do when a model call goes wrong.
2//!
3//! The engine's own answers ([`DefaultRecovery`]): a request refused for size
4//! is compacted and retried once. A transient
5//! failure after the stream had started — a stream that broke off, went
6//! silent, or ended in an overload event — is sent again as it was, twice at
7//! most, after 2s and then 8s, or after the provider's own `retry-after` —
8//! unless it asks for longer than the client's ladder would wait
9//! ([`LadderBackoff::MAX_SERVER_HINT`]), which fails instead. Anything else
10//! fails. A response cut off at the
11//! output limit escalates the limit — to 64K the first time, 8K after that,
12//! three attempts, each time with a user message saying the reply was cut off
13//! and asking it to go on; the engine holds the raised limit to what the model
14//! accepts. A response the provider paused is sent back to be continued.
15//!
16//! Every one of those is a reasonable answer and none of them is the only
17//! one. One paying per token would rather fail than escalate to 64K. Moving
18//! to another provider is not among them: the router does that below the
19//! turn, before a failure reaches this policy.
20//!
21//! # Which failures reach it
22//!
23//! A failure is put to the policy when nothing of the call has been kept: the
24//! provider refused the request, or its stream broke off — an error event, or
25//! an end before the message's — before the reply asked for a tool. The
26//! partial reply is dropped, so what a recovery retries is the request that
27//! failed. Once a tool has run, the reply stays in the transcript with its
28//! results and the turn ends with the error: sending it again would run the
29//! tool again.
30//!
31//! A failure before the first byte has already been through the client's own
32//! backoff ([`BackoffPolicy`](crate::interface::backoff::BackoffPolicy)), so
33//! sending the same request again is not this policy's to decide — that
34//! would multiply one ladder by another. [`ModelFailure::after_first_byte`]
35//! says which side of that line a failure is on.
36//!
37//! What one call has already spent is handed in as [`CallRecovery`]. However
38//! the policy answers, the loop recovers one call at most
39//! [`MAX_RECOVERIES_PER_CALL`] times.
40//!
41//! # The policy decides; the loop acts
42//!
43//! Recovery *mechanisms* — compacting, rebuilding a request, sending it —
44//! belong to the turn: they touch the session, the compactor and the model in
45//! ways that only the loop can sequence correctly. What was missing is the
46//! choice between them. So this contract answers "what should happen", in a
47//! vocabulary the loop already implements, and nothing else. That is what
48//! keeps the skeleton closed while the decision opens.
49//!
50//! # Attempt counts are the policy's memory
51//!
52//! Both recovery paths bound themselves with a counter the loop kept. The
53//! counters are still the loop's — they belong to one turn, and a policy is
54//! shared across turns — but they are *given* to the policy, so a policy that
55//! wants to allow four escalations rather than three needs no state of its
56//! own.
57
58use crate::interface::backoff::LadderBackoff;
59use crate::interface::model::ModelErrorKind;
60use std::time::Duration;
61
62/// Why a model call failed: the protocol client's classification, carried
63/// over as it stands.
64#[non_exhaustive]
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct ModelFailure<'a> {
67    pub kind: ModelErrorKind,
68    pub message: &'a str,
69    /// How long the provider asked to be left alone, when it said.
70    pub retry_after: Option<Duration>,
71    /// The provider had started answering: the client's backoff no longer
72    /// covered this call.
73    pub after_first_byte: bool,
74}
75
76impl<'a> ModelFailure<'a> {
77    pub fn new(kind: ModelErrorKind, message: &'a str) -> Self {
78        Self {
79            kind,
80            message,
81            retry_after: None,
82            after_first_byte: false,
83        }
84    }
85
86    pub fn with_retry_after(mut self, retry_after: Option<Duration>) -> Self {
87        self.retry_after = retry_after;
88        self
89    }
90
91    pub fn with_after_first_byte(mut self, after_first_byte: bool) -> Self {
92        self.after_first_byte = after_first_byte;
93        self
94    }
95}
96
97/// What one model call has already spent on recovering.
98#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
99pub struct CallRecovery {
100    pub compacted: bool,
101    /// [`Recovery::RetrySame`]s so far.
102    pub same_retries: u32,
103}
104
105/// The most recoveries the loop gives one call, whatever the policy answers.
106pub const MAX_RECOVERIES_PER_CALL: u32 = 4;
107
108/// What the turn should do about it.
109#[derive(Debug, Clone, PartialEq, Eq)]
110pub enum Recovery {
111    /// Give up. The turn fails and the message reaches the host.
112    Fail,
113    /// Shorten the conversation, then retry against the same model. Failing to
114    /// shorten it is a failure: retrying an unshortened request that was
115    /// refused for size just spends another call to be told the same thing.
116    CompactAndRetry,
117    /// Wait, then send the same request again. The host is told with a
118    /// `model_retry` event, and the step starts over.
119    RetrySame { after: Duration },
120}
121
122/// What to do about a response that stopped early.
123#[derive(Debug, Clone, PartialEq, Eq)]
124pub enum StopRecovery {
125    /// Accept the response as it is.
126    Accept,
127    /// Send the conversation again as it stands, the response included, so
128    /// the model picks up where it stopped — what a provider asks for with
129    /// `pause_turn`. Each continuation is another call of the turn, bounded
130    /// by the turn policy's ceiling on calls.
131    Continue,
132    /// Raise the output limit and ask again.
133    RaiseOutputLimit {
134        /// Held to the model's own output limit by the engine.
135        max_tokens: u32,
136        /// Text to append as a user message before retrying, if any. Without
137        /// one the retry ends on the cut-off reply, which the provider takes
138        /// as a prefill to continue — and several refuse: Anthropic with
139        /// thinking on, or when the reply ends in whitespace.
140        nudge: Option<String>,
141    },
142}
143
144/// How many times this turn has already tried to recover.
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146pub struct RecoveryAttempt {
147    /// Output-limit escalations so far in this turn.
148    pub output_limit_escalations: u32,
149    /// The limit currently in force.
150    pub current_max_tokens: u32,
151}
152
153/// What to do when a model call goes wrong.
154pub trait RecoveryPolicy: Send + Sync {
155    /// The call failed, after `so_far` was already spent on it.
156    fn on_failure(&self, failure: &ModelFailure<'_>, so_far: &CallRecovery) -> Recovery;
157
158    /// The call succeeded but stopped early — `reason` is the model's own
159    /// stop reason.
160    ///
161    /// Asked only for a reply that called no tools, after
162    /// [`TurnPolicy::after_model_call`] let the turn go on. A retry decided
163    /// here comes before the `Stop` hook and before
164    /// [`BudgetPolicy::on_output_target`], which see the reply only when this
165    /// gives up.
166    ///
167    /// [`TurnPolicy::after_model_call`]: crate::interface::turn_policy::TurnPolicy::after_model_call
168    /// [`BudgetPolicy::on_output_target`]: crate::interface::budget_policy::BudgetPolicy::on_output_target
169    fn on_early_stop(&self, reason: &str, attempt: &RecoveryAttempt) -> StopRecovery;
170}
171
172/// The engine's own answers.
173pub struct DefaultRecovery {
174    /// How many output-limit escalations a turn may spend.
175    pub max_output_escalations: u32,
176}
177
178impl DefaultRecovery {
179    /// First escalation goes straight to 64K on the theory that a response cut
180    /// off once will be cut off again at a smaller bump; later ones settle at
181    /// 8K. The engine holds either to the model's own limit.
182    pub const FIRST_ESCALATION: u32 = 64_000;
183    pub const LATER_ESCALATION: u32 = 8_000;
184
185    pub const NUDGE: &'static str = "Your previous reply was cut off at the output token \
186                                     limit. Continue from exactly where it stopped — no \
187                                     apology, no recap of what you were doing. Pick up \
188                                     mid-thought if that is where the cut happened. Break \
189                                     remaining work into smaller pieces.";
190
191    /// How long to wait before each [`Recovery::RetrySame`] when the provider
192    /// named no delay. Its length is the budget.
193    pub const SAME_RETRY_DELAYS: &'static [Duration] =
194        &[Duration::from_secs(2), Duration::from_secs(8)];
195}
196
197impl Default for DefaultRecovery {
198    fn default() -> Self {
199        Self {
200            max_output_escalations: 3,
201        }
202    }
203}
204
205impl RecoveryPolicy for DefaultRecovery {
206    fn on_failure(&self, failure: &ModelFailure<'_>, so_far: &CallRecovery) -> Recovery {
207        if failure.kind == ModelErrorKind::ContextTooLong && !so_far.compacted {
208            return Recovery::CompactAndRetry;
209        }
210        if failure.after_first_byte && failure.kind.transient() {
211            if let Some(delay) = Self::SAME_RETRY_DELAYS.get(so_far.same_retries as usize) {
212                return match failure.retry_after {
213                    Some(hint) if hint > LadderBackoff::MAX_SERVER_HINT => Recovery::Fail,
214                    hint => Recovery::RetrySame {
215                        after: hint.unwrap_or(*delay),
216                    },
217                };
218            }
219        }
220        Recovery::Fail
221    }
222
223    fn on_early_stop(&self, reason: &str, attempt: &RecoveryAttempt) -> StopRecovery {
224        if reason == "pause_turn" {
225            return StopRecovery::Continue;
226        }
227        if reason != "max_tokens" || attempt.output_limit_escalations >= self.max_output_escalations
228        {
229            return StopRecovery::Accept;
230        }
231        let max_tokens = if attempt.output_limit_escalations == 0 {
232            attempt.current_max_tokens.max(Self::FIRST_ESCALATION)
233        } else {
234            attempt.current_max_tokens.max(Self::LATER_ESCALATION)
235        };
236        StopRecovery::RaiseOutputLimit {
237            max_tokens,
238            nudge: Some(Self::NUDGE.to_string()),
239        }
240    }
241}
242
243/// Fails on everything and escalates nothing.
244///
245/// The second implementation, and a real configuration rather than a stub: a
246/// deployment billed per token, or one running a batch where a surprise 64K
247/// call is worse than a truncated answer, wants exactly this.
248pub struct NeverRecover;
249
250impl RecoveryPolicy for NeverRecover {
251    fn on_failure(&self, _failure: &ModelFailure<'_>, _so_far: &CallRecovery) -> Recovery {
252        Recovery::Fail
253    }
254
255    fn on_early_stop(&self, _reason: &str, _attempt: &RecoveryAttempt) -> StopRecovery {
256        StopRecovery::Accept
257    }
258}
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263
264    fn failure(kind: ModelErrorKind) -> ModelFailure<'static> {
265        ModelFailure::new(kind, "")
266    }
267
268    fn streamed(kind: ModelErrorKind) -> ModelFailure<'static> {
269        ModelFailure::new(kind, "").with_after_first_byte(true)
270    }
271
272    fn fresh() -> CallRecovery {
273        CallRecovery::default()
274    }
275
276    fn attempt(escalations: u32, max_tokens: u32) -> RecoveryAttempt {
277        RecoveryAttempt {
278            output_limit_escalations: escalations,
279            current_max_tokens: max_tokens,
280        }
281    }
282
283    #[test]
284    fn an_overload_before_the_first_byte_fails() {
285        assert_eq!(
286            DefaultRecovery::default().on_failure(&failure(ModelErrorKind::Overloaded), &fresh()),
287            Recovery::Fail,
288            "before the first byte the client's ladder already waited"
289        );
290    }
291
292    #[test]
293    fn a_request_refused_for_size_is_shortened_rather_than_resent() {
294        assert_eq!(
295            DefaultRecovery::default()
296                .on_failure(&failure(ModelErrorKind::ContextTooLong), &fresh()),
297            Recovery::CompactAndRetry
298        );
299    }
300
301    #[test]
302    fn anything_else_fails() {
303        assert_eq!(
304            DefaultRecovery::default().on_failure(&failure(ModelErrorKind::Transport), &fresh()),
305            Recovery::Fail
306        );
307    }
308
309    #[test]
310    fn a_request_is_compacted_once() {
311        let compacted = CallRecovery {
312            compacted: true,
313            ..fresh()
314        };
315        assert_eq!(
316            DefaultRecovery::default()
317                .on_failure(&failure(ModelErrorKind::ContextTooLong), &compacted),
318            Recovery::Fail
319        );
320    }
321
322    #[test]
323    fn a_stream_that_broke_off_is_sent_again_twice() {
324        let p = DefaultRecovery::default();
325        let after = |same_retries| {
326            p.on_failure(
327                &streamed(ModelErrorKind::StreamInterrupted),
328                &CallRecovery {
329                    same_retries,
330                    ..fresh()
331                },
332            )
333        };
334        assert_eq!(
335            after(0),
336            Recovery::RetrySame {
337                after: Duration::from_secs(2)
338            }
339        );
340        assert_eq!(
341            after(1),
342            Recovery::RetrySame {
343                after: Duration::from_secs(8)
344            }
345        );
346        assert_eq!(after(2), Recovery::Fail);
347    }
348
349    #[test]
350    fn the_providers_delay_wins_over_the_default() {
351        let hinted =
352            streamed(ModelErrorKind::Overloaded).with_retry_after(Some(Duration::from_secs(5)));
353        assert_eq!(
354            DefaultRecovery::default().on_failure(&hinted, &fresh()),
355            Recovery::RetrySame {
356                after: Duration::from_secs(5)
357            }
358        );
359    }
360
361    #[test]
362    fn a_provider_delay_beyond_the_ladders_cap_is_not_waited_for() {
363        let p = DefaultRecovery::default();
364        let asking = |delay| streamed(ModelErrorKind::Overloaded).with_retry_after(Some(delay));
365        assert_eq!(
366            p.on_failure(&asking(LadderBackoff::MAX_SERVER_HINT), &fresh()),
367            Recovery::RetrySame {
368                after: LadderBackoff::MAX_SERVER_HINT
369            }
370        );
371        assert_eq!(
372            p.on_failure(
373                &asking(LadderBackoff::MAX_SERVER_HINT + Duration::from_secs(1)),
374                &fresh()
375            ),
376            Recovery::Fail
377        );
378        assert_eq!(
379            p.on_failure(&asking(Duration::from_secs(u64::MAX)), &fresh()),
380            Recovery::Fail
381        );
382    }
383
384    #[test]
385    fn only_a_transient_failure_after_the_first_byte_is_sent_again() {
386        let p = DefaultRecovery::default();
387        for kind in [ModelErrorKind::Timeout, ModelErrorKind::Transport] {
388            assert_eq!(
389                p.on_failure(&failure(kind), &fresh()),
390                Recovery::Fail,
391                "{kind}: before the first byte"
392            );
393            assert!(matches!(
394                p.on_failure(&streamed(kind), &fresh()),
395                Recovery::RetrySame { .. }
396            ));
397        }
398        for kind in [
399            ModelErrorKind::Auth,
400            ModelErrorKind::InvalidRequest,
401            ModelErrorKind::Protocol,
402            ModelErrorKind::Cancelled,
403        ] {
404            assert_eq!(
405                p.on_failure(&streamed(kind), &fresh()),
406                Recovery::Fail,
407                "{kind}"
408            );
409        }
410    }
411
412    /// The escalation ladder, which is three numbers and an ordering that a
413    /// reader has no way to check against intent — so it is checked here.
414    #[test]
415    fn the_escalation_ladder_is_64k_then_8k_each_with_a_nudge() {
416        let p = DefaultRecovery::default();
417        assert_eq!(
418            p.on_early_stop("max_tokens", &attempt(0, 2000)),
419            StopRecovery::RaiseOutputLimit {
420                max_tokens: 64_000,
421                nudge: Some(DefaultRecovery::NUDGE.to_string())
422            },
423            "the first retry must not end on the cut-off reply"
424        );
425        assert_eq!(
426            p.on_early_stop("max_tokens", &attempt(1, 64_000)),
427            StopRecovery::RaiseOutputLimit {
428                max_tokens: 64_000,
429                nudge: Some(DefaultRecovery::NUDGE.to_string())
430            },
431            "a limit already above 8K is not lowered to it"
432        );
433        assert_eq!(
434            p.on_early_stop("max_tokens", &attempt(3, 64_000)),
435            StopRecovery::Accept,
436            "three escalations is the bound"
437        );
438    }
439
440    #[test]
441    fn a_paused_response_is_continued_whatever_the_escalations() {
442        let p = DefaultRecovery::default();
443        for escalations in [0, 3] {
444            assert_eq!(
445                p.on_early_stop("pause_turn", &attempt(escalations, 2000)),
446                StopRecovery::Continue
447            );
448        }
449        assert_eq!(
450            NeverRecover.on_early_stop("pause_turn", &attempt(0, 2000)),
451            StopRecovery::Accept
452        );
453    }
454
455    #[test]
456    fn an_ordinary_stop_reason_is_not_a_recovery() {
457        assert_eq!(
458            DefaultRecovery::default().on_early_stop("end_turn", &attempt(0, 2000)),
459            StopRecovery::Accept
460        );
461    }
462
463    #[test]
464    fn a_deployment_can_refuse_to_spend_anything_on_recovery() {
465        assert_eq!(
466            NeverRecover.on_failure(&streamed(ModelErrorKind::Overloaded), &fresh()),
467            Recovery::Fail
468        );
469        assert_eq!(
470            NeverRecover.on_early_stop("max_tokens", &attempt(0, 2000)),
471            StopRecovery::Accept
472        );
473    }
474}