From a5d572b651efd0f61c613b5822e8ac22d015e17a Mon Sep 17 00:00:00 2001 From: Steve Coffey Date: Wed, 2 Dec 2026 18:00:14 +0000 Subject: [PATCH] Record Guardian token usage on the requesting turn (#65312) ## Why The requesting thread's rollout lacks per-response token usage for Guardian work, including requests that consume tokens without producing a usable result. ## What changed Persist reported token usage from Guardian reviews, background review compaction, and classifier requests in the requesting thread's rollout. Each record identifies the requesting turn, response, and model, and marks incomplete responses that report usage. These records stay separate from the thread's cumulative token totals and are excluded from forked history. ## Testing Cover review attribution and unchanged parent token totals, compaction that reports usage without a usable summary, and thread shutdown waiting for an interrupted classifier's usage write. GitOrigin-RevId: da5d3711cdb7c7aeab829d3537ef59b724c57171 --- .../app-server-exports-stable.json.zst | Bin 175189 -> 175321 bytes ...c__recorded_v3_review_request_history.snap | 4 +- codex-rs/core/src/agent/history.rs | 6 +- codex-rs/core/src/compact_remote_v2.rs | 144 ++++++++++++++++-- .../core/src/guardian/review_session_setup.rs | 21 +-- codex-rs/core/src/guardian_review.rs | 37 +++++ codex-rs/core/src/session/mod.rs | 55 ++++++- codex-rs/core/src/session/tests.rs | 33 +++- codex-rs/core/tests/suite/auto_review.rs | 44 +++++- .../src/async_scorer/classification.rs | 5 +- .../src/async_scorer/conversation.rs | 51 ++++--- .../guardian-v2/src/async_scorer/extension.rs | 2 +- .../src/async_scorer/extension_tests.rs | 55 +++++-- .../src/async_scorer/pending_score_tests.rs | 103 ++++++++++--- .../guardian-v2/src/async_scorer/sampler.rs | 9 ++ .../connection_pool_cancellation_tests.rs | 4 +- .../src/async_scorer/sampler/execution.rs | 11 +- .../src/async_scorer/sampler/response.rs | 76 +++++++-- .../src/async_scorer/sampler_tests.rs | 3 + codex-rs/protocol/src/protocol.rs | 14 ++ codex-rs/rollout/src/policy.rs | 4 +- 21 files changed, 571 insertions(+), 110 deletions(-) diff --git a/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-stable.json.zst b/codex-rs/app-server-protocol/schema/precomputed/app-server-exports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{O^L`e|fzsN0D$|hGjbUgT7IssF<3EXlmbM zY+^ZyWj)T3U0^eu#OY_oIGe%icE1M+3O$914^D#l>4&}mcpsUZYN=(pnyvt$W)US^ zQ2<=vHC;x|>U$*^*%p%Bl$8bBpWTjZ`_MtAkB^m`KGMVZ&!PlLcGf822u?d1DaAZ5 zf3f!+VbuHtM4hzwtV%sFvIm+HoFkUovd-{h@;a<9v7DuoEG8QUp(NV&W??7z1A#fb zn24R%@A5?_c1lEU9!mU$iPJsf!g=u_Ww7xflrwQCf%F%0Tp&k02cm>IG4x``O|?8r zD3=F~I=3G>Gp)szpjpFvv6slsKS;)Ee@0}yk`yBS^hH$eJV6hy{MF;E9_wc1 zz#yaX!Z0PuNeNrT>o8q7jOv_}a2hG!eyMAmXPo;1Eycpe-DKH zAqrl^A91J}a7%ZC>c!eE@x1$L=!Bk(4zq0Q`oE0pZ}1pLiRmKdWN}w*0+%4)AJ@XB zT;DXlC0u*H;fqp7AMF3Lv&C#5$_MaSj0fdCpDT7-fUi3;HTpt$7YQnx@Gln#&h%qx z>W&5PERcQsOT01h7XVDK~ z$WdH+>?E3Z38N1Ww~$5L@x_DK7Wc)RQ)05tImHQnE`_I1oLe9e;9$7-k$`wwa$_Ld z2~WuRUWhi2A{J^DkzXaw^8eL)PaxGI>(~smznKZoeqsr~`n{T3CRmN~KG<0_{j2SBdkxVuA=*u@SjSIF+#xi){(w k8ta4sd+)I=;UacIW{ZuZD7eo(HHerS??CO?@j(@bD55wU+yDRo diff --git a/codex-rs/app-server/tests/suite/v2/snapshots/all__suite__v2__guardian_v2__v3_sync__recorded_v3_review_request_history.snap b/codex-rs/app-server/tests/suite/v2/snapshots/all__suite__v2__guardian_v2__v3_sync__recorded_v3_review_request_history.snap index 53eccf2545..5d751b1a61 100644 --- a/codex-rs/app-server/tests/suite/v2/snapshots/all__suite__v2__guardian_v2__v3_sync__recorded_v3_review_request_history.snap +++ b/codex-rs/app-server/tests/suite/v2/snapshots/all__suite__v2__guardian_v2__v3_sync__recorded_v3_review_request_history.snap @@ -62,7 +62,7 @@ Scenario: Review two recorded release commands on the same thread without execut 01:function_call_output/guardian.guardian_housekeeper_input:{"catalog":{},"sources":[{"id":{"ordinal":6},"original":{"metadata":{"client_authored":false,"user_input...":"user","type":"message"},"type":"response_item"}}]} [hash=0dd2f579990a825b] 02:message/assistant: {"descriptions":[{"channel":"release","description":"Release policy"}],"routes":[["release"]]} -03:function_call_output/guardian.guardian_housekeeper_input:{"catalog":{"release":"Release policy"},"sources":[{"id":{"ordinal":7},"original":{"metadata":{"client_a...":"user","type":"message"},"type":"response_item"}}]} [hash=9d78dce86b0be577] +03:function_call_output/guardian.guardian_housekeeper_input:{"catalog":{"release":"Release policy"},"sources":[{"id":{"ordinal":9},"original":{"metadata":{"client_a...":"user","type":"message"},"type":"response_item"}}]} [hash=32b8d0ce6c516fc9] ## Window 4 (after request 4: input diverged at item 00, settings changed (model, parallel_tool_calls, prompt_cache_key, reasoning, text, tool_choice, tools)) -- request 5 (request) -- @@ -146,4 +146,4 @@ Scenario: Review two recorded release commands on the same thread without execut -- request 6 (request) -- 09:function_call/guardian_board.search_posts:{"channel_name":"release","max_chars_per_post":2048} -10:function_call_output:{"has_more":false,"n_returned":4,"next_cursor":null,"results":[{"author":"/root","channel_name":"release...item\\"}}","thread_id":"","truncated":false}]} [hash=edb9ecc6950ff740] +10:function_call_output:{"has_more":false,"n_returned":4,"next_cursor":null,"results":[{"author":"/root","channel_name":"release...item\\"}}","thread_id":"","truncated":false}]} [hash=c4667395386e5aee] diff --git a/codex-rs/core/src/agent/history.rs b/codex-rs/core/src/agent/history.rs index 99dae46e33..b35522ee5b 100644 --- a/codex-rs/core/src/agent/history.rs +++ b/codex-rs/core/src/agent/history.rs @@ -282,7 +282,11 @@ fn keep_forked_rollout_item(item: &RolloutItem, preserve_context_baselines: bool // from the parent's durable baseline unless legacy compaction requires rebuilding it. RolloutItem::TurnContext(_) | RolloutItem::WorldState(_) => preserve_context_baselines, // Child threads inherit model context, not the parent's cumulative usage state. - RolloutItem::TokenUsageRecord(_) => false, + RolloutItem::TokenUsageRecord(_) + | RolloutItem::EventMsg { + event: EventMsg::RawResponseCompleted(_), + .. + } => false, RolloutItem::DynamicToolsUpdated { .. } | RolloutItem::Compacted(_) | RolloutItem::EventMsg { .. } diff --git a/codex-rs/core/src/compact_remote_v2.rs b/codex-rs/core/src/compact_remote_v2.rs index c2b9af3dc3..6479d1fb3a 100644 --- a/codex-rs/core/src/compact_remote_v2.rs +++ b/codex-rs/core/src/compact_remote_v2.rs @@ -104,7 +104,10 @@ const MAX_REMOTE_COMPACTION_V2_STREAM_RETRIES: u64 = 2; #[derive(Clone, Copy)] enum CompactionRequestKind<'a> { Foreground(&'a CancellationToken), - Background(&'a CancellationToken), + Background { + cancellation: &'a CancellationToken, + model: &'a str, + }, } enum CompactionRequestTransport<'a> { @@ -348,7 +351,10 @@ async fn run_remote_compaction_request_v2( sess, turn_context, stream, - CompactionRequestKind::Background(&cancellation), + CompactionRequestKind::Background { + cancellation: &cancellation, + model: &settings.model_info.slug, + }, ) .await; } @@ -452,7 +458,7 @@ async fn collect_compaction_output( CompactionRequestKind::Foreground(cancellation) => { stream.next_for_turn(cancellation).await } - CompactionRequestKind::Background(cancellation) => tokio::select! { + CompactionRequestKind::Background { cancellation, .. } => tokio::select! { biased; // Charge completed usage even when cancellation arrives at the same time. event = stream.next() => event, @@ -467,7 +473,19 @@ async fn collect_compaction_output( Err(err) => { if let CodexErrorDetails::ResponseIncomplete(incomplete) = err.details() { match request_kind { - CompactionRequestKind::Background(_) => { + CompactionRequestKind::Background { model, .. } => { + if let (Some(id), Some(tokens)) = + (&incomplete.response_id, &incomplete.token_usage) + { + sess.forward_guardian_usage( + turn_context, + model, + id, + tokens, + /*incomplete_error*/ true, + ) + .await; + } // Match completed background requests without replacing the terminal error. let usage = SamplingUsage { provider: incomplete.token_usage.clone(), @@ -512,15 +530,30 @@ async fn collect_compaction_output( provider: token_usage, charge: hook_output, }; - if matches!(request_kind, CompactionRequestKind::Foreground(_)) { - sess.record_observed_response_completed( - turn_context, - /*sampling_settings*/ None, - &response_id, - usage.provider.as_ref(), - usage_metadata.as_ref(), - ) - .await; + match request_kind { + CompactionRequestKind::Foreground(_) => { + sess.record_observed_response_completed( + turn_context, + /*sampling_settings*/ None, + &response_id, + usage.provider.as_ref(), + usage_metadata.as_ref(), + ) + .await; + } + CompactionRequestKind::Background { model, .. } => { + // Count the request even if its summary is never installed. + if let Some(tokens) = &usage.provider { + sess.forward_guardian_usage( + turn_context, + model, + &response_id, + tokens, + /*incomplete_error*/ false, + ) + .await; + } + } } // Both callers consumed this response. Whether it contains an // installable summary is a separate decision below. @@ -1589,6 +1622,81 @@ mod tests { assert_eq!(truncated, vec![newest]); } + #[test_case::test_case(false; "completed without an installable summary")] + #[test_case::test_case(true; "incomplete with reported tokens")] + #[tokio::test] + async fn background_compaction_forwards_guardian_usage(incomplete: bool) { + let (mut parent, _) = crate::session::tests::make_session_and_context().await; + let path = crate::session::tests::attach_thread_persistence(&mut parent).await; + let parent = Arc::new(parent); + let (reviewer, turn) = crate::session::tests::make_session_and_context().await; + reviewer + .services + .thread_extension_data + .insert(crate::guardian_review::GuardianParent(Arc::downgrade( + &parent, + ))); + turn.turn_metadata_state + .set_parent_turn_id("owner-turn".into()); + + let usage = TokenUsage { + input_tokens: 30, + output_tokens: 12, + total_tokens: 42, + ..Default::default() + }; + let terminal = if incomplete { + Err(CodexErr::new(CodexErrorDetails::ResponseIncomplete( + Box::new(codex_protocol::error::ResponseIncompleteError { + partial_output: Vec::new(), + reason: "max_output_tokens".into(), + response_id: Some("compact".into()), + token_usage: Some(usage.clone()), + }), + ))) + } else { + Ok(ResponseEvent::Completed { + response_id: "compact".into(), + token_usage: Some(usage.clone()), + usage_metadata: None, + reasoning_removals: None, + end_turn: Some(true), + }) + }; + // Neither response produces a usable summary. Both consumed tokens. + let result = collect_compaction_output( + &reviewer, + &turn, + response_stream(vec![terminal]), + CompactionRequestKind::Background { + cancellation: &CancellationToken::new(), + model: "background-reviewer", + }, + ) + .await; + assert!(result.is_err()); + let history = crate::session::tests::read_review_history(&parent, &path).await; + let records = history + .get_rollout_items() + .iter() + .filter_map(|item| match item.event_msg()? { + EventMsg::RawResponseCompleted(event) => Some(event), + _ => None, + }) + .collect::>(); + let [record] = records.as_slice() else { + panic!("expected exactly one forwarded response, got {records:?}"); + }; + assert_eq!(record.response_id, "compact"); + assert_eq!(record.token_usage.as_ref(), Some(&usage)); + let owner = record.guardian.as_ref().expect("Guardian attribution"); + assert_eq!(owner.parent_turn_id, "owner-turn"); + assert_eq!(owner.model, "background-reviewer"); + assert_eq!(owner.incomplete_error, incomplete); + assert_eq!(parent.token_usage_info().await, None); + assert_eq!(reviewer.token_usage_info().await, None); + } + #[test_case::test_case(false; "turn interrupt discards queued incomplete usage")] #[test_case::test_case(true; "session shutdown preserves queued incomplete usage without foreground updates")] #[tokio::test] @@ -1631,7 +1739,10 @@ mod tests { &turn_context, stream, if background { - CompactionRequestKind::Background(&cancellation) + CompactionRequestKind::Background { + cancellation: &cancellation, + model: &turn_context.model_info().slug, + } } else { CompactionRequestKind::Foreground(&cancellation) }, @@ -1710,7 +1821,10 @@ mod tests { cancellation.cancel(); } let kind = if background { - CompactionRequestKind::Background(&cancellation) + CompactionRequestKind::Background { + cancellation: &cancellation, + model: &turn.model_info().slug, + } } else { CompactionRequestKind::Foreground(&cancellation) }; diff --git a/codex-rs/core/src/guardian/review_session_setup.rs b/codex-rs/core/src/guardian/review_session_setup.rs index db4a8357df..fc383b271e 100644 --- a/codex-rs/core/src/guardian/review_session_setup.rs +++ b/codex-rs/core/src/guardian/review_session_setup.rs @@ -197,16 +197,19 @@ impl PreparedGuardianContext { cancellation: CancellationToken, ) -> GuardianReviewSession { let session = Arc::clone(&thread.session); - if self.parent.enabled(Feature::GuardianRecordedItems) - && session - .services - .thread_extension_data - .get::() - .is_none() + let extensions = &session.services.thread_extension_data; + if extensions + .get::() + .is_none() { - session - .parent_observer_event_tx - .get_or_init(|| self.parent.get_tx_event()); + extensions.get_or_init(|| { + crate::guardian_review::GuardianParent(Arc::downgrade(&self.parent)) + }); + if self.parent.enabled(Feature::GuardianRecordedItems) { + session + .parent_observer_event_tx + .get_or_init(|| self.parent.get_tx_event()); + } } let io = SessionIo { tx_sub: thread.io.tx_sub.clone(), diff --git a/codex-rs/core/src/guardian_review.rs b/codex-rs/core/src/guardian_review.rs index 3e7117e497..96f2cfcebf 100644 --- a/codex-rs/core/src/guardian_review.rs +++ b/codex-rs/core/src/guardian_review.rs @@ -7,6 +7,43 @@ pub use crate::guardian::PreparedGuardianContext; pub use crate::guardian::prepare_review_prewarm; pub use crate::mcp_tool_call::conversation_history::conversation_history_tools; +use crate::session::session::Session; +use codex_history::RolloutItem; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::GuardianResponseAttribution; +use codex_protocol::protocol::RawResponseCompletedEvent; +use codex_protocol::protocol::TokenUsage; +use std::sync::Weak; + +/// Reviewers are pooled across turns, so only the requesting thread is bound here. +pub(crate) struct GuardianParent(pub(crate) Weak); + +impl crate::CodexThread { + /// Save a classifier response on the requesting turn, even after that turn ends. + pub async fn record_guardian_usage( + &self, + attribution: GuardianResponseAttribution, + response_id: String, + usage: TokenUsage, + ) { + let item = guardian_usage_item(attribution, response_id, usage); + self.session.persist_rollout_items(&[item]).await; + } +} + +pub(crate) fn guardian_usage_item( + attribution: GuardianResponseAttribution, + response_id: String, + usage: TokenUsage, +) -> RolloutItem { + RolloutItem::EventMsg(EventMsg::RawResponseCompleted(RawResponseCompletedEvent { + response_id, + guardian: Some(attribution), + token_usage: Some(usage), + usage_metadata: None, + })) +} + /// Opts a root into session-owned evidence saves that survive turn cancellation. /// Install at thread startup. Reviewers do not wait for these writes. pub struct PreserveReviewWrites; diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index 78a34583c2..a92343aa45 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -2001,6 +2001,10 @@ impl Session { rollout_items.push(thread_settings_applied); } ForkPersistence::Copied | ForkPersistence::CopiedDeferred => { + // A review's usage belongs only to the thread that requested it. + rollout_items.retain(|item| { + !matches!(item.event_msg(), Some(EventMsg::RawResponseCompleted(event)) if event.guardian.is_some()) + }); // Keep the copied prefix and effective child settings in one append so a // cold resume cannot observe inherited settings as the latest value. rollout_items.push(thread_settings_applied); @@ -6056,6 +6060,7 @@ impl Session { sampling_settings, response_id, incomplete.token_usage.as_ref(), + /*incomplete_error*/ true, ) .await; } @@ -6106,13 +6111,20 @@ impl Session { turn_context, EventMsg::RawResponseCompleted(RawResponseCompletedEvent { response_id: response_id.to_string(), + guardian: None, token_usage: usage.cloned(), usage_metadata: usage_metadata.cloned(), }), ) .await; - self.record_response_token_usage(turn_context, sampling_settings, response_id, usage) - .await; + self.record_response_token_usage( + turn_context, + sampling_settings, + response_id, + usage, + /*incomplete_error*/ false, + ) + .await; } pub(crate) async fn record_response_token_usage( @@ -6121,6 +6133,7 @@ impl Session { sampling_settings: Option<&ResolvedStepSettings>, response_id: &str, usage: Option<&TokenUsage>, + incomplete_error: bool, ) { let Some(usage) = usage else { return; @@ -6133,10 +6146,48 @@ impl Session { sampling_settings.map(|settings| settings.model_info.slug.as_str()), usage, ); + if let Some(model) = &record.model { + self.forward_guardian_usage(turn_context, model, response_id, usage, incomplete_error) + .await; + } self.persist_rollout_items(&[RolloutItem::TokenUsageRecord(record)]) .await; } + pub(crate) async fn forward_guardian_usage( + &self, + turn_context: &TurnContext, + model: &str, + response_id: &str, + usage: &TokenUsage, + incomplete_error: bool, + ) { + if let Some(parent) = self + .services + .thread_extension_data + .get::() + && let Some(parent_turn_id) = turn_context.turn_metadata_state.parent_turn_id() + && let Some(session) = parent.0.upgrade() + { + let attribution = codex_protocol::protocol::GuardianResponseAttribution { + parent_turn_id, + model: model.to_owned(), + incomplete_error, + }; + let item = crate::guardian_review::guardian_usage_item( + attribution, + response_id.to_owned(), + usage.clone(), + ); + // Let the parent finish the write without delaying the review verdict. + if let Some(write) = session.track_code_mode_message() { + session.start_review_write(vec![item], write, /*settings*/ None); + } else { + session.persist_rollout_items(&[item]).await; + } + } + } + pub(crate) async fn record_token_usage_info( &self, turn_context: &TurnContext, diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index 97d59bbedc..36f4d321e7 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -4162,10 +4162,17 @@ async fn record_initial_history_assigns_and_persists_id_for_forked_response_item metadata: Some(CodexHarnessMetadata::default()), }; + let review = serde_json::from_value(json!({ + "response_id": "parent-review", + "guardian": {"model": "reviewer", "parent_turn_id": "parent-turn"}, + "token_usage": TokenUsage::default(), + })) + .expect("Guardian response"); session - .record_initial_history(InitialHistory::Forked(vec![RolloutItem::ResponseItem( - response_item, - )])) + .record_initial_history(InitialHistory::Forked(vec![ + RolloutItem::ResponseItem(response_item), + RolloutItem::EventMsg(EventMsg::RawResponseCompleted(review)), + ])) .await; let live_history = session.clone_history().await; @@ -4196,6 +4203,13 @@ async fn record_initial_history_assigns_and_persists_id_for_forked_response_item else { panic!("expected resumed rollout history"); }; + assert!(!resumed.history.iter().any(|item| matches!( + item, + RolloutItem::EventMsg { + event: EventMsg::RawResponseCompleted(_), + .. + } + ))); let persisted_item = resumed.history.iter().find_map(|item| match item { RolloutItem::ResponseItem(response_item) => Some(response_item), RolloutItem::DynamicToolsUpdated { .. } @@ -4835,7 +4849,7 @@ async fn open_thread_persistence(session: &mut Session) -> PathBuf { .expect("thread should have rollout path") } -pub(super) async fn attach_thread_persistence(session: &mut Session) -> PathBuf { +pub(crate) async fn attach_thread_persistence(session: &mut Session) -> PathBuf { let rollout_path = open_thread_persistence(session).await; session .ensure_rollout_materialized(PersistContext::Standard) @@ -4847,6 +4861,17 @@ pub(super) async fn attach_thread_persistence(session: &mut Session) -> PathBuf rollout_path } +pub(crate) async fn read_review_history( + session: &Session, + path: &std::path::Path, +) -> InitialHistory { + session.drain_code_mode_messages().await; + session.flush_rollout().await.expect("flush review writes"); + RolloutRecorder::get_rollout_history(path) + .await + .expect("read review history") +} + fn text_block(s: &str) -> serde_json::Value { json!({ "type": "text", diff --git a/codex-rs/core/tests/suite/auto_review.rs b/codex-rs/core/tests/suite/auto_review.rs index 0d541991f3..0bc0c72e44 100644 --- a/codex-rs/core/tests/suite/auto_review.rs +++ b/codex-rs/core/tests/suite/auto_review.rs @@ -11,6 +11,7 @@ use codex_extension_api::ApprovalReviewContributor; use codex_extension_api::ExtensionFuture; use codex_extension_api::ExtensionRegistryBuilder; use codex_features::Feature; +use codex_history::RolloutItem; use codex_login::CodexAuth; use codex_models_manager::manager::RefreshStrategy; use codex_protocol::config_types::ApprovalsReviewer; @@ -37,6 +38,7 @@ use core_test_support::TempDirExt; use core_test_support::responses::ev_apply_patch_custom_tool_call; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; +use core_test_support::responses::ev_completed_with_tokens; use core_test_support::responses::ev_function_call; use core_test_support::responses::ev_response_created; use core_test_support::responses::mount_sse_sequence; @@ -477,12 +479,12 @@ async fn remote_model_override_uses_catalog_model_for_strict_auto_review() -> Re "request_permissions", &serde_json::to_string(&permissions_args)?, ), - ev_completed("resp-parent-1"), + ev_completed_with_tokens("resp-parent-1", /*total_tokens*/ 10), ]), sse(vec![ ev_response_created("resp-parent-2"), ev_apply_patch_custom_tool_call(patch_call_id, patch), - ev_completed("resp-parent-2"), + ev_completed_with_tokens("resp-parent-2", /*total_tokens*/ 20), ]), sse(vec![ ev_response_created("resp-guardian"), @@ -496,12 +498,12 @@ async fn remote_model_override_uses_catalog_model_for_strict_auto_review() -> Re }) .to_string(), ), - ev_completed("resp-guardian"), + ev_completed_with_tokens("resp-guardian", /*total_tokens*/ 7), ]), sse(vec![ ev_response_created("resp-parent-3"), ev_assistant_message("msg-parent", "done"), - ev_completed("resp-parent-3"), + ev_completed_with_tokens("resp-parent-3", /*total_tokens*/ 30), ]), ], ) @@ -625,6 +627,40 @@ async fn remote_model_override_uses_catalog_model_for_strict_auto_review() -> Re Some(review_model) ); assert_eq!(guardian_request.path(), "/v1/responses"); + codex.flush_rollout().await?; + let history = codex.load_history(/*include_archived*/ false).await?; + let mut agent_totals = Vec::new(); + let mut reviews = Vec::new(); + for item in history.items { + match item { + RolloutItem::TokenUsageRecord(record) => { + agent_totals.push(record.thread_token_usage.total_tokens); + } + RolloutItem::EventMsg { + event: EventMsg::RawResponseCompleted(event), + .. + } => reviews.push(event), + _ => {} + } + } + assert_eq!(agent_totals, [10, 30, 60]); + assert_eq!(reviews.len(), 1); + let attribution = reviews[0].guardian.as_ref().expect("review attribution"); + assert_eq!(attribution.model, review_model); + assert!(!attribution.incomplete_error); + assert_eq!( + guardian_request.body_json()["client_metadata"]["parent_turn_id"], + attribution.parent_turn_id + ); + assert_eq!(reviews[0].response_id, "resp-guardian"); + assert_eq!( + reviews[0].token_usage, + Some(codex_protocol::protocol::TokenUsage { + input_tokens: 7, + total_tokens: 7, + ..Default::default() + }) + ); timeout(Duration::from_secs(10), codex.shutdown_and_wait()).await??; diff --git a/codex-rs/ext/guardian-v2/src/async_scorer/classification.rs b/codex-rs/ext/guardian-v2/src/async_scorer/classification.rs index 7c5c616e4e..6aad41051c 100644 --- a/codex-rs/ext/guardian-v2/src/async_scorer/classification.rs +++ b/codex-rs/ext/guardian-v2/src/async_scorer/classification.rs @@ -149,7 +149,7 @@ impl Classification { score_authorization, } = self; let generation = reservation.generation.clone(); - let active = Arc::clone(&reservation.active); + let active = reservation.active.clone(); let pending_score = PendingScore { progress: Arc::clone(&score_progress), index: tool_call_index, @@ -354,6 +354,7 @@ impl Classification { parent_compaction, reasoning_effort: guardian_config.reasoning_effort.clone(), parent_turn_id: turn_id.clone(), + usage: None, root_turn_id, pending_score: None, turn_id: request_turn_id, @@ -433,7 +434,7 @@ impl Classification { sampled_at: Some(sampled_at.into()), }; let current = score_authorization.is_current(&thread).await; - if !active.load(std::sync::atomic::Ordering::Acquire) + if !*active.borrow() || generation.strong_count() == 0 || matches!(current, Ok(false)) { diff --git a/codex-rs/ext/guardian-v2/src/async_scorer/conversation.rs b/codex-rs/ext/guardian-v2/src/async_scorer/conversation.rs index b68258ec25..59befa87b8 100644 --- a/codex-rs/ext/guardian-v2/src/async_scorer/conversation.rs +++ b/codex-rs/ext/guardian-v2/src/async_scorer/conversation.rs @@ -15,8 +15,6 @@ use std::sync::Arc; use std::sync::Mutex; use std::sync::Weak; -use std::sync::atomic::AtomicBool; -use std::sync::atomic::Ordering; use std::time::SystemTime; use codex_context_fragments::RenderedFragment; @@ -30,6 +28,7 @@ use codex_protocol::models::ResponseItem; use tokio::sync::OwnedSemaphorePermit; use tokio::sync::Semaphore; use tokio::sync::oneshot; +use tokio::sync::watch; use super::authorization::ScoreAuthorization; use super::request::PreparedRequest; @@ -52,7 +51,7 @@ pub(super) struct ConversationBackend { sampler: Arc, capacity: Arc>>, generation: Arc<()>, - active: Arc, + active: watch::Sender, } struct CompletedConversation { @@ -67,7 +66,7 @@ pub(super) struct Reservation { sampler: Arc, _permit: OwnedSemaphorePermit, pub(super) generation: Weak<()>, - pub(super) active: Arc, + pub(super) active: watch::Sender, } pub(super) struct ConversationRequest { @@ -119,22 +118,30 @@ impl ConversationBackend { sampler, capacity: Arc::new(Mutex::new(Arc::new(Semaphore::new(MAX_OUTSTANDING)))), generation: Arc::new(()), - active: Arc::new(AtomicBool::new(/*v*/ true)), + active: watch::Sender::new(/*init*/ true), } } pub(super) fn install(thread: &ExtensionData, backend: Self) { - Self::stop(thread); + Self::retire(thread); thread.insert(Mutex::new(Arc::new(backend))); } - pub(super) fn stop(thread: &ExtensionData) { - if let Some(owner) = thread.remove::>>() { - owner - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .active - .store(/*val*/ false, Ordering::Release); + fn retire(thread: &ExtensionData) -> Option> { + let owner = thread.remove::>>()?; + let active = owner + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .active + .clone(); + active.send_replace(/*value*/ false); + Some(active) + } + + pub(super) async fn stop(thread: &ExtensionData) { + if let Some(active) = Self::retire(thread) { + // Each classifier keeps a receiver through its final usage write. + active.closed().await; } } @@ -191,12 +198,12 @@ impl ConversationBackend { sampler: Arc::clone(&self.sampler), capacity: Arc::clone(&self.capacity), generation: Arc::new(()), - active: Arc::clone(&self.active), + active: self.active.clone(), } } fn is_active(&self) -> bool { - self.active.load(Ordering::Acquire) + *self.active.borrow() } pub(super) fn reserve( @@ -219,7 +226,7 @@ impl ConversationBackend { sampler: Arc::clone(&self.sampler), _permit: permit, generation: Arc::downgrade(&self.generation), - active: Arc::clone(&self.active), + active: self.active.clone(), }) })(); (index, reservation) @@ -233,7 +240,7 @@ impl Reservation { thread: &CodexThread, pending: &PendingScore, ) -> Result<(), LunaSamplerError> { - let active = || self.active.load(Ordering::Acquire) && self.generation.strong_count() > 0; + let active = || *self.active.borrow() && self.generation.strong_count() > 0; if !active() { return Err(LunaSamplerError::Superseded); } @@ -339,6 +346,7 @@ impl Reservation { impl PreparedConversation { /// Publishes the first score, then drains and commits only valid completed history. pub(super) async fn run(mut self) { + let mut active = self.reservation.active.subscribe(); // A caller can retain prepared input while authorization or admission expires. let authorization = self .reservation @@ -369,18 +377,25 @@ impl PreparedConversation { } let cursor = self.request.cursor; let pending_truncations = std::mem::take(&mut self.request.truncations); + self.sampling.usage = Some(Arc::new(super::sampler::ClassifierUsage { + thread: Arc::clone(&self.thread), + parent_turn_id: self.sampling.parent_turn_id.clone(), + _active: active.clone(), + })); let sample = ConversationSample { input: self.request, sampling: self.sampling, }; let history = tokio::select! { biased; + _ = active.changed() => None, () = self.pending_score.expired() => None, history = self.reservation.sampler.sample_retained(sample, self.ready) => history, }; + drop(active); if let Some(history) = history && let Ok(true) = self.key.authorization.is_current(&self.thread).await - && self.reservation.active.load(Ordering::Acquire) + && *self.reservation.active.borrow() && self.reservation.generation.strong_count() > 0 { let mut truncations = super::truncation::ClassificationTruncations::default(); diff --git a/codex-rs/ext/guardian-v2/src/async_scorer/extension.rs b/codex-rs/ext/guardian-v2/src/async_scorer/extension.rs index eed0ba409b..1f86b3c652 100644 --- a/codex-rs/ext/guardian-v2/src/async_scorer/extension.rs +++ b/codex-rs/ext/guardian-v2/src/async_scorer/extension.rs @@ -153,7 +153,7 @@ impl ThreadLifecycleContributor for GuardianV2Extension { } fn on_thread_stop<'a>(&'a self, input: ThreadStopInput<'a>) -> ExtensionFuture<'a, ()> { Box::pin(async move { - ConversationBackend::stop(input.thread_store); + ConversationBackend::stop(input.thread_store).await; }) } } diff --git a/codex-rs/ext/guardian-v2/src/async_scorer/extension_tests.rs b/codex-rs/ext/guardian-v2/src/async_scorer/extension_tests.rs index 1ea2d66351..5cc5d87409 100644 --- a/codex-rs/ext/guardian-v2/src/async_scorer/extension_tests.rs +++ b/codex-rs/ext/guardian-v2/src/async_scorer/extension_tests.rs @@ -2667,17 +2667,6 @@ async fn contributor_samples_tool_calls_with_the_existing_luna_pool() -> Result< } ); assert!(score.sampled_at.is_some()); - test.codex.ensure_rollout_materialized().await; - assert!( - !test - .codex - .load_history(/*include_archived*/ false) - .await? - .items - .into_iter() - .any(|item| matches!(item, RolloutItem::SecurityRiskScore(_))), - "risk scores should not be persisted unless explicitly enabled" - ); assert_eq!( cached_approval( ®istry, @@ -2787,9 +2776,53 @@ async fn contributor_samples_tool_calls_with_the_existing_luna_pool() -> Result< None ); + ConversationBackend::stop(thread_store).await; + test.codex.ensure_rollout_materialized().await; + let history = test.codex.load_history(/*include_archived*/ false).await?; + assert!( + !history + .items + .iter() + .any(|item| matches!(item, RolloutItem::SecurityRiskScore(_))), + "risk scores should not be persisted unless explicitly enabled" + ); + let review = classifier_response(history.items, "response-1"); + let attribution = review.guardian.expect("classifier attribution"); + assert_eq!(attribution.model, "gpt-5.6-luna"); + assert_eq!(attribution.parent_turn_id, "turn-1"); + assert_eq!( + review.token_usage, + Some(codex_protocol::protocol::TokenUsage { + input_tokens: 120, + cached_input_tokens: 40, + cache_write_input_tokens: 20, + output_tokens: 30, + reasoning_output_tokens: 10, + total_tokens: 150, + ..Default::default() + }) + ); Ok(()) } +fn classifier_response( + items: Vec, + response_id: &str, +) -> codex_protocol::protocol::RawResponseCompletedEvent { + let mut responses = items.into_iter().filter_map(|item| match item { + RolloutItem::EventMsg { + event: EventMsg::RawResponseCompleted(event), + .. + } if event.response_id == response_id => Some(event), + _ => None, + }); + let response = responses + .next() + .expect("classifier usage on the requesting thread"); + assert!(responses.next().is_none(), "duplicate classifier usage"); + response +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn contributor_persists_nested_code_mode_action_with_score() -> Result<()> { skip_if_no_network!(Ok(())); diff --git a/codex-rs/ext/guardian-v2/src/async_scorer/pending_score_tests.rs b/codex-rs/ext/guardian-v2/src/async_scorer/pending_score_tests.rs index 84a65a91db..b16c999417 100644 --- a/codex-rs/ext/guardian-v2/src/async_scorer/pending_score_tests.rs +++ b/codex-rs/ext/guardian-v2/src/async_scorer/pending_score_tests.rs @@ -7,6 +7,31 @@ use crate::async_scorer::sampler::tests::RecordingMetrics; use crate::async_scorer::sampler::tests::sampler_config; use pretty_assertions::assert_eq; +async fn install_sampler( + store: &ExtensionData, + server: &responses::WebSocketTestServer, +) -> Result> { + let metrics = Arc::new(RecordingMetrics::default()); + let mut config = sampler_config( + proxy_websocket_servers_with_http( + &[server], + ProxyPrewarmLimit::AllConnections, + /*http_url*/ None, + ) + .await?, + ); + config.metrics = Some(metrics.clone()); + store.insert(LunaSampler::new(config)); + let sampler = store.get::().unwrap(); + sampler.prewarm().await; + store.remove::(); + ConversationBackend::install( + store, + ConversationBackend::new(sampler, /*revision*/ 0, /*metrics*/ None), + ); + Ok(metrics) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn stale_classifications_close_the_transport_without_invalidating_scores() -> Result<()> { skip_if_no_network!(Ok(())); @@ -38,28 +63,7 @@ async fn stale_classifications_close_the_transport_without_invalidating_scores() }]) .await; let store = fixture.test.codex.thread_extension_data(); - let metrics = Arc::new(RecordingMetrics::default()); - let mut config = sampler_config( - proxy_websocket_servers_with_http( - &[&server], - ProxyPrewarmLimit::AllConnections, - /*http_url*/ None, - ) - .await?, - ); - config.metrics = Some(metrics.clone()); - store.insert(LunaSampler::new(config)); - let sampler = store.get::().unwrap(); - sampler.prewarm().await; - store.remove::(); - ConversationBackend::install( - store, - ConversationBackend::new( - Arc::clone(&sampler), - /*revision*/ 0, - /*metrics*/ None, - ), - ); + let metrics = install_sampler(store, &server).await?; let progress = ConversationBackend::for_turn(store, store) .map(|cache| Arc::clone(&cache.progress)) .unwrap(); @@ -121,3 +125,58 @@ async fn stale_classifications_close_the_transport_without_invalidating_scores() } Ok(()) } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn thread_stop_waits_for_interrupted_classifier_usage() -> Result<()> { + skip_if_no_network!(Ok(())); + // The transport treats an acknowledged interruption as a normal stop. + for (reason, incomplete_error) in [("interrupted", false), ("max_output_tokens", true)] { + let fixture = GuardianFailureFixture::new().await?; + let mut incomplete = + responses::ev_completed_with_tokens("interrupted", /*total_tokens*/ 42); + incomplete["type"] = json!("response.incomplete"); + incomplete["response"]["incomplete_details"] = json!({"reason": reason}); + let server = responses::start_websocket_server(vec![vec![ + vec![responses::ev_response_created("interrupted")], + vec![ + json!({"type": "response.interrupt.accepted", "response_id": "interrupted"}), + incomplete, + ], + ]]) + .await; + let store = fixture.test.codex.thread_extension_data(); + install_sampler(store, &server).await?; + fixture.score_tool(ToolName::plain("read_file")).await; + tokio::time::timeout( + ASYNC_TEST_TIMEOUT, + server.wait_for_request(/*connection_index*/ 0, /*request_index*/ 0), + ) + .await?; + tokio::time::timeout( + ASYNC_TEST_TIMEOUT, + fixture.registry.thread_lifecycle_contributors()[0].on_thread_stop( + codex_extension_api::ThreadStopInput { + session_store: &fixture.session_store, + thread_store: store, + }, + ), + ) + .await?; + fixture.test.codex.ensure_rollout_materialized().await; + let history = fixture + .test + .codex + .load_history(/*include_archived*/ false) + .await?; + let response = classifier_response(history.items, "interrupted"); + let attribution = response.guardian.expect("classifier attribution"); + assert_eq!(attribution.incomplete_error, incomplete_error); + assert_eq!( + response.token_usage.expect("reported usage").total_tokens, + 42 + ); + fixture.test.codex.shutdown_and_wait().await?; + server.shutdown().await; + } + Ok(()) +} diff --git a/codex-rs/ext/guardian-v2/src/async_scorer/sampler.rs b/codex-rs/ext/guardian-v2/src/async_scorer/sampler.rs index 97c448f7bf..00f94e4af1 100644 --- a/codex-rs/ext/guardian-v2/src/async_scorer/sampler.rs +++ b/codex-rs/ext/guardian-v2/src/async_scorer/sampler.rs @@ -80,6 +80,13 @@ pub struct LunaSamplerConfig { pub metrics: Option>, } +/// Shutdown must wait for a cancelled stream and any detached usage write. +pub(super) struct ClassifierUsage { + pub(super) thread: Arc, + pub(super) parent_turn_id: String, + pub(super) _active: tokio::sync::watch::Receiver, +} + /// One tool-less Luna classification request. pub struct LunaSamplingRequest { /// Generator selected by the owning session for response items. @@ -101,6 +108,7 @@ pub struct LunaSamplingRequest { pub parent_turn_id: String, /// Trusted causal root of the owning turn, absent when unknown or ambiguous. pub root_turn_id: Option, + pub(super) usage: Option>, /// Sampling expiry remains active until its response finishes draining. pub(super) pending_score: Option, /// Responses turn ID for this classifier execution. @@ -310,6 +318,7 @@ impl LunaSampler { parent_response_id: request.parent_response_id.clone(), parent_turn_id: request.parent_turn_id.clone(), root_turn_id: request.root_turn_id.clone(), + usage: request.usage.clone(), } } diff --git a/codex-rs/ext/guardian-v2/src/async_scorer/sampler/connection_pool_cancellation_tests.rs b/codex-rs/ext/guardian-v2/src/async_scorer/sampler/connection_pool_cancellation_tests.rs index a69de4927f..f4bd1be53f 100644 --- a/codex-rs/ext/guardian-v2/src/async_scorer/sampler/connection_pool_cancellation_tests.rs +++ b/codex-rs/ext/guardian-v2/src/async_scorer/sampler/connection_pool_cancellation_tests.rs @@ -158,7 +158,9 @@ async fn cancellation_preserves_unused_sockets_and_backpressured_completion() -> .request; // Cancel before this current-thread runtime can dispatch, then reuse its only socket. let stream = lease.stream_request(&request).await?; - drop(PendingResponse::new(stream, lease, /*metrics*/ None)); + drop(PendingResponse::new( + stream, lease, /*metrics*/ None, /*usage*/ None, + )); let cleanup = pool .classifications .acquire_many(u32::try_from(MAX_CONCURRENT_REQUESTS)?); diff --git a/codex-rs/ext/guardian-v2/src/async_scorer/sampler/execution.rs b/codex-rs/ext/guardian-v2/src/async_scorer/sampler/execution.rs index dd3da8673c..d8160d04d5 100644 --- a/codex-rs/ext/guardian-v2/src/async_scorer/sampler/execution.rs +++ b/codex-rs/ext/guardian-v2/src/async_scorer/sampler/execution.rs @@ -5,6 +5,7 @@ //! Dropped responses interrupt and drain before their transport can return to the pool. use super::CLASSIFICATION_TOKEN_USAGE_METRIC; +use super::ClassifierUsage; use super::ConnectionPool; use super::LunaSamplerConfig; use super::LunaSamplerError; @@ -47,6 +48,7 @@ pub(super) struct SamplingExecution { pub(super) parent_response_id: Option, pub(super) parent_turn_id: String, pub(super) root_turn_id: Option, + pub(super) usage: Option>, } pub(super) struct RetainedCompletion { @@ -322,7 +324,12 @@ impl SamplingExecution { } }; - let mut response = PendingResponse::new(stream, lease, self.config.metrics.clone()); + let mut response = PendingResponse::new( + stream, + lease, + self.config.metrics.clone(), + self.usage.clone(), + ); let mut output = String::new(); while let Some(event) = tokio::select! { biased; @@ -384,7 +391,7 @@ impl SamplingExecution { usize::try_from(usage.tokens_in_context_window()).ok() }) .filter(|tokens| *tokens > 0); - response.reuse(token_usage.as_ref()).await; + response.reuse().await; if !output.is_empty() { return Ok(output); } diff --git a/codex-rs/ext/guardian-v2/src/async_scorer/sampler/response.rs b/codex-rs/ext/guardian-v2/src/async_scorer/sampler/response.rs index 065cea23ea..65c693e6bb 100644 --- a/codex-rs/ext/guardian-v2/src/async_scorer/sampler/response.rs +++ b/codex-rs/ext/guardian-v2/src/async_scorer/sampler/response.rs @@ -7,12 +7,12 @@ use std::sync::Arc; use std::time::Duration; +use super::ClassifierUsage; use codex_api::ApiError; use codex_api::ResponseEvent; use codex_api::ResponseInterrupt; use codex_api::ResponseStream; use codex_extension_api::ExtensionMetrics; -use codex_protocol::protocol::TokenUsage; use super::connection_pool::ConnectionLease; use super::execution::record_token_usage; @@ -20,6 +20,7 @@ use super::execution::record_token_usage; pub(super) struct PendingResponse { response: Option<(ResponseStream, ConnectionLease)>, metrics: Option>, + usage: Option>, } impl PendingResponse { @@ -27,20 +28,23 @@ impl PendingResponse { stream: ResponseStream, lease: ConnectionLease, metrics: Option>, + usage: Option>, ) -> Self { Self { response: Some((stream, lease)), metrics, + usage, } } pub(super) async fn next(&mut self) -> Option> { - self.response.as_mut()?.0.rx_event.recv().await + let event = self.response.as_mut()?.0.rx_event.recv().await?; + record_terminal_usage(self.metrics.as_deref(), self.usage.as_ref(), &event); + Some(event) } - pub(super) async fn reuse(mut self, token_usage: Option<&TokenUsage>) { + pub(super) async fn reuse(mut self) { if let Some((_, lease)) = self.response.take() { - record_token_usage(self.metrics.as_deref(), token_usage); lease.reuse().await; } } @@ -51,23 +55,25 @@ impl Drop for PendingResponse { let Some((mut stream, lease)) = self.response.take() else { return; }; - let Some(interrupt) = stream.interrupt.take() else { - // HTTP cancellation has no response-interrupt handshake. - return; - }; let Ok(runtime) = tokio::runtime::Handle::try_current() else { return; }; // Signal before cleanup is scheduled so the transport can skip undispatched work. // Completion may already be queued even if the interrupt receiver has closed. - let _ = interrupt.send(ResponseInterrupt::Cancel { - deadline: tokio::time::Instant::now() + Duration::from_secs(/*secs*/ 1), - }); - let metrics = self.metrics.clone(); + if let Some(interrupt) = stream.interrupt.take() { + let _ = interrupt.send(ResponseInterrupt::Cancel { + deadline: tokio::time::Instant::now() + Duration::from_secs(/*secs*/ 1), + }); + } else { + // HTTP has no interrupt handshake. Drain only events already buffered. + stream.rx_event.close(); + } + let metrics = self.metrics.take(); + let usage = self.usage.take(); runtime.spawn(async move { - while let Some(Ok(event)) = stream.rx_event.recv().await { - if let ResponseEvent::Completed { token_usage, .. } = event { - record_token_usage(metrics.as_deref(), token_usage.as_ref()); + while let Some(event) = stream.rx_event.recv().await { + record_terminal_usage(metrics.as_deref(), usage.as_ref(), &event); + if matches!(event, Ok(ResponseEvent::Completed { .. }) | Err(_)) { break; } } @@ -77,3 +83,43 @@ impl Drop for PendingResponse { }); } } + +fn record_terminal_usage( + metrics: Option<&dyn ExtensionMetrics>, + recorder: Option<&Arc>, + event: &Result, +) { + let (response_id, usage) = match event { + Ok(ResponseEvent::Completed { + response_id, + token_usage, + .. + }) => { + record_token_usage(metrics, token_usage.as_ref()); + (Some(response_id), token_usage.as_ref()) + } + Err(ApiError::ResponseIncomplete(incomplete)) => ( + incomplete.response_id.as_ref(), + incomplete.token_usage.as_ref(), + ), + _ => return, + }; + if let (Some(recorder), Some(response_id), Some(usage)) = (recorder, response_id, usage) { + // Keep storage off the decision path. The classifier's receiver keeps + // thread shutdown waiting until this write finishes. + let classifier = Arc::clone(recorder); + let response_id = response_id.clone(); + let usage = usage.clone(); + let attribution = codex_protocol::protocol::GuardianResponseAttribution { + parent_turn_id: classifier.parent_turn_id.clone(), + model: super::MODEL.to_owned(), + incomplete_error: event.is_err(), + }; + tokio::spawn(async move { + classifier + .thread + .record_guardian_usage(attribution, response_id, usage) + .await; + }); + } +} diff --git a/codex-rs/ext/guardian-v2/src/async_scorer/sampler_tests.rs b/codex-rs/ext/guardian-v2/src/async_scorer/sampler_tests.rs index 07afc58e15..49f52b19f8 100644 --- a/codex-rs/ext/guardian-v2/src/async_scorer/sampler_tests.rs +++ b/codex-rs/ext/guardian-v2/src/async_scorer/sampler_tests.rs @@ -322,6 +322,7 @@ pub(in crate::async_scorer) fn sample_request(parent_turn_id: &str) -> LunaSampl reasoning_effort: ReasoningEffort::None, parent_turn_id: parent_turn_id.to_owned(), root_turn_id: None, + usage: None, pending_score: None, turn_id: Uuid::now_v7(), } @@ -737,6 +738,7 @@ async fn preconnected_sampler_reuses_authenticated_websocket_for_classifications reasoning_effort: ReasoningEffort::None, parent_turn_id: "turn-1".to_owned(), root_turn_id: Some("turn-1".to_owned()), + usage: None, pending_score: None, turn_id: Uuid::now_v7(), }) @@ -772,6 +774,7 @@ async fn preconnected_sampler_reuses_authenticated_websocket_for_classifications reasoning_effort: ReasoningEffort::Medium, parent_turn_id: "turn-2".to_owned(), root_turn_id: Some("root-2".to_owned()), + usage: None, pending_score: None, turn_id: Uuid::now_v7(), }) diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 9be686094f..cd3bf3fc3b 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -2201,12 +2201,26 @@ pub enum PrivateSessionEventPayload { TurnAborted(TurnAbortedEvent), } +/// Identifies the owner and model of a Guardian response in its parent's rollout. +#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema, PartialEq, Eq)] +pub struct GuardianResponseAttribution { + pub parent_turn_id: String, + pub model: String, + /// Whether Core received an incomplete-response error with usage. + #[serde(default)] + pub incomplete_error: bool, +} + /// Exact usage and metadata reported by one upstream Responses API completion. /// /// Unlike TokenCountEvent, this is not accumulated, estimated, or replayed. #[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)] pub struct RawResponseCompletedEvent { pub response_id: String, + /// Rollout-only Guardian usage can come from completed or incomplete responses. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub guardian: Option, pub token_usage: Option, pub usage_metadata: Option, } diff --git a/codex-rs/rollout/src/policy.rs b/codex-rs/rollout/src/policy.rs index 3dc9b3adec..fd0d1d2079 100644 --- a/codex-rs/rollout/src/policy.rs +++ b/codex-rs/rollout/src/policy.rs @@ -135,6 +135,9 @@ fn persisted_event_msg( history_mode: ThreadHistoryMode, ) -> Option> { match ev { + EventMsg::RawResponseCompleted(event) => { + event.guardian.is_some().then_some(Cow::Borrowed(ev)) + } EventMsg::ItemCompleted(event) => persisted_item_completed_event(ev, event, history_mode), EventMsg::TokenCount(_) | EventMsg::ThreadGoalUpdated(_) @@ -191,7 +194,6 @@ fn persisted_event_msg( | EventMsg::AgentReasoningSectionBreak(_) | EventMsg::PrivateSessionEvent(_) | EventMsg::RawResponseItem(_) - | EventMsg::RawResponseCompleted(_) | EventMsg::SessionConfigured(_) | EventMsg::EnvironmentConnected(_) | EventMsg::EnvironmentDisconnected(_)