Preserve harness metadata across conversation history (#38058)

## What changed

- Wrap response items with optional harness-owned metadata while keeping the persisted response payload shape backward compatible.
- Store compacted-history metadata in an aligned sidecar and reject malformed sidecars.
- Carry metadata through history normalization, compaction, resume, fork, truncation, migration, and rollout recording without sending it to model providers.

## Testing

- Cover legacy rollout compatibility, metadata serialization and validation, compaction retention, and resume/fork reconstruction.

GitOrigin-RevId: 17a6127c9048ff984cb4df4d97c0751a38c29f5f
This commit is contained in:
rka-oai authored and copyberry committed 2026-08-11 19:30:12 +00:00
1 parent 44d992c14e
commit 3a6f747d77
67 files changed
+2075 -655

No files matched your search

+53 -13
View File
@@ -284,6 +284,12 @@ async fn run_remote_compact_task_inner_impl(
replacement_history: &new_history,
});
}
// Legacy `/responses/compact` returns provider-normalized items without a stable link to their
// original envelopes, so it does not preserve harness metadata. Compaction-trigger/v2 does.
let new_history = new_history
.into_iter()
.map(ResponseItemEnvelope::new)
.collect();
sess.replace_compacted_history(
new_history,
reference_context_item,
@@ -307,6 +313,28 @@ pub(crate) async fn process_compacted_history(
compacted_history: Vec<ResponseItem>,
initial_context_injection: &InitialContextInjection,
) -> (Vec<ResponseItem>, Option<Arc<WorldState>>) {
let compacted_history = compacted_history
.into_iter()
.map(ResponseItemEnvelope::new)
.collect();
let (compacted_history, world_state_baseline) =
process_annotated_compacted_history(sess, compacted_history, initial_context_injection)
.await;
(
compacted_history
.into_iter()
.map(ResponseItemEnvelope::into_item)
.collect(),
world_state_baseline,
)
}
/// Installs already-annotated remote compaction output without dropping its metadata sidecar.
pub(crate) async fn process_annotated_compacted_history(
sess: &Session,
compacted_history: Vec<ResponseItemEnvelope>,
initial_context_injection: &InitialContextInjection,
) -> (Vec<ResponseItemEnvelope>, Option<Arc<WorldState>>) {
// Mid-turn compaction is the only path that must inject initial context above the last user
// message in the replacement history. Pre-turn compaction instead injects context after the
// compaction item, but mid-turn compaction keeps the compaction item last for model training.
@@ -314,7 +342,7 @@ pub(crate) async fn process_compacted_history(
build_compaction_initial_context(sess, initial_context_injection).await;
let compacted_history = history_item_groups(compacted_history)
.filter(|group| should_keep_compacted_history_item(&group.source))
.filter(|group| should_keep_compacted_history_item(&group.source.item))
.flat_map(HistoryItemGroup::into_items)
.collect();
(
@@ -386,7 +414,7 @@ pub(crate) fn trim_function_call_history_to_fit_context_window(
.fold(base_tokens, i128::saturating_add);
let initial_estimated_tokens = i64::try_from(estimated_tokens).unwrap_or(i64::MAX);
let mut rewritten_items = Vec::new();
let mut consumed_items = 0;
let mut consumed_items: usize = 0;
for group in history_item_groups(original_items.iter().map(|item| &item.item))
.collect::<Vec<_>>()
@@ -396,13 +424,20 @@ pub(crate) fn trim_function_call_history_to_fit_context_window(
if i64::try_from(estimated_tokens).unwrap_or(i64::MAX) <= context_window {
break;
}
let Some(rewritten_item) = rewritten_output_for_context_window(group.source) else {
let group_item_count = 1 + usize::from(group.attached_notice.is_some());
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 {
break;
};
estimated_tokens = estimated_tokens
.saturating_sub(group.estimated_token_count())
.saturating_add(i128::from(estimate_item_token_count(&rewritten_item)));
consumed_items += 1 + usize::from(group.attached_notice.is_some());
.saturating_add(i128::from(estimate_item_token_count(&rewritten_item.item)));
consumed_items += group_item_count;
rewritten_items.push(rewritten_item);
}
@@ -410,12 +445,7 @@ pub(crate) fn trim_function_call_history_to_fit_context_window(
if rewritten_outputs > 0 {
let retained_len = original_items.len() - consumed_items;
let mut items = original_items[..retained_len].to_vec();
items.extend(
rewritten_items
.into_iter()
.rev()
.map(ResponseItemEnvelope::new),
);
items.extend(rewritten_items.into_iter().rev());
history.replace_annotated(items);
}
@@ -424,8 +454,10 @@ pub(crate) fn trim_function_call_history_to_fit_context_window(
(rewritten_outputs, estimated_deleted_tokens)
}
fn rewritten_output_for_context_window(item: &ResponseItem) -> Option<ResponseItem> {
Some(match item {
fn rewritten_output_for_context_window(
envelope: &ResponseItemEnvelope,
) -> Option<ResponseItemEnvelope> {
let item = match &envelope.item {
ResponseItem::FunctionCallOutput {
id,
call_id,
@@ -466,6 +498,10 @@ fn rewritten_output_for_context_window(item: &ResponseItem) -> Option<ResponseIt
internal_chat_message_metadata_passthrough: metadata.clone(),
},
_ => return None,
};
Some(ResponseItemEnvelope {
item,
metadata: envelope.metadata.clone(),
})
}
@@ -475,3 +511,7 @@ fn truncated_output_payload(output: &FunctionCallOutputPayload) -> FunctionCallO
success: output.success,
}
}
#[cfg(test)]
#[path = "compact_remote_metadata_tests.rs"]
mod metadata_tests;