Centralize compaction checkpoint selection and validation (#46009)

## What changed

Add `codex_history::CompactionCheckpoint` to keep a checkpoint and its recorded producer model hash together, with shared checks for usability and reviewer compatibility.

Replace `ConversationHistorySnapshot::latest_compaction_model_hash()` with `latest_compaction()` and use the shared abstraction in Guardian context selection, review sessions, and parent compaction reuse. Preserve selection of the latest checkpoint even when unusable, and leave missing producer metadata unknown.

## Testing

Add coverage showing that the latest checkpoint retains its own provenance even with missing or empty encrypted content, and that compatibility requires matching producer and reviewer hashes. Adapt existing history, migration, and parent compaction tests to the new API.

GitOrigin-RevId: 98e794644edf979c98fcc8294baa48ff82ea0ed0
This commit is contained in:
felixxia-oai authored and copyberry committed 2026-09-16 19:25:50 +00:00
1 parent 2b59d92dbd
commit 7f0ab95827
12 files changed
+187 -105

No files matched your search

@@ -443,8 +443,15 @@ impl ConversationHistorySnapshot for TestRetainedHistory {
self.retained_context.as_ref()
}
fn latest_compaction_model_hash(&self) -> Option<&str> {
self.compaction_model_hash.as_deref()
fn latest_compaction(&self) -> Option<codex_history::CompactionCheckpoint<'_>> {
self.items()
.filter_map(|item| {
codex_history::CompactionCheckpoint::from_item(
item,
self.compaction_model_hash.as_deref(),
)
})
.last()
}
fn history_version(&self) -> u64 {
self.current.history_version()
@@ -29,23 +29,19 @@ pub(super) fn select_parent_compaction(
sampler: &LunaSampler,
legacy_model_hash: Option<&str>,
) -> Result<ParentCompaction, ParentCompactionError> {
let checkpoint = history.latest_compaction();
let model_hash = match mode {
GuardianContextMode::Legacy => legacy_model_hash,
GuardianContextMode::ThreadOwned => history.latest_compaction_model_hash(),
GuardianContextMode::ThreadOwned => checkpoint.and_then(|checkpoint| checkpoint.model_hash),
};
if mode == GuardianContextMode::ThreadOwned
&& history.items().any(|item| {
matches!(
item,
ResponseItem::Compaction { .. } | ResponseItem::ContextCompaction { .. }
)
})
&& checkpoint.is_some()
&& (!config.reuse_parent_compaction || !sampler.supports_parent_compaction(model_hash))
{
return Err(ParentCompactionError::RequiresSync);
}
let item = if config.reuse_parent_compaction {
match encrypted_parent_compaction(history.items(), config.max_parent_compaction_tokens) {
match encrypted_parent_compaction(checkpoint, config.max_parent_compaction_tokens) {
Ok(item) => item,
Err(ParentCompactionError::Unusable) if mode == GuardianContextMode::Legacy => None,
Err(error) => return Err(error),
@@ -66,39 +62,18 @@ pub(super) fn select_parent_compaction(
// An unusable latest compaction must never fall back to an older one. Missing
// encrypted content is rejected here; only legacy callers may omit that checkpoint.
fn encrypted_parent_compaction<'a>(
items: impl Iterator<Item = &'a ResponseItem>,
fn encrypted_parent_compaction(
checkpoint: Option<codex_history::CompactionCheckpoint<'_>>,
max_parent_compaction_tokens: usize,
) -> Result<Option<ResponseItem>, ParentCompactionError> {
let max_compaction_bytes = TruncationPolicy::Tokens(max_parent_compaction_tokens).byte_budget();
let Some(item) = items
.filter(|item| {
matches!(
item,
ResponseItem::Compaction { .. } | ResponseItem::ContextCompaction { .. }
)
})
.last()
else {
let Some(checkpoint) = checkpoint else {
return Ok(None);
};
let encrypted_content = match item {
ResponseItem::Compaction {
id: Some(_),
encrypted_content,
..
}
| ResponseItem::ContextCompaction {
id: Some(_),
encrypted_content: Some(encrypted_content),
..
} => encrypted_content,
_ => return Err(ParentCompactionError::Unusable),
};
if encrypted_content.is_empty() {
if !checkpoint.is_usable() {
return Err(ParentCompactionError::Unusable);
}
let item = checkpoint.item;
let serialized = serde_json::to_vec(item).map_err(|_| ParentCompactionError::Serialization)?;
if serialized.len() > max_compaction_bytes {
return Err(ParentCompactionError::Oversized);
@@ -3,6 +3,8 @@
use super::super::config::DEFAULT_PARENT_COMPACTION_TOKENS;
use super::*;
use anyhow::Result;
use codex_history::CompactionCheckpoint;
use codex_history::ResponseItemEnvelope;
use codex_protocol::ResponseItemId;
use codex_protocol::models::InternalChatMessageMetadataPassthrough;
use pretty_assertions::assert_eq;
@@ -21,14 +23,14 @@ fn encrypted_parent_compaction_preserves_the_latest_valid_item() {
};
assert_eq!(
encrypted_parent_compaction(
encrypted_checkpoint(
[&older, &latest].into_iter(),
DEFAULT_PARENT_COMPACTION_TOKENS,
),
Ok(Some(latest.clone()))
);
assert_eq!(
encrypted_parent_compaction(
encrypted_checkpoint(
[&latest, &older].into_iter(),
DEFAULT_PARENT_COMPACTION_TOKENS,
),
@@ -73,7 +75,7 @@ fn encrypted_parent_compaction_rejects_invalid_latest_item() {
for latest in &invalid {
assert_eq!(
encrypted_parent_compaction(
encrypted_checkpoint(
[&older, latest].into_iter(),
DEFAULT_PARENT_COMPACTION_TOKENS,
),
@@ -115,7 +117,7 @@ fn encrypted_parent_compaction_rejects_oversized_latest_item() -> Result<()> {
*encrypted_content = "a".repeat(max_compaction_bytes - envelope_bytes);
assert_eq!(serde_json::to_vec(&*item)?.len(), max_compaction_bytes);
assert_eq!(
encrypted_parent_compaction(std::iter::once(&*item), DEFAULT_PARENT_COMPACTION_TOKENS,),
encrypted_checkpoint(std::iter::once(&*item), DEFAULT_PARENT_COMPACTION_TOKENS,),
Ok(Some(item.clone()))
);
@@ -135,7 +137,7 @@ fn encrypted_parent_compaction_rejects_oversized_latest_item() -> Result<()> {
max_compaction_bytes + 1
);
assert_eq!(
encrypted_parent_compaction(
encrypted_checkpoint(
[&*item, &oversized].into_iter(),
DEFAULT_PARENT_COMPACTION_TOKENS,
),
@@ -156,7 +158,7 @@ fn encrypted_parent_compaction_rejects_oversized_latest_item() -> Result<()> {
};
assert!(serde_json::to_vec(&oversized_metadata)?.len() > max_compaction_bytes);
assert_eq!(
encrypted_parent_compaction(
encrypted_checkpoint(
[&bounded[0], &oversized_metadata].into_iter(),
DEFAULT_PARENT_COMPACTION_TOKENS,
),
@@ -166,3 +168,17 @@ fn encrypted_parent_compaction_rejects_oversized_latest_item() -> Result<()> {
Ok(())
}
fn encrypted_checkpoint<'a>(
items: impl Iterator<Item = &'a ResponseItem>,
max_parent_compaction_tokens: usize,
) -> Result<Option<ResponseItem>, ParentCompactionError> {
let items = items
.cloned()
.map(ResponseItemEnvelope::from)
.collect::<Vec<_>>();
encrypted_parent_compaction(
CompactionCheckpoint::latest(&items),
max_parent_compaction_tokens,
)
}