mirror of
https://github.com/openai/codex.git
synced 2026-12-03 00:41:03 +00:00
Record provider error subreasons in turn analytics (#65356)
## Why Broad error categories make it hard to distinguish a model missing from the accessible catalog, an unsupported request value, and a route rate limit from other failures in the same categories. ## What changed Carry three structured provider subreasons through `CodexErr` and record them in `codex_error_subreason` only when they match the turn's terminal failure. - `model_not_in_accessible_catalog` for a matching HTTP 400 model-not-found error. - `unsupported_value` for an HTTP 400 invalid-request error with that code. - `route_rate_limit_exceeded` for a route-specific HTTP 429 that exhausts retries. ## Testing Cover subreason mapping, including wrapped WebSocket invalid requests, and verify that turn analytics omit subreasons for successful turns and mismatched terminal errors. Exercise recovery from a route-specific HTTP 429 using `Retry-After`. GitOrigin-RevId: 02d82082334e775020850e1a52ba7baff401cff1
This commit is contained in:
@@ -38,6 +38,7 @@ use codex_plugin::PluginId;
|
||||
use codex_plugin::PluginTelemetryMetadata;
|
||||
use codex_plugin_archive_verification::PluginInstallTelemetry;
|
||||
use codex_protocol::approvals::NetworkApprovalProtocol;
|
||||
use codex_protocol::error::CodexErrorSubreason;
|
||||
use codex_protocol::models::AdditionalPermissionProfile;
|
||||
use codex_protocol::models::SandboxPermissions;
|
||||
use codex_protocol::protocol::GuardianAssessmentOutcome;
|
||||
@@ -1223,6 +1224,7 @@ pub(crate) struct CodexTurnEventParams {
|
||||
pub(crate) explicit_client_interrupt_requested_at_ms: Option<u64>,
|
||||
pub(crate) turn_error: Option<CodexErrorInfo>,
|
||||
pub(crate) codex_error_kind: Option<CodexErrKind>,
|
||||
pub(crate) codex_error_subreason: Option<CodexErrorSubreason>,
|
||||
pub(crate) codex_error_http_status_code: Option<u16>,
|
||||
/// The server-selected window responsible for a usage limit, when known.
|
||||
pub(crate) usage_limit_window_minutes: Option<u16>,
|
||||
|
||||
@@ -20,6 +20,7 @@ use codex_protocol::config_types::ServiceTier;
|
||||
use codex_protocol::error::CodexErr;
|
||||
pub use codex_protocol::error::CodexErrKind;
|
||||
use codex_protocol::error::CodexErrorDetails;
|
||||
use codex_protocol::error::CodexErrorSubreason;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::openai_models::ReasoningEffort;
|
||||
use codex_protocol::protocol::AskForApproval;
|
||||
@@ -285,6 +286,7 @@ impl TurnCodexErrorFact {
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct TurnCodexError {
|
||||
pub(crate) kind: CodexErrKind,
|
||||
pub(crate) subreason: Option<CodexErrorSubreason>,
|
||||
pub(crate) http_status_code: Option<u16>,
|
||||
pub(crate) usage_limit_window_minutes: Option<u16>,
|
||||
}
|
||||
@@ -293,6 +295,7 @@ impl TurnCodexError {
|
||||
fn from_codex_err(error: &CodexErr) -> Self {
|
||||
Self {
|
||||
kind: error.into(),
|
||||
subreason: error.subreason(),
|
||||
http_status_code: error.http_status_code_value(),
|
||||
usage_limit_window_minutes: match error.details() {
|
||||
CodexErrorDetails::UsageLimitReached(error) => error.limit_window_minutes,
|
||||
|
||||
@@ -168,6 +168,7 @@ use codex_login::default_client::originator;
|
||||
use codex_protocol::config_types::ModeKind;
|
||||
use codex_protocol::config_types::Personality;
|
||||
use codex_protocol::config_types::ReasoningSummary;
|
||||
use codex_protocol::error::CodexErrorSubreason;
|
||||
use codex_protocol::items::ModelInvocationContext;
|
||||
use codex_protocol::items::is_safe_plugin_relative_path;
|
||||
use codex_protocol::mcp::is_node_repl_backed_connector;
|
||||
@@ -4070,6 +4071,30 @@ fn codex_turn_event_params(
|
||||
} = profile;
|
||||
let token_usage = turn_state.token_usage.clone();
|
||||
let codex_error = turn_state.codex_error.as_ref();
|
||||
let codex_error_subreason = match (
|
||||
completed.status,
|
||||
&completed.turn_error,
|
||||
codex_error.and_then(|error| error.subreason),
|
||||
) {
|
||||
(
|
||||
Some(TurnStatus::Failed),
|
||||
Some(CodexErrorInfo::ModelNotFound),
|
||||
Some(reason @ CodexErrorSubreason::ModelNotInAccessibleCatalog),
|
||||
)
|
||||
| (
|
||||
Some(TurnStatus::Failed),
|
||||
Some(CodexErrorInfo::Other),
|
||||
Some(reason @ CodexErrorSubreason::UnsupportedValue),
|
||||
)
|
||||
| (
|
||||
Some(TurnStatus::Failed),
|
||||
Some(CodexErrorInfo::ResponseTooManyFailedAttempts {
|
||||
http_status_code: Some(429),
|
||||
}),
|
||||
Some(reason @ CodexErrorSubreason::RouteRateLimitExceeded),
|
||||
) => Some(reason),
|
||||
_ => None,
|
||||
};
|
||||
CodexTurnEventParams {
|
||||
critical_path: critical_path.into(),
|
||||
thread_id,
|
||||
@@ -4115,6 +4140,7 @@ fn codex_turn_event_params(
|
||||
.explicit_client_interrupt_requested_at_ms,
|
||||
turn_error: completed.turn_error,
|
||||
codex_error_kind: codex_error.map(|error| error.kind),
|
||||
codex_error_subreason,
|
||||
codex_error_http_status_code: codex_error.and_then(|error| error.http_status_code),
|
||||
usage_limit_window_minutes: codex_error.and_then(|error| error.usage_limit_window_minutes),
|
||||
steer_count: Some(turn_state.steer_count),
|
||||
|
||||
@@ -151,6 +151,7 @@ fn turn_event_serializes_expected_shape() {
|
||||
explicit_client_interrupt_requested_at_ms: None,
|
||||
turn_error: None,
|
||||
codex_error_kind: None,
|
||||
codex_error_subreason: None,
|
||||
codex_error_http_status_code: None,
|
||||
usage_limit_window_minutes: None,
|
||||
steer_count: Some(0),
|
||||
@@ -256,6 +257,7 @@ fn turn_event_serializes_expected_shape() {
|
||||
"explicit_client_interrupt_requested_at_ms": null,
|
||||
"turn_error": null,
|
||||
"codex_error_kind": null,
|
||||
"codex_error_subreason": null,
|
||||
"codex_error_http_status_code": null,
|
||||
"usage_limit_window_minutes": null,
|
||||
"steer_count": 0,
|
||||
@@ -896,6 +898,135 @@ async fn turn_lifecycle_emits_failed_turn_event() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn turn_event_records_a_subreason_for_the_matching_terminal_failure() {
|
||||
use codex_app_server_protocol::CodexErrorInfo;
|
||||
use codex_protocol::error::CodexErrorDetails;
|
||||
use codex_protocol::error::CodexErrorSubreason;
|
||||
use codex_protocol::error::RetryLimitReachedError;
|
||||
|
||||
let catalog_miss = || {
|
||||
CodexErr::new(CodexErrorDetails::ModelNotFound {
|
||||
message: "Model not found".to_string(),
|
||||
status: None,
|
||||
})
|
||||
.with_subreason(Some(CodexErrorSubreason::ModelNotInAccessibleCatalog))
|
||||
};
|
||||
let unsupported_value = || {
|
||||
CodexErr::InvalidRequest("Unsupported value".to_string())
|
||||
.with_subreason(Some(CodexErrorSubreason::UnsupportedValue))
|
||||
};
|
||||
let route_rate_limit = || {
|
||||
CodexErr::RetryLimit(RetryLimitReachedError {
|
||||
status: http::StatusCode::TOO_MANY_REQUESTS,
|
||||
request_id: Some("gateway-request".to_string()),
|
||||
})
|
||||
.with_subreason(Some(CodexErrorSubreason::RouteRateLimitExceeded))
|
||||
};
|
||||
|
||||
for (error, status, terminal_error, expected) in [
|
||||
(
|
||||
catalog_miss(),
|
||||
AppServerTurnStatus::Failed,
|
||||
Some(CodexErrorInfo::ModelNotFound),
|
||||
json!("model_not_in_accessible_catalog"),
|
||||
),
|
||||
(
|
||||
catalog_miss(),
|
||||
AppServerTurnStatus::Failed,
|
||||
Some(CodexErrorInfo::Other),
|
||||
json!(null),
|
||||
),
|
||||
(
|
||||
catalog_miss(),
|
||||
AppServerTurnStatus::Completed,
|
||||
None,
|
||||
json!(null),
|
||||
),
|
||||
(
|
||||
unsupported_value(),
|
||||
AppServerTurnStatus::Failed,
|
||||
Some(CodexErrorInfo::Other),
|
||||
json!("unsupported_value"),
|
||||
),
|
||||
(
|
||||
unsupported_value(),
|
||||
AppServerTurnStatus::Failed,
|
||||
Some(CodexErrorInfo::ModelNotFound),
|
||||
json!(null),
|
||||
),
|
||||
(
|
||||
unsupported_value(),
|
||||
AppServerTurnStatus::Completed,
|
||||
None,
|
||||
json!(null),
|
||||
),
|
||||
(
|
||||
route_rate_limit(),
|
||||
AppServerTurnStatus::Failed,
|
||||
Some(CodexErrorInfo::ResponseTooManyFailedAttempts {
|
||||
http_status_code: Some(429),
|
||||
}),
|
||||
json!("route_rate_limit_exceeded"),
|
||||
),
|
||||
(
|
||||
route_rate_limit(),
|
||||
AppServerTurnStatus::Failed,
|
||||
Some(CodexErrorInfo::ResponseTooManyFailedAttempts {
|
||||
http_status_code: Some(500),
|
||||
}),
|
||||
json!(null),
|
||||
),
|
||||
(
|
||||
route_rate_limit(),
|
||||
AppServerTurnStatus::Completed,
|
||||
None,
|
||||
json!(null),
|
||||
),
|
||||
] {
|
||||
let mut reducer = AnalyticsReducer::default();
|
||||
let mut out = Vec::new();
|
||||
ingest_turn_prerequisites(
|
||||
&mut reducer,
|
||||
&mut out,
|
||||
/*include_initialize*/ true,
|
||||
/*include_resolved_config*/ true,
|
||||
/*include_started*/ true,
|
||||
/*include_token_usage*/ false,
|
||||
)
|
||||
.await;
|
||||
reducer
|
||||
.ingest(
|
||||
AnalyticsFact::Custom(CustomAnalyticsFact::TurnCodexError(Box::new(
|
||||
TurnCodexErrorFact::from_codex_err(
|
||||
"thread-2".to_string(),
|
||||
"turn-2".to_string(),
|
||||
&error,
|
||||
),
|
||||
))),
|
||||
&mut out,
|
||||
)
|
||||
.await;
|
||||
reducer
|
||||
.ingest(
|
||||
AnalyticsFact::Notification(Box::new(sample_turn_completed_notification(
|
||||
"thread-2",
|
||||
"turn-2",
|
||||
status,
|
||||
terminal_error,
|
||||
))),
|
||||
&mut out,
|
||||
)
|
||||
.await;
|
||||
|
||||
let [event] = out.as_slice() else {
|
||||
panic!("expected one turn event");
|
||||
};
|
||||
let payload = serde_json::to_value(event).expect("serialize turn event");
|
||||
assert_eq!(payload["event_params"]["codex_error_subreason"], expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn turn_event_reports_decisive_usage_limit_window() {
|
||||
let usage_limit = |limit_window_minutes| {
|
||||
|
||||
@@ -3401,6 +3401,7 @@ mod tests {
|
||||
ApiError::ModelNotFound {
|
||||
message: message(),
|
||||
status: Some(http::StatusCode::NOT_FOUND),
|
||||
subreason: None,
|
||||
},
|
||||
ApiError::InvalidPrompt { message: message() },
|
||||
ApiError::ContentPolicyViolation {
|
||||
|
||||
@@ -11,6 +11,7 @@ use codex_http_client::CodexHeaderMap;
|
||||
use codex_protocol::auth::PlanType;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::CodexErrorDetails;
|
||||
use codex_protocol::error::CodexErrorSubreason;
|
||||
use codex_protocol::error::ConnectionFailedError;
|
||||
use codex_protocol::error::ProviderRejection;
|
||||
use codex_protocol::error::RetryLimitReachedError;
|
||||
@@ -108,9 +109,12 @@ fn map_api_error_details(err: ApiError) -> CodexErr {
|
||||
message,
|
||||
per_recording,
|
||||
}),
|
||||
ApiError::ModelNotFound { message, status } => {
|
||||
CodexErr::new(CodexErrorDetails::ModelNotFound { message, status })
|
||||
}
|
||||
ApiError::ModelNotFound {
|
||||
message,
|
||||
status,
|
||||
subreason,
|
||||
} => CodexErr::new(CodexErrorDetails::ModelNotFound { message, status })
|
||||
.with_subreason(subreason),
|
||||
ApiError::InvalidPrompt { message } => {
|
||||
CodexErr::new(CodexErrorDetails::InvalidPrompt { message })
|
||||
}
|
||||
@@ -223,7 +227,12 @@ fn map_api_error_details(err: ApiError) -> CodexErr {
|
||||
{
|
||||
CodexErr::InvalidImageRequest()
|
||||
} else {
|
||||
CodexErr::InvalidRequest(body_text)
|
||||
let subreason = provider_error.and_then(|error| {
|
||||
(error.get("type")?.as_str()? == "invalid_request_error"
|
||||
&& error.get("code")?.as_str()? == "unsupported_value")
|
||||
.then_some(CodexErrorSubreason::UnsupportedValue)
|
||||
});
|
||||
CodexErr::InvalidRequest(body_text).with_subreason(subreason)
|
||||
}
|
||||
} else if status == http::StatusCode::INTERNAL_SERVER_ERROR {
|
||||
CodexErr::InternalServerError
|
||||
@@ -274,6 +283,9 @@ fn map_api_error_details(err: ApiError) -> CodexErr {
|
||||
}
|
||||
}
|
||||
|
||||
let code = provider_error.and_then(|error| error.get("code")?.as_str());
|
||||
let subreason = (code == Some("route_rate_limit_exceeded"))
|
||||
.then_some(CodexErrorSubreason::RouteRateLimitExceeded);
|
||||
CodexErr::RetryLimit(RetryLimitReachedError {
|
||||
status,
|
||||
request_id: response_headers
|
||||
@@ -282,6 +294,7 @@ fn map_api_error_details(err: ApiError) -> CodexErr {
|
||||
})
|
||||
.map(str::to_owned),
|
||||
})
|
||||
.with_subreason(subreason)
|
||||
} else {
|
||||
let response = UnexpectedResponseError {
|
||||
status,
|
||||
|
||||
@@ -428,6 +428,122 @@ fn map_api_error_maps_http_and_wrapped_websocket_typed_errors() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn map_api_error_retains_only_the_catalog_miss_subreason() {
|
||||
let catalog_miss = "model_not_in_accessible_catalog";
|
||||
for (status, subreason, expected) in [
|
||||
(
|
||||
http::StatusCode::BAD_REQUEST,
|
||||
Some(catalog_miss),
|
||||
Some(CodexErrorSubreason::ModelNotInAccessibleCatalog),
|
||||
),
|
||||
(http::StatusCode::BAD_REQUEST, None, None),
|
||||
(
|
||||
http::StatusCode::BAD_REQUEST,
|
||||
Some("unrecognized_reason"),
|
||||
None,
|
||||
),
|
||||
(http::StatusCode::NOT_FOUND, Some(catalog_miss), None),
|
||||
] {
|
||||
let error = map_api_error(ApiError::Transport(TransportError::Http {
|
||||
status,
|
||||
url: None,
|
||||
headers: None,
|
||||
body: Some(
|
||||
serde_json::json!({
|
||||
"error": {
|
||||
"code": "model_not_found",
|
||||
"message": catalog_miss,
|
||||
"subreason": subreason,
|
||||
}
|
||||
})
|
||||
.to_string(),
|
||||
),
|
||||
retry_after: None,
|
||||
}));
|
||||
assert!(matches!(
|
||||
error.details(),
|
||||
CodexErrorDetails::ModelNotFound { .. }
|
||||
));
|
||||
assert_eq!(error.subreason(), expected);
|
||||
assert_eq!(error.to_string(), catalog_miss);
|
||||
assert_eq!(
|
||||
error.to_codex_protocol_error(),
|
||||
CodexErrorInfo::ModelNotFound
|
||||
);
|
||||
assert_eq!(error.retry_delay(/*retry_count*/ 1), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn map_api_error_preserves_the_unsupported_value_subreason() {
|
||||
let bad_request = http::StatusCode::BAD_REQUEST;
|
||||
let unsupported = Some(CodexErrorSubreason::UnsupportedValue);
|
||||
for (status, error_type, code, param, expected) in [
|
||||
(
|
||||
bad_request,
|
||||
"invalid_request_error",
|
||||
"unsupported_value",
|
||||
Some("text.verbosity"),
|
||||
unsupported,
|
||||
),
|
||||
(
|
||||
bad_request,
|
||||
"invalid_request_error",
|
||||
"unsupported_value",
|
||||
None,
|
||||
unsupported,
|
||||
),
|
||||
(
|
||||
bad_request,
|
||||
"invalid_request_error",
|
||||
"invalid_value",
|
||||
None,
|
||||
None,
|
||||
),
|
||||
(bad_request, "server_error", "unsupported_value", None, None),
|
||||
(
|
||||
http::StatusCode::FORBIDDEN,
|
||||
"invalid_request_error",
|
||||
"unsupported_value",
|
||||
None,
|
||||
None,
|
||||
),
|
||||
] {
|
||||
let mut body = serde_json::json!({
|
||||
"error": {
|
||||
"type": error_type,
|
||||
"code": code,
|
||||
"message": "Unsupported value",
|
||||
},
|
||||
});
|
||||
if let Some(param) = param {
|
||||
body["error"]["param"] = serde_json::json!(param);
|
||||
}
|
||||
let body = body.to_string();
|
||||
let error = map_api_error(ApiError::Transport(TransportError::Http {
|
||||
status,
|
||||
url: None,
|
||||
headers: None,
|
||||
body: Some(body.clone()),
|
||||
retry_after: None,
|
||||
}));
|
||||
|
||||
assert_eq!(error.subreason(), expected);
|
||||
if status == http::StatusCode::BAD_REQUEST {
|
||||
assert!(
|
||||
matches!(error.details(), CodexErrorDetails::InvalidRequest(message) if message == &body)
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value(error.to_error_event(/*message_prefix*/ None)).unwrap(),
|
||||
serde_json::json!({"message": body, "codex_error_info": "other"}),
|
||||
);
|
||||
assert!(!error.requires_http_fallback());
|
||||
assert_eq!(error.retry_delay(/*retry_count*/ 1), None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn map_api_error_maps_misalignment_policy_violation_from_400_body() {
|
||||
assert_misalignment_policy_violation_from_http_body(http::StatusCode::BAD_REQUEST);
|
||||
@@ -587,6 +703,55 @@ fn map_api_error_keeps_other_400_errors_generic() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn route_rate_limit_subreason_preserves_the_429_error_and_retry_advice() {
|
||||
use std::time::Duration;
|
||||
|
||||
let retry_after = RetryAfter::from_delay(Duration::from_secs(3));
|
||||
let map_429 = |code: Option<&str>| {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
REQUEST_ID_HEADER,
|
||||
http::HeaderValue::from_static("gateway-request"),
|
||||
);
|
||||
let mut body = serde_json::json!({"detail": "Rate limit exceeded"});
|
||||
if let Some(code) = code {
|
||||
body["error"] = serde_json::json!({"code": code, "message": "Rate limit exceeded"});
|
||||
}
|
||||
map_api_error(ApiError::Transport(TransportError::Http {
|
||||
status: http::StatusCode::TOO_MANY_REQUESTS,
|
||||
url: None,
|
||||
headers: Some(headers),
|
||||
body: Some(body.to_string()),
|
||||
retry_after,
|
||||
}))
|
||||
};
|
||||
|
||||
let legacy = map_429(/*code*/ None);
|
||||
assert_eq!(legacy.subreason(), None);
|
||||
for (code, expected) in [
|
||||
(
|
||||
"route_rate_limit_exceeded",
|
||||
Some(CodexErrorSubreason::RouteRateLimitExceeded),
|
||||
),
|
||||
("rate_limit_exceeded", None),
|
||||
] {
|
||||
let error = map_429(Some(code));
|
||||
assert!(matches!(error.details(), CodexErrorDetails::RetryLimit(_)));
|
||||
assert_eq!(error.subreason(), expected);
|
||||
assert_eq!(
|
||||
error.to_error_event(/*message_prefix*/ None),
|
||||
legacy.to_error_event(/*message_prefix*/ None),
|
||||
);
|
||||
assert_eq!(error.retry_after(), retry_after);
|
||||
assert_eq!(
|
||||
error.retry_delay(/*retry_count*/ 1),
|
||||
Some(Duration::from_secs(3))
|
||||
);
|
||||
assert!(!error.requires_http_fallback());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn map_api_error_distinguishes_http_quota_errors_from_rate_limits() {
|
||||
use CodexErrorInfo::ApiKeySpendLimitExceeded;
|
||||
|
||||
@@ -1374,6 +1374,7 @@ mod tests {
|
||||
use crate::common::ResponseCreateWsRequest;
|
||||
use crate::common::ResponsesApiRequest;
|
||||
use codex_protocol::ResponseItemId;
|
||||
use codex_protocol::error::CodexErrorSubreason;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use http::HeaderValue;
|
||||
@@ -1606,27 +1607,43 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn parse_wrapped_websocket_error_event_with_status_maps_invalid_request() {
|
||||
let payload = json!({
|
||||
"type": "error",
|
||||
"status": 400,
|
||||
"error": {
|
||||
"type": "invalid_request_error",
|
||||
"message": "Model does not support image inputs"
|
||||
}
|
||||
})
|
||||
.to_string();
|
||||
|
||||
let wrapped_error = parse_wrapped_websocket_error_event(&payload)
|
||||
.expect("expected websocket error payload to be parsed");
|
||||
let api_error = map_wrapped_websocket_error_event(wrapped_error, payload)
|
||||
.expect("expected websocket error payload to map to ApiError");
|
||||
let ApiError::Transport(TransportError::Http { status, body, .. }) = api_error else {
|
||||
panic!("expected ApiError::Transport(Http)");
|
||||
};
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||
let body = body.expect("expected body");
|
||||
assert!(body.contains("invalid_request_error"));
|
||||
assert!(body.contains("Model does not support image inputs"));
|
||||
for (error_body, subreason) in [
|
||||
(
|
||||
json!({
|
||||
"type": "invalid_request_error",
|
||||
"message": "Model does not support image inputs",
|
||||
}),
|
||||
None,
|
||||
),
|
||||
(
|
||||
json!({
|
||||
"type": "invalid_request_error",
|
||||
"code": "unsupported_value",
|
||||
"param": "reasoning.effort",
|
||||
"message": "Unsupported value for reasoning.effort",
|
||||
}),
|
||||
Some(CodexErrorSubreason::UnsupportedValue),
|
||||
),
|
||||
] {
|
||||
let payload = json!({"type": "error", "status": 400, "error": error_body}).to_string();
|
||||
let wrapped_error = parse_wrapped_websocket_error_event(&payload)
|
||||
.expect("expected websocket error payload to be parsed");
|
||||
let api_error = map_wrapped_websocket_error_event(wrapped_error, payload.clone())
|
||||
.expect("expected websocket error payload to map to ApiError");
|
||||
assert!(matches!(
|
||||
api_error,
|
||||
ApiError::Transport(TransportError::Http {
|
||||
status: StatusCode::BAD_REQUEST,
|
||||
..
|
||||
})
|
||||
));
|
||||
let error = crate::api_bridge::map_api_error(api_error);
|
||||
assert_eq!(error.subreason(), subreason);
|
||||
assert_eq!(
|
||||
serde_json::to_value(error.to_error_event(/*message_prefix*/ None)).unwrap(),
|
||||
json!({"message": payload, "codex_error_info": "other"}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use crate::rate_limits::RateLimitError;
|
||||
use codex_client::TransportError;
|
||||
use codex_http_client::RetryAfter;
|
||||
use codex_protocol::error::CodexErrorSubreason;
|
||||
use codex_protocol::error::ResponseIncompleteError;
|
||||
use codex_protocol::error::SpendLimitScope;
|
||||
use codex_protocol::protocol::MisalignmentErrorDetails;
|
||||
@@ -58,6 +59,7 @@ pub enum ApiError {
|
||||
ModelNotFound {
|
||||
message: String,
|
||||
status: Option<StatusCode>,
|
||||
subreason: Option<CodexErrorSubreason>,
|
||||
},
|
||||
#[error("invalid prompt: {message}")]
|
||||
InvalidPrompt { message: String },
|
||||
@@ -196,6 +198,12 @@ pub(crate) fn parse_terminal_provider_error(
|
||||
) => Some(ApiError::ModelNotFound {
|
||||
message: message.unwrap_or(code).to_owned(),
|
||||
status,
|
||||
subreason: match (status, error.get("subreason").and_then(Value::as_str)) {
|
||||
(Some(StatusCode::BAD_REQUEST), Some("model_not_in_accessible_catalog")) => {
|
||||
Some(CodexErrorSubreason::ModelNotInAccessibleCatalog)
|
||||
}
|
||||
_ => None,
|
||||
},
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
|
||||
@@ -342,18 +342,29 @@ async fn responses_http_uses_retry_after() -> Result<()> {
|
||||
}
|
||||
|
||||
/// A 429 with server advice retries in the sampling loop and completes without a terminal error.
|
||||
#[test_case::test_case(false; "unclassified")]
|
||||
#[test_case::test_case(true; "gateway_route_limit")]
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn responses_http_429_uses_retry_after() -> Result<()> {
|
||||
async fn responses_http_429_uses_retry_after(gateway_route_limit: bool) -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let mut telemetry = RetryTelemetryCapture::install();
|
||||
let server = responses::start_mock_server().await;
|
||||
let body = if gateway_route_limit {
|
||||
json!({
|
||||
"detail": "Rate limit exceeded",
|
||||
"error": {"code": "route_rate_limit_exceeded", "message": "Rate limit exceeded"}
|
||||
})
|
||||
} else {
|
||||
json!({"error": {"code": "rate_limit_exceeded"}})
|
||||
};
|
||||
let rate_limit = ResponseTemplate::new(429)
|
||||
.insert_header("Retry-After", "1")
|
||||
.set_body_json(body);
|
||||
let response_mock = responses::mount_response_sequence(
|
||||
&server,
|
||||
vec![
|
||||
ResponseTemplate::new(429)
|
||||
.insert_header("Retry-After", "1")
|
||||
.set_body_json(json!({ "error": { "code": "rate_limit_exceeded" } })),
|
||||
rate_limit,
|
||||
responses::sse_response(responses::sse(vec![
|
||||
responses::ev_response_created("recovered"),
|
||||
responses::ev_completed("recovered"),
|
||||
|
||||
@@ -83,8 +83,18 @@ pub enum SpendLimitScope {
|
||||
Organization,
|
||||
}
|
||||
|
||||
/// A producer-supplied reason retained for diagnostics.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum CodexErrorSubreason {
|
||||
ModelNotInAccessibleCatalog,
|
||||
UnsupportedValue,
|
||||
RouteRateLimitExceeded,
|
||||
}
|
||||
|
||||
pub struct CodexErr {
|
||||
details: CodexErrorDetails,
|
||||
subreason: Option<CodexErrorSubreason>,
|
||||
retry_after: Option<RetryAfter>,
|
||||
agent_context: Option<AgentErrorContext>,
|
||||
}
|
||||
@@ -322,6 +332,7 @@ impl From<CodexErrorDetails> for CodexErr {
|
||||
fn from(details: CodexErrorDetails) -> Self {
|
||||
Self {
|
||||
details,
|
||||
subreason: None,
|
||||
retry_after: None,
|
||||
agent_context: None,
|
||||
}
|
||||
@@ -387,6 +398,7 @@ macro_rules! codex_err_unit_constructors {
|
||||
#[allow(non_upper_case_globals)]
|
||||
pub const $variant: Self = Self {
|
||||
details: CodexErrorDetails::$variant,
|
||||
subreason: None,
|
||||
retry_after: None,
|
||||
agent_context: None,
|
||||
};
|
||||
@@ -469,6 +481,15 @@ impl CodexErr {
|
||||
&self.details
|
||||
}
|
||||
|
||||
pub fn subreason(&self) -> Option<CodexErrorSubreason> {
|
||||
self.subreason
|
||||
}
|
||||
|
||||
pub fn with_subreason(mut self, subreason: Option<CodexErrorSubreason>) -> Self {
|
||||
self.subreason = subreason;
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether retrying this request requires switching from WebSocket to HTTP.
|
||||
pub fn requires_http_fallback(&self) -> bool {
|
||||
matches!(self.retry_policy(), RetryPolicy::FallBackToHttp)
|
||||
|
||||
Reference in New Issue
Block a user