Track additional context in conversation world state (#63769)

## Why

The baseline for comparing additional context submissions lived in memory,
so resuming a conversation could append context that was already in its
history.

## What changed

Persist the rendered fingerprints and history item IDs for active context
entries in world state. Reuse unchanged entries across turns and resumes,
and use their IDs to restore active items during compaction.

A client submission replaces the active set. Tool-provided context updates
only its own keys and is recorded after tool results, before the next
prompt.

## Testing

Extend scenario coverage to check deduplication after resume for both
message and tool-output rendering. Verify that edits in the truncated
portion of application context do not produce duplicate developer messages.

GitOrigin-RevId: 12a65a70d871f8dcefa082825c0ec4e9446efb56
This commit is contained in:
Dylan Hurd
2026-11-24 23:55:40 +00:00
committed by copyberry
parent bc6728ef68
commit ff2ee6212c
20 changed files with 433 additions and 459 deletions
@@ -51,11 +51,11 @@ impl<'a> PrefixCompactionInstallation<'a> {
let current = state.history.annotated_items();
let (replaced, suffix) = current.split_at(self.prefix.len);
let mut initial_context = self.initial_context;
initial_context.extend(
state
.additional_context
.restore_compacted_items(replaced, &mut items),
);
// The unchanged suffix already contains updates through this baseline.
if let Some(previous) = state.history.world_state_baseline() {
world_state_baseline = previous.clone();
}
initial_context.extend(world_state_baseline.restore_input_context(replaced, &mut items));
if suffix.iter().any(|envelope| {
crate::compact_retained_tool_outputs::is_retained_tool_output(envelope)
|| compact::is_real_user_or_agent_message(&envelope.item)
@@ -74,10 +74,6 @@ impl<'a> PrefixCompactionInstallation<'a> {
.map(ResponseItemEnvelope::new),
);
items.extend_from_slice(suffix);
// The unchanged suffix already contains updates through this baseline.
if let Some(checkpoint) = state.history.world_state_checkpoint() {
world_state_baseline = WorldStateSnapshot::from(&checkpoint.state);
}
// Volatile sections must refresh in the new window even if their
// previous messages and comparison state survived in the suffix.
for section_id in self.reset_world_state_sections {
+17 -9
View File
@@ -39,7 +39,6 @@ use crate::context::world_state::Placement;
use crate::context::world_state::WorldState;
use crate::context::world_state::WorldStateSnapshot;
use crate::context::world_state::WorldStateUpdate;
use crate::context::world_state::WorldStateUpdateContent;
use crate::context::world_state::split_prefix_updates;
use crate::current_time::TimeProvider;
use crate::environment_selection::TurnEnvironmentSnapshot;
@@ -4428,6 +4427,16 @@ impl Session {
.await;
}
self.commit_world_state(world_state_snapshot, world_state_item)
.await;
Ok(Arc::new(world_state))
}
async fn commit_world_state(
&self,
world_state_snapshot: WorldStateSnapshot,
world_state_item: Option<WorldStateItem>,
) {
self.state
.lock()
.await
@@ -4438,7 +4447,6 @@ impl Session {
self.persist_rollout_items(&[RolloutItem::WorldState(world_state_item)])
.await;
}
Ok(Arc::new(world_state))
}
/// Retains the step captured for execution.
@@ -5082,9 +5090,12 @@ impl Session {
matches!(&installation, CompactedHistoryInstallation::Complete(..));
let replacement = match installation {
CompactedHistoryInstallation::Complete(metadata, _) => {
let context = state
.additional_context
.restore_compacted_items(state.history.annotated_items(), &mut items);
let mut world_state_baseline = world_state_baseline;
if let Some(previous) = state.history.world_state_baseline() {
world_state_baseline.retain_input_context(previous);
}
let context = world_state_baseline
.restore_input_context(state.history.annotated_items(), &mut items);
if !context.is_empty() {
items = compact::insert_initial_context_before_last_real_user_or_summary(
items, context,
@@ -5594,10 +5605,7 @@ impl Session {
let updates = prefix
.into_iter()
.map(WorldStateUpdate::prefix_item)
.chain(items.into_iter().map(|item| WorldStateUpdate {
placement: Placement::Standalone,
content: WorldStateUpdateContent::Item(Box::new(item)),
}))
.chain(items.into_iter().map(WorldStateUpdate::item))
.collect();
(updates, snapshot)
}
+17 -19
View File
@@ -19,6 +19,7 @@ use crate::compact_remote_v2::run_inline_remote_auto_compact_task as run_inline_
use crate::connectors;
use crate::context::ContextualUserFragment;
use crate::context::UserVerificationNotice;
use crate::context::world_state::AdditionalContextState;
use crate::context_manager::rejected_audio;
use crate::cyber_access_program;
use crate::environment_selection::TurnEnvironmentSnapshot;
@@ -1178,6 +1179,15 @@ pub(crate) async fn run_hooks_and_record_input_entries(
pending_input: &[InputQueueEntry],
persist_context: PersistContext,
) -> CodexResult<bool> {
if let Some(pending) = turn_context.extension_data.get::<PendingToolContext>()
&& can_record_input(sess)
{
let sections = std::mem::take(&mut *pending.lock().await);
for section in sections {
sess.record_input_world_state(turn_context, model_info, section)
.await;
}
}
// A started turn owns one initial submission; consume its context exactly once.
let initial_context = turn_context
.extension_data
@@ -1261,30 +1271,18 @@ pub(crate) async fn record_delivered_additional_context(
model_info: &ModelInfo,
context: &SubmittedAdditionalContext,
) {
let items = merge_submitted_context(sess, turn_context, context).await;
if !items.is_empty() {
sess.record_annotated_conversation_items(turn_context, model_info, items)
.await;
}
}
pub(crate) async fn merge_submitted_context(
sess: &Session,
turn_context: &TurnContext,
context: &SubmittedAdditionalContext,
) -> Vec<ResponseItemEnvelope> {
let items = sess.state.lock().await.additional_context.merge(
context.0.clone(),
sess.additional_context_format(),
let section = AdditionalContextState::new(
&context.0,
sess.enabled(Feature::UntrustedAsToolOutput),
&turn_context.session_telemetry,
&sess.context_ids,
);
items
.into_iter()
.map(|item| sess.annotate_client_response_item(item))
.collect()
sess.record_input_world_state(turn_context, model_info, section)
.await;
}
pub(super) type PendingToolContext = tokio::sync::Mutex<Vec<AdditionalContextState>>;
/// Yields usable input with its context in order, then reports unsupported audio after valid siblings can be recorded.
pub(crate) fn recordable_inputs<'a>(
sess: &Session,
+13 -21
View File
@@ -28,8 +28,8 @@ use crate::WithTurnExtensionData;
use crate::agent::helper_daybreak::turn::HelperTurnAdmission;
use crate::context::ContextualUserFragment;
use crate::context::GuardianSenderMessages;
use crate::context::world_state::AdditionalContextState;
use crate::state::ActiveTurn;
use crate::state::AdditionalContextFormat;
use crate::state::TurnState;
use crate::tasks::RegularTask;
use codex_features::Feature;
@@ -870,31 +870,23 @@ impl Session {
else {
return;
};
let input = self.state.lock().await.additional_context.extend(
BTreeMap::from([(
let section = AdditionalContextState::new(
&BTreeMap::from([(
key.to_owned(),
AdditionalContextEntry::new(value, AdditionalContextKind::Untrusted),
)]),
self.additional_context_format(),
self.enabled(Feature::UntrustedAsToolOutput),
&task.turn_context.session_telemetry,
&self.context_ids,
);
if !input.is_empty() {
self.input_queue
.extend_pending_input_for_turn_state(
&turn.turn_state,
input.into_iter().map(TurnInput::ResponseItem).collect(),
)
.await;
}
}
pub(super) fn additional_context_format(&self) -> AdditionalContextFormat {
if self.enabled(Feature::UntrustedAsToolOutput) {
AdditionalContextFormat::ToolOutputs
} else {
AdditionalContextFormat::Messages
}
)
.extending();
// Tool-produced context belongs after tool results and before the next prompt.
task.turn_context
.extension_data
.get_or_init(super::turn::PendingToolContext::default)
.lock()
.await
.push(section);
}
/// Called under the active-turn lock when registering a task (or a realtime transcript turn).
+36
View File
@@ -8,6 +8,7 @@ use crate::agent::host::AgentRuntimeServices;
use crate::agent::host::AgentSessionReader;
use crate::connectors;
use crate::context::TokenBudgetContext;
use crate::context::world_state::AdditionalContextState;
use crate::context::world_state::AgentsMdState;
use crate::context::world_state::AppsInstructionsState;
use crate::context::world_state::CollaborationModeState;
@@ -34,6 +35,7 @@ use codex_connectors::AppToolPolicyEvaluator;
use codex_extension_api::WorldStateContributionInput;
use codex_features::Feature;
use codex_file_system::FileSystemSandboxContext;
use codex_history::ResponseItemEnvelope;
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
use codex_prompts::ApprovalPromptContext;
use codex_prompts::ResolvedModelMessages;
@@ -41,11 +43,45 @@ use codex_prompts::render_model_instructions;
use codex_protocol::error::Result as CodexResult;
use codex_protocol::models::BaseInstructionsProvenance;
use codex_protocol::models::ContentItemNamespace;
use codex_protocol::models::ResponseItem;
use codex_protocol::openai_models::ModelInfo;
use codex_protocol::protocol::MultiAgentVersion;
use codex_tools::ToolName;
use codex_tools::ToolSpec;
impl Session {
pub(super) async fn record_input_world_state(
&self,
turn_context: &TurnContext,
model_info: &ModelInfo,
section: AdditionalContextState,
) {
let (snapshot, updates, patch) = self
.state
.lock()
.await
.history
.render_input_world_state(section);
let items = crate::context_manager::updates::merge_world_state_updates(updates)
.into_iter()
.map(|item| {
let mut envelope = ResponseItemEnvelope::new(item);
if matches!(envelope.item, ResponseItem::FunctionCallOutput { .. }) {
envelope
.metadata
.get_or_insert_default()
.additional_context_tool_output = true;
}
self.annotate_client_response_item(envelope)
})
.collect::<Vec<_>>();
if !items.is_empty() {
self.record_annotated_conversation_items(turn_context, model_info, items)
.await;
}
self.commit_world_state(snapshot, patch).await;
}
pub(super) fn host_roster_reader(
&self,
turn_context: &TurnContext,