From 47725f9fa821d04cb7750ff0364ddf796ec62ac6 Mon Sep 17 00:00:00 2001 From: aibrahim-oai Date: Thu, 17 Jul 2025 10:40:28 -0700 Subject: [PATCH] refactor: use config for openai retries --- codex-rs/config.md | 12 ++++++ codex-rs/core/src/chat_completions.rs | 22 +++++++---- codex-rs/core/src/client.rs | 35 +++++++++++++----- codex-rs/core/src/codex.rs | 8 ++-- codex-rs/core/src/config.rs | 41 ++++++++++++++++++++- codex-rs/core/tests/live_agent.rs | 10 ++--- codex-rs/core/tests/previous_response_id.rs | 11 ++---- codex-rs/core/tests/stream_no_completed.rs | 18 +++------ 8 files changed, 108 insertions(+), 49 deletions(-) diff --git a/codex-rs/config.md b/codex-rs/config.md index 438b7e767d..78ade7ce6a 100644 --- a/codex-rs/config.md +++ b/codex-rs/config.md @@ -466,6 +466,18 @@ This is analogous to `model_context_window`, but for the maximum number of outpu Maximum number of bytes to read from an `AGENTS.md` file to include in the instructions sent with the first turn of a session. Defaults to 32 KiB. +## openai_request_max_retries + +How many times Codex will retry a failed HTTP request to the model provider. Defaults to `4`. + +## openai_stream_max_retries + +Number of times Codex will attempt to reconnect when a streaming response is interrupted. Defaults to `10`. + +## openai_stream_idle_timeout_ms + +How long Codex will wait for activity on a streaming response before treating the connection as lost. Defaults to `300000` (5 minutes). + ## tui Options that are specific to the TUI. diff --git a/codex-rs/core/src/chat_completions.rs b/codex-rs/core/src/chat_completions.rs index ad7b55952a..bd029fcd76 100644 --- a/codex-rs/core/src/chat_completions.rs +++ b/codex-rs/core/src/chat_completions.rs @@ -21,8 +21,7 @@ use crate::client_common::ResponseEvent; use crate::client_common::ResponseStream; use crate::error::CodexErr; use crate::error::Result; -use crate::flags::OPENAI_REQUEST_MAX_RETRIES; -use crate::flags::OPENAI_STREAM_IDLE_TIMEOUT_MS; +use crate::config::Config; use crate::models::ContentItem; use crate::models::ResponseItem; use crate::openai_tools::create_tools_json_for_chat_completions_api; @@ -34,6 +33,7 @@ pub(crate) async fn stream_chat_completions( model: &str, client: &reqwest::Client, provider: &ModelProviderInfo, + config: &Config, ) -> Result { // Build messages array let mut messages = Vec::::new(); @@ -136,7 +136,11 @@ pub(crate) async fn stream_chat_completions( Ok(resp) if resp.status().is_success() => { let (tx_event, rx_event) = mpsc::channel::>(1600); let stream = resp.bytes_stream().map_err(CodexErr::Reqwest); - tokio::spawn(process_chat_sse(stream, tx_event)); + tokio::spawn(process_chat_sse( + stream, + tx_event, + config.openai_stream_idle_timeout_ms, + )); return Ok(ResponseStream { rx_event }); } Ok(res) => { @@ -146,7 +150,7 @@ pub(crate) async fn stream_chat_completions( return Err(CodexErr::UnexpectedStatus(status, body)); } - if attempt > *OPENAI_REQUEST_MAX_RETRIES { + if attempt > config.openai_request_max_retries { return Err(CodexErr::RetryLimit(status)); } @@ -162,7 +166,7 @@ pub(crate) async fn stream_chat_completions( tokio::time::sleep(delay).await; } Err(e) => { - if attempt > *OPENAI_REQUEST_MAX_RETRIES { + if attempt > config.openai_request_max_retries { return Err(e.into()); } let delay = backoff(attempt); @@ -175,14 +179,16 @@ pub(crate) async fn stream_chat_completions( /// Lightweight SSE processor for the Chat Completions streaming format. The /// output is mapped onto Codex's internal [`ResponseEvent`] so that the rest /// of the pipeline can stay agnostic of the underlying wire format. -async fn process_chat_sse(stream: S, tx_event: mpsc::Sender>) +async fn process_chat_sse( + stream: S, + tx_event: mpsc::Sender>, + idle_timeout: Duration, +) where S: Stream> + Unpin, { let mut stream = stream.eventsource(); - let idle_timeout = *OPENAI_STREAM_IDLE_TIMEOUT_MS; - // State to accumulate a function call across streaming chunks. // OpenAI may split the `arguments` string over multiple `delta` events // until the chunk whose `finish_reason` is `tool_calls` is emitted. We diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index 8ec68d02e8..7c472fed78 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -29,8 +29,7 @@ use crate::config_types::ReasoningSummary as ReasoningSummaryConfig; use crate::error::CodexErr; use crate::error::Result; use crate::flags::CODEX_RS_SSE_FIXTURE; -use crate::flags::OPENAI_REQUEST_MAX_RETRIES; -use crate::flags::OPENAI_STREAM_IDLE_TIMEOUT_MS; +use crate::flags::OPENAI_STREAM_IDLE_TIMEOUT_MS; // retained for default config use crate::model_provider_info::ModelProviderInfo; use crate::model_provider_info::WireApi; use crate::models::ResponseItem; @@ -64,6 +63,10 @@ impl ModelClient { } } + pub fn config(&self) -> &Config { + &self.config + } + /// Dispatches to either the Responses or Chat implementation depending on /// the provider config. Public callers always invoke `stream()` – the /// specialised helpers are private to avoid accidental misuse. @@ -77,6 +80,7 @@ impl ModelClient { &self.config.model, &self.client, &self.provider, + &self.config, ) .await?; @@ -153,7 +157,11 @@ impl ModelClient { // spawn task to process SSE let stream = resp.bytes_stream().map_err(CodexErr::Reqwest); - tokio::spawn(process_sse(stream, tx_event)); + tokio::spawn(process_sse( + stream, + tx_event, + self.config.openai_stream_idle_timeout_ms, + )); return Ok(ResponseStream { rx_event }); } @@ -172,7 +180,7 @@ impl ModelClient { return Err(CodexErr::UnexpectedStatus(status, body)); } - if attempt > *OPENAI_REQUEST_MAX_RETRIES { + if attempt > self.config.openai_request_max_retries { return Err(CodexErr::RetryLimit(status)); } @@ -189,7 +197,7 @@ impl ModelClient { tokio::time::sleep(delay).await; } Err(e) => { - if attempt > *OPENAI_REQUEST_MAX_RETRIES { + if attempt > self.config.openai_request_max_retries { return Err(e.into()); } let delay = backoff(attempt); @@ -249,14 +257,17 @@ struct ResponseCompletedOutputTokensDetails { reasoning_tokens: u64, } -async fn process_sse(stream: S, tx_event: mpsc::Sender>) +async fn process_sse( + stream: S, + tx_event: mpsc::Sender>, + idle_timeout: Duration, +) where S: Stream> + Unpin, { let mut stream = stream.eventsource(); // If the stream stays completely silent for an extended period treat it as disconnected. - let idle_timeout = *OPENAI_STREAM_IDLE_TIMEOUT_MS; // The response id returned from the "complete" message. let mut response_completed: Option = None; @@ -404,7 +415,11 @@ async fn stream_from_fixture(path: impl AsRef) -> Result { let rdr = std::io::Cursor::new(content); let stream = ReaderStream::new(rdr).map_err(CodexErr::Io); - tokio::spawn(process_sse(stream, tx_event)); + tokio::spawn(process_sse( + stream, + tx_event, + *OPENAI_STREAM_IDLE_TIMEOUT_MS, + )); Ok(ResponseStream { rx_event }) } @@ -433,7 +448,7 @@ mod tests { let reader = builder.build(); let stream = ReaderStream::new(reader).map_err(CodexErr::Io); let (tx, mut rx) = mpsc::channel::>(16); - tokio::spawn(process_sse(stream, tx)); + tokio::spawn(process_sse(stream, tx, *OPENAI_STREAM_IDLE_TIMEOUT_MS)); let mut events = Vec::new(); while let Some(ev) = rx.recv().await { @@ -460,7 +475,7 @@ mod tests { let (tx, mut rx) = mpsc::channel::>(8); let stream = ReaderStream::new(std::io::Cursor::new(body)).map_err(CodexErr::Io); - tokio::spawn(process_sse(stream, tx)); + tokio::spawn(process_sse(stream, tx, *OPENAI_STREAM_IDLE_TIMEOUT_MS)); let mut out = Vec::new(); while let Some(ev) = rx.recv().await { diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 5227f93c8e..c0a907374c 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -49,7 +49,6 @@ use crate::exec::ExecToolCallOutput; use crate::exec::SandboxType; use crate::exec::process_exec_tool_call; use crate::exec_env::create_env; -use crate::flags::OPENAI_STREAM_MAX_RETRIES; use crate::mcp_connection_manager::McpConnectionManager; use crate::mcp_connection_manager::try_parse_fully_qualified_tool_name; use crate::mcp_tool_call::handle_mcp_tool_call; @@ -1027,12 +1026,12 @@ async fn run_turn( Err(CodexErr::Interrupted) => return Err(CodexErr::Interrupted), Err(CodexErr::EnvVar(var)) => return Err(CodexErr::EnvVar(var)), Err(e) => { - if retries < *OPENAI_STREAM_MAX_RETRIES { + if retries < sess.client.config().openai_stream_max_retries { retries += 1; let delay = backoff(retries); warn!( "stream disconnected - retrying turn ({retries}/{} in {delay:?})...", - *OPENAI_STREAM_MAX_RETRIES + sess.client.config().openai_stream_max_retries ); // Surface retry information to any UI/front‑end so the @@ -1042,7 +1041,8 @@ async fn run_turn( &sub_id, format!( "stream error: {e}; retrying {retries}/{} in {:?}…", - *OPENAI_STREAM_MAX_RETRIES, delay + sess.client.config().openai_stream_max_retries, + delay ), ) .await; diff --git a/codex-rs/core/src/config.rs b/codex-rs/core/src/config.rs index d67e692fc8..d76b557072 100644 --- a/codex-rs/core/src/config.rs +++ b/codex-rs/core/src/config.rs @@ -10,6 +10,9 @@ use crate::config_types::ShellEnvironmentPolicyToml; use crate::config_types::Tui; use crate::config_types::UriBasedFileOpener; use crate::flags::OPENAI_DEFAULT_MODEL; +use crate::flags::OPENAI_REQUEST_MAX_RETRIES; +use crate::flags::OPENAI_STREAM_MAX_RETRIES; +use crate::flags::OPENAI_STREAM_IDLE_TIMEOUT_MS; use crate::model_provider_info::ModelProviderInfo; use crate::model_provider_info::built_in_model_providers; use crate::openai_model_info::get_model_info; @@ -20,6 +23,7 @@ use serde::Deserialize; use std::collections::HashMap; use std::path::Path; use std::path::PathBuf; +use std::time::Duration; use toml::Value as TomlValue; /// Maximum number of bytes of the documentation that will be embedded. Larger @@ -137,6 +141,15 @@ pub struct Config { /// Base URL for requests to ChatGPT (as opposed to the OpenAI API). pub chatgpt_base_url: String, + + /// Maximum number of retries for failed HTTP requests to the model provider. + pub openai_request_max_retries: u64, + + /// Maximum number of retries for a dropped SSE stream. + pub openai_stream_max_retries: u64, + + /// Idle timeout for streaming responses. + pub openai_stream_idle_timeout_ms: Duration, } impl Config { @@ -321,6 +334,10 @@ pub struct ConfigToml { /// Base URL for requests to ChatGPT (as opposed to the OpenAI API). pub chatgpt_base_url: Option, + + pub openai_request_max_retries: Option, + pub openai_stream_max_retries: Option, + pub openai_stream_idle_timeout_ms: Option, } impl ConfigToml { @@ -494,6 +511,17 @@ impl Config { .chatgpt_base_url .or(cfg.chatgpt_base_url) .unwrap_or("https://chatgpt.com/backend-api/".to_string()), + + openai_request_max_retries: cfg + .openai_request_max_retries + .unwrap_or(*OPENAI_REQUEST_MAX_RETRIES), + openai_stream_max_retries: cfg + .openai_stream_max_retries + .unwrap_or(*OPENAI_STREAM_MAX_RETRIES), + openai_stream_idle_timeout_ms: cfg + .openai_stream_idle_timeout_ms + .map(Duration::from_millis) + .unwrap_or(*OPENAI_STREAM_IDLE_TIMEOUT_MS), }; Ok(config) } @@ -799,8 +827,11 @@ disable_response_storage = true model_reasoning_effort: ReasoningEffort::High, model_reasoning_summary: ReasoningSummary::Detailed, model_supports_reasoning_summaries: false, - chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(), - }, + chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(), + openai_request_max_retries: *OPENAI_REQUEST_MAX_RETRIES, + openai_stream_max_retries: *OPENAI_STREAM_MAX_RETRIES, + openai_stream_idle_timeout_ms: *OPENAI_STREAM_IDLE_TIMEOUT_MS, + }, o3_profile_config ); Ok(()) @@ -846,6 +877,9 @@ disable_response_storage = true model_reasoning_summary: ReasoningSummary::default(), model_supports_reasoning_summaries: false, chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(), + openai_request_max_retries: *OPENAI_REQUEST_MAX_RETRIES, + openai_stream_max_retries: *OPENAI_STREAM_MAX_RETRIES, + openai_stream_idle_timeout_ms: *OPENAI_STREAM_IDLE_TIMEOUT_MS, }; assert_eq!(expected_gpt3_profile_config, gpt3_profile_config); @@ -907,6 +941,9 @@ disable_response_storage = true model_reasoning_summary: ReasoningSummary::default(), model_supports_reasoning_summaries: false, chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(), + openai_request_max_retries: *OPENAI_REQUEST_MAX_RETRIES, + openai_stream_max_retries: *OPENAI_STREAM_MAX_RETRIES, + openai_stream_idle_timeout_ms: *OPENAI_STREAM_IDLE_TIMEOUT_MS, }; assert_eq!(expected_zdr_profile_config, zdr_profile_config); diff --git a/codex-rs/core/tests/live_agent.rs b/codex-rs/core/tests/live_agent.rs index c21f9d0032..9f2f2a672f 100644 --- a/codex-rs/core/tests/live_agent.rs +++ b/codex-rs/core/tests/live_agent.rs @@ -54,13 +54,13 @@ async fn spawn_codex() -> Result { // Restrict the unsafety to this tiny block that happens at the very // beginning of the test, before we spawn any background tasks that could // observe the environment. - unsafe { - std::env::set_var("OPENAI_REQUEST_MAX_RETRIES", "2"); - std::env::set_var("OPENAI_STREAM_MAX_RETRIES", "2"); - } + // Configure retry behaviour explicitly to avoid mutating process-wide + // environment variables. let codex_home = TempDir::new().unwrap(); - let config = load_default_config_for_test(&codex_home); + let mut config = load_default_config_for_test(&codex_home); + config.openai_request_max_retries = 2; + config.openai_stream_max_retries = 2; let (agent, _init_id) = Codex::spawn(config, std::sync::Arc::new(Notify::new())).await?; Ok(agent) diff --git a/codex-rs/core/tests/previous_response_id.rs b/codex-rs/core/tests/previous_response_id.rs index e64271a0ff..781cd91de2 100644 --- a/codex-rs/core/tests/previous_response_id.rs +++ b/codex-rs/core/tests/previous_response_id.rs @@ -88,13 +88,8 @@ async fn keeps_previous_response_id_between_tasks() { .mount(&server) .await; - // Environment - // Update environment – `set_var` is `unsafe` starting with the 2024 - // edition so we group the calls into a single `unsafe { … }` block. - unsafe { - std::env::set_var("OPENAI_REQUEST_MAX_RETRIES", "0"); - std::env::set_var("OPENAI_STREAM_MAX_RETRIES", "0"); - } + // Configure retry behaviour explicitly to avoid mutating process-wide + // environment variables. let model_provider = ModelProviderInfo { name: "openai".into(), base_url: format!("{}/v1", server.uri()), @@ -112,6 +107,8 @@ async fn keeps_previous_response_id_between_tasks() { // Init session let codex_home = TempDir::new().unwrap(); let mut config = load_default_config_for_test(&codex_home); + config.openai_request_max_retries = 0; + config.openai_stream_max_retries = 0; config.model_provider = model_provider; let ctrl_c = std::sync::Arc::new(tokio::sync::Notify::new()); let (codex, _init_id) = Codex::spawn(config, ctrl_c.clone()).await.unwrap(); diff --git a/codex-rs/core/tests/stream_no_completed.rs b/codex-rs/core/tests/stream_no_completed.rs index 8883eff373..f4865eb62a 100644 --- a/codex-rs/core/tests/stream_no_completed.rs +++ b/codex-rs/core/tests/stream_no_completed.rs @@ -72,19 +72,8 @@ async fn retries_on_early_close() { .mount(&server) .await; - // Environment - // - // As of Rust 2024 `std::env::set_var` has been made `unsafe` because - // mutating the process environment is inherently racy when other threads - // are running. We therefore have to wrap every call in an explicit - // `unsafe` block. These are limited to the test-setup section so the - // scope is very small and clearly delineated. - - unsafe { - std::env::set_var("OPENAI_REQUEST_MAX_RETRIES", "0"); - std::env::set_var("OPENAI_STREAM_MAX_RETRIES", "1"); - std::env::set_var("OPENAI_STREAM_IDLE_TIMEOUT_MS", "2000"); - } + // Configure retry behaviour explicitly to avoid mutating process-wide + // environment variables. let model_provider = ModelProviderInfo { name: "openai".into(), @@ -103,6 +92,9 @@ async fn retries_on_early_close() { let ctrl_c = std::sync::Arc::new(tokio::sync::Notify::new()); let codex_home = TempDir::new().unwrap(); let mut config = load_default_config_for_test(&codex_home); + config.openai_request_max_retries = 0; + config.openai_stream_max_retries = 1; + config.openai_stream_idle_timeout_ms = Duration::from_millis(2000); config.model_provider = model_provider; let (codex, _init_id) = Codex::spawn(config, ctrl_c).await.unwrap();