| 1 | use crate::llm_client::{LlmError, RequestTransmission}; |
| 2 | use codewhale_error_taxonomy::{ |
| 3 | ErrorCategory, ErrorEnvelope, ErrorSeverity, classify_error_message, |
| 4 | }; |
| 5 | use serde::{Deserialize, Serialize}; |
| 6 | |
| 7 | /// Structured, secret-free failure cause attached to provider request receipts |
| 8 | /// and persisted turn outcomes so downstream tools do not have to parse English |
| 9 | /// error prose (#7328). |
| 10 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 11 | pub struct ProviderFailureCause { |
| 12 | pub code: String, |
| 13 | pub category: ErrorCategory, |
| 14 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 15 | pub transmission: Option<RequestTransmission>, |
| 16 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 17 | pub http_status: Option<u16>, |
| 18 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 19 | pub timeout_ms: Option<u64>, |
| 20 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 21 | pub phase: Option<String>, |
| 22 | } |
| 23 | |
| 24 | fn llm_error_http_status(error: &LlmError) -> Option<u16> { |
| 25 | match error { |
| 26 | LlmError::ServerError { status, .. } | LlmError::InvalidRequest { status, .. } => { |
| 27 | Some(*status) |
| 28 | } |
| 29 | _ => None, |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | fn llm_error_timeout_ms(error: &LlmError) -> Option<u64> { |
| 34 | match error { |
| 35 | LlmError::Timeout(duration) if !duration.is_zero() => { |
| 36 | Some(u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)) |
| 37 | } |
| 38 | LlmError::HeaderTimeout { waited, .. } => { |
| 39 | Some(u64::try_from(waited.as_millis()).unwrap_or(u64::MAX)) |
| 40 | } |
| 41 | _ => None, |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | impl ProviderFailureCause { |
| 46 | #[must_use] |
| 47 | pub fn from_llm_error(error: &anyhow::Error, phase: Option<&str>) -> Self { |
| 48 | if let Some(llm) = error.downcast_ref::<LlmError>() { |
| 49 | let (code, category, default_phase) = match llm { |
| 50 | LlmError::QuotaWindow { .. } => ( |
| 51 | "llm_quota_window".to_string(), |
| 52 | ErrorCategory::RateLimit, |
| 53 | None, |
| 54 | ), |
| 55 | LlmError::RateLimited { .. } => ( |
| 56 | "llm_rate_limited".to_string(), |
| 57 | ErrorCategory::RateLimit, |
| 58 | None, |
| 59 | ), |
| 60 | LlmError::QuotaExhausted(_) => ( |
| 61 | "llm_quota_exhausted".to_string(), |
| 62 | ErrorCategory::RateLimit, |
| 63 | None, |
| 64 | ), |
| 65 | LlmError::ServerError { status, .. } => ( |
| 66 | format!("llm_server_{status}"), |
| 67 | ErrorCategory::Internal, |
| 68 | None, |
| 69 | ), |
| 70 | LlmError::NetworkError(_) => ( |
| 71 | "llm_network_error".to_string(), |
| 72 | ErrorCategory::Network, |
| 73 | None, |
| 74 | ), |
| 75 | LlmError::HeaderTimeout { .. } => ( |
| 76 | "llm_network_error".to_string(), |
| 77 | ErrorCategory::Network, |
| 78 | Some("header_timeout"), |
| 79 | ), |
| 80 | LlmError::ConnectError { .. } => ( |
| 81 | "llm_connect_before_dispatch".to_string(), |
| 82 | ErrorCategory::Network, |
| 83 | Some("connect"), |
| 84 | ), |
| 85 | LlmError::Timeout(_) => ( |
| 86 | "llm_timeout".to_string(), |
| 87 | ErrorCategory::Timeout, |
| 88 | Some("timeout"), |
| 89 | ), |
| 90 | LlmError::AuthenticationError(_) => ( |
| 91 | "llm_auth_error".to_string(), |
| 92 | ErrorCategory::Authentication, |
| 93 | None, |
| 94 | ), |
| 95 | LlmError::AuthorizationError(_) => ( |
| 96 | "llm_authorization_error".to_string(), |
| 97 | ErrorCategory::Authorization, |
| 98 | None, |
| 99 | ), |
| 100 | LlmError::InvalidRequest { .. } => ( |
| 101 | "llm_invalid_request".to_string(), |
| 102 | ErrorCategory::InvalidInput, |
| 103 | None, |
| 104 | ), |
| 105 | LlmError::ModelError(_) => ( |
| 106 | "llm_model_error".to_string(), |
| 107 | ErrorCategory::InvalidInput, |
| 108 | None, |
| 109 | ), |
| 110 | LlmError::ContentPolicyError(_) => ( |
| 111 | "llm_content_policy".to_string(), |
| 112 | ErrorCategory::Authorization, |
| 113 | None, |
| 114 | ), |
| 115 | LlmError::ParseError(_) => { |
| 116 | ("llm_parse_error".to_string(), ErrorCategory::Parse, None) |
| 117 | } |
| 118 | LlmError::ContextLengthError(_) => ( |
| 119 | "llm_context_length".to_string(), |
| 120 | ErrorCategory::InvalidInput, |
| 121 | None, |
| 122 | ), |
| 123 | LlmError::Other(message) => { |
| 124 | let envelope = envelope_for_other_llm_error(message.clone()); |
| 125 | (envelope.code, envelope.category, None) |
| 126 | } |
| 127 | }; |
| 128 | return Self { |
| 129 | code, |
| 130 | category, |
| 131 | transmission: Some(llm.transmission()), |
| 132 | http_status: llm_error_http_status(llm), |
| 133 | timeout_ms: llm_error_timeout_ms(llm), |
| 134 | phase: default_phase.or(phase).map(str::to_string), |
| 135 | }; |
| 136 | } |
| 137 | let envelope = ErrorEnvelope::classify(error.to_string(), false); |
| 138 | Self { |
| 139 | code: envelope.code, |
| 140 | category: envelope.category, |
| 141 | transmission: Some(RequestTransmission::OutcomeUnknown), |
| 142 | http_status: None, |
| 143 | timeout_ms: None, |
| 144 | phase: phase.map(str::to_string), |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | #[must_use] |
| 149 | pub fn from_envelope(envelope: &ErrorEnvelope, phase: Option<&str>) -> Self { |
| 150 | Self { |
| 151 | code: envelope.code.clone(), |
| 152 | category: envelope.category, |
| 153 | transmission: envelope.request_transmission, |
| 154 | http_status: None, |
| 155 | timeout_ms: None, |
| 156 | phase: phase.map(str::to_string), |
| 157 | } |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | /// Classify a boundary error from the typed [`LlmError`] when one is |
| 162 | /// available, keeping the caller's display message. |
| 163 | /// |
| 164 | /// Boundaries that only have an `anyhow::Error` historically stringified it |
| 165 | /// and classified the *string* with `recoverable = true`. That downgraded |
| 166 | /// terminal provider rejections such as `Model error: Model not exist.` |
| 167 | /// (typed `LlmError::ModelError` → InvalidInput / `Error` severity / |
| 168 | /// not recoverable) into `Internal` + `Warning` + recoverable noise, so the |
| 169 | /// transcript showed a dismissable "Warn" row for a failure that actually |
| 170 | /// ended the turn. When the typed error survives to the boundary, preserve |
| 171 | /// its category, severity, and recovery contract verbatim; only genuinely |
| 172 | /// untyped errors fall back to string classification. |
| 173 | #[must_use] |
| 174 | pub fn envelope_for_llm_error(error: anyhow::Error, display_message: String) -> ErrorEnvelope { |
| 175 | let llm = error.downcast_ref::<LlmError>(); |
| 176 | let transmission = llm.map_or(RequestTransmission::OutcomeUnknown, LlmError::transmission); |
| 177 | let http_status = llm.and_then(llm_error_http_status); |
| 178 | let timeout_ms = llm.and_then(llm_error_timeout_ms); |
| 179 | let mut envelope = match error.downcast::<LlmError>() { |
| 180 | Ok(llm) => { |
| 181 | let mut envelope = ErrorEnvelope::from(llm); |
| 182 | envelope.message = display_message; |
| 183 | envelope |
| 184 | } |
| 185 | Err(error) => { |
| 186 | drop(error); |
| 187 | ErrorEnvelope::classify(display_message, false) |
| 188 | } |
| 189 | }; |
| 190 | envelope.request_transmission = Some(transmission); |
| 191 | tracing::warn!( |
| 192 | code = %envelope.code, |
| 193 | category = %envelope.category, |
| 194 | ?transmission, |
| 195 | ?http_status, |
| 196 | ?timeout_ms, |
| 197 | "provider request failed" |
| 198 | ); |
| 199 | envelope |
| 200 | } |
| 201 | |
| 202 | impl From<LlmError> for ErrorEnvelope { |
| 203 | fn from(value: LlmError) -> Self { |
| 204 | match value { |
| 205 | LlmError::QuotaWindow { message, .. } => Self::new( |
| 206 | ErrorCategory::RateLimit, |
| 207 | ErrorSeverity::Error, |
| 208 | false, |
| 209 | "llm_quota_window", |
| 210 | message, |
| 211 | ), |
| 212 | LlmError::RateLimited { message, .. } => Self::new( |
| 213 | ErrorCategory::RateLimit, |
| 214 | ErrorSeverity::Warning, |
| 215 | true, |
| 216 | "llm_rate_limited", |
| 217 | message, |
| 218 | ), |
| 219 | // Keep the broad wire-compatible category while making the typed |
| 220 | // code and recovery contract distinct from an ordinary 429. |
| 221 | LlmError::QuotaExhausted(error) => Self::new( |
| 222 | ErrorCategory::RateLimit, |
| 223 | ErrorSeverity::Error, |
| 224 | false, |
| 225 | "llm_quota_exhausted", |
| 226 | error.into_message(), |
| 227 | ), |
| 228 | LlmError::ServerError { status, message } => Self::new( |
| 229 | ErrorCategory::Internal, |
| 230 | ErrorSeverity::Error, |
| 231 | false, |
| 232 | format!("llm_server_{status}"), |
| 233 | message, |
| 234 | ), |
| 235 | LlmError::NetworkError(message) => Self::new( |
| 236 | ErrorCategory::Network, |
| 237 | ErrorSeverity::Error, |
| 238 | false, |
| 239 | "llm_network_error", |
| 240 | message, |
| 241 | ), |
| 242 | LlmError::HeaderTimeout { .. } => Self::new( |
| 243 | ErrorCategory::Network, |
| 244 | ErrorSeverity::Error, |
| 245 | false, |
| 246 | "llm_network_error", |
| 247 | value.header_timeout_message(), |
| 248 | ), |
| 249 | LlmError::ConnectError { |
| 250 | message, transient, .. |
| 251 | } => Self::new( |
| 252 | ErrorCategory::Network, |
| 253 | ErrorSeverity::Error, |
| 254 | transient, |
| 255 | "llm_connect_before_dispatch", |
| 256 | message, |
| 257 | ), |
| 258 | LlmError::Timeout(duration) if duration.is_zero() => Self::new( |
| 259 | ErrorCategory::Timeout, |
| 260 | ErrorSeverity::Warning, |
| 261 | false, |
| 262 | "llm_timeout", |
| 263 | "Request timed out (provider request exceeded its transport \ |
| 264 | budget; exact duration not recorded)" |
| 265 | .to_string(), |
| 266 | ), |
| 267 | LlmError::Timeout(duration) => Self::new( |
| 268 | ErrorCategory::Timeout, |
| 269 | ErrorSeverity::Warning, |
| 270 | false, |
| 271 | "llm_timeout", |
| 272 | format!("Request timed out after {duration:?}"), |
| 273 | ), |
| 274 | LlmError::AuthenticationError(auth) => Self::new( |
| 275 | ErrorCategory::Authentication, |
| 276 | ErrorSeverity::Critical, |
| 277 | false, |
| 278 | "llm_auth_error", |
| 279 | auth.to_user_message(), |
| 280 | ), |
| 281 | LlmError::AuthorizationError(message) => Self::new( |
| 282 | ErrorCategory::Authorization, |
| 283 | ErrorSeverity::Error, |
| 284 | false, |
| 285 | "llm_authorization_error", |
| 286 | message, |
| 287 | ), |
| 288 | LlmError::InvalidRequest { message, .. } => Self::new( |
| 289 | ErrorCategory::InvalidInput, |
| 290 | ErrorSeverity::Error, |
| 291 | false, |
| 292 | "llm_invalid_request", |
| 293 | message, |
| 294 | ), |
| 295 | LlmError::ModelError(message) => Self::new( |
| 296 | ErrorCategory::InvalidInput, |
| 297 | ErrorSeverity::Error, |
| 298 | false, |
| 299 | "llm_model_error", |
| 300 | message, |
| 301 | ), |
| 302 | LlmError::ContentPolicyError(message) => Self::new( |
| 303 | ErrorCategory::Authorization, |
| 304 | ErrorSeverity::Error, |
| 305 | false, |
| 306 | "llm_content_policy", |
| 307 | message, |
| 308 | ), |
| 309 | LlmError::ParseError(message) => Self::new( |
| 310 | ErrorCategory::Parse, |
| 311 | ErrorSeverity::Error, |
| 312 | false, |
| 313 | "llm_parse_error", |
| 314 | message, |
| 315 | ), |
| 316 | LlmError::ContextLengthError(message) => Self::new( |
| 317 | ErrorCategory::InvalidInput, |
| 318 | ErrorSeverity::Error, |
| 319 | false, |
| 320 | "llm_context_length", |
| 321 | message, |
| 322 | ), |
| 323 | LlmError::Other(message) => envelope_for_other_llm_error(message), |
| 324 | } |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | /// `LlmError::Other` is the catch-all for an HTTP status with no dedicated |
| 329 | /// variant (a 402 without explicit quota evidence, a 405/409/413/422 |
| 330 | /// rejection). Its text still says what happened, so a determinate answer from |
| 331 | /// the string classifier wins over the blanket `Internal` label (#6843): an |
| 332 | /// out-of-credits 402 reads as a spent balance, a 4xx as a rejected input. |
| 333 | /// Only text the classifier cannot place stays `Internal`. |
| 334 | fn envelope_for_other_llm_error(message: String) -> ErrorEnvelope { |
| 335 | let category = classify_error_message(&message); |
| 336 | if matches!( |
| 337 | category, |
| 338 | ErrorCategory::Tool | ErrorCategory::State | ErrorCategory::Internal |
| 339 | ) { |
| 340 | return ErrorEnvelope::new( |
| 341 | ErrorCategory::Internal, |
| 342 | ErrorSeverity::Error, |
| 343 | false, |
| 344 | "llm_other", |
| 345 | message, |
| 346 | ); |
| 347 | } |
| 348 | let recoverable = false; |
| 349 | let mut envelope = ErrorEnvelope::classify(message, recoverable); |
| 350 | // The typed `NetworkError` is an Error-severity card; an `Other` that reads |
| 351 | // as one must not turn amber for a turn that later fails after its retries. |
| 352 | if matches!(category, ErrorCategory::Network | ErrorCategory::Budget) { |
| 353 | envelope.severity = ErrorSeverity::Error; |
| 354 | } |
| 355 | envelope |
| 356 | } |
| 357 | |
| 358 | #[cfg(test)] |
| 359 | mod tests { |
| 360 | use super::*; |
| 361 | |
| 362 | #[test] |
| 363 | fn provider_error_envelope_carries_request_transmission() { |
| 364 | let envelope = envelope_for_llm_error( |
| 365 | LlmError::Timeout(std::time::Duration::from_secs(1)).into(), |
| 366 | "Request timed out".into(), |
| 367 | ); |
| 368 | |
| 369 | assert_eq!( |
| 370 | envelope.request_transmission, |
| 371 | Some(RequestTransmission::OutcomeUnknown) |
| 372 | ); |
| 373 | } |
| 374 | |
| 375 | #[test] |
| 376 | fn request_transmission_is_optional_and_uses_snake_case_on_the_wire() { |
| 377 | let legacy: ErrorEnvelope = serde_json::from_value(serde_json::json!({ |
| 378 | "category": "network", |
| 379 | "severity": "error", |
| 380 | "recoverable": false, |
| 381 | "code": "llm_network_error", |
| 382 | "message": "connection reset" |
| 383 | })) |
| 384 | .expect("legacy envelope"); |
| 385 | assert_eq!(legacy.request_transmission, None); |
| 386 | assert!( |
| 387 | serde_json::to_value(&legacy) |
| 388 | .expect("serialize legacy envelope") |
| 389 | .get("request_transmission") |
| 390 | .is_none() |
| 391 | ); |
| 392 | |
| 393 | let mut current = legacy; |
| 394 | current.request_transmission = Some(RequestTransmission::OutcomeUnknown); |
| 395 | assert_eq!( |
| 396 | serde_json::to_value(current).expect("serialize current envelope")["request_transmission"], |
| 397 | "outcome_unknown" |
| 398 | ); |
| 399 | } |
| 400 | |
| 401 | #[test] |
| 402 | fn provider_failures_reach_info_filtered_logs_without_raw_error_text() { |
| 403 | use std::io::{Read, Seek, SeekFrom}; |
| 404 | use std::time::Duration; |
| 405 | |
| 406 | let secret = "sk-diagnostic-fixture-secret"; |
| 407 | let display_message = format!("connection reset: {secret}"); |
| 408 | let cases: [(anyhow::Error, &[&str], bool); 6] = [ |
| 409 | ( |
| 410 | anyhow::Error::new(LlmError::Timeout(Duration::from_millis(38_689))) |
| 411 | .context(format!("request context: {secret}")), |
| 412 | &[ |
| 413 | "code=llm_timeout", |
| 414 | "category=timeout", |
| 415 | "transmission=OutcomeUnknown", |
| 416 | "http_status=None", |
| 417 | "timeout_ms=Some(38689)", |
| 418 | ], |
| 419 | false, |
| 420 | ), |
| 421 | ( |
| 422 | LlmError::Timeout(Duration::ZERO).into(), |
| 423 | &[ |
| 424 | "code=llm_timeout", |
| 425 | "transmission=OutcomeUnknown", |
| 426 | "http_status=None", |
| 427 | "timeout_ms=None", |
| 428 | ], |
| 429 | false, |
| 430 | ), |
| 431 | ( |
| 432 | LlmError::ConnectError { |
| 433 | message: secret.into(), |
| 434 | transient: true, |
| 435 | timed_out: false, |
| 436 | } |
| 437 | .into(), |
| 438 | &[ |
| 439 | "code=llm_connect_before_dispatch", |
| 440 | "category=network", |
| 441 | "transmission=NotDispatched", |
| 442 | "http_status=None", |
| 443 | "timeout_ms=None", |
| 444 | ], |
| 445 | true, |
| 446 | ), |
| 447 | ( |
| 448 | LlmError::ServerError { |
| 449 | status: 503, |
| 450 | message: secret.into(), |
| 451 | } |
| 452 | .into(), |
| 453 | &[ |
| 454 | "code=llm_server_503", |
| 455 | "category=internal", |
| 456 | "transmission=OutcomeUnknown", |
| 457 | "http_status=Some(503)", |
| 458 | "timeout_ms=None", |
| 459 | ], |
| 460 | false, |
| 461 | ), |
| 462 | ( |
| 463 | LlmError::InvalidRequest { |
| 464 | status: 413, |
| 465 | message: secret.into(), |
| 466 | } |
| 467 | .into(), |
| 468 | &[ |
| 469 | "code=llm_invalid_request", |
| 470 | "category=invalid_input", |
| 471 | "transmission=Rejected", |
| 472 | "http_status=Some(413)", |
| 473 | "timeout_ms=None", |
| 474 | ], |
| 475 | false, |
| 476 | ), |
| 477 | ( |
| 478 | anyhow::anyhow!("connection reset: {secret}"), |
| 479 | &[ |
| 480 | "code=network", |
| 481 | "category=network", |
| 482 | "transmission=OutcomeUnknown", |
| 483 | "http_status=None", |
| 484 | "timeout_ms=None", |
| 485 | ], |
| 486 | false, |
| 487 | ), |
| 488 | ]; |
| 489 | let mut output = tempfile::tempfile().unwrap(); |
| 490 | let subscriber = tracing_subscriber::fmt() |
| 491 | .without_time() |
| 492 | .with_ansi(false) |
| 493 | .with_env_filter(tracing_subscriber::EnvFilter::new("info")) |
| 494 | .with_writer(std::sync::Mutex::new(output.try_clone().unwrap())) |
| 495 | .finish(); |
| 496 | let expected = tracing::subscriber::with_default(subscriber, || { |
| 497 | cases.map(|(error, fields, recoverable)| { |
| 498 | let envelope = envelope_for_llm_error(error, display_message.clone()); |
| 499 | assert_eq!(envelope.message, display_message); |
| 500 | assert_eq!(envelope.recoverable, recoverable); |
| 501 | fields |
| 502 | }) |
| 503 | }); |
| 504 | output.seek(SeekFrom::Start(0)).unwrap(); |
| 505 | let mut logs = String::new(); |
| 506 | output.read_to_string(&mut logs).unwrap(); |
| 507 | assert!(!logs.contains(secret), "{logs}"); |
| 508 | assert!(!logs.contains("connection reset"), "{logs}"); |
| 509 | assert!(!logs.contains("request context"), "{logs}"); |
| 510 | let lines: Vec<_> = logs.lines().collect(); |
| 511 | assert_eq!(lines.len(), expected.len(), "{logs}"); |
| 512 | for (line, fields) in lines.into_iter().zip(expected) { |
| 513 | for field in ["WARN", "provider request failed"] |
| 514 | .into_iter() |
| 515 | .chain(fields.iter().copied()) |
| 516 | { |
| 517 | assert!(line.contains(field), "missing {field}: {line}"); |
| 518 | } |
| 519 | } |
| 520 | } |
| 521 | |
| 522 | #[test] |
| 523 | fn typed_llm_quota_envelope_is_non_recoverable_and_distinct_from_rate_limit() { |
| 524 | let envelope = ErrorEnvelope::from(LlmError::from_http_response( |
| 525 | 429, |
| 526 | r#"{"error":{"code":"insufficient_quota"}}"#, |
| 527 | )); |
| 528 | assert_eq!(envelope.category, ErrorCategory::RateLimit); |
| 529 | assert_eq!(envelope.severity, ErrorSeverity::Error); |
| 530 | assert!(!envelope.recoverable); |
| 531 | assert_eq!(envelope.code, "llm_quota_exhausted"); |
| 532 | } |
| 533 | |
| 534 | #[test] |
| 535 | fn llm_auth_error_envelope_renders_context_without_secret() { |
| 536 | let api_key = "tp-secret-token-plan-value"; |
| 537 | let envelope = ErrorEnvelope::from(LlmError::from_http_response_with_request_context( |
| 538 | 401, |
| 539 | &format!("Invalid API Key: {api_key}"), |
| 540 | Some("Xiaomi MiMo"), |
| 541 | Some("https://token-plan-sgp.xiaomimimo.com/v1"), |
| 542 | Some("mimo-v2.5"), |
| 543 | Some("env"), |
| 544 | Some(api_key), |
| 545 | )); |
| 546 | assert_eq!(envelope.category, ErrorCategory::Authentication); |
| 547 | assert_eq!(envelope.severity, ErrorSeverity::Critical); |
| 548 | assert!(!envelope.recoverable); |
| 549 | for expected in [ |
| 550 | "provider: Xiaomi MiMo", |
| 551 | "base URL authority: token-plan-sgp.xiaomimimo.com", |
| 552 | "model: mimo-v2.5", |
| 553 | "key source: env", |
| 554 | "key fingerprint: tp-... (len=26)", |
| 555 | "key type: Xiaomi MiMo Token Plan key", |
| 556 | ] { |
| 557 | assert!(envelope.message.contains(expected)); |
| 558 | } |
| 559 | assert!(!envelope.message.contains(api_key)); |
| 560 | assert!(!envelope.message.contains("secret-token-plan-value")); |
| 561 | } |
| 562 | |
| 563 | #[test] |
| 564 | fn typed_llm_error_preserves_terminal_severity_across_boundary() { |
| 565 | // Even where the typed error survives to the boundary (the turn loop's |
| 566 | // stream-initiation and mid-stream paths), `envelope_for_llm_error` |
| 567 | // must keep the typed contract instead of re-classifying the string |
| 568 | // with `recoverable = true`. |
| 569 | let typed: anyhow::Error = LlmError::ModelError("Model not exist.".to_string()).into(); |
| 570 | let envelope = envelope_for_llm_error(typed, "Model error: Model not exist.".to_string()); |
| 571 | assert_eq!(envelope.category, ErrorCategory::InvalidInput); |
| 572 | assert_eq!(envelope.severity, ErrorSeverity::Error); |
| 573 | assert_eq!(envelope.code, "llm_model_error"); |
| 574 | assert_eq!(envelope.message, "Model error: Model not exist."); |
| 575 | |
| 576 | // Untyped errors keep the legacy string fallback. |
| 577 | let untyped: anyhow::Error = anyhow::anyhow!("stream read error: connection reset"); |
| 578 | let envelope = |
| 579 | envelope_for_llm_error(untyped, "stream read error: connection reset".into()); |
| 580 | assert_eq!(envelope.category, ErrorCategory::Network); |
| 581 | assert!(!envelope.recoverable); |
| 582 | } |
| 583 | |
| 584 | #[test] |
| 585 | fn untyped_other_llm_error_keeps_its_determinate_class() { |
| 586 | // Row 4 of the report: `LlmError::Other` carries a 402 without explicit |
| 587 | // quota evidence. It is a spent balance, not an internal fault, and |
| 588 | // resending cannot fix it. |
| 589 | let envelope = ErrorEnvelope::from(LlmError::Other( |
| 590 | "HTTP 402: This request requires more credits, or fewer max_tokens.".to_string(), |
| 591 | )); |
| 592 | assert_eq!(envelope.category, ErrorCategory::RateLimit); |
| 593 | assert_eq!(envelope.severity, ErrorSeverity::Error); |
| 594 | assert!(!envelope.recoverable); |
| 595 | |
| 596 | // A rejected input is terminal like the typed `InvalidRequest`. |
| 597 | let envelope = |
| 598 | ErrorEnvelope::from(LlmError::Other("HTTP 413: payload too large".to_string())); |
| 599 | assert_eq!(envelope.category, ErrorCategory::InvalidInput); |
| 600 | assert!(!envelope.recoverable); |
| 601 | |
| 602 | // Text the classifier cannot place keeps the legacy label. |
| 603 | let envelope = ErrorEnvelope::from(LlmError::Other("Unknown retry error".to_string())); |
| 604 | assert_eq!(envelope.category, ErrorCategory::Internal); |
| 605 | assert_eq!(envelope.code, "llm_other"); |
| 606 | assert!(!envelope.recoverable); |
| 607 | } |
| 608 | |
| 609 | #[test] |
| 610 | fn untyped_other_llm_error_keeps_the_retry_tail_unless_it_cannot_heal() { |
| 611 | // A malformed chunk or a transient class wrapped as `Other` keeps the |
| 612 | // legacy retry contract; only a rejected input, a refused credential and a |
| 613 | // spent balance are terminal. |
| 614 | for message in ["malformed chunk in stream", "error decoding response body"] { |
| 615 | let envelope = ErrorEnvelope::from(LlmError::Other(message.to_string())); |
| 616 | assert!(!envelope.recoverable, "{message}"); |
| 617 | } |
| 618 | // A transient `Other` is an Error-severity card like the typed |
| 619 | // `NetworkError`, not an amber one that outlives a failed retry. |
| 620 | let envelope = |
| 621 | ErrorEnvelope::from(LlmError::Other("error decoding response body".to_string())); |
| 622 | assert_eq!(envelope.category, ErrorCategory::Network); |
| 623 | assert_eq!(envelope.severity, ErrorSeverity::Error); |
| 624 | let envelope = ErrorEnvelope::from(LlmError::Other("HTTP 403: forbidden".to_string())); |
| 625 | assert_eq!(envelope.category, ErrorCategory::Authorization); |
| 626 | assert!(!envelope.recoverable); |
| 627 | } |
| 628 | |
| 629 | #[test] |
| 630 | fn zero_timeout_envelope_reports_unknown_duration_not_0ns() { |
| 631 | let envelope = ErrorEnvelope::from(LlmError::Timeout(std::time::Duration::from_secs(0))); |
| 632 | assert_eq!(envelope.category, ErrorCategory::Timeout); |
| 633 | assert_eq!(envelope.code, "llm_timeout"); |
| 634 | assert!( |
| 635 | !envelope.message.contains("0ns"), |
| 636 | "zero duration leaked as 0ns: {}", |
| 637 | envelope.message |
| 638 | ); |
| 639 | assert!( |
| 640 | envelope.message.contains("duration not recorded"), |
| 641 | "{}", |
| 642 | envelope.message |
| 643 | ); |
| 644 | |
| 645 | let measured = ErrorEnvelope::from(LlmError::Timeout(std::time::Duration::from_secs(90))); |
| 646 | assert!( |
| 647 | measured.message.contains("Request timed out after 90s"), |
| 648 | "{}", |
| 649 | measured.message |
| 650 | ); |
| 651 | } |
| 652 | |
| 653 | #[test] |
| 654 | fn provider_failure_cause_extracts_structured_fields_from_llm_errors() { |
| 655 | let header_timeout: anyhow::Error = LlmError::HeaderTimeout { |
| 656 | waited: std::time::Duration::from_secs(45), |
| 657 | http1: false, |
| 658 | retried: 0, |
| 659 | } |
| 660 | .into(); |
| 661 | let cause = ProviderFailureCause::from_llm_error(&header_timeout, Some("open")); |
| 662 | assert_eq!(cause.code, "llm_network_error"); |
| 663 | assert_eq!(cause.category, ErrorCategory::Network); |
| 664 | assert_eq!( |
| 665 | cause.transmission, |
| 666 | Some(RequestTransmission::OutcomeUnknown) |
| 667 | ); |
| 668 | assert_eq!(cause.http_status, None); |
| 669 | assert_eq!(cause.timeout_ms, Some(45_000)); |
| 670 | assert_eq!(cause.phase.as_deref(), Some("header_timeout")); |
| 671 | |
| 672 | let server_502: anyhow::Error = LlmError::ServerError { |
| 673 | status: 502, |
| 674 | message: "bad gateway".to_string(), |
| 675 | } |
| 676 | .into(); |
| 677 | let cause = ProviderFailureCause::from_llm_error(&server_502, Some("open")); |
| 678 | assert_eq!(cause.code, "llm_server_502"); |
| 679 | assert_eq!(cause.category, ErrorCategory::Internal); |
| 680 | assert_eq!(cause.http_status, Some(502)); |
| 681 | assert_eq!(cause.phase.as_deref(), Some("open")); |
| 682 | |
| 683 | let envelope = envelope_for_llm_error( |
| 684 | LlmError::Timeout(std::time::Duration::from_secs(12)).into(), |
| 685 | "Request timed out after 12s".to_string(), |
| 686 | ); |
| 687 | let from_env = ProviderFailureCause::from_envelope(&envelope, Some("idle_timeout")); |
| 688 | assert_eq!(from_env.code, "llm_timeout"); |
| 689 | assert_eq!(from_env.category, ErrorCategory::Timeout); |
| 690 | assert_eq!( |
| 691 | from_env.transmission, |
| 692 | Some(RequestTransmission::OutcomeUnknown) |
| 693 | ); |
| 694 | assert_eq!(from_env.phase.as_deref(), Some("idle_timeout")); |
| 695 | } |
| 696 | } |
| 697 |