use crate::interface::backoff::LadderBackoff;
use crate::interface::model::ModelErrorKind;
use std::time::Duration;
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ModelFailure<'a> {
pub kind: ModelErrorKind,
pub message: &'a str,
pub retry_after: Option<Duration>,
pub after_first_byte: bool,
}
impl<'a> ModelFailure<'a> {
pub fn new(kind: ModelErrorKind, message: &'a str) -> Self {
Self {
kind,
message,
retry_after: None,
after_first_byte: false,
}
}
pub fn with_retry_after(mut self, retry_after: Option<Duration>) -> Self {
self.retry_after = retry_after;
self
}
pub fn with_after_first_byte(mut self, after_first_byte: bool) -> Self {
self.after_first_byte = after_first_byte;
self
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct CallRecovery {
pub compacted: bool,
pub same_retries: u32,
}
pub const MAX_RECOVERIES_PER_CALL: u32 = 4;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Recovery {
Fail,
CompactAndRetry,
RetrySame { after: Duration },
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StopRecovery {
Accept,
Continue,
RaiseOutputLimit {
max_tokens: u32,
nudge: Option<String>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RecoveryAttempt {
pub output_limit_escalations: u32,
pub current_max_tokens: u32,
}
pub trait RecoveryPolicy: Send + Sync {
fn on_failure(&self, failure: &ModelFailure<'_>, so_far: &CallRecovery) -> Recovery;
fn on_early_stop(&self, reason: &str, attempt: &RecoveryAttempt) -> StopRecovery;
}
pub struct DefaultRecovery {
pub max_output_escalations: u32,
}
impl DefaultRecovery {
pub const FIRST_ESCALATION: u32 = 64_000;
pub const LATER_ESCALATION: u32 = 8_000;
pub const NUDGE: &'static str = "Your previous reply was cut off at the output token \
limit. Continue from exactly where it stopped — no \
apology, no recap of what you were doing. Pick up \
mid-thought if that is where the cut happened. Break \
remaining work into smaller pieces.";
pub const SAME_RETRY_DELAYS: &'static [Duration] =
&[Duration::from_secs(2), Duration::from_secs(8)];
}
impl Default for DefaultRecovery {
fn default() -> Self {
Self {
max_output_escalations: 3,
}
}
}
impl RecoveryPolicy for DefaultRecovery {
fn on_failure(&self, failure: &ModelFailure<'_>, so_far: &CallRecovery) -> Recovery {
if failure.kind == ModelErrorKind::ContextTooLong && !so_far.compacted {
return Recovery::CompactAndRetry;
}
if failure.after_first_byte && failure.kind.transient() {
if let Some(delay) = Self::SAME_RETRY_DELAYS.get(so_far.same_retries as usize) {
return match failure.retry_after {
Some(hint) if hint > LadderBackoff::MAX_SERVER_HINT => Recovery::Fail,
hint => Recovery::RetrySame {
after: hint.unwrap_or(*delay),
},
};
}
}
Recovery::Fail
}
fn on_early_stop(&self, reason: &str, attempt: &RecoveryAttempt) -> StopRecovery {
if reason == "pause_turn" {
return StopRecovery::Continue;
}
if reason != "max_tokens" || attempt.output_limit_escalations >= self.max_output_escalations
{
return StopRecovery::Accept;
}
let max_tokens = if attempt.output_limit_escalations == 0 {
attempt.current_max_tokens.max(Self::FIRST_ESCALATION)
} else {
attempt.current_max_tokens.max(Self::LATER_ESCALATION)
};
StopRecovery::RaiseOutputLimit {
max_tokens,
nudge: Some(Self::NUDGE.to_string()),
}
}
}
pub struct NeverRecover;
impl RecoveryPolicy for NeverRecover {
fn on_failure(&self, _failure: &ModelFailure<'_>, _so_far: &CallRecovery) -> Recovery {
Recovery::Fail
}
fn on_early_stop(&self, _reason: &str, _attempt: &RecoveryAttempt) -> StopRecovery {
StopRecovery::Accept
}
}
#[cfg(test)]
mod tests {
use super::*;
fn failure(kind: ModelErrorKind) -> ModelFailure<'static> {
ModelFailure::new(kind, "")
}
fn streamed(kind: ModelErrorKind) -> ModelFailure<'static> {
ModelFailure::new(kind, "").with_after_first_byte(true)
}
fn fresh() -> CallRecovery {
CallRecovery::default()
}
fn attempt(escalations: u32, max_tokens: u32) -> RecoveryAttempt {
RecoveryAttempt {
output_limit_escalations: escalations,
current_max_tokens: max_tokens,
}
}
#[test]
fn an_overload_before_the_first_byte_fails() {
assert_eq!(
DefaultRecovery::default().on_failure(&failure(ModelErrorKind::Overloaded), &fresh()),
Recovery::Fail,
"before the first byte the client's ladder already waited"
);
}
#[test]
fn a_request_refused_for_size_is_shortened_rather_than_resent() {
assert_eq!(
DefaultRecovery::default()
.on_failure(&failure(ModelErrorKind::ContextTooLong), &fresh()),
Recovery::CompactAndRetry
);
}
#[test]
fn anything_else_fails() {
assert_eq!(
DefaultRecovery::default().on_failure(&failure(ModelErrorKind::Transport), &fresh()),
Recovery::Fail
);
}
#[test]
fn a_request_is_compacted_once() {
let compacted = CallRecovery {
compacted: true,
..fresh()
};
assert_eq!(
DefaultRecovery::default()
.on_failure(&failure(ModelErrorKind::ContextTooLong), &compacted),
Recovery::Fail
);
}
#[test]
fn a_stream_that_broke_off_is_sent_again_twice() {
let p = DefaultRecovery::default();
let after = |same_retries| {
p.on_failure(
&streamed(ModelErrorKind::StreamInterrupted),
&CallRecovery {
same_retries,
..fresh()
},
)
};
assert_eq!(
after(0),
Recovery::RetrySame {
after: Duration::from_secs(2)
}
);
assert_eq!(
after(1),
Recovery::RetrySame {
after: Duration::from_secs(8)
}
);
assert_eq!(after(2), Recovery::Fail);
}
#[test]
fn the_providers_delay_wins_over_the_default() {
let hinted =
streamed(ModelErrorKind::Overloaded).with_retry_after(Some(Duration::from_secs(5)));
assert_eq!(
DefaultRecovery::default().on_failure(&hinted, &fresh()),
Recovery::RetrySame {
after: Duration::from_secs(5)
}
);
}
#[test]
fn a_provider_delay_beyond_the_ladders_cap_is_not_waited_for() {
let p = DefaultRecovery::default();
let asking = |delay| streamed(ModelErrorKind::Overloaded).with_retry_after(Some(delay));
assert_eq!(
p.on_failure(&asking(LadderBackoff::MAX_SERVER_HINT), &fresh()),
Recovery::RetrySame {
after: LadderBackoff::MAX_SERVER_HINT
}
);
assert_eq!(
p.on_failure(
&asking(LadderBackoff::MAX_SERVER_HINT + Duration::from_secs(1)),
&fresh()
),
Recovery::Fail
);
assert_eq!(
p.on_failure(&asking(Duration::from_secs(u64::MAX)), &fresh()),
Recovery::Fail
);
}
#[test]
fn only_a_transient_failure_after_the_first_byte_is_sent_again() {
let p = DefaultRecovery::default();
for kind in [ModelErrorKind::Timeout, ModelErrorKind::Transport] {
assert_eq!(
p.on_failure(&failure(kind), &fresh()),
Recovery::Fail,
"{kind}: before the first byte"
);
assert!(matches!(
p.on_failure(&streamed(kind), &fresh()),
Recovery::RetrySame { .. }
));
}
for kind in [
ModelErrorKind::Auth,
ModelErrorKind::InvalidRequest,
ModelErrorKind::Protocol,
ModelErrorKind::Cancelled,
] {
assert_eq!(
p.on_failure(&streamed(kind), &fresh()),
Recovery::Fail,
"{kind}"
);
}
}
#[test]
fn the_escalation_ladder_is_64k_then_8k_each_with_a_nudge() {
let p = DefaultRecovery::default();
assert_eq!(
p.on_early_stop("max_tokens", &attempt(0, 2000)),
StopRecovery::RaiseOutputLimit {
max_tokens: 64_000,
nudge: Some(DefaultRecovery::NUDGE.to_string())
},
"the first retry must not end on the cut-off reply"
);
assert_eq!(
p.on_early_stop("max_tokens", &attempt(1, 64_000)),
StopRecovery::RaiseOutputLimit {
max_tokens: 64_000,
nudge: Some(DefaultRecovery::NUDGE.to_string())
},
"a limit already above 8K is not lowered to it"
);
assert_eq!(
p.on_early_stop("max_tokens", &attempt(3, 64_000)),
StopRecovery::Accept,
"three escalations is the bound"
);
}
#[test]
fn a_paused_response_is_continued_whatever_the_escalations() {
let p = DefaultRecovery::default();
for escalations in [0, 3] {
assert_eq!(
p.on_early_stop("pause_turn", &attempt(escalations, 2000)),
StopRecovery::Continue
);
}
assert_eq!(
NeverRecover.on_early_stop("pause_turn", &attempt(0, 2000)),
StopRecovery::Accept
);
}
#[test]
fn an_ordinary_stop_reason_is_not_a_recovery() {
assert_eq!(
DefaultRecovery::default().on_early_stop("end_turn", &attempt(0, 2000)),
StopRecovery::Accept
);
}
#[test]
fn a_deployment_can_refuse_to_spend_anything_on_recovery() {
assert_eq!(
NeverRecover.on_failure(&streamed(ModelErrorKind::Overloaded), &fresh()),
Recovery::Fail
);
assert_eq!(
NeverRecover.on_early_stop("max_tokens", &attempt(0, 2000)),
StopRecovery::Accept
);
}
}