Standardize response request IDs across Codex clients (#65135)

## Why

Different response paths recognize different request ID headers, so
diagnostics can lose the ID needed to correlate a failed request. For
example, an Azure response may carry only `x-ms-request-id`.

## What changed

Use `CodexHeaderMap` to share response header parsing across API clients,
OAuth errors, and response debug context. When a caller needs one
request ID, fall back to the next supported header if the preferred
value is missing, empty, or unreadable.

Preserve recognized request ID headers on Responses WebSocket
handshakes. Use a shared summary for remote control errors and tracing,
omitting sensitive, empty, unreadable, and unrelated values.

## Testing

Cover fallback from an empty or unreadable primary ID, Azure-only debug
context, filtering in diagnostic summaries, and preservation of request
IDs in WebSocket handshakes and remote control pairing errors.

GitOrigin-RevId: f728a4a867f4705b784916b331f413e560f8626b
This commit is contained in:
Adam Perry @ OpenAI
2026-12-02 01:44:46 +00:00
committed by copyberry
parent cf24cd5a93
commit 55ea9a4620
26 changed files with 366 additions and 182 deletions
+21 -38
View File
@@ -7,6 +7,7 @@ use crate::rate_limits::parse_rate_limit_reached_type;
use base64::Engine;
use chrono::DateTime;
use chrono::Utc;
use codex_http_client::CodexHeaderMap;
use codex_protocol::auth::PlanType;
use codex_protocol::error::CodexErr;
use codex_protocol::error::CodexErrorDetails;
@@ -16,7 +17,6 @@ use codex_protocol::error::RetryLimitReachedError;
use codex_protocol::error::UnexpectedResponseError;
use codex_protocol::error::UsageLimitReachedError;
use codex_protocol::protocol::MisalignmentErrorDetails;
use http::HeaderMap;
use serde::Deserialize;
use serde_json::Value;
@@ -139,6 +139,7 @@ fn map_api_error_details(err: ApiError) -> CodexErr {
body,
..
} => {
let response_headers = headers.as_ref().map(CodexHeaderMap::from_http);
let body_text = body.unwrap_or_default();
let parsed_body = serde_json::from_str::<Value>(&body_text).ok();
let provider_error = parsed_body.as_ref().and_then(|body| body.get("error"));
@@ -229,15 +230,13 @@ fn map_api_error_details(err: ApiError) -> CodexErr {
} else if status == http::StatusCode::TOO_MANY_REQUESTS {
if let Ok(err) = serde_json::from_str::<UsageErrorResponse>(&body_text) {
if err.error.error_type.as_deref() == Some("usage_limit_reached") {
let limit_id = extract_header(headers.as_ref(), ACTIVE_LIMIT_HEADER);
let limit_id = response_headers.and_then(CodexHeaderMap::active_limit);
let promo_message = headers.as_ref().and_then(parse_promo_message);
let rate_limit_reached_type =
headers.as_ref().and_then(parse_rate_limit_reached_type);
let rate_limits = headers
.as_ref()
.and_then(|map| {
parse_rate_limit_for_limit(map, limit_id.as_deref())
})
.and_then(|map| parse_rate_limit_for_limit(map, limit_id))
.map(|mut snapshot| {
snapshot.rate_limit_reached_type = rate_limit_reached_type;
snapshot
@@ -277,7 +276,11 @@ fn map_api_error_details(err: ApiError) -> CodexErr {
CodexErr::RetryLimit(RetryLimitReachedError {
status,
request_id: extract_request_tracking_id(headers.as_ref()),
request_id: response_headers
.and_then(|headers| {
headers.preferred_request_id().or_else(|| headers.cf_ray())
})
.map(str::to_owned),
})
} else {
let response = UnexpectedResponseError {
@@ -285,13 +288,16 @@ fn map_api_error_details(err: ApiError) -> CodexErr {
user_message: api_error_user_message(status, &body_text),
body: body_text,
url,
cf_ray: extract_header(headers.as_ref(), CF_RAY_HEADER),
request_id: extract_request_id(headers.as_ref()),
identity_authorization_error: extract_header(
headers.as_ref(),
X_OPENAI_AUTHORIZATION_ERROR_HEADER,
),
identity_error_code: extract_x_error_json_code(headers.as_ref()),
cf_ray: response_headers
.and_then(CodexHeaderMap::cf_ray)
.map(str::to_owned),
request_id: response_headers
.and_then(CodexHeaderMap::preferred_request_id)
.map(str::to_owned),
identity_authorization_error: response_headers
.and_then(CodexHeaderMap::authorization_error)
.map(str::to_owned),
identity_error_code: response_headers.and_then(extract_x_error_json_code),
};
let body_code = parsed_body.as_ref().and_then(|body| {
["/detail/code", "/error/code"]
@@ -332,12 +338,6 @@ fn map_api_error_details(err: ApiError) -> CodexErr {
}
}
const ACTIVE_LIMIT_HEADER: &str = "x-codex-active-limit";
const REQUEST_ID_HEADER: &str = "x-request-id";
const OAI_REQUEST_ID_HEADER: &str = "x-oai-request-id";
const CF_RAY_HEADER: &str = "cf-ray";
const X_OPENAI_AUTHORIZATION_ERROR_HEADER: &str = "x-openai-authorization-error";
const X_ERROR_JSON_HEADER: &str = "x-error-json";
const INVALID_PROMPT_ERROR_CODE: &str = "invalid_prompt";
const INVALID_PROMPT_FALLBACK_MESSAGE: &str = "Invalid request.";
const CYBER_POLICY_ERROR_CODE: &str = "cyber_policy";
@@ -355,10 +355,6 @@ const CLOUDFLARE_BLOCKED_MESSAGE: &str =
#[path = "api_bridge_tests.rs"]
mod tests;
fn extract_request_tracking_id(headers: Option<&HeaderMap>) -> Option<String> {
extract_request_id(headers).or_else(|| extract_header(headers, CF_RAY_HEADER))
}
fn api_error_user_message(status: http::StatusCode, body: &str) -> Option<String> {
if status == http::StatusCode::FORBIDDEN
&& body.contains("Cloudflare")
@@ -370,21 +366,8 @@ fn api_error_user_message(status: http::StatusCode, body: &str) -> Option<String
}
}
fn extract_request_id(headers: Option<&HeaderMap>) -> Option<String> {
extract_header(headers, REQUEST_ID_HEADER)
.or_else(|| extract_header(headers, OAI_REQUEST_ID_HEADER))
}
fn extract_header(headers: Option<&HeaderMap>, name: &str) -> Option<String> {
headers.and_then(|map| {
map.get(name)
.and_then(|value| value.to_str().ok())
.map(str::to_string)
})
}
fn extract_x_error_json_code(headers: Option<&HeaderMap>) -> Option<String> {
let encoded = extract_header(headers, X_ERROR_JSON_HEADER)?;
fn extract_x_error_json_code(headers: &CodexHeaderMap) -> Option<String> {
let encoded = headers.encoded_error_json()?;
let decoded = base64::engine::general_purpose::STANDARD
.decode(encoded)
.ok()?;
+9 -4
View File
@@ -3,8 +3,13 @@ use base64::Engine;
use codex_http_client::RetryAfter;
use codex_protocol::protocol::CodexErrorInfo;
use codex_protocol::protocol::RateLimitReachedType;
use http::HeaderMap;
use pretty_assertions::assert_eq;
const ACTIVE_LIMIT_HEADER: &str = "x-codex-active-limit";
const X_OPENAI_AUTHORIZATION_ERROR_HEADER: &str = "x-openai-authorization-error";
const X_ERROR_JSON_HEADER: &str = "x-error-json";
#[test]
fn map_api_error_maps_server_overloaded() {
let err = map_api_error(ApiError::ServerOverloaded { retry_after: None });
@@ -226,7 +231,7 @@ fn map_http_error_classifies_provider_codes() {
#[test]
fn map_api_error_maps_cloudflare_blocked_response_to_user_message() {
let mut headers = HeaderMap::new();
headers.insert(CF_RAY_HEADER, http::HeaderValue::from_static("ray-id"));
headers.insert("cf-ray", http::HeaderValue::from_static("ray-id"));
let err = map_api_error(ApiError::Transport(TransportError::Http {
retry_after: None,
status: http::StatusCode::FORBIDDEN,
@@ -880,7 +885,7 @@ fn only_an_explicit_workspace_403_stops_retries() {
(StatusCode::UNAUTHORIZED, detail, true, false),
] {
let mut headers = HeaderMap::new();
headers.insert(REQUEST_ID_HEADER, http::HeaderValue::from_static("req-403"));
headers.insert("x-request-id", http::HeaderValue::from_static("req-403"));
if with_header {
headers.insert(X_ERROR_JSON_HEADER, workspace_header.clone());
}
@@ -909,8 +914,8 @@ fn only_an_explicit_workspace_403_stops_retries() {
#[test]
fn map_api_error_extracts_identity_auth_details_from_headers() {
let mut headers = HeaderMap::new();
headers.insert(REQUEST_ID_HEADER, http::HeaderValue::from_static("req-401"));
headers.insert(CF_RAY_HEADER, http::HeaderValue::from_static("ray-401"));
headers.insert("x-request-id", http::HeaderValue::from_static("req-401"));
headers.insert("cf-ray", http::HeaderValue::from_static("ray-401"));
headers.insert(
X_OPENAI_AUTHORIZATION_ERROR_HEADER,
http::HeaderValue::from_static("missing_authorization_header"),
+1 -1
View File
@@ -566,7 +566,7 @@ pub struct ResponseStream {
/// Routing pin from the connection that produced these responses. Never model metadata.
pub routing_affinity: Option<codex_http_client::ChatGptRoutingAffinity>,
pub rx_event: mpsc::Receiver<Result<ResponseEvent, ApiError>>,
/// Server-assigned `x-request-id` response header, when present.
/// Server-assigned request ID from the response headers.
pub upstream_request_id: Option<String>,
/// Requests a graceful interrupt. Keep consuming events through completion.
/// Only `Cancel` validates and waits for an interruption acknowledgement.
+10 -15
View File
@@ -8,14 +8,13 @@ use crate::provider::Provider;
use codex_client::HttpTransport;
use codex_client::RequestTelemetry;
use codex_client::TransportError;
use codex_http_client::CodexHeaderMap;
use http::HeaderMap;
use http::Method;
use serde::Serialize;
use serde_json::to_value;
use std::sync::Arc;
const X_CODEX_IMAGEGEN_REQUEST_ID_HEADER: &str = "x-codex-imagegen-request-id";
pub struct ImagesClient<T: HttpTransport> {
session: EndpointSession<T>,
}
@@ -30,9 +29,11 @@ pub struct ImageRequestError {
impl ImageRequestError {
fn from_api_error(error: ApiError) -> Self {
let imagegen_request_id = match &error {
ApiError::Transport(TransportError::Http { headers, .. }) => {
headers.as_ref().and_then(imagegen_request_id_from_headers)
}
ApiError::Transport(TransportError::Http { headers, .. }) => headers
.as_ref()
.map(CodexHeaderMap::from_http)
.and_then(CodexHeaderMap::imagegen_request_id)
.map(str::to_owned),
_ => None,
};
Self {
@@ -98,7 +99,9 @@ impl<T: HttpTransport> ImagesClient<T> {
.execute(Method::POST, path, extra_headers, Some(body))
.await
.map_err(ImageRequestError::from_api_error)?;
let imagegen_request_id = imagegen_request_id_from_headers(&resp.headers);
let imagegen_request_id = CodexHeaderMap::from_http(&resp.headers)
.imagegen_request_id()
.map(str::to_owned);
let response = serde_json::from_slice(&resp.body).map_err(|e| ImageRequestError {
error: ApiError::Stream(format!("failed to decode {operation} response: {e}")),
imagegen_request_id: imagegen_request_id.clone(),
@@ -107,14 +110,6 @@ impl<T: HttpTransport> ImagesClient<T> {
}
}
fn imagegen_request_id_from_headers(headers: &HeaderMap) -> Option<String> {
headers
.get(X_CODEX_IMAGEGEN_REQUEST_ID_HEADER)
.and_then(|value| value.to_str().ok())
.filter(|request_id| !request_id.is_empty())
.map(str::to_string)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -249,7 +244,7 @@ mod tests {
async fn generate_posts_typed_request_and_parses_image_response() {
let mut response_headers = HeaderMap::new();
response_headers.insert(
X_CODEX_IMAGEGEN_REQUEST_ID_HEADER,
"x-codex-imagegen-request-id",
http::HeaderValue::from_static("req-imagegen-123"),
);
response_headers.insert(
@@ -21,6 +21,7 @@ use crate::sse::process_responses_event;
use crate::telemetry::WebsocketTelemetry;
use bytes::Bytes;
use codex_client::TransportError;
use codex_http_client::CodexHeaderMap;
use codex_http_client::HttpClientFactory;
use codex_http_client::RetryAfter;
use codex_websocket_client::WebSocketConnection;
@@ -788,17 +789,9 @@ impl ResponsesWebsocketClient {
)
.await?;
let status = response.status();
let mut headers = HeaderMap::new();
for name in [
"x-request-id",
"x-oai-request-id",
"cf-ray",
"x-ms-request-id",
] {
for value in response.headers().get_all(name) {
headers.append(name, value.clone());
}
}
let headers = CodexHeaderMap::from_http(response.headers())
.copy_request_id_headers()
.into_http();
let immediate_close = tokio::time::timeout(immediate_close_timeout, stream.next())
.await
.ok()
+9 -13
View File
@@ -4,7 +4,6 @@ use std::time::Duration;
use crate::AuthProvider;
use bytes::Bytes;
use codex_http_client::HttpResponse;
use codex_http_client::RequestBuilder;
use codex_http_client::RouteAwareClientPool;
use codex_http_client::RouteAwareRequestError;
@@ -272,9 +271,15 @@ where
Ok(response) => {
let upload_status = response.status();
status = Some(upload_status.to_string());
cloudflare_ray_id = upload_response_header(&response, "cf-ray");
azure_request_id = upload_response_header(&response, "x-ms-request-id");
azure_error_code = upload_response_header(&response, "x-ms-error-code");
let headers = response.codex_headers();
cloudflare_ray_id = headers.cf_ray().unwrap_or("missing").to_owned();
azure_request_id = headers.ms_request_id().unwrap_or("missing").to_owned();
azure_error_code = response
.headers()
.get("x-ms-error-code")
.and_then(|value| value.to_str().ok())
.unwrap_or("missing")
.to_owned();
if upload_status.is_success() {
if attempt > 1 {
tracing::event!(
@@ -460,15 +465,6 @@ async fn authorized_request(
.headers(headers))
}
fn upload_response_header(response: &HttpResponse, header: &str) -> String {
response
.headers()
.get(header)
.and_then(|value| value.to_str().ok())
.unwrap_or("missing")
.to_string()
}
fn blob_retry_after(headers: &http::HeaderMap) -> Option<Duration> {
if let Some(delay) = headers
.get("x-ms-retry-after-ms")
+4 -6
View File
@@ -12,6 +12,7 @@ use crate::safety_buffering::treatment_from_headers;
use crate::telemetry::SseTelemetry;
use codex_client::ByteStream;
use codex_client::StreamResponse;
use codex_http_client::CodexHeaderMap;
use codex_protocol::ResponseUsageMetadata;
use codex_protocol::error::ResponseIncompleteError;
use codex_protocol::models::ResponseItem;
@@ -35,7 +36,6 @@ use tracing::trace;
const X_REASONING_INCLUDED_HEADER: &str = "x-reasoning-included";
const X_CODEX_TURN_STATE_HEADER: &str = "x-codex-turn-state";
const OPENAI_MODEL_HEADER: &str = "openai-model";
const REQUEST_ID_HEADER: &str = "x-request-id";
const TRUSTED_ACCESS_FOR_CYBER_VERIFICATION: &str = "trusted_access_for_cyber";
pub fn spawn_response_stream(
@@ -59,10 +59,8 @@ pub fn spawn_response_stream(
.headers
.get(X_REASONING_INCLUDED_HEADER)
.is_some();
let upstream_request_id = stream_response
.headers
.get(REQUEST_ID_HEADER)
.and_then(|value| value.to_str().ok())
let upstream_request_id = CodexHeaderMap::from_http(&stream_response.headers)
.preferred_request_id()
.map(str::to_string);
let safety_buffering_treatment =
treatment_from_headers(&stream_response.headers).unwrap_or_default();
@@ -1641,7 +1639,7 @@ mod tests {
#[tokio::test]
async fn spawn_response_stream_emits_header_events() {
let mut headers = HeaderMap::new();
headers.insert(REQUEST_ID_HEADER, HeaderValue::from_static("req-1"));
headers.insert("x-request-id", HeaderValue::from_static("req-1"));
headers.insert(
OPENAI_MODEL_HEADER,
HeaderValue::from_static(CYBER_RESTRICTED_MODEL_FOR_TESTS),