Exclude per-item usage attribution by default (#63219)

## What changed

Add `usage.attribution` to the `x-codex-exclude` header for Responses HTTP
requests and WebSocket handshakes by default. Threads started with
`experimentalRawEvents` keep receiving per-item attribution in raw responses.
Subagents inherit the policy, and the app server restores it when a thread
resumes with an existing raw-event subscription.

## Testing

Cover the default exclusion, raw completion events with upstream usage,
subagent inheritance, and resuming a closed subagent after both its runtime
and its parent's runtime have unloaded.

GitOrigin-RevId: 0dad92f97606300907f1294f09dd7845d1e6476f
This commit is contained in:
Charlie Marsh
2026-11-23 01:06:41 +00:00
committed by copyberry
parent 9e3479e00a
commit ae6c0c8ac1
13 changed files with 237 additions and 19 deletions
+3
View File
@@ -32,6 +32,7 @@ use crate::thread_state::ThreadListenerCommand;
use crate::thread_state::ThreadStateManager;
pub(crate) struct ThreadExtensionDependencies {
pub(crate) thread_state_manager: ThreadStateManager,
pub(crate) sample_responses: Arc<crate::thread_sample::SampleResponseRegistry>,
pub(crate) event_sink: Arc<dyn ExtensionEventSink>,
pub(crate) auth_manager: Arc<AuthManager>,
@@ -54,6 +55,7 @@ pub(crate) fn thread_extensions(
dependencies: ThreadExtensionDependencies,
) -> Arc<ExtensionRegistry<Config>> {
let ThreadExtensionDependencies {
thread_state_manager,
sample_responses,
event_sink,
auth_manager,
@@ -70,6 +72,7 @@ pub(crate) fn thread_extensions(
turn_start_admission,
} = dependencies;
let mut builder = ExtensionRegistryBuilder::<Config>::with_event_sink(Arc::clone(&event_sink));
builder.thread_lifecycle_contributor(Arc::new(thread_state_manager));
if config
.features
.enabled(codex_features::Feature::MultiEnvCopyFile)
+1
View File
@@ -548,6 +548,7 @@ enabled = false
thread_extensions(
&good_config,
ThreadExtensionDependencies {
thread_state_manager: Default::default(),
sample_responses: Arc::new(
crate::thread_sample::SampleResponseRegistry::default(),
),
@@ -393,6 +393,7 @@ impl MessageProcessor {
thread_extensions(
config.as_ref(),
ThreadExtensionDependencies {
thread_state_manager: thread_state_manager.clone(),
sample_responses: Arc::clone(&sample_responses),
event_sink: Arc::clone(&extension_event_sink),
auth_manager: auth_manager.clone(),
@@ -206,11 +206,8 @@ pub(super) async fn attach_created_thread_listener(
!connection_ids.is_empty()
&& listener_task_context
.thread_state_manager
.thread_state(parent_thread_id)
.raw_events_enabled(parent_thread_id)
.await
.lock()
.await
.experimental_raw_events
} else {
false
};
@@ -1646,6 +1646,9 @@ impl ThreadRequestProcessor {
.then_some(ThreadHistoryMode::Paginated)
});
let mut thread_extension_init = ExtensionDataInit::new();
if experimental_raw_events {
thread_extension_init.insert(codex_core::UsageAttributionPolicy::Retain);
}
if !selected_capability_roots.is_empty() {
thread_extension_init.insert(selected_capability_roots);
}
+35
View File
@@ -13,6 +13,11 @@ use codex_app_server_protocol::TurnError;
use codex_app_server_protocol::TurnItemsView;
use codex_core::CodexThread;
use codex_core::ThreadConfigSnapshot;
use codex_core::UsageAttributionPolicy;
use codex_core::config::Config;
use codex_extension_api::ExtensionFuture;
use codex_extension_api::ThreadLifecycleContributor;
use codex_extension_api::ThreadStartInput;
use codex_file_watcher::WatchRegistration;
use codex_protocol::ThreadId;
#[cfg(test)]
@@ -499,6 +504,25 @@ impl ListenerStateCandidate {
}
}
impl ThreadLifecycleContributor<Config> for ThreadStateManager {
/// Restore attribution for raw-event subscriptions that outlive a Core runtime.
fn on_thread_start<'a>(
&'a self,
input: ThreadStartInput<'a, Config>,
) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
let thread_id = ThreadId::from_string(input.thread_store.level_id()).ok();
let parent_id = input.session_source.parent_thread_id();
for id in [thread_id, parent_id].into_iter().flatten() {
if self.raw_events_enabled(id).await {
input.thread_store.insert(UsageAttributionPolicy::Retain);
break;
}
}
})
}
}
impl ThreadStateManager {
/// Coordinates goal edits with cold/path-based resume for just this thread.
pub(crate) async fn lock_goal_resume(
@@ -589,6 +613,17 @@ impl ThreadStateManager {
state.threads.entry(thread_id).or_default().state.clone()
}
pub(crate) async fn raw_events_enabled(&self, thread_id: ThreadId) -> bool {
let thread_state = {
let state = self.state.lock().await;
let Some(entry) = state.threads.get(&thread_id) else {
return false;
};
Arc::clone(&entry.state)
};
thread_state.lock().await.experimental_raw_events
}
pub(crate) async fn created_listener_state(
&self,
thread_id: ThreadId,
@@ -3,18 +3,24 @@ use app_test_support::MockResponsesConfig;
use app_test_support::TestAppServer;
use app_test_support::create_fake_parented_rollout_with_source;
use app_test_support::create_fake_rollout;
use codex_app_server_protocol::RawResponseCompletedNotification;
use codex_app_server_protocol::ReviewDelivery;
use codex_app_server_protocol::ReviewStartParams;
use codex_app_server_protocol::ReviewStartResponse;
use codex_app_server_protocol::ReviewTarget;
use codex_app_server_protocol::SessionSource as ApiSessionSource;
use codex_app_server_protocol::ThreadClosedNotification;
use codex_app_server_protocol::ThreadForkParams;
use codex_app_server_protocol::ThreadForkResponse;
use codex_app_server_protocol::ThreadLoadedListResponse;
use codex_app_server_protocol::ThreadResumeParams;
use codex_app_server_protocol::ThreadResumeResponse;
use codex_app_server_protocol::ThreadSource;
use codex_app_server_protocol::ThreadStartParams;
use codex_app_server_protocol::ThreadStartResponse;
use codex_app_server_protocol::ThreadUnsubscribeParams;
use codex_app_server_protocol::ThreadUnsubscribeResponse;
use codex_app_server_protocol::TurnCompletedNotification;
use codex_app_server_protocol::TurnStartParams;
use codex_app_server_protocol::TurnStartResponse;
use codex_app_server_protocol::TurnSteerParams;
@@ -110,6 +116,10 @@ async fn turn_start_forwards_client_metadata_to_responses_request_v2() -> Result
.await??;
let request = response_mock.single_request();
assert_eq!(
request.header("x-codex-exclude").as_deref(),
Some("tools,usage.attribution")
);
let metadata = request
.header("x-codex-turn-metadata")
.as_deref()
@@ -624,13 +634,127 @@ async fn turn_steer_updates_client_metadata_on_follow_up_responses_request_v2(
Ok(())
}
#[test_case::test_case(false, "none"; "legacy")]
#[test_case::test_case(true, "none"; "v2 fresh")]
#[test_case::test_case(true, "all"; "v2 fork")]
#[tokio::test]
async fn resumed_closed_subagent_retains_raw_usage_attribution() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = responses::start_mock_server().await;
let codex_home = TempDir::new()?;
MockResponsesConfig::new(&server.uri())
.with_model("gpt-5.6-luna")
.with_root_config("thread_unload_delay_secs = 0")
.with_extra_config("[features.multi_agent_v2]\nenabled = false")
.write(codex_home.path())?;
let mut app = TestAppServer::builder()
.with_codex_home(codex_home.path())
.build_initialized()
.await?;
let parent = app
.start_thread(ThreadStartParams {
experimental_raw_events: true,
..Default::default()
})
.await?
.thread;
let turn = |thread_id: &str, prompt: &str| TurnStartParams {
thread_id: thread_id.to_owned(),
input: vec![V2UserInput::Text {
text: prompt.to_owned(),
text_elements: vec![],
}],
..Default::default()
};
let tool = |name: &str, args: serde_json::Value| {
responses::sse(vec![
responses::ev_function_call_with_namespace(
name,
"multi_agent_v1",
name,
&args.to_string(),
),
responses::ev_completed(name),
])
};
responses::mount_sse_sequence(
&server,
vec![
tool("spawn_agent", json!({"message": "Inspect the example"})),
responses::sse_completed("done-1"),
responses::sse_completed("done-2"),
],
)
.await;
app.start_turn_and_wait_for_completion(turn(&parent.id, "Spawn a child"))
.await?;
let child_turn: TurnCompletedNotification = timeout(
DEFAULT_READ_TIMEOUT,
app.read_notification("turn/completed"),
)
.await??;
let child_id = child_turn.thread_id;
responses::mount_sse_sequence(
&server,
vec![
tool("close_agent", json!({"target": child_id})),
responses::sse_completed("closed"),
],
)
.await;
app.start_turn_and_wait_for_completion(turn(&parent.id, "Close the child"))
.await?;
// Resume from the child's subscription after both original runtimes are gone.
let id = app
.send_thread_unsubscribe_request(ThreadUnsubscribeParams {
thread_id: parent.id.clone(),
})
.await?;
let _: ThreadUnsubscribeResponse = app.read_response(id).await?;
let closed: ThreadClosedNotification =
timeout(DEFAULT_READ_TIMEOUT, app.read_notification("thread/closed")).await??;
assert_eq!(closed.thread_id, parent.id);
let id = app
.send_thread_loaded_list_request(Default::default())
.await?;
let loaded: ThreadLoadedListResponse = app.read_response(id).await?;
assert!(loaded.data.is_empty());
let id = app
.send_thread_resume_request(ThreadResumeParams {
thread_id: child_id.clone(),
..Default::default()
})
.await?;
let _: ThreadResumeResponse = app.read_response(id).await?;
let request = responses::mount_sse_once(&server, responses::sse_completed("resumed")).await;
app.clear_message_buffer();
app.start_turn_and_wait_for_completion(turn(&child_id, "Continue"))
.await?;
assert_eq!(
request
.single_request()
.header("x-codex-exclude")
.as_deref(),
Some("tools")
);
let raw: RawResponseCompletedNotification = timeout(
DEFAULT_READ_TIMEOUT,
app.read_notification("rawResponse/completed"),
)
.await??;
assert_eq!(raw.response_id, "resumed");
Ok(())
}
#[test_case::test_case(false, "none", false; "legacy")]
#[test_case::test_case(true, "none", false; "v2 fresh")]
#[test_case::test_case(true, "all", false; "v2 fork")]
#[test_case::test_case(true, "none", true; "v2 fresh with raw events")]
#[tokio::test]
async fn subagents_inherit_spawn_metadata_without_live_parent_updates(
multi_agent_v2: bool,
fork_turns: &str,
experimental_raw_events: bool,
) -> Result<()> {
skip_if_no_network!(Ok(()));
@@ -703,7 +827,10 @@ async fn subagents_inherit_spawn_metadata_without_live_parent_updates(
.await?;
let thread_req = app_server
.send_thread_start_request_with_auto_env(ThreadStartParams::default())
.send_thread_start_request_with_auto_env(ThreadStartParams {
experimental_raw_events,
..Default::default()
})
.await?;
let ThreadStartResponse { thread, .. } =
timeout(DEFAULT_READ_TIMEOUT, app_server.read_response(thread_req)).await??;
@@ -770,6 +897,17 @@ async fn subagents_inherit_spawn_metadata_without_live_parent_updates(
)
.await?;
let expected_exclusions = if experimental_raw_events {
"tools"
} else {
"tools,usage.attribution"
};
for handshake in server.handshakes() {
assert_eq!(
handshake.header("x-codex-exclude").as_deref(),
Some(expected_exclusions)
);
}
for request in [&child_first, &grandchild] {
let body = request.body_json();
let tools = body["input"]
@@ -1324,7 +1324,8 @@ async fn turn_start_emits_raw_response_completed_with_upstream_usage(
"input_tokens_details": { "cached_tokens": 11 },
"output_tokens": 7,
"output_tokens_details": { "reasoning_tokens": 3 },
"total_tokens": 37
"total_tokens": 37,
"attribution": {"items": {"msg_input": {"input_tokens": 30, "cached_tokens": 11}}}
}
}
});
@@ -1412,7 +1413,13 @@ async fn turn_start_emits_raw_response_completed_with_upstream_usage(
}
);
response_mock.single_request();
assert_eq!(
response_mock
.single_request()
.header("x-codex-exclude")
.as_deref(),
Some("tools")
);
Ok(())
}
+18 -4
View File
@@ -41,6 +41,7 @@ use response_delivery::ResponseDelivery;
use crate::CodexResponsesHeaders;
use crate::PromptCacheKey;
use crate::UsageAttributionPolicy;
use crate::tools::ExecutedToolCalls;
use async_channel::Sender;
use codex_api::AgentIdentityTelemetry;
@@ -354,6 +355,7 @@ impl RequestRouteTelemetry {
/// call site.
#[derive(Debug, Clone)]
pub struct ModelClient {
usage_attribution_policy: UsageAttributionPolicy,
state: Arc<ModelClientState>,
agent_identity_policy: AgentIdentityAuthPolicy,
prompt_cache_key_policy: PromptCacheKey,
@@ -708,6 +710,7 @@ impl ModelClient {
prompt_cache_key_policy: PromptCacheKey::default(),
session_id_override: None,
codex_responses_headers: None,
usage_attribution_policy: UsageAttributionPolicy::default(),
event_sender: None,
http_client_factory,
restored_history: false,
@@ -749,7 +752,7 @@ impl ModelClient {
prompt_cache_key: PromptCacheKey,
session_id_override: Option<String>,
event_sender: Sender<ProtocolEvent>,
codex_responses_headers: Option<Arc<CodexResponsesHeaders>>,
thread_extension_data: &codex_extension_api::ExtensionData,
api_key_cyber_access_programs: cyber_access_program::ApiKeyCyberAccessPrograms,
required_cyber_access_programs: Option<
Arc<cyber_access_program::RequiredCyberAccessPrograms>,
@@ -758,7 +761,11 @@ impl ModelClient {
self.prompt_cache_key_policy = prompt_cache_key;
self.session_id_override = session_id_override;
self.event_sender = Some(event_sender);
self.codex_responses_headers = codex_responses_headers;
self.codex_responses_headers = thread_extension_data.get::<CodexResponsesHeaders>();
self.usage_attribution_policy = thread_extension_data
.get::<UsageAttributionPolicy>()
.map(|policy| *policy)
.unwrap_or_default();
self.api_key_cyber_access_programs = api_key_cyber_access_programs;
self.required_cyber_access_programs = required_cyber_access_programs;
self
@@ -1690,6 +1697,7 @@ impl ModelClient {
) -> ApiHeaderMap {
let mut headers = build_responses_headers(
self.state.beta_features_header.as_deref(),
self.usage_attribution_policy,
/*turn_state*/ None,
);
add_originator_header(&mut headers, self.state.originator.as_str());
@@ -1766,6 +1774,7 @@ impl<'a> ResponsesHttpExecutor<'a> {
extra_headers: {
let mut headers = build_responses_headers(
self.client.state.beta_features_header.as_deref(),
self.client.usage_attribution_policy,
Some(turn_state),
);
add_originator_header(&mut headers, self.client.state.originator.as_str());
@@ -2947,13 +2956,18 @@ fn is_guardian_reviewer(responses_headers: &ApiHeaderMap) -> bool {
///
/// - `x-codex-beta-features`: comma-separated beta feature keys enabled for the session.
/// - `x-codex-turn-state`: sticky routing token captured earlier in the turn.
/// - `x-codex-exclude` asks the server to omit the echoed tool catalog.
/// - `x-codex-exclude`: response fields the client can omit from the stream.
fn build_responses_headers(
beta_features_header: Option<&str>,
usage_attribution_policy: UsageAttributionPolicy,
turn_state: Option<&Arc<OnceLock<String>>>,
) -> ApiHeaderMap {
let mut headers = ApiHeaderMap::new();
headers.insert("x-codex-exclude", HeaderValue::from_static("tools"));
let exclusions = match usage_attribution_policy {
UsageAttributionPolicy::Exclude => "tools,usage.attribution",
UsageAttributionPolicy::Retain => "tools",
};
headers.insert("x-codex-exclude", HeaderValue::from_static(exclusions));
if let Some(value) = beta_features_header
&& !value.is_empty()
&& let Ok(header_value) = HeaderValue::from_str(value)
+1
View File
@@ -15,6 +15,7 @@ mod realtime_conversation;
mod realtime_history;
mod responses_headers;
pub use responses_headers::CodexResponsesHeaders;
pub use responses_headers::UsageAttributionPolicy;
mod responses_metadata;
mod responses_retry;
pub(crate) mod session;
+11 -2
View File
@@ -1,8 +1,17 @@
//! Header overrides for host-created threads on the Codex Responses endpoint.
//! Headers are scoped to a model and rechecked against current auth on each attempt.
//! Host-supplied header settings for threads on the Codex Responses endpoint.
use http::HeaderMap;
/// Controls delivery of per-item attribution requested by the Codex backend for
/// accounting. Seed in `StartThreadOptions::thread_extension_init` to set the
/// policy for a thread and its subagents.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum UsageAttributionPolicy {
#[default]
Exclude,
Retain,
}
/// Seed in `StartThreadOptions::thread_extension_init` to supply Responses headers.
///
/// Applied only to the selected model on the OpenAI provider with Codex backend
+1 -3
View File
@@ -1869,8 +1869,6 @@ impl Session {
};
let executed_tool_calls =
crate::state::ExecutedToolCalls::new(&config.features, &initial_history);
let codex_responses_headers =
thread_extension_data.get::<crate::CodexResponsesHeaders>();
// Ephemeral title requests use request-level effort even when managed settings
// enable overrides. The client-supplied tag selects cache behavior, not permissions.
let title_request = config.ephemeral
@@ -1926,7 +1924,7 @@ impl Session {
)
.or(fork_cache_key),
tx_event.clone(),
codex_responses_headers,
&thread_extension_data,
crate::cyber_access_program::ApiKeyCyberAccessPrograms::from_config(&config),
required_cyber_access_programs,
);
+11
View File
@@ -2698,6 +2698,17 @@ impl ThreadManagerState {
}
let inherited_environments = captured_environments.or(inherited_environments);
let session_source = session_source.unwrap_or_else(|| self.session_source.clone());
if let Some(parent_id) = parent_thread_id
&& thread_extension_init
.get::<crate::UsageAttributionPolicy>()
.is_none()
&& let Some(parent) = self.threads.read().await.get(&parent_id)
&& let Some(policy) = parent
.thread_extension_data()
.get::<crate::UsageAttributionPolicy>()
{
thread_extension_init.insert(*policy);
}
if thread_extension_init.get::<InheritedSessionId>().is_some()
&& (session_source.is_non_root_agent()
|| !matches!(