Persist response token usage in rollout history (#41912)

## Why

Resumed threads need to continue per-turn and per-thread token totals without scanning arbitrarily far beyond the latest compaction checkpoint.

## What changed

- Add durable `TokenUsageRecord` rollout items with response, turn, thread, session, and root-turn attribution.
- Restore accumulated usage on resume and snapshot the latest record plus the compaction response ID in compaction checkpoints.
- Preserve root-turn lineage in persisted turn context, while ensuring forked child threads start with their own usage totals.

## Testing

- Cover usage accumulation across multiple responses and resumed turns.
- Cover local and remote compaction checkpoints, invalid remote compaction output, rollout reconstruction, and fork isolation.

GitOrigin-RevId: ef9e0c4a9102a08a2c382be4cdac68c84353c90a
This commit is contained in:
Owen Lin authored and copyberry committed 2026-08-31 21:15:38 +00:00
1 parent a7913390f7
commit 5f79a92e39
67 files changed
+932 -162

No files matched your search

+10
View File
@@ -21,6 +21,7 @@ use codex_protocol::protocol::SessionMetaLine;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::ThreadHistoryMode;
use codex_protocol::protocol::ThreadSource;
use codex_protocol::protocol::TokenUsageRecord;
use codex_protocol::protocol::TurnContextItem;
use codex_protocol::protocol::WorldStateItem;
use codex_protocol::realtime::RealtimeItem;
@@ -107,6 +108,7 @@ pub enum RolloutItem {
},
Compacted(CompactedItem),
TurnContext(TurnContextItem),
TokenUsageRecord(TokenUsageRecord),
WorldState(WorldStateItem),
SecurityRiskScore(SecurityRiskScore),
EventMsg(EventMsg),
@@ -157,6 +159,13 @@ pub struct CompactedItem {
pub first_window_id: Option<String>,
pub previous_window_id: Option<String>,
pub window_id: Option<String>,
/// Responses API ID for the model-backed compaction request, when one exists.
pub compaction_response_id: Option<String>,
/// Snapshot of the latest reachable token usage record when this compaction was written.
///
/// `thread/resume` can restore token usage totals from this field without scanning arbitrarily
/// far past the compaction.
pub latest_token_usage_record: Option<TokenUsageRecord>,
}
impl Serialize for CompactedItem {
@@ -423,6 +432,7 @@ fn multi_agent_version_from_items(
| RolloutItem::InterAgentCommunication(_)
| RolloutItem::InterAgentCommunicationMetadata { .. }
| RolloutItem::Compacted(_)
| RolloutItem::TokenUsageRecord(_)
| RolloutItem::WorldState(_)
| RolloutItem::SecurityRiskScore(_)
| RolloutItem::RealtimeItem(_)