1use crate::interface::backoff::LadderBackoff;
59use crate::interface::model::ModelErrorKind;
60use std::time::Duration;
61
62#[non_exhaustive]
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct ModelFailure<'a> {
67 pub kind: ModelErrorKind,
68 pub message: &'a str,
69 pub retry_after: Option<Duration>,
71 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
99pub struct CallRecovery {
100 pub compacted: bool,
101 pub same_retries: u32,
103}
104
105pub const MAX_RECOVERIES_PER_CALL: u32 = 4;
107
108#[derive(Debug, Clone, PartialEq, Eq)]
110pub enum Recovery {
111 Fail,
113 CompactAndRetry,
117 RetrySame { after: Duration },
120}
121
122#[derive(Debug, Clone, PartialEq, Eq)]
124pub enum StopRecovery {
125 Accept,
127 Continue,
132 RaiseOutputLimit {
134 max_tokens: u32,
136 nudge: Option<String>,
141 },
142}
143
144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146pub struct RecoveryAttempt {
147 pub output_limit_escalations: u32,
149 pub current_max_tokens: u32,
151}
152
153pub trait RecoveryPolicy: Send + Sync {
155 fn on_failure(&self, failure: &ModelFailure<'_>, so_far: &CallRecovery) -> Recovery;
157
158 fn on_early_stop(&self, reason: &str, attempt: &RecoveryAttempt) -> StopRecovery;
170}
171
172pub struct DefaultRecovery {
174 pub max_output_escalations: u32,
176}
177
178impl DefaultRecovery {
179 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 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
243pub 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 #[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}