mirror of
https://github.com/openai/codex.git
synced 2026-11-26 23:40:43 +00:00
Retain client-marked tool outputs across compaction (#52937)
## Why Client-supplied tool outputs can carry task instructions. Even when marked with `retain: true`, these instructions could be trimmed before compaction and disappear from the compacted history. ## What changed Add the disabled-by-default `retain_client_tool_outputs` feature to honor retention for explicitly marked, named `function_call_output` items without a `call_id`. - Preserve eligible outputs in remote compaction v2 and when starting a new context window, keeping their original role. - Stop emergency tool-output trimming at a retained output. - Share the existing 64,000-token retention budget, keeping outputs whole and dropping an oversized output and older items rather than partially truncating it. - Place initial context before retained standalone outputs and account for their images in retained-image counts. ## Testing Add a scenario covering enabled and disabled retention, emergency trimming, oversized-output handling, and preservation of the latest instruction after compaction and cold resume. Verify that retention annotations stay out of model requests. GitOrigin-RevId: 449179670e4d2be2623928700738758e43b5dc1a
This commit is contained in:
@@ -606,7 +606,7 @@ pub(crate) fn is_summary_message(message: &str) -> bool {
|
||||
/// model-expected boundary.
|
||||
///
|
||||
/// Placement rules:
|
||||
/// - Prefer immediately before the last real user or agent message.
|
||||
/// - Prefer immediately before the last real user, agent message, or retained standalone output.
|
||||
/// - If no real user messages remain, insert before the compaction summary so
|
||||
/// the summary stays last.
|
||||
/// - If there are no user messages, insert before the last compaction item so
|
||||
@@ -619,6 +619,10 @@ pub(crate) fn insert_initial_context_before_last_real_user_or_summary(
|
||||
let mut last_user_or_summary_index = None;
|
||||
let mut last_real_user_index = None;
|
||||
for (i, item) in compacted_history.iter().enumerate().rev() {
|
||||
if crate::compact_retained_tool_outputs::is_retained_tool_output(item) {
|
||||
last_real_user_index = Some(i);
|
||||
break;
|
||||
}
|
||||
if let ResponseItem::AgentMessage { content, .. } = &item.item
|
||||
&& !matches!(
|
||||
content.first(),
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
use std::borrow::Borrow;
|
||||
|
||||
use crate::compact_retained_tool_outputs::is_retained_tool_output;
|
||||
use crate::context::ContextualUserFragment;
|
||||
use crate::context::ImageResizeNotice;
|
||||
use crate::context_manager::ContextManager;
|
||||
use crate::context_manager::estimate_item_token_count;
|
||||
use crate::session::turn_context::TurnContext;
|
||||
use codex_features::Feature;
|
||||
use codex_history::ResponseItemEnvelope;
|
||||
use codex_protocol::models::BaseInstructions;
|
||||
use codex_protocol::models::ContentItem;
|
||||
@@ -97,10 +99,19 @@ pub(crate) fn trim_function_call_history_to_fit_context_window(
|
||||
let source_index = original_items
|
||||
.len()
|
||||
.saturating_sub(consumed_items.saturating_add(group_item_count));
|
||||
let Some(rewritten_item) = original_items
|
||||
.get(source_index)
|
||||
.and_then(rewritten_output_for_context_window)
|
||||
else {
|
||||
let Some(rewritten_item) = original_items.get(source_index).and_then(|envelope| {
|
||||
if turn_context
|
||||
.config
|
||||
.features
|
||||
.enabled(Feature::RetainClientToolOutputs)
|
||||
&& is_retained_tool_output(envelope)
|
||||
{
|
||||
// Enabled retained outputs form the same boundary as user/developer messages.
|
||||
None
|
||||
} else {
|
||||
rewritten_output_for_context_window(envelope)
|
||||
}
|
||||
}) else {
|
||||
break;
|
||||
};
|
||||
estimated_tokens = estimated_tokens
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::compact_retained_tool_outputs::is_retained_tool_output;
|
||||
|
||||
use crate::Prompt;
|
||||
use crate::ResponseStream;
|
||||
use crate::client::ModelClientSession;
|
||||
@@ -35,6 +37,7 @@ use codex_analytics::CompactionTrigger;
|
||||
use codex_context_fragments::set_annotated_content;
|
||||
use codex_context_fragments::to_annotated_content;
|
||||
use codex_features::Feature;
|
||||
use codex_features::Features;
|
||||
use codex_history::CodexHarnessMetadata;
|
||||
use codex_history::ResponseItemEnvelope;
|
||||
use codex_protocol::error::CodexErr;
|
||||
@@ -44,6 +47,8 @@ use codex_protocol::items::ContextCompactionItem;
|
||||
use codex_protocol::items::TurnItem;
|
||||
use codex_protocol::models::AgentMessageInputContent;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::FunctionCallOutputBody;
|
||||
use codex_protocol::models::FunctionCallOutputContentItem;
|
||||
#[cfg(test)]
|
||||
use codex_protocol::models::ImageReference;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
@@ -303,7 +308,7 @@ async fn run_remote_compact_task_inner_impl(
|
||||
prompt_input,
|
||||
prompt_input_metadata,
|
||||
compaction_output,
|
||||
sess.enabled(Feature::RetainClientDeveloperMessages),
|
||||
sess.features().get(),
|
||||
if sess.enabled(Feature::CompactionImageBudget) {
|
||||
RetainedImageBudget::Enabled
|
||||
} else {
|
||||
@@ -495,7 +500,7 @@ fn build_v2_compacted_history(
|
||||
prompt_input: Vec<ResponseItem>,
|
||||
prompt_input_metadata: Vec<Option<CodexHarnessMetadata>>,
|
||||
compaction_output: ResponseItem,
|
||||
retain_client_developer_messages: bool,
|
||||
features: &Features,
|
||||
image_budget: RetainedImageBudget,
|
||||
) -> (Vec<ResponseItemEnvelope>, usize) {
|
||||
debug_assert_eq!(prompt_input.len(), prompt_input_metadata.len());
|
||||
@@ -505,9 +510,7 @@ fn build_v2_compacted_history(
|
||||
.map(|(item, metadata)| ResponseItemEnvelope { item, metadata })
|
||||
.collect::<Vec<_>>();
|
||||
let retained = v2_history_item_groups(prompt_input)
|
||||
.filter(|group| {
|
||||
is_retained_for_remote_compaction_v2(&group.source, retain_client_developer_messages)
|
||||
})
|
||||
.filter(|group| is_retained_for_remote_compaction_v2(&group.source, features))
|
||||
.flat_map(HistoryItemGroup::into_items)
|
||||
.collect::<Vec<_>>();
|
||||
let mut retained =
|
||||
@@ -544,8 +547,11 @@ fn v2_history_item_groups(
|
||||
|
||||
fn is_retained_for_remote_compaction_v2(
|
||||
envelope: &ResponseItemEnvelope,
|
||||
retain_client_developer_messages: bool,
|
||||
features: &Features,
|
||||
) -> bool {
|
||||
if features.enabled(Feature::RetainClientToolOutputs) && is_retained_tool_output(envelope) {
|
||||
return true;
|
||||
}
|
||||
let item = &envelope.item;
|
||||
if let ResponseItem::AgentMessage {
|
||||
author,
|
||||
@@ -583,13 +589,22 @@ fn is_retained_for_remote_compaction_v2(
|
||||
Some(TurnItem::UserMessage(_) | TurnItem::HookPrompt(_))
|
||||
),
|
||||
"developer" => {
|
||||
retain_client_developer_messages && is_client_authored_developer_message(envelope)
|
||||
features.enabled(Feature::RetainClientDeveloperMessages)
|
||||
&& is_client_authored_developer_message(envelope)
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn retained_input_image_count(item: &ResponseItem) -> usize {
|
||||
if let ResponseItem::FunctionCallOutput { output, .. } = item
|
||||
&& let FunctionCallOutputBody::ContentItems(content) = &output.body
|
||||
{
|
||||
return content
|
||||
.iter()
|
||||
.filter(|item| matches!(item, FunctionCallOutputContentItem::InputImage { .. }))
|
||||
.count();
|
||||
}
|
||||
let ResponseItem::Message { content, .. } = item else {
|
||||
return 0;
|
||||
};
|
||||
@@ -648,6 +663,9 @@ fn truncate_retained_messages(
|
||||
}
|
||||
truncated_reversed.push(group.source);
|
||||
remaining = remaining.saturating_sub(token_count);
|
||||
} else if is_retained_tool_output(&group.source) {
|
||||
// Keep outputs whole and stop before older items to preserve newest-first ordering.
|
||||
break;
|
||||
} else if remaining > notice_tokens {
|
||||
let available_tokens = remaining - notice_tokens;
|
||||
let content_budget = if client_developer {
|
||||
@@ -804,7 +822,7 @@ mod tests {
|
||||
input,
|
||||
metadata,
|
||||
output,
|
||||
/*retain_client_developer_messages*/ false,
|
||||
&Features::with_defaults(),
|
||||
RetainedImageBudget::Disabled,
|
||||
)
|
||||
}
|
||||
@@ -907,6 +925,10 @@ mod tests {
|
||||
};
|
||||
|
||||
for enabled in [false, true] {
|
||||
let mut features = Features::with_defaults();
|
||||
if enabled {
|
||||
features.enable(Feature::RetainClientDeveloperMessages);
|
||||
}
|
||||
let (history, _) = build_v2_compacted_history(
|
||||
vec![
|
||||
harness.clone(),
|
||||
@@ -924,7 +946,7 @@ mod tests {
|
||||
None,
|
||||
],
|
||||
output.clone(),
|
||||
enabled,
|
||||
&features,
|
||||
RetainedImageBudget::Disabled,
|
||||
);
|
||||
let mut expected = vec![
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
//! Retains explicitly marked, named function outputs that have no matching call.
|
||||
//! Outputs share the normal history token budget and are retained whole or dropped.
|
||||
|
||||
use codex_history::ResponseItemEnvelope;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
|
||||
pub(crate) fn is_retained_tool_output(envelope: &ResponseItemEnvelope) -> bool {
|
||||
envelope
|
||||
.metadata
|
||||
.as_ref()
|
||||
.is_some_and(|metadata| metadata.client_authored)
|
||||
&& matches!(
|
||||
envelope.item,
|
||||
ResponseItem::FunctionCallOutput {
|
||||
call_id: None,
|
||||
name: Some(_),
|
||||
..
|
||||
}
|
||||
)
|
||||
}
|
||||
@@ -36,6 +36,7 @@ pub use turn_extension_data::WithTurnExtensionData;
|
||||
mod compact_model_fallback;
|
||||
mod compact_remote_history;
|
||||
mod compact_remote_v2;
|
||||
mod compact_retained_tool_outputs;
|
||||
mod compact_token_budget;
|
||||
mod thread_startup_metadata;
|
||||
pub use codex_network_proxy::EnvironmentNetworkPolicy;
|
||||
|
||||
@@ -4663,22 +4663,23 @@ impl Session {
|
||||
let turn_context = step_context.turn.as_ref();
|
||||
let history = self.clone_history().await;
|
||||
let input_goal_ids = crate::context::UserGoalUpdate::message_ids(history.raw_items());
|
||||
let retained_client_developer_messages =
|
||||
if self.enabled(Feature::RetainClientDeveloperMessages) {
|
||||
crate::compact_remote_v2::truncate_retained_messages_for_remote_compaction(
|
||||
history
|
||||
.annotated_items()
|
||||
.iter()
|
||||
.filter(|item| {
|
||||
crate::compact_remote_v2::is_client_authored_developer_message(item)
|
||||
})
|
||||
.cloned()
|
||||
.collect(),
|
||||
crate::compact_remote_v2::RETAINED_MESSAGE_TOKEN_BUDGET,
|
||||
)
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let retained_client_items =
|
||||
crate::compact_remote_v2::truncate_retained_messages_for_remote_compaction(
|
||||
history
|
||||
.annotated_items()
|
||||
.iter()
|
||||
.filter(|item| {
|
||||
(self.enabled(Feature::RetainClientToolOutputs)
|
||||
&& crate::compact_retained_tool_outputs::is_retained_tool_output(item))
|
||||
|| (self.enabled(Feature::RetainClientDeveloperMessages)
|
||||
&& crate::compact_remote_v2::is_client_authored_developer_message(
|
||||
item,
|
||||
))
|
||||
})
|
||||
.cloned()
|
||||
.collect(),
|
||||
crate::compact_remote_v2::RETAINED_MESSAGE_TOKEN_BUDGET,
|
||||
);
|
||||
let window = {
|
||||
let mut state = self.state.lock().await;
|
||||
state.start_new_context_window()
|
||||
@@ -4691,7 +4692,7 @@ impl Session {
|
||||
crate::context_manager::updates::merge_world_state_updates(context_updates)
|
||||
.into_iter()
|
||||
.map(ResponseItemEnvelope::new)
|
||||
.chain(retained_client_developer_messages)
|
||||
.chain(retained_client_items)
|
||||
.collect();
|
||||
let turn_context_item = step_context.to_turn_context_item();
|
||||
self.replace_compacted_history(
|
||||
|
||||
Reference in New Issue
Block a user