Honor Guardian retention settings for assistant messages (#62828)

## Why

The fixed retention window can discard assistant messages before elastic
Guardian reviews can use them as context for a user's reply.

## What changed

Apply the thread's Guardian retention policy when recording assistant messages,
including confirmed messages sent through the user messaging tool. Keep full
text within the configured record limit and the overall assistant history byte
budget. Preserve an incomplete marker when a confirmed delivery exceeds the
record limit.

Recover the thread's retention settings from saved history and compaction
checkpoints. Fixed-budget reviews continue to use the fixed retention window.

## Testing

Add coverage for record limits during capture and restore, thread-owned
settings recovery, and replay of oversized confirmed deliveries.

GitOrigin-RevId: e828f06824ce6712910a9cc5ef42a438d1ddf27e
This commit is contained in:
ioanbudea-OAI
2026-11-20 20:10:51 +00:00
committed by copyberry
parent 7fcb825b46
commit ab7a93771e
33 changed files with 608 additions and 122 deletions
@@ -12,7 +12,7 @@ use pretty_assertions::assert_eq;
#[test]
fn history_sums_measured_and_unknown_file_audio() {
let mut history = ContextManager::new(thread_context_ids());
let mut history = ContextManager::new(thread_context_ids(), /*retention*/ None);
let item = ResponseInputItem::Message {
role: "user".to_string(),
content: ["short", "unknown"]
@@ -119,7 +119,7 @@ async fn producer_bounded_audio_keeps_the_same_parts_as_inline_history() {
)
.unwrap();
codex_utils_audio::prepare_response_items(std::slice::from_mut(&mut inline));
let mut history = ContextManager::new(thread_context_ids());
let mut history = ContextManager::new(thread_context_ids(), /*retention*/ None);
history.record_items([&inline], policy);
let expected =
serde_json::to_value(history.raw_items().last().unwrap()).unwrap()["output"].take();
@@ -41,6 +41,7 @@ async fn guardian_checkpoint_preserves_live_context_without_storage(
/*reuse_parent_compaction*/ true,
codex_guardian_context::ContextBudgeting::Fixed,
thread_context_ids(),
/*retention*/ None,
);
state
.history
@@ -115,6 +116,7 @@ async fn guardian_checkpoint_preserves_live_context_without_storage(
/*reuse_parent_compaction*/ true,
codex_guardian_context::ContextBudgeting::Fixed,
thread_context_ids(),
/*retention*/ None,
);
fork.record_initial_history(InitialHistory::Forked(items))
.await;
+13 -1
View File
@@ -196,7 +196,7 @@ impl Session {
/// Starts recording confirmed delivery synchronously while the tool's admission is held.
pub(crate) fn record_delivered_assistant_message(
self: &Arc<Self>,
message: RetainedUserMessage,
mut message: RetainedUserMessage,
) -> (JoinHandle<()>, watch::Receiver<()>) {
let session = Arc::clone(self);
let persistence_session = Arc::clone(self);
@@ -208,6 +208,18 @@ impl Session {
.await
.unwrap_or_else(|_| unreachable!("communication boundary remains open"));
let mut state = session.state.lock().await;
if !state
.history
.retained_context()
.retains_original_assistant_messages()
{
let (text, truncated) = crate::guardian::guardian_truncate_text(
&message.text,
crate::guardian::GUARDIAN_MAX_ROOT_MESSAGE_TOKENS,
);
message.text = text;
message.complete &= !truncated;
}
let mut event = RetainedContextEvent::DeliveredAssistantMessage {
message,
retained_source: None,
@@ -193,6 +193,16 @@ impl Session {
turn_context: &TurnContext,
rollout_items: &[RolloutItem],
) -> RolloutReconstruction {
let policy = self
.state
.lock()
.await
.session_configuration
.guardian_retention;
let retention = policy.map(|policy| codex_history::MessageRetention {
thread_id: self.thread_id(),
policy,
});
ContextManager::reconstruct_rollout(
rollout_items,
turn_context.history_mode,
@@ -203,6 +213,7 @@ impl Session {
turn_context.config.guardian_reuses_parent_compaction(),
turn_context.config.guardian_context_budgeting(),
ids,
retention,
)
},
turn_context.model_info().truncation_policy.into(),
@@ -132,6 +132,7 @@ async fn sender_context_follows_its_delivery_through_checkpoint_and_rollback() {
/*reuse_parent_compaction*/ true,
codex_guardian_context::ContextBudgeting::Fixed,
thread_context_ids(),
/*retention*/ None,
);
let mut items = Vec::new();
let mut snapshots = Vec::new();
+4
View File
@@ -1298,6 +1298,9 @@ impl Session {
error!("failed to initialize thread persistence: {e:#}");
e
})?;
let retention = session_configuration
.guardian_retention
.map(|policy| codex_history::MessageRetention { thread_id, policy });
// Keep the large initialization future out of callers' stack frames.
let session_result: anyhow::Result<Arc<Self>> = Box::pin(async {
if let InitialHistory::Resumed(resumed) = &mut initial_history {
@@ -1618,6 +1621,7 @@ impl Session {
config.guardian_reuses_parent_compaction(),
config.guardian_context_budgeting(),
context_ids.clone(),
retention,
),
);
if matches!(initial_history, InitialHistory::Resumed(_)) {
+2
View File
@@ -6636,6 +6636,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) {
config.guardian_reuses_parent_compaction(),
config.guardian_context_budgeting(),
context_ids.clone(),
/*retention*/ None,
);
let (environment_manager, resolved_environments) =
resolved_environments_for_configuration(&session_configuration, &default_environments)
@@ -9001,6 +9002,7 @@ where
config.guardian_reuses_parent_compaction(),
config.guardian_context_budgeting(),
context_ids.clone(),
/*retention*/ None,
);
let (environment_manager, resolved_turn_environments) =
resolved_environments_for_configuration(&session_configuration, &default_environments)