From f53f5a6fed662bd6f352d08066925c871a061182 Mon Sep 17 00:00:00 2001 From: Bryan Ashley Date: Tue, 29 Sep 2026 02:22:42 +0000 Subject: [PATCH] Expose original error details to turn lifecycle contributors (#49138) ## Why Turn error hooks receive only a `CodexErrorInfo` category, which omits backend metadata such as usage-limit reset times and rate-limit snapshots. ## What changed Add borrowed `CodexErrorDetails` to `TurnErrorInput` and pass the original details through turn and compaction error notifications, alongside the existing error category. ## Testing Add coverage for usage-limit metadata during sampling, manual compaction, and post-turn compaction, including preservation of completed answers and existing error events. Extend lifecycle tests to verify that an `InvalidImageRequest` retains its details when surfaced as `BadRequest`. GitOrigin-RevId: 6f2058992126da0f69508ef51998e7581557deea --- codex-rs/core/src/session/tests.rs | 28 ++- codex-rs/core/src/session/turn.rs | 28 ++- codex-rs/core/src/tasks/compact.rs | 4 +- codex-rs/core/src/tasks/lifecycle.rs | 3 + codex-rs/core/src/tasks/mod.rs | 1 + codex-rs/core/tests/suite/mod.rs | 2 + .../tests/suite/turn_error_details_tests.rs | 182 ++++++++++++++++++ .../src/contributors/turn_lifecycle.rs | 3 + .../ext/goal/tests/goal_extension_backend.rs | 11 +- 9 files changed, 245 insertions(+), 17 deletions(-) create mode 100644 codex-rs/core/tests/suite/turn_error_details_tests.rs diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index 5d440240e8..13ebc68245 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -3568,16 +3568,19 @@ async fn turn_start_lifecycle_exposes_turn_metadata_and_token_baseline() { #[tokio::test] async fn turn_error_lifecycle_exposes_error_and_stores() { + use codex_protocol::error::CodexErrKind; + struct SessionTurnErrorMarker; struct ThreadTurnErrorMarker; - #[derive(Debug, PartialEq, Eq)] + #[derive(Clone, Debug, PartialEq, Eq)] struct RecordedTurnError { session_level_id: String, thread_level_id: String, turn_level_id: String, turn_id: String, error: CodexErrorInfo, + error_kind: CodexErrKind, saw_session_store: bool, saw_thread_store: bool, } @@ -3601,6 +3604,7 @@ async fn turn_error_lifecycle_exposes_error_and_stores() { turn_level_id: input.turn_store.level_id().to_string(), turn_id: input.turn_id.to_string(), error: input.error, + error_kind: input.error_details.into(), saw_session_store: input .session_store .get::() @@ -3636,12 +3640,30 @@ async fn turn_error_lifecycle_exposes_error_and_stores() { turn_level_id: turn_context.sub_id.clone(), turn_id: turn_context.sub_id.clone(), error: CodexErrorInfo::UsageLimitExceeded, + error_kind: CodexErrKind::QuotaExceeded, saw_session_store: true, saw_thread_store: true, }; session - .emit_turn_error_lifecycle(&turn_context, CodexErrorInfo::UsageLimitExceeded) + .emit_turn_error_lifecycle( + &turn_context, + CodexErrorInfo::UsageLimitExceeded, + &CodexErrorDetails::QuotaExceeded, + ) + .await; + + let expected_override = RecordedTurnError { + error: CodexErrorInfo::BadRequest, + error_kind: CodexErrKind::InvalidImageRequest, + ..expected.clone() + }; + session + .emit_turn_error_lifecycle( + &turn_context, + CodexErrorInfo::BadRequest, + &CodexErrorDetails::InvalidImageRequest(), + ) .await; let actual = records @@ -3649,7 +3671,7 @@ async fn turn_error_lifecycle_exposes_error_and_stores() { .expect("turn error records lock") .drain(..) .collect::>(); - assert_eq!(vec![expected], actual); + assert_eq!(vec![expected, expected_override], actual); } #[tokio::test] diff --git a/codex-rs/core/src/session/turn.rs b/codex-rs/core/src/session/turn.rs index 3e5836a290..5b335c2c05 100644 --- a/codex-rs/core/src/session/turn.rs +++ b/codex-rs/core/src/session/turn.rs @@ -204,7 +204,7 @@ pub(crate) async fn run_turn( return Err(err); } let error = err.to_codex_protocol_error(); - sess.emit_turn_error_lifecycle(turn_context.as_ref(), error.clone()) + sess.emit_turn_error_lifecycle(turn_context.as_ref(), error.clone(), err.details()) .await; // Publish the failure only after prompt hooks finish, so clients cannot react to // an error by steering follow-up input into a turn still preserving its prompt. @@ -629,8 +629,12 @@ pub(crate) async fn run_turn( return Err(err); } let error = err.to_codex_protocol_error(); - sess.emit_turn_error_lifecycle(turn_context.as_ref(), error.clone()) - .await; + sess.emit_turn_error_lifecycle( + turn_context.as_ref(), + error.clone(), + err.details(), + ) + .await; return Ok(None); } if run_pending_session_start_hooks(&sess, &turn_context).await { @@ -739,8 +743,12 @@ pub(crate) async fn run_turn( let error = err.to_codex_protocol_error(); if matches!(error, CodexErrorInfo::UsageLimitExceeded) { // Preserve the completed answer while stopping automatic work. - sess.emit_turn_error_lifecycle(turn_context.as_ref(), error) - .await; + sess.emit_turn_error_lifecycle( + turn_context.as_ref(), + error, + err.details(), + ) + .await; } warn!(error = %err, "Post-turn compaction failed; preserving the completed turn"); } @@ -793,8 +801,12 @@ pub(crate) async fn run_turn( { sess.track_turn_codex_error(turn_context.as_ref(), &codex_error); let error = CodexErrorInfo::BadRequest; - sess.emit_turn_error_lifecycle(turn_context.as_ref(), error.clone()) - .await; + sess.emit_turn_error_lifecycle( + turn_context.as_ref(), + error.clone(), + codex_error.details(), + ) + .await; let event = EventMsg::Error(ErrorEvent { misalignment: None, message: "Invalid image in your last message. Please remove it and try again." @@ -813,7 +825,7 @@ pub(crate) async fn run_turn( sess.conversation.retire_handoffs_for_misalignment().await; } let error = e.to_codex_protocol_error(); - sess.emit_turn_error_lifecycle(turn_context.as_ref(), error.clone()) + sess.emit_turn_error_lifecycle(turn_context.as_ref(), error.clone(), e.details()) .await; sess.track_turn_codex_error(turn_context.as_ref(), &e); let event = EventMsg::Error(e.to_error_event(/*message_prefix*/ None)); diff --git a/codex-rs/core/src/tasks/compact.rs b/codex-rs/core/src/tasks/compact.rs index 85f1a54f91..4235fb6de1 100644 --- a/codex-rs/core/src/tasks/compact.rs +++ b/codex-rs/core/src/tasks/compact.rs @@ -75,7 +75,9 @@ impl SessionTask for CompactTask { let error = err.to_codex_protocol_error(); if matches!(error, CodexErrorInfo::UsageLimitExceeded) { // Compaction already emitted the error; notify extensions without emitting it twice. - session.emit_turn_error_lifecycle(ctx.as_ref(), error).await; + session + .emit_turn_error_lifecycle(ctx.as_ref(), error, err.details()) + .await; } } Ok(None) diff --git a/codex-rs/core/src/tasks/lifecycle.rs b/codex-rs/core/src/tasks/lifecycle.rs index 27835be8fc..afecaede5a 100644 --- a/codex-rs/core/src/tasks/lifecycle.rs +++ b/codex-rs/core/src/tasks/lifecycle.rs @@ -4,6 +4,7 @@ use codex_analytics::TurnAnalyticsMetadata; use codex_extension_api::ExtensionData; use codex_extension_api::ThreadIdleCause; use codex_extension_api::TurnStartPhase; +use codex_protocol::error::CodexErrorDetails; use codex_protocol::protocol::CodexErrorInfo; use codex_protocol::protocol::TokenUsage; use codex_protocol::protocol::TurnAbortReason; @@ -103,12 +104,14 @@ impl Session { &self, turn_context: &TurnContext, error: CodexErrorInfo, + error_details: &CodexErrorDetails, ) { for contributor in self.services.extensions.turn_lifecycle_contributors() { contributor .on_turn_error(codex_extension_api::TurnErrorInput { turn_id: turn_context.sub_id.as_str(), error: error.clone(), + error_details, session_store: &self.services.session_extension_data, thread_store: &self.services.thread_extension_data, turn_store: turn_context.extension_data.as_ref(), diff --git a/codex-rs/core/src/tasks/mod.rs b/codex-rs/core/src/tasks/mod.rs index 323c8015a5..28a3b54b1c 100644 --- a/codex-rs/core/src/tasks/mod.rs +++ b/codex-rs/core/src/tasks/mod.rs @@ -641,6 +641,7 @@ impl Session { self.emit_turn_error_lifecycle( turn_context.as_ref(), err.to_codex_protocol_error(), + err.details(), ) .await; self.track_turn_codex_error(turn_context.as_ref(), &err); diff --git a/codex-rs/core/tests/suite/mod.rs b/codex-rs/core/tests/suite/mod.rs index ada5d56124..50f965cd5f 100644 --- a/codex-rs/core/tests/suite/mod.rs +++ b/codex-rs/core/tests/suite/mod.rs @@ -216,6 +216,8 @@ mod tool_lifecycle; mod tool_parallelism; mod tools; mod truncation; +#[path = "turn_error_details_tests.rs"] +mod turn_error_details; mod turn_input_submission; mod turn_state; mod unified_exec; diff --git a/codex-rs/core/tests/suite/turn_error_details_tests.rs b/codex-rs/core/tests/suite/turn_error_details_tests.rs new file mode 100644 index 0000000000..0cc0c8c8db --- /dev/null +++ b/codex-rs/core/tests/suite/turn_error_details_tests.rs @@ -0,0 +1,182 @@ +//! Verify error hooks retain backend details without changing compaction outcomes. + +use codex_core::TurnInputRequest; +use codex_extension_api::ExtensionFuture; +use codex_extension_api::ExtensionRegistryBuilder; +use codex_extension_api::TurnErrorInput; +use codex_extension_api::TurnLifecycleContributor; +use codex_protocol::error::CodexErrorDetails; +use codex_protocol::protocol::CodexErrorInfo; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::RateLimitReachedType; +use codex_protocol::user_input::UserInput; +use core_test_support::responses; +use core_test_support::skip_if_no_network; +use core_test_support::test_codex::test_codex; +use core_test_support::wait_for_event; +use pretty_assertions::assert_eq; +use serde_json::json; +use std::sync::Arc; +use std::sync::Mutex; +use wiremock::ResponseTemplate; + +#[derive(Debug, PartialEq)] +struct ObservedUsageLimit { + turn_id: String, + error: CodexErrorInfo, + resets_at: Option, + limit_window_minutes: Option, + limit_id: Option, + snapshot_resets_at: Option, + rate_limit_reached_type: Option, +} + +struct ErrorRecorder(Arc>>); + +impl TurnLifecycleContributor for ErrorRecorder { + fn on_turn_error<'a>(&'a self, input: TurnErrorInput<'a>) -> ExtensionFuture<'a, ()> { + Box::pin(async move { + let CodexErrorDetails::UsageLimitReached(details) = input.error_details else { + panic!("expected usage-limit details"); + }; + let snapshot = details.rate_limits.as_ref(); + self.0 + .lock() + .expect("usage limit records lock") + .push(ObservedUsageLimit { + turn_id: input.turn_id.to_string(), + error: input.error, + resets_at: details.resets_at.map(|reset| reset.timestamp()), + limit_window_minutes: details.limit_window_minutes, + limit_id: snapshot.and_then(|snapshot| snapshot.limit_id.clone()), + snapshot_resets_at: snapshot + .and_then(|snapshot| snapshot.primary.as_ref()) + .and_then(|window| window.resets_at), + rate_limit_reached_type: details.rate_limit_reached_type, + }); + }) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Phase { + Sampling, + ManualCompaction, + PostTurnCompaction, +} + +/// Backend reset details reach the hook even when post-turn compaction preserves a completed answer. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn turn_error_details_preserve_usage_reset_and_compaction_outcomes() -> anyhow::Result<()> { + skip_if_no_network!(Ok(())); + + for phase in [ + Phase::Sampling, + Phase::ManualCompaction, + Phase::PostTurnCompaction, + ] { + let server = responses::start_mock_server().await; + let denial = ResponseTemplate::new(429) + .insert_header("x-codex-active-limit", "test_limit") + .insert_header("x-test-limit-primary-used-percent", "100") + .insert_header("x-test-limit-primary-reset-at", "1700000000") + .insert_header("x-codex-rate-limit-reached-type", "rate_limit_reached") + .set_body_json(json!({ + "error": { + "type": "usage_limit_reached", + "resets_at": 1800000000, + "limit_window_minutes": 10080 + } + })); + let mut responses = Vec::new(); + if phase == Phase::PostTurnCompaction { + responses.push(responses::sse_response(responses::sse(vec![ + responses::ev_response_created("answer"), + responses::ev_assistant_message("answer-message", "Completed answer"), + responses::ev_completed_with_tokens("answer", /*total_tokens*/ 7_000), + ]))); + } + responses.push(denial); + let expected_requests = responses.len(); + let mock = responses::mount_response_sequence(&server, responses).await; + let observed = Arc::new(Mutex::new(Vec::new())); + let mut extensions = ExtensionRegistryBuilder::new(); + extensions.turn_lifecycle_contributor(Arc::new(ErrorRecorder(observed.clone()))); + let mut builder = test_codex() + .with_extensions(Arc::new(extensions.build())) + .with_model_info_override("gpt-5.5", |info| { + info.context_window = Some(12_000); + info.max_context_window = None; + }) + .with_config(move |config| { + config.model_provider.name = "Local compaction test provider".to_string(); + config.model_provider.request_max_retries = Some(0); + config.model_provider.stream_max_retries = Some(0); + config.model_auto_compact_token_limit = Some(100_000); + config.model_post_turn_compact_threshold_percent = + if phase == Phase::PostTurnCompaction { + 50 + } else { + 0 + }; + }); + let test = builder.build_with_auto_env(&server).await?; + if phase == Phase::ManualCompaction { + test.codex.submit(Op::Compact).await?; + } else { + test.codex + .start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text { + text: "Answer the request".to_string(), + text_elements: Vec::new(), + }])) + .await?; + } + + let mut errors = Vec::new(); + let completed = wait_for_event(&test.codex, |event| { + if let EventMsg::Error(error) = event { + errors.push(error.codex_error_info.clone()); + } + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; + let EventMsg::TurnComplete(completed) = completed else { + unreachable!() + }; + assert_eq!( + *observed.lock().expect("usage limit records lock"), + vec![ObservedUsageLimit { + turn_id: completed.turn_id.clone(), + error: CodexErrorInfo::UsageLimitExceeded, + resets_at: Some(1_800_000_000), + limit_window_minutes: Some(10_080), + limit_id: Some("test_limit".to_string()), + snapshot_resets_at: Some(1_700_000_000), + rate_limit_reached_type: Some(RateLimitReachedType::RateLimitReached), + }], + "{phase:?}", + ); + let expected_error = + (phase != Phase::PostTurnCompaction).then_some(CodexErrorInfo::UsageLimitExceeded); + assert_eq!( + completed.error.and_then(|error| error.codex_error_info), + expected_error, + "{phase:?}" + ); + assert_eq!( + errors, + expected_error.map(Some).into_iter().collect::>(), + "{phase:?}" + ); + if phase == Phase::PostTurnCompaction { + assert_eq!( + completed.last_agent_message.as_deref(), + Some("Completed answer") + ); + } + assert_eq!(mock.requests().len(), expected_requests); + test.codex.shutdown_and_wait().await?; + } + Ok(()) +} diff --git a/codex-rs/ext/extension-api/src/contributors/turn_lifecycle.rs b/codex-rs/ext/extension-api/src/contributors/turn_lifecycle.rs index ce9e854930..7361c20c5f 100644 --- a/codex-rs/ext/extension-api/src/contributors/turn_lifecycle.rs +++ b/codex-rs/ext/extension-api/src/contributors/turn_lifecycle.rs @@ -1,6 +1,7 @@ //! Turn lifecycle inputs and scheduling phases for host-owned contributors. use codex_protocol::config_types::CollaborationMode; +use codex_protocol::error::CodexErrorDetails; use codex_protocol::protocol::CodexErrorInfo; use codex_protocol::protocol::TokenUsage; use codex_protocol::protocol::TurnAbortReason; @@ -60,6 +61,8 @@ pub struct TurnErrorInput<'a> { pub turn_id: &'a str, /// Error surfaced by the host for this turn. pub error: CodexErrorInfo, + /// Original error details, including backend metadata omitted from the public category. + pub error_details: &'a CodexErrorDetails, /// Store scoped to the host session runtime. pub session_store: &'a ExtensionData, /// Store scoped to this thread runtime. diff --git a/codex-rs/ext/goal/tests/goal_extension_backend.rs b/codex-rs/ext/goal/tests/goal_extension_backend.rs index 4b41740f89..e0a952d1a8 100644 --- a/codex-rs/ext/goal/tests/goal_extension_backend.rs +++ b/codex-rs/ext/goal/tests/goal_extension_backend.rs @@ -38,7 +38,7 @@ use codex_protocol::ThreadId; use codex_protocol::config_types::CollaborationMode; use codex_protocol::config_types::ModeKind; use codex_protocol::config_types::Settings; -use codex_protocol::protocol::CodexErrorInfo; +use codex_protocol::error::CodexErr; use codex_protocol::protocol::Event; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::SessionSource; @@ -786,7 +786,7 @@ async fn turn_error_usage_limit_accounts_progress_and_clears_accounting() -> any ) .await; harness - .notify_turn_error("turn-1", CodexErrorInfo::UsageLimitExceeded) + .notify_turn_error("turn-1", CodexErr::UsageNotIncluded) .await; let goal = runtime @@ -857,7 +857,7 @@ async fn turn_error_blocks_goal() -> anyhow::Result<()> { .await?; harness - .notify_turn_error("turn-1", CodexErrorInfo::Other) + .notify_turn_error("turn-1", CodexErr::Fatal("test error".to_string())) .await; let goal = runtime @@ -1887,13 +1887,14 @@ impl GoalExtensionHarness { } } - async fn notify_turn_error(&self, turn_id: &str, error: CodexErrorInfo) { + async fn notify_turn_error(&self, turn_id: &str, error: CodexErr) { let turn_store = ExtensionData::new(turn_id); for contributor in self.registry.turn_lifecycle_contributors() { contributor .on_turn_error(TurnErrorInput { turn_id, - error: error.clone(), + error: error.to_codex_protocol_error(), + error_details: error.details(), session_store: &self.session_store, thread_store: &self.thread_store, turn_store: &turn_store,