Remove cumulative MCP attribution from requests and rollouts (#62589)

## What changed

Stop collecting cumulative MCP tool attribution, sending it in Responses
API request metadata, and writing it to rollout checkpoints.

Use `model_search_state` for search provider history in new rollouts. When
reading older rollouts, decode `mcp_attribution` only to determine whether
Search MCP may have been used. Treat malformed or error attribution as
possible Search MCP use so native search fallback stays disabled.

## Testing

Add a history test that distinguishes legacy Search MCP use, an explicit
record of no use, and missing attribution.

GitOrigin-RevId: a145b5b6b7d2f423d989af10623ef21120f49d4d
This commit is contained in:
Owen Lin
2026-11-19 21:06:08 +00:00
committed by copyberry
parent 5f8c36e836
commit 30c69e60a3
24 changed files with 98 additions and 1248 deletions
@@ -4,7 +4,6 @@
#[cfg(test)]
#[path = "executed_tool_calls_direct_tests.rs"]
mod direct_tests;
mod mcp_attribution;
mod request_metadata;
use std::collections::HashMap;
@@ -26,8 +25,6 @@ use codex_model_provider::provider_uses_first_party_auth_path;
use codex_protocol::ResponseItemId;
use codex_protocol::auth::AuthMode;
use codex_protocol::mcp::CallToolResult;
use codex_protocol::mcp::McpAttribution;
use codex_protocol::mcp::McpAttributionSource;
use codex_protocol::models::ExecutedToolCall;
use codex_protocol::models::ExecutedToolCallArguments;
use codex_protocol::models::ResponseItem;
@@ -72,7 +69,6 @@ pub(crate) struct ExecutedToolCalls {
captures_result_bodies: bool,
retained_direct_metadata_bytes: Arc<AtomicUsize>,
pending_direct_calls: Arc<AtomicUsize>,
mcp_attribution: mcp_attribution::McpAttributionRecorder,
}
/// Private bytes belong to one regular task. History keeps only the host-issued IDs.
@@ -453,7 +449,6 @@ impl ExecutedToolCalls {
}))),
retained_direct_metadata_bytes: Arc::new(AtomicUsize::new(0)),
pending_direct_calls: Arc::new(AtomicUsize::new(0)),
mcp_attribution: mcp_attribution::McpAttributionRecorder::new(history),
}
}
@@ -561,23 +556,6 @@ impl ExecutedToolCalls {
.filter(|capture| call.permits_result_body(capture.auth_mode))?
.start_capture(nested_call_id)
}
pub(crate) fn record_mcp_source(&self, source: McpAttributionSource) {
self.mcp_attribution.record(source);
}
pub(crate) fn mcp_attribution_snapshot(&self) -> McpAttribution {
self.mcp_attribution.snapshot()
}
pub(crate) fn mcp_attribution_checkpoint(&self, force: bool) -> Option<(McpAttribution, u64)> {
self.mcp_attribution.checkpoint(force)
}
pub(crate) fn mark_mcp_attribution_persisted(&self, revision: u64) {
self.mcp_attribution.mark_persisted(revision);
}
/// Consult the inventory attached to this exact exec output during actor sampling.
/// Pending cells can still produce other outputs and have no per-output inventory yet.
pub(crate) fn exec_output_matches(
@@ -1,180 +0,0 @@
//! Cumulative MCP result attribution, independent of the best-effort call recorder.
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::MutexGuard;
use codex_history::InitialHistory;
use codex_history::RolloutItem;
use codex_protocol::mcp::McpAttribution;
use codex_protocol::mcp::McpAttributionErrorReason;
use codex_protocol::mcp::McpAttributionSource;
use codex_protocol::mcp::McpAttributionStatus;
#[derive(Clone)]
pub(super) struct McpAttributionRecorder(Arc<Mutex<State>>);
struct State {
attribution: McpAttribution,
revision: u64,
persisted_revision: u64,
}
#[derive(PartialEq, Eq)]
struct SourceIdentity<'a> {
connector_id: Option<&'a str>,
plugin_id: Option<&'a str>,
server_name: &'a str,
tool_name: &'a str,
}
impl<'a> From<&'a McpAttributionSource> for SourceIdentity<'a> {
fn from(source: &'a McpAttributionSource) -> Self {
Self {
connector_id: source.connector_id.as_deref(),
plugin_id: source.plugin_id.as_deref(),
server_name: &source.server_name,
tool_name: &source.tool_name,
}
}
}
impl Default for McpAttributionRecorder {
fn default() -> Self {
Self::new(&InitialHistory::New)
}
}
impl McpAttributionRecorder {
pub(super) fn new(history: &InitialHistory) -> Self {
let mut state = State {
attribution: McpAttribution::default(),
// Persist an initial checkpoint even when no MCP result has been recorded.
revision: 1,
persisted_revision: 0,
};
let mut found_checkpoint = matches!(history, InitialHistory::New | InitialHistory::Cleared);
for item in history.get_rollout_items() {
match item {
RolloutItem::ResponseItem(envelope) => {
if let Some(metadata) = envelope.metadata.as_ref()
&& let Some(checkpoint) = metadata.mcp_attribution.as_ref()
{
found_checkpoint = true;
state.merge_checkpoint(checkpoint);
}
}
RolloutItem::Compacted(compacted) => {
for metadata in compacted
.replacement_history
.iter()
.flatten()
.filter_map(|envelope| envelope.metadata.as_ref())
{
if let Some(checkpoint) = metadata.mcp_attribution.as_ref() {
found_checkpoint = true;
state.merge_checkpoint(checkpoint);
}
}
}
_ => {}
}
}
if !found_checkpoint {
// Pre-attribution history cannot establish that earlier context was MCP-free.
state.mark_error(McpAttributionErrorReason::HistoryMissingCheckpoint);
}
Self(Arc::new(Mutex::new(state)))
}
fn lock(&self) -> MutexGuard<'_, State> {
self.0.lock().unwrap_or_else(|poisoned| {
let mut state = poisoned.into_inner();
state.mark_error(McpAttributionErrorReason::RecorderPoisoned);
state
})
}
pub(super) fn record(&self, source: McpAttributionSource) {
self.lock().record(source, /*restoring*/ false);
}
pub(super) fn snapshot(&self) -> McpAttribution {
self.lock().attribution.clone()
}
pub(super) fn checkpoint(&self, force: bool) -> Option<(McpAttribution, u64)> {
let state = self.lock();
(force || state.revision != state.persisted_revision)
.then(|| (state.attribution.clone(), state.revision))
}
pub(super) fn mark_persisted(&self, revision: u64) {
let mut state = self.lock();
state.persisted_revision = state.persisted_revision.max(revision.min(state.revision));
}
}
impl State {
fn mark_error(&mut self, reason: McpAttributionErrorReason) {
if self.attribution.status != McpAttributionStatus::AttributionError {
self.attribution.status = McpAttributionStatus::AttributionError;
self.attribution.error_reason = Some(reason);
self.revision += 1;
}
}
fn merge_checkpoint(&mut self, checkpoint: &McpAttribution) {
if checkpoint.status == McpAttributionStatus::AttributionError {
self.mark_error(
checkpoint
.error_reason
.unwrap_or(McpAttributionErrorReason::RestoredErrorUnknown),
);
} else if (checkpoint.status == McpAttributionStatus::None
&& !checkpoint.sources.is_empty())
|| (checkpoint.status == McpAttributionStatus::Complete
&& checkpoint.sources.is_empty())
{
self.mark_error(McpAttributionErrorReason::CheckpointInvalid);
}
for source in &checkpoint.sources {
self.record(source.clone(), /*restoring*/ true);
}
}
fn record(&mut self, source: McpAttributionSource, restoring: bool) {
let identity = SourceIdentity::from(&source);
if let Some(existing) = self
.attribution
.sources
.iter()
.find(|existing| SourceIdentity::from(*existing) == identity)
{
if restoring && existing.first_turn_id != source.first_turn_id {
self.mark_error(McpAttributionErrorReason::CheckpointSourceConflict);
}
return;
}
if source.server_name.is_empty()
|| source.tool_name.is_empty()
|| source.first_turn_id.is_empty()
{
self.mark_error(if restoring {
McpAttributionErrorReason::CheckpointInvalid
} else {
McpAttributionErrorReason::SourceInvalid
});
return;
}
if self.attribution.status == McpAttributionStatus::None {
self.attribution.status = McpAttributionStatus::Complete;
}
self.attribution.sources.push(source);
self.revision += 1;
}
}
#[cfg(test)]
#[path = "mcp_attribution_tests.rs"]
mod tests;
@@ -1,242 +0,0 @@
//! Tests for cumulative MCP attribution restoration and checkpoint acknowledgements.
use super::*;
use codex_history::CodexHarnessMetadata;
use codex_history::CompactedItem;
use codex_history::ResponseItemEnvelope;
use codex_protocol::models::ResponseItem;
use pretty_assertions::assert_eq;
fn source(tool_name: &str, first_turn_id: &str) -> McpAttributionSource {
McpAttributionSource {
connector_id: None,
plugin_id: None,
server_name: "example".to_string(),
tool_name: tool_name.to_string(),
first_turn_id: first_turn_id.to_string(),
}
}
fn envelope(attribution: Option<McpAttribution>) -> ResponseItemEnvelope {
ResponseItemEnvelope {
item: ResponseItem::Message {
status: None,
encrypted_content: None,
id: None,
role: "user".to_string(),
content: Vec::new(),
phase: None,
internal_chat_message_metadata_passthrough: None,
},
metadata: attribution.map(|mcp_attribution| CodexHarnessMetadata {
mcp_attribution: Some(mcp_attribution),
..Default::default()
}),
}
}
#[test]
fn records_the_first_turn_for_each_unique_source() {
let recorder = McpAttributionRecorder::default();
recorder.record(source("search", "turn_1"));
recorder.record(source("search", "turn_2"));
recorder.record(source("fetch", "turn_2"));
assert_eq!(
recorder.snapshot(),
McpAttribution {
status: McpAttributionStatus::Complete,
error_reason: None,
sources: vec![source("search", "turn_1"), source("fetch", "turn_2")],
}
);
}
#[test]
fn restores_cumulative_item_and_compaction_checkpoints() {
let initial = McpAttribution {
status: McpAttributionStatus::Complete,
error_reason: None,
sources: vec![source("search", "turn_1")],
};
let cumulative = McpAttribution {
status: McpAttributionStatus::Complete,
error_reason: None,
sources: vec![source("search", "turn_1"), source("fetch", "turn_2")],
};
let history = InitialHistory::Forked(vec![
RolloutItem::ResponseItem(envelope(Some(initial))),
RolloutItem::Compacted(Box::new(CompactedItem {
message: "summary".to_string(),
replacement_history: Some(vec![envelope(Some(cumulative.clone()))]),
guardian_history: None,
retained_context: None,
mcp_resource_origins: None,
window_number: None,
first_window_id: None,
previous_window_id: None,
window_id: None,
compaction_response_id: None,
latest_token_usage_record: None,
resume_metadata: None,
})),
]);
assert_eq!(McpAttributionRecorder::new(&history).snapshot(), cumulative);
}
#[test]
fn legacy_or_conflicting_history_is_not_complete() {
let legacy = InitialHistory::Forked(vec![RolloutItem::ResponseItem(envelope(
/*attribution*/ None,
))]);
assert_eq!(
McpAttributionRecorder::new(&legacy).snapshot(),
McpAttribution {
status: McpAttributionStatus::AttributionError,
error_reason: Some(McpAttributionErrorReason::HistoryMissingCheckpoint),
sources: Vec::new(),
}
);
let history = InitialHistory::Forked(
["turn_1", "turn_2"]
.map(|turn_id| {
RolloutItem::ResponseItem(envelope(Some(McpAttribution {
status: McpAttributionStatus::Complete,
error_reason: None,
sources: vec![source("search", turn_id)],
})))
})
.to_vec(),
);
assert_eq!(
McpAttributionRecorder::new(&history).snapshot(),
McpAttribution {
status: McpAttributionStatus::AttributionError,
error_reason: Some(McpAttributionErrorReason::CheckpointSourceConflict),
sources: vec![source("search", "turn_1")],
}
);
}
#[test]
fn first_error_reason_survives_checkpoints_and_later_sources() {
let recorder = McpAttributionRecorder::default();
recorder.record(source("", "turn_1"));
recorder.record(source("search", "turn_2"));
let (snapshot, _) = recorder
.checkpoint(/*force*/ true)
.expect("error checkpoint");
let checkpoint = envelope(Some(snapshot));
let mut compacted: CompactedItem =
serde_json::from_value(serde_json::json!({"message": "summary"}))
.expect("compaction checkpoint");
compacted.replacement_history = Some(vec![checkpoint.clone()]);
for item in [
RolloutItem::ResponseItem(checkpoint),
RolloutItem::Compacted(Box::new(compacted)),
] {
let restored = McpAttributionRecorder::new(&InitialHistory::Forked(vec![item]));
restored.record(source("", "turn_3"));
assert_eq!(
restored.snapshot(),
McpAttribution {
status: McpAttributionStatus::AttributionError,
error_reason: Some(McpAttributionErrorReason::SourceInvalid),
sources: vec![source("search", "turn_2")],
},
);
}
}
#[test]
fn poisoned_recorder_reports_a_bounded_reason() {
let recorder = McpAttributionRecorder::default();
let poisoned = recorder.clone();
assert!(
std::thread::spawn(move || {
let _state = poisoned.0.lock().expect("unpoisoned recorder");
panic!("poison recorder");
})
.join()
.is_err()
);
assert_eq!(
recorder.snapshot(),
McpAttribution {
status: McpAttributionStatus::AttributionError,
error_reason: Some(McpAttributionErrorReason::RecorderPoisoned),
sources: Vec::new(),
}
);
}
#[test]
fn restored_diagnostics_do_not_change_attribution_state() {
let checkpoint = envelope(Some(McpAttribution {
status: McpAttributionStatus::Complete,
error_reason: Some(McpAttributionErrorReason::SourceInvalid),
sources: vec![source("search", "turn_1")],
}));
assert_eq!(
McpAttributionRecorder::new(&InitialHistory::Forked(vec![RolloutItem::ResponseItem(
checkpoint
),]))
.snapshot(),
McpAttribution {
status: McpAttributionStatus::Complete,
error_reason: None,
sources: vec![source("search", "turn_1")],
}
);
for (attribution, expected_reason) in [
(
McpAttribution {
status: McpAttributionStatus::AttributionError,
error_reason: None,
sources: Vec::new(),
},
McpAttributionErrorReason::RestoredErrorUnknown,
),
(
McpAttribution {
status: McpAttributionStatus::Complete,
error_reason: None,
sources: Vec::new(),
},
McpAttributionErrorReason::CheckpointInvalid,
),
] {
assert_eq!(
McpAttributionRecorder::new(&InitialHistory::Forked(vec![RolloutItem::ResponseItem(
envelope(Some(attribution))
),]))
.snapshot(),
McpAttribution {
status: McpAttributionStatus::AttributionError,
error_reason: Some(expected_reason),
sources: Vec::new(),
}
);
}
}
#[test]
fn acknowledging_an_older_checkpoint_does_not_clear_newer_changes() {
let recorder = McpAttributionRecorder::default();
let (_, initial_revision) = recorder
.checkpoint(/*force*/ false)
.expect("initial checkpoint");
recorder.record(source("search", "turn_1"));
recorder.mark_persisted(initial_revision);
let (_, latest_revision) = recorder
.checkpoint(/*force*/ false)
.expect("dirty checkpoint");
recorder.mark_persisted(latest_revision);
assert_eq!(recorder.checkpoint(/*force*/ false), None);
assert!(recorder.checkpoint(/*force*/ true).is_some());
}