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(())
}