Bind direct tool-call metadata to invocation outputs (#45185)

## Why

Direct tool-call records need to stay associated with the invocation that produced each output, including when call IDs are reused. Completeness must describe the recorded call inventory, independently of tool success.

## What changed

- Attach direct-call records to outputs before they enter history, and set `tool_calls_complete` when the invocation's arguments are fully recorded.
- Bound pending recordings and retained metadata, release reservations on completion or cancellation, and invalidate pending records when capture is disabled.
- Apply request budgets to direct metadata and strip it from inference and compaction inputs when capture is disabled.
- Remove executed-call metadata from app-server raw response notifications and exclude its size from Guardian history retention budgets.
- Track call IDs that bypass dispatch so their reuse cannot incorrectly establish Code Mode completeness.

## Testing

Add regression coverage for direct-call attribution, malformed calls, metadata budgets, cancellation, configuration changes, compaction, notification filtering, and Guardian context isolation.

GitOrigin-RevId: 2ebd39c7f141d04788736491495109841656b4c0
This commit is contained in:
ningyi-oai authored and copyberry committed 2026-09-13 06:53:20 +00:00
1 parent e61f381900
commit 1715e55076
24 files changed
+1760 -297

No files matched your search

+182 -78
View File
@@ -1,6 +1,9 @@
//! Records attempted calls at existing execution boundaries. Request metadata policy
//! lives in the private request metadata module; this recorder must never dispatch or await tools.
#[cfg(test)]
#[path = "executed_tool_calls_direct_tests.rs"]
mod direct_tests;
mod request_metadata;
use std::collections::HashMap;
@@ -8,6 +11,9 @@ use std::collections::HashSet;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::MutexGuard;
use std::sync::Weak;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use codex_code_mode::CellId;
use codex_features::Feature;
@@ -37,6 +43,10 @@ use seen_ids::SeenIds;
const MAX_EXECUTED_TOOL_CALL_ARGUMENT_BYTES: usize = 8 * 1024;
const MAX_EXECUTED_TOOL_CALL_FULL_ARGUMENT_BYTES_PER_OUTPUT: usize = 32 * 1024;
const MAX_PENDING_EXECUTED_TOOL_CALLS: usize = 256;
// Limits new Direct metadata retained in history and the append-only rollout
// during one recorder lifetime. A new process cannot recover the exact prior
// budget because raw result metadata is intentionally not deserialized.
const MAX_RETAINED_DIRECT_METADATA_BYTES: usize = 1024 * 1024;
type ExecutedToolCallCache =
HashMap<(std::mem::Discriminant<ResponseItem>, String), Vec<ExecutedToolCall>>;
@@ -46,11 +56,32 @@ type ExecutedToolCallCache =
#[derive(Clone, Default)]
pub(crate) struct ExecutedToolCalls {
state: Arc<Mutex<Option<ExecutedToolCallRecorderState>>>,
retained_direct_metadata_bytes: Arc<AtomicUsize>,
pending_direct_calls: Arc<AtomicUsize>,
}
// The tool future owns this reservation, so completion or cancellation releases it.
pub(crate) struct DirectCallPermit {
recording: Weak<()>,
pending_direct_calls: Arc<AtomicUsize>,
}
impl DirectCallPermit {
pub(crate) fn strong_count(&self) -> usize {
self.recording.strong_count()
}
}
impl Drop for DirectCallPermit {
fn drop(&mut self) {
self.pending_direct_calls.fetch_sub(1, Ordering::Relaxed);
}
}
#[derive(Default)]
struct ExecutedToolCallRecorderState {
direct_calls: HashMap<String, ExecutedToolCall>,
// Disabling drops this lifetime, permanently invalidating prepared Direct records.
recording: Arc<()>,
cells: HashMap<CellId, RecordedCell>,
output_cells: HashMap<String, CellId>,
retained_calls: HashMap<(std::mem::Discriminant<ResponseItem>, String), RetainedToolCalls>,
@@ -175,6 +206,8 @@ impl ExecutedToolCalls {
..Default::default()
}
}))),
retained_direct_metadata_bytes: Arc::new(AtomicUsize::new(0)),
pending_direct_calls: Arc::new(AtomicUsize::new(0)),
}
}
@@ -210,12 +243,105 @@ impl ExecutedToolCalls {
self.record_call(call, source, step_context.tool_router.tool_mode());
}
/// Keep a Direct record with its invocation so it can be attached to that invocation's output.
pub(crate) fn prepare_direct_call(
&self,
call: &ToolCall,
source: &ToolCallSource,
step_context: &StepContext,
) -> Option<(ExecutedToolCall, DirectCallPermit)> {
if is_code_mode_wrapper(call, source, step_context.tool_router.tool_mode()) {
return None;
}
let permit = self.reserve_direct_call()?;
let (mut recorded, _) = recorded_call(call);
let argument_bytes = serialized_json_bytes(recorded.arguments()).unwrap_or(usize::MAX);
if matches!(recorded.arguments(), ExecutedToolCallArguments::Raw(_))
&& argument_bytes > MAX_EXECUTED_TOOL_CALL_ARGUMENT_BYTES
{
recorded = ExecutedToolCall::truncated(
recorded.name,
argument_bytes,
MAX_EXECUTED_TOOL_CALL_ARGUMENT_BYTES,
);
}
Some((recorded, permit))
}
fn reserve_direct_call(&self) -> Option<DirectCallPermit> {
let recording = Arc::downgrade(&self.lock_state().as_ref()?.recording);
self.pending_direct_calls
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |pending| {
(pending < MAX_PENDING_EXECUTED_TOOL_CALLS).then_some(pending + 1)
})
.ok()?;
Some(DirectCallPermit {
recording,
pending_direct_calls: Arc::clone(&self.pending_direct_calls),
})
}
/// Validate the recording lifetime and attach together so a config refresh
/// cannot invalidate the call between those two operations.
pub(crate) fn attach_direct_call_to_output(
&self,
item: &mut ResponseItem,
prepared: Option<(ExecutedToolCall, DirectCallPermit)>,
) {
let Some((call, permit)) = prepared else {
return;
};
let state = self.lock_state();
let Some(state) = state.as_ref() else {
return;
};
if !permit.recording.ptr_eq(&Arc::downgrade(&state.recording)) {
return;
}
let complete = matches!(call.arguments(), ExecutedToolCallArguments::Raw(_));
item.append_executed_tool_calls(vec![call]);
if complete {
item.mark_tool_calls_complete();
}
let retained = self.retained_direct_metadata_bytes.load(Ordering::Relaxed);
let available = MAX_RETAINED_DIRECT_METADATA_BYTES.saturating_sub(retained);
let mut bytes = executed_tool_call_metadata_bytes(item);
if bytes > available {
item.clear_tool_result_metadata();
bytes = executed_tool_call_metadata_bytes(item);
}
if bytes > available {
item.clear_executed_tool_calls();
return;
}
// All Direct attachments share the recorder lock, including cloned handles.
self.retained_direct_metadata_bytes
.store(retained + bytes, Ordering::Relaxed);
}
/// Remember IDs from response items that bypass local tool dispatch.
pub(crate) fn observe_non_dispatched_call(&self, item: &ResponseItem) {
let Some(call_id) = input_call_id(item) else {
return;
};
let mut state = self.lock_state();
let Some(state) = state.as_mut() else {
return;
};
if !state.seen_ids.observe_call_id(call_id) {
state.invalidate_origin(call_id);
}
}
pub(crate) fn record_accepted_result(
&self,
source: &ToolCallSource,
call_id: &str,
result: &dyn ToolOutput,
) {
if !matches!(source, ToolCallSource::CodeMode { .. }) {
return;
}
// Release the lock before calling the output's trait method.
let recording = self.lock_state().is_some();
if recording && let Some(metadata) = result.tool_result_metadata() {
@@ -227,83 +353,25 @@ impl ExecutedToolCalls {
if self.lock_state().is_none() {
return;
}
if matches!(source, ToolCallSource::Direct)
&& matches!(tool_mode, ToolMode::CodeMode | ToolMode::CodeModeOnly)
&& call.tool_name.is_default_namespace()
&& matches!(
(call.tool_name.name.as_str(), &call.payload),
(
crate::tools::code_mode::PUBLIC_TOOL_NAME,
ToolPayload::Custom { .. }
) | (
crate::tools::code_mode::WAIT_TOOL_NAME,
ToolPayload::Function { .. }
)
)
{
let mut state = self.lock_state();
let Some(state) = state.as_mut() else {
return;
};
let fresh = state.seen_ids.observe_call_id(&call.call_id);
if !fresh {
state.invalidate_origin(&call.call_id);
}
if fresh && state.pending_wrapper_origins.len() < MAX_PENDING_EXECUTED_TOOL_CALLS {
state.pending_wrapper_origins.insert(call.call_id.clone());
}
return;
}
let original_bytes = match &call.payload {
ToolPayload::Function { arguments } => arguments.len(),
ToolPayload::Custom { input } => serialized_json_bytes(input).unwrap_or(usize::MAX),
ToolPayload::ToolSearch { arguments } => {
serialized_json_bytes(arguments).unwrap_or(usize::MAX)
}
};
let name = codex_tools::code_mode_name_for_tool_name(&call.tool_name);
let recorded_call = if original_bytes > MAX_EXECUTED_TOOL_CALL_ARGUMENT_BYTES {
ExecutedToolCall::truncated(name, original_bytes, MAX_EXECUTED_TOOL_CALL_ARGUMENT_BYTES)
} else {
let arguments = match &call.payload {
ToolPayload::Function { arguments } => serde_json::from_str(arguments)
.unwrap_or_else(|_| JsonValue::String(arguments.clone())),
ToolPayload::Custom { input } => JsonValue::String(input.clone()),
ToolPayload::ToolSearch { arguments } => {
serde_json::to_value(arguments).unwrap_or_default()
}
};
ExecutedToolCall::new(name, arguments)
};
match source {
ToolCallSource::Direct | ToolCallSource::DirectPlaintextMessage => {
let mut state = self.lock_state();
let Some(state) = state.as_mut() else {
return;
};
if !state.seen_ids.observe_call_id(&call.call_id) {
let fresh = state.seen_ids.observe_call_id(&call.call_id);
if !fresh {
state.invalidate_origin(&call.call_id);
}
if state.direct_calls.len() < MAX_PENDING_EXECUTED_TOOL_CALLS {
state
.direct_calls
.entry(call.call_id.clone())
.or_insert(recorded_call);
} else if state.direct_calls.len() == MAX_PENDING_EXECUTED_TOOL_CALLS
&& !state.direct_calls.contains_key(&call.call_id)
if fresh
&& is_code_mode_wrapper(call, source, tool_mode)
&& state.pending_wrapper_origins.len() < MAX_PENDING_EXECUTED_TOOL_CALLS
{
state.direct_calls.insert(
call.call_id.clone(),
ExecutedToolCall::truncated(
recorded_call.name,
original_bytes,
/*max_bytes*/ 0,
),
);
state.pending_wrapper_origins.insert(call.call_id.clone());
}
}
ToolCallSource::CodeMode { cell_id, .. } => {
let (recorded_call, original_bytes) = recorded_call(call);
self.record_nested_tool_call(
CellId::new(cell_id.clone()),
call.call_id.clone(),
@@ -376,28 +444,23 @@ impl ExecutedToolCalls {
call_id: &str,
metadata: &JsonValue,
) -> bool {
let ToolCallSource::CodeMode { cell_id, .. } = source else {
return false;
};
let metadata = codex_protocol::models::ToolResultMetadata::new(metadata);
let has_metadata = metadata.is_some();
let mut state = self.lock_state();
let Some(state) = state.as_mut() else {
return false;
};
let call = match source {
ToolCallSource::Direct | ToolCallSource::DirectPlaintextMessage => {
state.direct_calls.get_mut(call_id)
}
ToolCallSource::CodeMode { cell_id, .. } => state
.cells
.get_mut(&CellId::new(cell_id.clone()))
.and_then(|cell| cell.pending_calls.get_mut(call_id)),
};
let call = state
.cells
.get_mut(&CellId::new(cell_id.clone()))
.and_then(|cell| cell.pending_calls.get_mut(call_id));
if let Some(call) = call {
call.set_tool_result_metadata(metadata);
return has_metadata;
}
let ToolCallSource::CodeMode { cell_id, .. } = source else {
return false;
};
let Some((retained, index)) = state.retained_calls.values_mut().find_map(|retained| {
if retained.runtime_cell_id.as_ref()?.as_str() != cell_id.as_str() {
return None;
@@ -461,6 +524,47 @@ impl ExecutedToolCalls {
}
}
fn is_code_mode_wrapper(call: &ToolCall, source: &ToolCallSource, tool_mode: ToolMode) -> bool {
matches!(source, ToolCallSource::Direct)
&& matches!(tool_mode, ToolMode::CodeMode | ToolMode::CodeModeOnly)
&& call.tool_name.is_default_namespace()
&& matches!(
(call.tool_name.name.as_str(), &call.payload),
(
crate::tools::code_mode::PUBLIC_TOOL_NAME,
ToolPayload::Custom { .. }
) | (
crate::tools::code_mode::WAIT_TOOL_NAME,
ToolPayload::Function { .. }
)
)
}
fn recorded_call(call: &ToolCall) -> (ExecutedToolCall, usize) {
let original_bytes = match &call.payload {
ToolPayload::Function { arguments } => arguments.len(),
ToolPayload::Custom { input } => serialized_json_bytes(input).unwrap_or(usize::MAX),
ToolPayload::ToolSearch { arguments } => {
serialized_json_bytes(arguments).unwrap_or(usize::MAX)
}
};
let name = codex_tools::code_mode_name_for_tool_name(&call.tool_name);
let recorded_call = if original_bytes > MAX_EXECUTED_TOOL_CALL_ARGUMENT_BYTES {
ExecutedToolCall::truncated(name, original_bytes, MAX_EXECUTED_TOOL_CALL_ARGUMENT_BYTES)
} else {
let arguments = match &call.payload {
ToolPayload::Function { arguments } => serde_json::from_str(arguments)
.unwrap_or_else(|_| JsonValue::String(arguments.clone())),
ToolPayload::Custom { input } => JsonValue::String(input.clone()),
ToolPayload::ToolSearch { arguments } => {
serde_json::to_value(arguments).unwrap_or_default()
}
};
ExecutedToolCall::new(name, arguments)
};
(recorded_call, original_bytes)
}
fn input_call_id(item: &ResponseItem) -> Option<&str> {
match item {
ResponseItem::FunctionCall { call_id, .. }
@@ -4,30 +4,43 @@
use super::*;
impl ExecutedToolCalls {
/// Compaction preserves captured records without applying the sampling request budget.
pub(crate) fn strip_disabled_direct_metadata(&self, items: &mut [ResponseItem]) {
if self.lock_state().is_none() {
clear_direct_call_metadata(items);
}
}
/// Attaches trusted completeness; request budgeting only revokes damaged inventories.
pub(crate) fn attach_to_prompt(
&self,
items: &mut [ResponseItem],
retry_cache: &mut ExecutedToolCallCache,
) {
if self.attach_pending_to_prompt(items, retry_cache) {
let attached = {
let mut state = self.lock_state();
state
.as_mut()
.map(|state| Self::attach_pending_to_prompt_with_state(state, items, retry_cache))
};
let Some(attached) = attached else {
// Direct records now live in history; disabling capture also stops replaying them.
clear_direct_call_metadata(items);
return;
};
if attached || items.iter().any(has_direct_call_metadata) {
bound_executed_tool_calls_for_prompt(items);
}
}
fn attach_pending_to_prompt(
&self,
fn attach_pending_to_prompt_with_state(
state: &mut ExecutedToolCallRecorderState,
items: &mut [ResponseItem],
retry_cache: &mut ExecutedToolCallCache,
) -> bool {
let mut state = self.lock_state();
let Some(state) = state.as_mut() else {
return false;
};
// Failed wrappers have no callback; only their bounded bitmap observation survives.
state.pending_wrapper_origins.clear();
if state.direct_calls.is_empty()
&& state.output_cells.is_empty()
if state.output_cells.is_empty()
&& state.retained_calls.is_empty()
&& retry_cache.is_empty()
{
@@ -62,13 +75,13 @@ impl ExecutedToolCalls {
.collect::<HashSet<_>>();
let mut attached = false;
for index in (0..items.len()).rev() {
if state.direct_calls.is_empty()
&& state.output_cells.is_empty()
&& pending_outputs.is_empty()
{
if state.output_cells.is_empty() && pending_outputs.is_empty() {
break;
}
let item = &items[index];
if has_direct_call_metadata(item) {
continue;
}
let Some(call_id) = output_call_id(item) else {
continue;
};
@@ -85,12 +98,7 @@ impl ExecutedToolCalls {
cached.clone()
} else {
let mut runtime_cell_id = None;
let mut calls = state
.direct_calls
.remove(call_id)
.into_iter()
.collect::<Vec<_>>();
let direct_call_collision = !calls.is_empty();
let mut calls = Vec::new();
let mut call_index_by_id = HashMap::new();
if let Some(output_cell_id) = state.output_cells.remove(call_id)
&& let Some(cell) = state.cells.get_mut(&output_cell_id)
@@ -127,7 +135,6 @@ impl ExecutedToolCalls {
}
cell.pending_full_argument_bytes = 0;
complete = cell.completion == CellCompletion::Complete
&& !direct_call_collision
&& (state.can_prove_wait_completion
|| matches!(item, ResponseItem::CustomToolCallOutput { .. }));
if matches!(
@@ -179,6 +186,9 @@ impl ExecutedToolCalls {
let mut invalid_cells = HashSet::new();
for index in 0..items.len() {
let item = &items[index];
if has_direct_call_metadata(item) {
continue;
}
let Some(call_id) = output_call_id(item) else {
continue;
};
@@ -232,6 +242,9 @@ impl ExecutedToolCalls {
}
}
for item in items.iter_mut() {
if has_direct_call_metadata(item) {
continue;
}
let Some(call_id) = output_call_id(item) else {
continue;
};
@@ -254,6 +267,9 @@ impl ExecutedToolCalls {
let retained_before_bounding = std::mem::take(&mut state.retained_calls);
let mut bounded_outputs = HashSet::new();
for item in items.iter_mut() {
if has_direct_call_metadata(item) {
continue;
}
let Some(call_id) = output_call_id(item) else {
continue;
};
@@ -305,6 +321,22 @@ impl ExecutedToolCalls {
}
}
// Direct records already belong to their output; never rebuild them from the Code Mode cache.
fn clear_direct_call_metadata(items: &mut [ResponseItem]) {
for item in items
.iter_mut()
.filter(|item| has_direct_call_metadata(item))
{
item.clear_executed_tool_calls();
}
}
fn has_direct_call_metadata(item: &ResponseItem) -> bool {
item.executed_tool_call_metadata().is_some_and(|metadata| {
metadata.cell_id.is_none() && metadata.executed_tool_calls.is_some()
})
}
fn code_mode_input_matches_output(
input: &ResponseItem,
output: &ResponseItem,
@@ -10,6 +10,20 @@ use serde_json::json;
use super::*;
impl ExecutedToolCalls {
fn attach_pending_to_prompt(
&self,
items: &mut [ResponseItem],
retry_cache: &mut ExecutedToolCallCache,
) -> bool {
let mut state = self.lock_state();
let Some(state) = state.as_mut() else {
return false;
};
Self::attach_pending_to_prompt_with_state(state, items, retry_cache)
}
}
fn new_recorder(history: InitialHistory) -> ExecutedToolCalls {
let mut features = Features::default();
features.enable(Feature::ExecutedToolCallMetadata);
@@ -66,6 +80,82 @@ fn tool_calls_complete(item: &ResponseItem) -> Option<bool> {
.and_then(|metadata| metadata.tool_calls_complete)
}
#[test]
fn direct_retained_metadata_budget_sheds_results_then_calls_across_refresh() {
let recorder = new_recorder(InitialHistory::New);
let mut call = ExecutedToolCall::new("test_tool".to_string(), json!({"argument": "kept"}));
call.set_tool_result_metadata(ToolResultMetadata::new(&json!({
"provider": "x".repeat(1024),
})));
let mut first = output("first");
recorder.attach_direct_call_to_output(
&mut first,
Some((call.clone(), recorder.reserve_direct_call().unwrap())),
);
let full_bytes = executed_tool_call_metadata_bytes(&first);
assert!(full_bytes > 0);
assert_eq!(
recorder
.retained_direct_metadata_bytes
.load(Ordering::Relaxed),
full_bytes,
);
let mut without_result = first.clone();
without_result.clear_tool_result_metadata();
let call_bytes = executed_tool_call_metadata_bytes(&without_result);
assert!(full_bytes > call_bytes);
recorder.retained_direct_metadata_bytes.store(
MAX_RETAINED_DIRECT_METADATA_BYTES - call_bytes,
Ordering::Relaxed,
);
let mut second = output("second");
let result_before =
serde_json::to_value(&second).expect("serializable output")["output"].clone();
recorder.clone().attach_direct_call_to_output(
&mut second,
Some((call.clone(), recorder.reserve_direct_call().unwrap())),
);
let second_metadata = second
.executed_tool_call_metadata()
.expect("call remains when only its result metadata exceeds the budget");
assert_eq!(second_metadata.tool_calls_complete, Some(true));
assert_eq!(
second_metadata.executed_tool_calls.as_ref().map(Vec::len),
Some(1)
);
let serialized = serde_json::to_value(&second).expect("serializable output");
assert!(
serialized["internal_chat_message_metadata_passthrough"]["executed_tool_calls"][0]
.get("tool_result_metadata")
.is_none()
);
assert_eq!(serialized["output"], result_before);
assert_eq!(
recorder
.retained_direct_metadata_bytes
.load(Ordering::Relaxed),
MAX_RETAINED_DIRECT_METADATA_BYTES,
);
let mut features = Features::default();
recorder.refresh(&features);
features.enable(Feature::ExecutedToolCallMetadata);
recorder.refresh(&features);
let mut third = output("third");
recorder.attach_direct_call_to_output(
&mut third,
Some((call, recorder.reserve_direct_call().unwrap())),
);
assert!(third.executed_tool_call_metadata().is_none());
assert_eq!(
recorder
.retained_direct_metadata_bytes
.load(Ordering::Relaxed),
MAX_RETAINED_DIRECT_METADATA_BYTES,
);
}
#[tokio::test]
async fn recorder_refreshes_without_changing_execution_features_or_claiming_missing_history() {
struct MetadataLookup<'a>(std::cell::Cell<usize>, JsonValue, &'a ExecutedToolCalls);
@@ -100,6 +190,7 @@ async fn recorder_refreshes_without_changing_execution_features_or_claiming_miss
assert!(calls.lock_state().is_none());
let mut next_config = (*session.get_config().await).clone();
let mut retry_cache = HashMap::new();
let mut prior_generation = None;
for (index, enabled) in [false, true, false, true].into_iter().enumerate() {
next_config
.features
@@ -124,51 +215,46 @@ async fn recorder_refreshes_without_changing_execution_features_or_claiming_miss
},
encrypted_function_args: None,
};
calls.record_tool_call(&call, &ToolCallSource::Direct, &step);
let result = MetadataLookup(std::cell::Cell::new(0), json!({}), &calls);
calls.record_accepted_result(&ToolCallSource::Direct, &call.call_id, &result);
assert_eq!(result.0.get(), usize::from(enabled));
let input = serde_json::from_value(json!({
"type": "function_call",
"call_id": call.call_id,
"name": "test_tool",
"arguments": "{\"value\":7}",
}))
.expect("tool input must deserialize");
let mut prompt = vec![input, output(&call.call_id)];
if !enabled {
prompt[1].mark_tool_calls_complete();
}
let original = prompt.clone();
calls.attach_to_prompt(&mut prompt, &mut retry_cache);
if !enabled {
assert_eq!(prompt, original);
} else {
assert_eq!(tool_calls_complete(&prompt[1]), None);
}
let mut expected_call = ExecutedToolCall::new("test_tool".to_string(), json!({"value": 7}));
expected_call.set_tool_result_metadata(ToolResultMetadata::new(&json!({})));
let expected_calls = vec![expected_call];
let prepared = calls.prepare_direct_call(&call, &ToolCallSource::Direct, &step);
let expected = ExecutedToolCall::new("test_tool".to_string(), json!({"value": 7}));
assert_eq!(
prompt[1]
prepared.as_ref().map(|(call, _)| call),
enabled.then_some(&expected)
);
if enabled {
if let Some(stale) = prior_generation.take() {
let mut stale_output = output("stale");
calls.attach_direct_call_to_output(&mut stale_output, Some(stale));
assert!(stale_output.executed_tool_call_metadata().is_none());
}
prior_generation = calls.prepare_direct_call(&call, &ToolCallSource::Direct, &step);
}
let mut direct_output = output(&call.call_id);
calls.attach_direct_call_to_output(&mut direct_output, prepared);
assert_eq!(
direct_output
.executed_tool_call_metadata()
.and_then(|metadata| metadata.executed_tool_calls.as_ref()),
enabled.then_some(&expected_calls),
enabled.then_some(&vec![expected]),
);
if enabled {
// Reapplying an enabled config must preserve already-recorded calls.
session.refresh_runtime_config(next_config.clone()).await;
let mut replay = original;
calls.attach_to_prompt(&mut replay, &mut HashMap::new());
assert_eq!(replay, prompt);
}
assert_eq!(tool_calls_complete(&direct_output), enabled.then_some(true));
let cell = CellId::new(format!("cell-{index}"));
let origin = format!("exec-{index}");
calls.start_cell(&cell, &origin);
let nested = record_nested_call(&calls, &cell, "nested");
let mut nested = record_nested_call(&calls, &cell, "nested");
let source = ToolCallSource::CodeMode {
cell_id: cell.as_str().to_string(),
runtime_tool_call_id: "runtime-nested".to_string(),
};
let result = MetadataLookup(std::cell::Cell::new(0), json!({}), &calls);
calls.record_accepted_result(&source, "nested", &result);
assert_eq!(result.0.get(), usize::from(enabled));
nested.set_tool_result_metadata(ToolResultMetadata::new(&json!({})));
if enabled {
// Reapplying an enabled config must preserve pending calls and their metadata.
session.refresh_runtime_config(next_config.clone()).await;
}
calls.finish_cell_recording(&cell);
let mut prompt = vec![exec_input(&origin), exec_output(&origin)];
calls.attach_to_prompt(&mut prompt, &mut retry_cache);
@@ -187,18 +273,6 @@ fn executed_tool_call_recorder_bounds_pending_calls_and_preserves_overflow() {
let recorder = new_recorder(InitialHistory::Forked(Vec::new()));
for index in 0..MAX_PENDING_EXECUTED_TOOL_CALLS + 2 {
recorder.record_call(
&ToolCall {
tool_name: codex_tools::ToolName::plain("direct_tool"),
call_id: format!("direct-{index}"),
payload: ToolPayload::Function {
arguments: "{}".to_string(),
},
encrypted_function_args: None,
},
&ToolCallSource::Direct,
ToolMode::Direct,
);
recorder.record_call(
&ToolCall {
tool_name: codex_tools::ToolName::plain(crate::tools::code_mode::PUBLIC_TOOL_NAME),
@@ -212,8 +286,6 @@ fn executed_tool_call_recorder_bounds_pending_calls_and_preserves_overflow() {
ToolMode::CodeMode,
);
}
let metadata = json!({ "arbitrary-key": ["R1", null] });
assert!(recorder.record_tool_result_metadata(&ToolCallSource::Direct, "direct-0", &metadata));
let cell_id = CellId::new("bounded-cell".to_string());
recorder.start_cell(&cell_id, "bounded-output");
@@ -236,32 +308,6 @@ fn executed_tool_call_recorder_bounds_pending_calls_and_preserves_overflow() {
{
let state = recorder.lock_state();
let state = state.as_ref().unwrap();
assert_eq!(
state.direct_calls.len(),
MAX_PENDING_EXECUTED_TOOL_CALLS + 1
);
assert_eq!(
serde_json::to_value(state.direct_calls.get("direct-0").unwrap()).unwrap()["tool_result_metadata"],
metadata,
);
assert_eq!(
serde_json::to_value(
state
.direct_calls
.get(&format!("direct-{MAX_PENDING_EXECUTED_TOOL_CALLS}"))
.expect("first excess direct call must be marked"),
)
.expect("direct overflow marker must serialize"),
json!({
"name": "direct_tool",
"arguments": {
"_codex_executed_tool_call_truncated": {
"original_bytes": 2,
"max_bytes": 0,
},
},
}),
);
assert_eq!(
state.pending_nested_calls,
MAX_PENDING_EXECUTED_TOOL_CALLS + 1
@@ -341,26 +387,19 @@ fn executed_tool_call_recorder_bounds_retained_history_and_keeps_latest_calls()
for index in 0..512 {
let call_id = format!("retained-{index}");
recorder.record_call(
&ToolCall {
tool_name: codex_tools::ToolName::plain(format!("retained_tool_{index}")),
call_id: call_id.clone(),
payload: ToolPayload::Function {
arguments: arguments.clone(),
},
encrypted_function_args: None,
},
&ToolCallSource::Direct,
ToolMode::Direct,
let cell_id = CellId::new(format!("retained-cell-{index}"));
recorder.start_cell(&cell_id, &call_id);
recorder.record_nested_tool_call(
cell_id.clone(),
format!("nested-{index}"),
ExecutedToolCall::new(
format!("retained_tool_{index}"),
json!({ "payload": "x".repeat(1024) }),
),
arguments.len(),
);
history.push(ResponseItem::FunctionCallOutput {
id: None,
call_id: Some(call_id),
name: None,
namespace: None,
output: FunctionCallOutputPayload::from_text(String::new()),
internal_chat_message_metadata_passthrough: None,
});
recorder.finish_cell_recording(&cell_id);
history.extend([exec_input(&call_id), exec_output(&call_id)]);
prompt = history.clone();
assert!(recorder.attach_pending_to_prompt(&mut prompt, &mut HashMap::new()));
codex_protocol::models::bound_executed_tool_calls_for_prompt(&mut prompt);
@@ -756,6 +795,26 @@ fn completeness_rejects_reused_origin() {
assert_eq!(tool_calls_complete(&prompt[1]), None);
}
#[test]
fn malformed_search_id_cannot_prove_a_later_exec_complete() {
let recorder = new_recorder(InitialHistory::New);
let malformed_search = serde_json::from_value(json!({
"type": "tool_search_call", "call_id": "reused", "execution": "client",
"arguments": {"query": 42},
}))
.expect("tool search response item");
recorder.observe_non_dispatched_call(&malformed_search);
let cell = CellId::new("later-runtime".to_string());
recorder.start_cell(&cell, "reused");
record_nested_call(&recorder, &cell, "nested");
recorder.finish_cell_recording(&cell);
let mut prompt = [exec_input("reused"), exec_output("reused")];
recorder.attach_to_prompt(&mut prompt, &mut HashMap::new());
assert_eq!(tool_calls_complete(&prompt[1]), None);
assert!(prompt[1].executed_tool_call_metadata().is_some());
}
#[test]
fn completeness_rejects_direct_id_collision_and_late_calls() {
let recorder = new_recorder(InitialHistory::New);
@@ -0,0 +1,123 @@
//! Tests Direct metadata admission and permit lifetimes.
//! Metadata limits must leave ordinary tool outputs unchanged.
use codex_protocol::models::FunctionCallOutputPayload;
use codex_protocol::models::ResponseInputItem;
use pretty_assertions::assert_eq;
use serde_json::json;
use super::*;
fn output(call_id: &str) -> ResponseItem {
ResponseItem::from(ResponseInputItem::FunctionCallOutput {
call_id: call_id.to_string(),
output: FunctionCallOutputPayload::from_text("tool result".to_string()),
})
}
#[tokio::test]
async fn direct_pending_limit_releases_on_completion_or_dropped_future() {
let (_, turn) = crate::session::tests::make_session_and_context().await;
let step = StepContext::for_test(Arc::new(turn));
let mut features = Features::default();
features.enable(Feature::ExecutedToolCallMetadata);
let recorder = ExecutedToolCalls::new(&features, &InitialHistory::New);
let call = ToolCall {
tool_name: codex_tools::ToolName::plain("test_tool"),
call_id: "direct".to_string(),
payload: ToolPayload::Function {
arguments: json!({ "argument": "kept" }).to_string(),
},
encrypted_function_args: None,
};
let prepare = |recorder: &ExecutedToolCalls| {
recorder.prepare_direct_call(&call, &ToolCallSource::Direct, &step)
};
let mut pending = (0..MAX_PENDING_EXECUTED_TOOL_CALLS)
.map(|_| prepare(&recorder).expect("metadata slot"))
.collect::<Vec<_>>();
let cloned = recorder.clone();
let mut overflow = output("overflow");
let before = serde_json::to_value(&overflow).expect("serializable output");
cloned.attach_direct_call_to_output(&mut overflow, prepare(&cloned));
assert_eq!(
serde_json::to_value(&overflow).expect("serializable output"),
before,
);
let canceled = pending.pop().expect("pending call");
let unpolled = async move {
std::future::pending::<()>().await;
drop(canceled);
};
assert!(prepare(&cloned).is_none());
drop(unpolled);
let replacement = prepare(&cloned).expect("dropped future released its slot");
assert!(prepare(&recorder).is_none());
let mut completed = output("completed");
recorder.attach_direct_call_to_output(&mut completed, pending.pop());
assert_eq!(
completed
.executed_tool_call_metadata()
.and_then(|metadata| metadata.tool_calls_complete),
Some(true),
);
let after_completion = prepare(&recorder).expect("completion released its slot");
recorder.refresh(&Features::default());
recorder.refresh(&features);
assert!(prepare(&recorder).is_none());
let mut stale = output("stale");
recorder.attach_direct_call_to_output(&mut stale, Some(replacement));
assert!(stale.executed_tool_call_metadata().is_none());
let current = prepare(&recorder).expect("stale call released its slot");
let mut current_output = output("current");
recorder.attach_direct_call_to_output(&mut current_output, Some(current));
assert_eq!(
current_output
.executed_tool_call_metadata()
.and_then(|metadata| metadata.tool_calls_complete),
Some(true),
);
drop(pending);
drop(after_completion);
assert_eq!(recorder.pending_direct_calls.load(Ordering::Relaxed), 0);
}
#[tokio::test]
async fn direct_budget_counts_the_encoded_argument_before_it_enters_history() {
let (_, turn) = crate::session::tests::make_session_and_context().await;
let step = StepContext::for_test(Arc::new(turn));
let mut features = Features::default();
features.enable(Feature::ExecutedToolCallMetadata);
let recorder = ExecutedToolCalls::new(&features, &InitialHistory::New);
let invalid_json = "\"".repeat(5_000);
let wire_bytes = serialized_json_bytes(&JsonValue::String(invalid_json.clone())).unwrap();
assert!(invalid_json.len() < MAX_EXECUTED_TOOL_CALL_ARGUMENT_BYTES);
assert!(wire_bytes > MAX_EXECUTED_TOOL_CALL_ARGUMENT_BYTES);
let call = ToolCall {
tool_name: codex_tools::ToolName::plain("test_tool"),
call_id: "direct".to_string(),
payload: ToolPayload::Function {
arguments: invalid_json,
},
encrypted_function_args: None,
};
let mut item = output("direct");
let ordinary_output = serde_json::to_value(&item).unwrap()["output"].clone();
recorder.attach_direct_call_to_output(
&mut item,
recorder.prepare_direct_call(&call, &ToolCallSource::Direct, &step),
);
let wire = serde_json::to_value(&item).unwrap();
assert_eq!(wire["output"], ordinary_output);
let metadata = &wire["internal_chat_message_metadata_passthrough"];
let arguments = &metadata["executed_tool_calls"][0]["arguments"];
assert!(serialized_json_bytes(arguments).unwrap() < MAX_EXECUTED_TOOL_CALL_ARGUMENT_BYTES);
assert_eq!(
arguments["_codex_executed_tool_call_truncated"]["original_bytes"],
wire_bytes,
);
assert!(metadata.get("tool_calls_complete").is_none());
}
+12 -4
View File
@@ -748,7 +748,14 @@ mod tests {
})
);
// Reuse the direct invocation to catch recording placed after the Code Mode-only return.
// Nested MCP result metadata still reaches the owning Code Mode cell.
let cell_id = codex_code_mode::CellId::new("mcp-cell".to_string());
recorder.start_cell(&cell_id, "exec-mcp-post");
let mut invocation = invocation;
invocation.source = ToolCallSource::CodeMode {
cell_id: cell_id.as_str().to_string(),
runtime_tool_call_id: "mcp-runtime-call".to_string(),
};
let mut output = output;
output.result.meta = Some(json!({ "provider/custom": { "items": [1, null] } }));
output.result_metadata_capture_allowed = true;
@@ -763,9 +770,10 @@ mod tests {
&invocation.step_context,
);
handler.on_tool_result_accepted(&invocation, &output);
let mut items = [codex_protocol::models::ResponseItem::from(
output.to_response_item(&invocation.call_id, &invocation.payload),
)];
let mut items = [serde_json::from_value(json!({
"type": "custom_tool_call_output", "call_id": "exec-mcp-post", "output": "notes",
}))
.expect("Code Mode output")];
recorder.attach_to_prompt(&mut items, &mut Default::default());
assert_eq!(
serde_json::to_value(items[0].executed_tool_call_metadata()).unwrap()["executed_tool_calls"],
+22 -7
View File
@@ -29,6 +29,7 @@ use crate::tools::router::ToolCallSource;
use codex_history::ResponseItemEnvelope;
use codex_protocol::error::CodexErr;
use codex_protocol::models::ResponseInputItem;
use codex_protocol::models::ToolResultMetadata;
struct ToolCallTimingGuard {
started_at: Instant,
@@ -79,17 +80,31 @@ impl ToolCallRuntime {
) -> impl std::future::Future<Output = Result<ResponseItemEnvelope, CodexErr>> {
let error_call = call.clone();
let source = call.direct_source();
let recorder = self.session.services.executed_tool_calls.clone();
let recorded_call = recorder.prepare_direct_call(&call, &source, &self.step_context);
let step_context = Arc::clone(&self.step_context);
let future =
self.handle_tool_call_with_source(step_context, call, source, cancellation_token);
async move {
match future.await {
Ok(response) => Ok(response.into_response()),
Err(FunctionCallError::Fatal(message)) => Err(CodexErr::Fatal(message)),
Err(other) => Ok(ResponseItemEnvelope::new(
Self::failure_response(error_call, other).into(),
)),
}
let result = future.await;
let mut recorded_call =
recorded_call.filter(|(_, recording)| recording.strong_count() > 0);
let mut response = match result {
Ok(result) => {
if let Some((call, _)) = recorded_call.as_mut()
&& let Some(metadata) = result.result.tool_result_metadata()
{
call.set_tool_result_metadata(ToolResultMetadata::new(metadata));
}
result.into_response()
}
Err(FunctionCallError::Fatal(message)) => return Err(CodexErr::Fatal(message)),
Err(other) => {
ResponseItemEnvelope::new(Self::failure_response(error_call, other).into())
}
};
recorder.attach_direct_call_to_output(&mut response.item, recorded_call);
Ok(response)
}
}