Restore token usage after compaction on paginated thread resume (#65035)

## Why

A compaction checkpoint can leave the turn's `TurnStarted` event outside
the replay window. When `thread/resume` excludes turns, the app server
can then miss the turn ID and omit the saved token usage update.

## What changed

Fall back to the latest saved `TurnContext` in the active turn when
that turn starts at a compaction checkpoint. Use its turn ID to replay
the saved `thread/tokenUsage/updated` notification.

## Testing

Extend cold resume tests to check the turn ID, total and last token
counts, and context window after compaction. Cover a rollback that
leaves the usage owner unknown and verify that replay is skipped.

GitOrigin-RevId: 4ea4f5e7a561fbba00fbe6b063f632a23193bc5a
This commit is contained in:
Eric Traut
2026-12-01 16:53:34 +00:00
committed by copyberry
parent 949cdb56ef
commit 214b9007dd
2 changed files with 56 additions and 4 deletions
@@ -89,7 +89,20 @@ fn latest_token_usage_turn_id_from_rollout_items(
}
if turns.is_empty() {
return builder.active_turn_id_if_explicit();
return builder.active_turn_id_if_explicit().or_else(|| {
// A compaction checkpoint can cut off TurnStarted. Only trust a
// saved context from the turn that owns this count.
let start = builder.active_turn_start_index()?;
let [RolloutItem::Compacted(_), rest @ ..] = &rollout_items[start..token_count_index]
else {
return None;
};
let context = rest.iter().rev().find_map(|item| match item {
RolloutItem::TurnContext(context) => Some(context),
_ => None,
})?;
context.turn_id.clone()
});
}
let active_turn_id = builder.active_turn_id()?;
@@ -115,6 +115,7 @@ use codex_protocol::protocol::SessionMeta;
use codex_protocol::protocol::SessionMetaLine;
use codex_protocol::protocol::SessionSource as RolloutSessionSource;
use codex_protocol::protocol::SubAgentSource;
use codex_protocol::protocol::ThreadRolledBackEvent;
use codex_protocol::protocol::ThreadSettingsAppliedEvent;
use codex_protocol::protocol::TokenCountEvent;
use codex_protocol::protocol::TokenUsage;
@@ -4711,8 +4712,27 @@ async fn thread_resume_emits_restored_token_usage_before_next_turn() -> Result<(
Ok(())
}
async fn append_compaction_with_context(path: &Path, cwd: &Path, turn_id: &str) -> Result<()> {
let checkpoint = serde_json::from_value(json!({
"message": "summary", "replacement_history": [], "window_number": 1,
}))?;
append_rollout_item_to_path(path, &RolloutItem::Compacted(checkpoint)).await?;
let context = serde_json::from_value(json!({
"turn_id": turn_id,
"cwd": cwd,
"approval_policy": "never",
"sandbox_policy": {"type": "read-only"},
"model": "gpt-5.4",
"summary": "auto",
}))?;
append_rollout_item_to_path(path, &RolloutItem::TurnContext(context)).await?;
Ok(())
}
#[test_case(false; "explicit turn start")]
#[test_case(true; "compaction inside the last turn")]
#[tokio::test]
async fn cold_paginated_resume_restores_usage_without_loading_turns() -> Result<()> {
async fn cold_paginated_resume_restores_usage_without_loading_turns(compacted: bool) -> Result<()> {
let server = create_mock_responses_server_repeating_assistant("Done").await;
let codex_home = TempDir::new()?;
mock_responses_config(&server.uri()).write(codex_home.path())?;
@@ -4739,6 +4759,9 @@ async fn cold_paginated_resume_restores_usage_without_loading_turns() -> Result<
})),
)
.await?;
if compacted {
append_compaction_with_context(&path, codex_home.path(), canonical_turn_id).await?;
}
append_rollout_item_to_path(
&path,
&RolloutItem::EventMsg(EventMsg::TokenCount(TokenCountEvent {
@@ -4789,6 +4812,8 @@ async fn cold_paginated_resume_restores_usage_without_loading_turns() -> Result<
assert_eq!(notification.thread_id, thread.id);
assert_eq!(notification.turn_id, canonical_turn_id);
assert_eq!(notification.token_usage.total.total_tokens, 150);
assert_eq!(notification.token_usage.last.total_tokens, 90);
assert_eq!(notification.token_usage.model_context_window, Some(200_000));
let turns_id = app_server
.send_thread_turns_list_request(ThreadTurnsListParams {
@@ -4838,8 +4863,12 @@ async fn cold_paginated_resume_restores_usage_without_loading_turns() -> Result<
Ok(())
}
#[test_case(false; "implicit turn")]
#[test_case(true; "rolled back compacted turn")]
#[tokio::test]
async fn cold_paginated_resume_omits_usage_when_its_turn_is_ambiguous() -> Result<()> {
async fn cold_paginated_resume_omits_usage_when_its_turn_is_ambiguous(
rolled_back: bool,
) -> Result<()> {
let server = create_mock_responses_server_repeating_assistant("Done").await;
let codex_home = TempDir::new()?;
mock_responses_config(&server.uri()).write(codex_home.path())?;
@@ -4853,6 +4882,16 @@ async fn cold_paginated_resume_omits_usage_when_its_turn_is_ambiguous() -> Resul
/*git_info*/ None,
)?;
let path = rollout_path(codex_home.path(), filename_ts, &conversation_id);
if rolled_back {
append_compaction_with_context(&path, codex_home.path(), "rolled-back-turn").await?;
append_rollout_item_to_path(
&path,
&RolloutItem::EventMsg(EventMsg::ThreadRolledBack(ThreadRolledBackEvent {
num_turns: 1,
})),
)
.await?;
}
append_rollout_item_to_path(
&path,
&RolloutItem::EventMsg(EventMsg::TokenCount(TokenCountEvent {
@@ -4920,7 +4959,7 @@ async fn cold_paginated_resume_omits_usage_when_its_turn_is_ambiguous() -> Resul
)
.await
.is_err(),
"usage owned by an implicit turn must not be attributed to {interrupted_turn_id}"
"usage with no known owner must not be replayed"
);
Ok(())