mirror of
https://github.com/openai/codex.git
synced 2026-12-02 00:31:03 +00:00
Record why Responses WebSockets fall back to HTTP (#64923)
## Why The fallback counter identifies the original transport but gives no indication of what triggered the switch to HTTP. ## What changed Include the triggering Codex error kind and HTTP status, when available, in the fallback warning and the `codex.transport.fallback_to_http` counter. The counter uses `none` when the error has no HTTP status. ## Testing Integration tests assert a single counter increment with the expected tags for HTTP 426 during connection setup, HTTP 403 after retries, server overload, and oversized WebSocket messages. GitOrigin-RevId: 6f8b9d5049da1563e035fff62473c85693f0ad1b
This commit is contained in:
+26
-25
@@ -160,6 +160,7 @@ use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_model_provider_info::OPENAI_PROVIDER_NAME;
|
||||
use codex_model_provider_info::WireApi;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::CodexErrKind;
|
||||
use codex_protocol::error::CodexErrorDetails;
|
||||
use codex_protocol::error::Result;
|
||||
use codex_response_debug_context::extract_response_debug_context;
|
||||
@@ -875,20 +876,23 @@ impl ModelClient {
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) = websocket_session;
|
||||
}
|
||||
|
||||
pub(crate) fn force_http_fallback(
|
||||
&self,
|
||||
session_telemetry: &SessionTelemetry,
|
||||
_model_info: &ModelInfo,
|
||||
) -> bool {
|
||||
fn force_http_fallback(&self, session_telemetry: &SessionTelemetry, err: &CodexErr) -> bool {
|
||||
let websocket_enabled = self.responses_websocket_enabled();
|
||||
let activated =
|
||||
websocket_enabled && !self.state.disable_websockets.swap(true, Ordering::Relaxed);
|
||||
if activated {
|
||||
warn!("falling back to HTTP");
|
||||
let reason: &'static str = CodexErrKind::from(err).into();
|
||||
let http_status_code = err.http_status_code_value();
|
||||
warn!(reason, http_status_code, "falling back to HTTP");
|
||||
let status = http_status_code.map(|code| code.to_string());
|
||||
session_telemetry.counter(
|
||||
"codex.transport.fallback_to_http",
|
||||
/*inc*/ 1,
|
||||
&[("from_wire_api", "responses_websocket")],
|
||||
&[
|
||||
("from_wire_api", "responses_websocket"),
|
||||
("reason", reason),
|
||||
("http_status_code", status.as_deref().unwrap_or("none")),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1959,10 +1963,13 @@ impl ModelClientSession {
|
||||
.await
|
||||
{
|
||||
Ok(_) => return Ok(()),
|
||||
Err(ApiError::Transport(TransportError::Http { status, .. }))
|
||||
Err(err @ ApiError::Transport(TransportError::Http { status, .. }))
|
||||
if status == StatusCode::UPGRADE_REQUIRED =>
|
||||
{
|
||||
self.try_switch_fallback_transport(session_telemetry, model_info);
|
||||
self.try_switch_fallback_transport(
|
||||
session_telemetry,
|
||||
&provider.map_api_error(err),
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
Err(ApiError::Transport(unauthorized_transport))
|
||||
@@ -2461,9 +2468,13 @@ impl ModelClientSession {
|
||||
.await
|
||||
{
|
||||
Ok(_) => {}
|
||||
Err(ApiError::Transport(TransportError::Http { status, .. }))
|
||||
Err(err @ ApiError::Transport(TransportError::Http { status, .. }))
|
||||
if status == StatusCode::UPGRADE_REQUIRED =>
|
||||
{
|
||||
self.try_switch_fallback_transport(
|
||||
session_telemetry,
|
||||
&provider.map_api_error(err),
|
||||
);
|
||||
return Ok(WebsocketStreamOutcome::FallbackToHttp);
|
||||
}
|
||||
Err(ApiError::Transport(unauthorized_transport))
|
||||
@@ -2828,7 +2839,7 @@ impl ModelClientSession {
|
||||
match event {
|
||||
Ok(ResponseEvent::Completed { .. }) => break,
|
||||
Err(err) if err.requires_http_fallback() => {
|
||||
self.try_switch_fallback_transport(session_telemetry, model_info);
|
||||
self.try_switch_fallback_transport(session_telemetry, &err);
|
||||
break;
|
||||
}
|
||||
Err(err) => return Err(err),
|
||||
@@ -2837,10 +2848,7 @@ impl ModelClientSession {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Ok(WebsocketStreamOutcome::FallbackToHttp) => {
|
||||
self.try_switch_fallback_transport(session_telemetry, model_info);
|
||||
Ok(())
|
||||
}
|
||||
Ok(WebsocketStreamOutcome::FallbackToHttp) => Ok(()),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
@@ -2909,9 +2917,7 @@ impl ModelClientSession {
|
||||
.await?
|
||||
{
|
||||
WebsocketStreamOutcome::Stream(stream) => return Ok(*stream),
|
||||
WebsocketStreamOutcome::FallbackToHttp => {
|
||||
self.try_switch_fallback_transport(session_telemetry, model_info);
|
||||
}
|
||||
WebsocketStreamOutcome::FallbackToHttp => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2934,18 +2940,13 @@ impl ModelClientSession {
|
||||
|
||||
/// Permanently disables WebSockets for this Codex session and resets WebSocket state.
|
||||
///
|
||||
/// This is used after exhausting the provider retry budget, to force subsequent requests onto
|
||||
/// the HTTP transport.
|
||||
///
|
||||
/// Returns `true` if this call activated fallback, or `false` if fallback was already active.
|
||||
pub(crate) fn try_switch_fallback_transport(
|
||||
&mut self,
|
||||
session_telemetry: &SessionTelemetry,
|
||||
model_info: &ModelInfo,
|
||||
err: &CodexErr,
|
||||
) -> bool {
|
||||
let activated = self
|
||||
.client
|
||||
.force_http_fallback(session_telemetry, model_info);
|
||||
let activated = self.client.force_http_fallback(session_telemetry, err);
|
||||
self.websocket_session = WebsocketSession::default();
|
||||
activated
|
||||
}
|
||||
|
||||
@@ -2935,7 +2935,6 @@ async fn intercepted_output_reaches_trace_and_websocket_bookkeeping() -> anyhow:
|
||||
async fn inference_tools_changes_follow_full_specs_across_turns() {
|
||||
let client = test_model_client(SessionSource::Cli);
|
||||
let telemetry = test_session_telemetry();
|
||||
let model_info = test_model_info();
|
||||
let alpha = ResponsesApiTool {
|
||||
name: "alpha".into(),
|
||||
description: "Original".into(),
|
||||
@@ -2967,7 +2966,7 @@ async fn inference_tools_changes_follow_full_specs_across_turns() {
|
||||
.enumerate()
|
||||
{
|
||||
if index == 4 {
|
||||
session.try_switch_fallback_transport(&telemetry, &model_info);
|
||||
session.try_switch_fallback_transport(&telemetry, &CodexErr::Timeout);
|
||||
drop(session);
|
||||
session = client.new_session();
|
||||
}
|
||||
|
||||
@@ -134,10 +134,7 @@ pub(crate) async fn handle_response_stream_error(
|
||||
|
||||
let requires_http_fallback = err.requires_http_fallback();
|
||||
let switched = (requires_http_fallback || retry_state.retries >= max_retries)
|
||||
&& client_session.try_switch_fallback_transport(
|
||||
&turn_context.session_telemetry,
|
||||
turn_context.model_info(),
|
||||
);
|
||||
&& client_session.try_switch_fallback_transport(&turn_context.session_telemetry, &err);
|
||||
if switched {
|
||||
// Changing transport must not bypass the server's retry deadline.
|
||||
if let Some(retry_after) = retry_after {
|
||||
|
||||
@@ -3185,7 +3185,7 @@ fn assert_continuation_metrics_with_item_types(
|
||||
);
|
||||
}
|
||||
|
||||
fn assert_counter<const N: usize>(
|
||||
pub(super) fn assert_counter<const N: usize>(
|
||||
snapshot: &ResourceMetrics,
|
||||
name: &str,
|
||||
tag_names: [&str; N],
|
||||
|
||||
@@ -1852,6 +1852,7 @@ async fn websocket_upgrade_rejection_uses_retry_after() -> Result<()> {
|
||||
)
|
||||
.await;
|
||||
let test = test_codex()
|
||||
.with_thread_extension(super::websocket_fallback::fallback_metrics())
|
||||
.with_config(|config| {
|
||||
config.model_catalog = Some(bundled_models_response().expect("bundled models"));
|
||||
config.model_provider.supports_websockets = true;
|
||||
@@ -1882,6 +1883,7 @@ async fn websocket_upgrade_rejection_uses_retry_after() -> Result<()> {
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(methods, vec!["GET", "GET", "GET", "POST", "POST"]);
|
||||
assert_eq!(response_mock.requests().len(), 2);
|
||||
super::websocket_fallback::assert_fallback_metric(&test, "server_overloaded", "none");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
use anyhow::Result;
|
||||
use codex_core::TurnInputRequest;
|
||||
use codex_model_provider_info::WireApi;
|
||||
use codex_otel::MetricsClient;
|
||||
use codex_otel::MetricsConfig;
|
||||
use codex_protocol::config_types::CollaborationMode;
|
||||
use codex_protocol::config_types::ModeKind;
|
||||
use codex_protocol::config_types::Settings;
|
||||
@@ -33,6 +35,26 @@ use wiremock::matchers::path_regex;
|
||||
#[path = "websocket_fallback_close.rs"]
|
||||
mod close_code;
|
||||
|
||||
pub(super) fn fallback_metrics() -> MetricsClient {
|
||||
MetricsClient::new(
|
||||
MetricsConfig::in_memory("test", "test", "1", Default::default()).with_runtime_reader(),
|
||||
)
|
||||
.expect("in-memory metrics")
|
||||
}
|
||||
|
||||
pub(super) fn assert_fallback_metric(test: &TestCodex, reason: &str, http_status_code: &str) {
|
||||
super::client_websockets::assert_counter(
|
||||
&test
|
||||
.codex
|
||||
.session_telemetry()
|
||||
.snapshot_metrics()
|
||||
.expect("metrics snapshot"),
|
||||
"codex.transport.fallback_to_http",
|
||||
["from_wire_api", "reason", "http_status_code"],
|
||||
&[(["responses_websocket", reason, http_status_code], 1)],
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn websocket_fallback_switches_to_http_on_upgrade_required_connect() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
@@ -45,18 +67,20 @@ async fn websocket_fallback_switches_to_http_on_upgrade_required_connect() -> Re
|
||||
)
|
||||
.await;
|
||||
|
||||
let mut builder = test_codex().with_config({
|
||||
let base_url = format!("{}/v1", server.uri());
|
||||
move |config| {
|
||||
config.model_provider.base_url = Some(base_url);
|
||||
config.model_provider.wire_api = WireApi::Responses;
|
||||
config.model_provider.supports_websockets = true;
|
||||
// If we don't treat 426 specially, the sampling loop would retry the WebSocket
|
||||
// handshake before switching to the HTTP transport.
|
||||
config.model_provider.stream_max_retries = Some(2);
|
||||
config.model_provider.request_max_retries = Some(0);
|
||||
}
|
||||
});
|
||||
let mut builder = test_codex()
|
||||
.with_thread_extension(fallback_metrics())
|
||||
.with_config({
|
||||
let base_url = format!("{}/v1", server.uri());
|
||||
move |config| {
|
||||
config.model_provider.base_url = Some(base_url);
|
||||
config.model_provider.wire_api = WireApi::Responses;
|
||||
config.model_provider.supports_websockets = true;
|
||||
// If we don't treat 426 specially, the sampling loop would retry the WebSocket
|
||||
// handshake before switching to the HTTP transport.
|
||||
config.model_provider.stream_max_retries = Some(2);
|
||||
config.model_provider.request_max_retries = Some(0);
|
||||
}
|
||||
});
|
||||
let test = builder.build(&server).await?;
|
||||
|
||||
test.submit_turn("hello").await?;
|
||||
@@ -73,6 +97,7 @@ async fn websocket_fallback_switches_to_http_on_upgrade_required_connect() -> Re
|
||||
|
||||
// The startup prewarm request sees 426 and immediately switches the session to HTTP fallback,
|
||||
// so the first turn goes straight to HTTP with no additional websocket connect attempt.
|
||||
assert_fallback_metric(&test, "unexpected_status", "426");
|
||||
assert_eq!(websocket_attempts, 1);
|
||||
assert_eq!(http_attempts, 1);
|
||||
assert_eq!(response_mock.requests().len(), 1);
|
||||
@@ -155,6 +180,7 @@ async fn forbidden_responses_retry_only_without_an_explicit_access_denial(
|
||||
}
|
||||
|
||||
let test = test_codex()
|
||||
.with_thread_extension(fallback_metrics())
|
||||
.with_config(move |config| {
|
||||
config.model_provider.supports_websockets = supports_websockets;
|
||||
config.model_provider.stream_max_retries = Some(1);
|
||||
@@ -167,6 +193,9 @@ async fn forbidden_responses_retry_only_without_an_explicit_access_denial(
|
||||
// should leave the next turn eligible for its own WebSocket attempt.
|
||||
test.submit_turn("first").await?;
|
||||
test.submit_turn("second").await?;
|
||||
if supports_websockets && code.is_none() {
|
||||
assert_fallback_metric(&test, "unexpected_status", "403");
|
||||
}
|
||||
server.verify().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -74,15 +74,20 @@ async fn retry_transport(
|
||||
}
|
||||
});
|
||||
|
||||
let mut builder = test_codex().with_config(move |config| {
|
||||
config.model_provider.base_url = Some(base_url);
|
||||
config.model_provider.supports_websockets = true;
|
||||
config.model_provider.stream_max_retries = Some(1);
|
||||
config.model_provider.request_max_retries = Some(0);
|
||||
});
|
||||
let mut builder = test_codex()
|
||||
.with_thread_extension(super::fallback_metrics())
|
||||
.with_config(move |config| {
|
||||
config.model_provider.base_url = Some(base_url);
|
||||
config.model_provider.supports_websockets = true;
|
||||
config.model_provider.stream_max_retries = Some(1);
|
||||
config.model_provider.request_max_retries = Some(0);
|
||||
});
|
||||
let test = builder.build_with_auto_env(&http).await?;
|
||||
test.submit_turn("first").await?;
|
||||
assert_eq!(generations.load(Ordering::Relaxed), expected_ws_generations);
|
||||
if expected_posts == 1 {
|
||||
super::assert_fallback_metric(&test, "websocket_message_too_large", "none");
|
||||
}
|
||||
assert_eq!(
|
||||
responses::received_responses_requests(&http).await.len(),
|
||||
expected_posts
|
||||
|
||||
Reference in New Issue
Block a user