Reuse Guardian v2 async history after large fresh reviews (#65318)

## Why

When a fresh async review already reaches the soft reset limit, adding
evidence can trigger another rebuild that replays the same large transcript
on every check.

## What changed

If a fresh review reports usage at or above
`async_classifier_conversation_token_limit`, allow projected input to grow
up to 20,000 tokens beyond that first report. Use the latest reported usage
to estimate each continuation while keeping the ceiling anchored to the
fresh review. The model's input limit still applies.

For this extra allowance, rebuild when reported usage is missing or the
next request would truncate elastic context or omit whole transcript
entries from the fixed window. A fresh review with elastic truncation
cannot start the allowance.

## Testing

Extend coverage for reuse across multiple reviews, resets at the growth
ceiling and model input limit, missing usage, and transcript evidence
recovered by rebuilding.

GitOrigin-RevId: 4c5c69a898b83e051241b06c324773a0b9e46ede
This commit is contained in:
jif
2026-12-02 19:40:40 +00:00
committed by copyberry
parent 0f5e7be1a7
commit 1bca83f820
9 changed files with 200 additions and 32 deletions
+1 -1
View File
@@ -2364,7 +2364,7 @@
"description": "User-configurable prompt, approval, and context settings for Guardian v2.",
"properties": {
"async_classifier_conversation_token_limit": {
"description": "Reset retained async history when the next request exceeds this token estimate. Defaults to 100,000. Fresh requests remain subject to the model's input limit.",
"description": "Soft reset limit for retained async history. Defaults to 100,000 tokens. If a fresh review reaches this limit, projected input may grow up to 20,000 tokens beyond that review's reported usage. Even a limit of 1 can allow reuse. The model's input limit still applies.",
"format": "uint",
"minimum": 1.0,
"type": "integer"
@@ -5,7 +5,8 @@
//! Permits bound preparation and sampling through full response completion.
//! Policy caches isolate history and generations while sharing admission and action progress.
//! Thread stop retires every retained policy backend.
//! Oversized retained requests rebuild from fresh evidence before the model's hard limit.
//! A large fresh request can grow within a fixed allowance before the next soft reset.
//! Every request still passes hard admission before reuse.
//! Preparation exposes the complete input without starting model execution.
//! Each request owns its fork; failed or cancelled requests leave committed history intact.
//! Host-only instruction delivery metadata is committed with its completed input messages.
@@ -57,6 +58,8 @@ pub(super) struct ConversationBackend {
struct CompletedConversation {
index: usize,
key: ReuseKey,
/// Reported usage of the first request, if eligible for growth.
fresh_tokens: Option<usize>,
state: ConversationState<RetainedHistory>,
}
@@ -88,6 +91,8 @@ pub(super) struct PreparedConversation {
pub(super) request: PreparedRequest,
sampling: LunaSamplingRequest,
key: ReuseKey,
fresh_tokens: Option<usize>,
elastic_truncation: bool,
state: ConversationState<RetainedHistory>,
thread: Arc<CodexThread>,
ready: oneshot::Sender<Result<SampledScore, LunaSamplerError>>,
@@ -282,9 +287,11 @@ impl Reservation {
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone();
let mut state = previous
let previous = previous
// Delayed preparation must never import a later action's evidence.
.filter(|previous| previous.index < self.index && previous.key == key)
.filter(|previous| previous.index < self.index && previous.key == key);
let fresh_tokens = previous.as_ref().and_then(|previous| previous.fresh_tokens);
let mut state = previous
.and_then(|previous| previous.state.snapshot().cloned())
.map(ConversationState::from)
.unwrap_or_default();
@@ -295,13 +302,12 @@ impl Reservation {
.sampling
.prepare_retained(&request.evidence, &mut state, request.max_input_tokens)
.filter(|review_request| {
// Hard admission and metrics keep the conservative full-request estimate.
let estimated_prefix = review_request.existing_context_tokens;
let new_tokens = review_request.input_tokens.saturating_sub(estimated_prefix);
let reset_tokens = reported_prefix
.unwrap_or(estimated_prefix)
.saturating_add(new_tokens);
estimated_prefix == 0 || reset_tokens <= request.reset_token_limit
review_request.fits_reset_limit(
&request.evidence,
request.reset_token_limit,
reported_prefix,
fresh_tokens,
)
})
.or_else(|| {
if !had_history {
@@ -327,12 +333,15 @@ impl Reservation {
review_request.existing_context_tokens,
review_request.input_tokens,
);
let elastic_truncation = review_request.has_elastic_truncation(&request.evidence);
drop(request.evidence);
Some(PreparedConversation {
reservation: self,
request: review_request,
sampling: request.sampling,
key,
fresh_tokens,
elastic_truncation,
state,
thread: request.thread,
ready: request.ready,
@@ -401,6 +410,12 @@ impl PreparedConversation {
let mut truncations = super::truncation::ClassificationTruncations::default();
truncations.extend(pending_truncations);
truncations.emit(self.metrics.as_deref());
let fresh_tokens = if self.state.completed_review_count() == 0 {
// The cursor advances past omitted entries. A rebuild might recover them.
history.reported_tokens.filter(|_| !self.elastic_truncation)
} else {
self.fresh_tokens
};
self.state.complete_review(cursor);
self.state.commit_snapshot(history);
let mut latest = self
@@ -415,6 +430,7 @@ impl PreparedConversation {
*latest = Some(Arc::new(CompletedConversation {
index: self.reservation.index,
key: self.key,
fresh_tokens,
state: self.state,
}));
}
@@ -104,7 +104,14 @@ async fn configured_reset_limit_rebuilds_history_without_rejecting_fresh_evidenc
skip_if_no_network!(Ok(()));
let elastic = budgeting == ContextBudgeting::Elastic;
for (limit, reused) in [(1, false), (100_000, true)] {
let large_entry = "evidence ".repeat(/*n*/ 6_000);
for (limit, tokens, entry, reused) in [
(1, 0, None, false),
(1, 101_000, None, true),
(100_000, 0, None, true),
(100_000, 101_000, None, true),
(100_000, 101_000, Some(large_entry), !elastic),
] {
let server = responses::start_mock_server().await;
let fixture = GuardianFailureFixture::with_config(&format!(
"[features]\nguardianv2_decisions_comparison = true\n[features.guardianv2]\nasync_classifier_mode = 'conversation'\nasync_classifier_conversation_token_limit = {limit}\nasync_elastic_budgeting = {elastic}\n{}",
@@ -126,7 +133,7 @@ async fn configured_reset_limit_rebuilds_history_without_rejecting_fresh_evidenc
let backend = ConversationBackend::for_turn(store, store).unwrap();
let events = responses::sse(vec![
ev_assistant_message("score", "low"),
ev_completed("score"),
responses::ev_completed_with_tokens("score", tokens),
]);
let mock = responses::mount_sse_sequence(&server, vec![events; 2]).await;
let (finish_decisions, decisions_gate) = tokio::sync::oneshot::channel();
@@ -144,6 +151,15 @@ async fn configured_reset_limit_rebuilds_history_without_rejecting_fresh_evidenc
format!("{}/v1/responses", decisions_server.uri()),
/*auth_context*/ None,
)?);
if let Some(entry) = entry {
// The fresh review truncates this entry. The next delta starts past it.
let mut event = ev_assistant_message("large", &entry);
fixture
.test
.codex
.inject_response_items(vec![serde_json::from_value(event["item"].take())?])
.await?;
}
let (mut request, score) = pending_request(&fixture, "parent").await?;
request.metrics = Some(metrics.clone());
let reservation = backend.reserve(|| 0).1.unwrap();
@@ -253,7 +269,7 @@ async fn configured_reset_limit_rebuilds_history_without_rejecting_fresh_evidenc
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn soft_reset_uses_only_the_latest_completed_prefix_usage() -> Result<()> {
async fn soft_reset_uses_latest_usage_but_bounds_growth_from_the_fresh_request() -> Result<()> {
skip_if_no_network!(Ok(()));
let fixture = GuardianFailureFixture::new().await?;
let store = fixture.test.codex.thread_extension_data();
@@ -275,25 +291,44 @@ async fn soft_reset_uses_only_the_latest_completed_prefix_usage() -> Result<()>
/*revision*/ 0,
/*metrics*/ None,
);
// The image reserves 10k. A 2k report allows reuse under 8k. The next
// report fills even a 100k limit before adding the new evidence. Without
// usable usage on that fresh request, fall back to the image reservation.
// A 2k report beats the 10k image reservation. Crossing the limit on a
// continuation still resets. Only the fresh 150k request gets room to grow,
// and the next two completions must not move its 170k ceiling.
// Request, soft limit, reported total after completion, expected prior scores.
let checks = [
("seed", 8_000, 2_000),
("continued", 8_000, 100_000),
("rebuilt", 100_000, 0),
("fallback", 8_000, 0),
("seed", 8_000, 2_000, &[] as &[&str]),
("continued", 8_000, 100_000, &["seed"]),
("oversized", 100_000, 150_000, &[]),
("first_delta", 100_000, 160_000, &["oversized"]),
(
"second_delta",
100_000,
169_999,
&["oversized", "first_delta"],
),
// The rebuild sets a new ceiling of 130k.
("rebuilt", 100_000, 110_000, &[]),
("new_delta", 100_000, 130_000, &["rebuilt"]),
("rebuilt_again", 100_000, 120_000, &[]),
// An extension needs a usage report on every continuation.
("missing", 100_000, 0, &["rebuilt_again"]),
("at_hard_limit", 100_000, 200_000, &[]),
// The reported prefix now fills the hard budget.
("no_room", 100_000, 0, &[]),
// Missing usage falls back to the image reservation.
("fallback", 8_000, 0, &[]),
];
let events = checks.map(|(id, _, tokens)| {
let events = checks.map(|(id, _, tokens, _)| {
responses::sse(vec![
ev_assistant_message(id, "low"),
responses::ev_completed_with_tokens(id, tokens),
])
});
let mock = responses::mount_sse_sequence(&server, Vec::from(events)).await;
for (id, limit, _) in checks {
for (id, limit, _, _) in checks {
let (mut request, score) = pending_request(&fixture, id).await?;
request.reset_token_limit = limit;
request.max_input_tokens = 200_000;
let (index, reservation) =
backend.reserve(|| observe_unscored_call(&backend.progress, store));
request.pending_score.progress = Arc::clone(&backend.progress);
@@ -314,10 +349,62 @@ async fn soft_reset_uses_only_the_latest_completed_prefix_usage() -> Result<()>
.collect::<Vec<_>>()
})
.collect::<Vec<_>>();
assert_eq!(
retained_scores,
[vec![], vec![json!("seed")], vec![], vec![]]
assert_eq!(retained_scores, checks.map(|(_, _, _, expected)| expected));
fixture.test.codex.shutdown_and_wait().await?;
Ok(())
}
#[test_case::test_case(101_000, ["C", "D", "E", "F"]; "rebuild above the soft limit")]
#[test_case::test_case(2_000, ["A", "D", "E", "F"]; "ordinary reuse below the soft limit")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn fixed_window_eviction_limits_growth(tokens: i64, expected: [&str; 4]) -> Result<()> {
skip_if_no_network!(Ok(()));
let fixture = GuardianFailureFixture::with_config(
"[features.guardianv2.transcript]\nmax_recent_non_user_entries = 4\n",
)
.await?;
let store = fixture.test.codex.thread_extension_data();
let server = responses::start_mock_server().await;
let backend = ConversationBackend::new(
Arc::new(LunaSampler::new(sampler_config(server.uri()))),
/*revision*/ 0,
/*metrics*/ None,
);
let events = ["seed", "next"].map(|id| {
responses::sse(vec![
ev_assistant_message(id, "low"),
responses::ev_completed_with_tokens(id, tokens),
])
});
let mock = responses::mount_sse_sequence(&server, Vec::from(events)).await;
// The full window evicts A and B together. The delta starts at B and evicts B and C.
for (id, entries) in [("seed", "A"), ("next", "BCDEF")] {
let items = entries
.chars()
.map(|label| {
let mut call = responses::ev_function_call(
&label.to_string(),
"read_file",
&format!("evidence-{label}"),
);
serde_json::from_value(call["item"].take())
})
.collect::<serde_json::Result<Vec<_>>>()?;
fixture.test.codex.inject_response_items(items).await?;
let (mut request, score) = pending_request(&fixture, id).await?;
let (index, reservation) =
backend.reserve(|| observe_unscored_call(&backend.progress, store));
request.pending_score.progress = Arc::clone(&backend.progress);
request.pending_score.index = index;
reservation?.prepare(request).await.unwrap().run().await;
assert_eq!(score.await??, "low");
}
let texts = mock.requests()[1].message_input_texts("user");
let evidence = texts
.iter()
.filter_map(|text| text.split_once("evidence-").map(|(_, label)| label.trim()))
.collect::<Vec<_>>();
assert_eq!(evidence, expected);
fixture.test.codex.shutdown_and_wait().await?;
Ok(())
}
@@ -21,6 +21,8 @@ use super::sampler::LunaSamplingRequest;
use super::sampler::RetainedHistory;
use super::transcript::CollectedTranscript;
const OVERSIZED_FRESH_GROWTH_TOKENS: usize = 20_000;
impl LunaSamplingRequest {
/// Takes committed history only after admission; rejection leaves the checkpoint intact.
pub(super) fn prepare_retained(
@@ -128,3 +130,47 @@ pub(super) struct PreparedRequest {
pub(super) input_tokens: usize,
pub(super) max_input_tokens: usize,
}
impl PreparedRequest {
pub(super) fn has_elastic_truncation(&self, evidence: &CollectedTranscript) -> bool {
evidence.elastic.is_some() && !self.truncations.is_empty()
}
/// Hard admission has already checked the conservative full-request estimate.
pub(super) fn fits_reset_limit(
&self,
evidence: &CollectedTranscript,
limit: usize,
reported_prefix: Option<usize>,
fresh_tokens: Option<usize>,
) -> bool {
if self.existing_context_tokens == 0 {
return true;
}
let new_tokens = self
.input_tokens
.saturating_sub(self.existing_context_tokens);
let Some(fresh) = fresh_tokens.filter(|&tokens| tokens >= limit) else {
return reported_prefix
.unwrap_or(self.existing_context_tokens)
.saturating_add(new_tokens)
<= limit;
};
// Rebuilding can replay the same oversized prompt on every check. Anchor the
// allowance to the first completion so continuing never moves the ceiling.
let Some(prefix) = reported_prefix else {
return false;
};
// Fixed windows evict in batches. Replaying the full transcript can recover
// entries the delta dropped before the cursor advances past them.
let projected = prefix.saturating_add(new_tokens);
projected <= fresh.saturating_add(OVERSIZED_FRESH_GROWTH_TOKENS)
&& projected <= self.max_input_tokens.saturating_sub(INPUT_TOKEN_MARGIN)
&& !self.has_elastic_truncation(evidence)
&& !self
.truncations
.iter()
.any(TruncationObservation::is_omitted_transcript_entry)
}
}
@@ -337,6 +337,12 @@ fn elastic_fits_ids_without_resetting_committed_history() {
let bounded = config
.prepare_retained(&evidence, &mut state, maximum + INPUT_TOKEN_MARGIN)
.expect("allocate evidence with room for IDs");
// Both candidates fit hard admission. Only the one that kept the image can
// extend a conversation that started at the soft limit.
let limit = first.input_tokens;
let reported = Some(limit);
assert!(full.fits_reset_limit(&evidence, limit, reported, reported));
assert!(!bounded.fits_reset_limit(&evidence, limit, reported, reported));
assert_eq!(&bounded.input[..first.input.len()], first.input);
assert!(bounded.input_tokens <= maximum);
assert!(bounded.input.iter().all(|item| item.id().is_some()));
+4 -2
View File
@@ -205,8 +205,10 @@ pub struct GuardianV2ConfigToml {
/// Deprecated and ignored; asynchronous classification always uses conversations.
#[serde(skip_serializing_if = "Option::is_none")]
pub async_classifier_mode: Option<codex_protocol::openai_models::AsyncClassifierMode>,
/// Reset retained async history when the next request exceeds this token estimate.
/// Defaults to 100,000. Fresh requests remain subject to the model's input limit.
/// Soft reset limit for retained async history. Defaults to 100,000 tokens.
/// If a fresh review reaches this limit, projected input may grow up to 20,000
/// tokens beyond that review's reported usage. Even a limit of 1 can allow reuse.
/// The model's input limit still applies.
#[serde(skip_serializing_if = "Option::is_none")]
#[schemars(range(min = 1))]
pub async_classifier_conversation_token_limit: Option<usize>,
@@ -34,6 +34,15 @@ use self::window::TranscriptWindow;
mod window;
const MIN_RECENT_TOOL_ENTRIES: usize = 5;
const TRANSCRIPT_MESSAGE: &str = "transcript_message";
const TRANSCRIPT_TOOL: &str = "transcript_tool";
impl TruncationObservation {
/// Whether the fixed transcript window omitted a whole message or tool entry.
pub fn is_omitted_transcript_entry(&self) -> bool {
self.retained_bytes == 0 && matches!(self.component, TRANSCRIPT_MESSAGE | TRANSCRIPT_TOOL)
}
}
/// Request-local policy resolved from the consumer's model and configuration.
/// Registry scope follows `target`; fixed preparation applies its legacy caps and retention.
@@ -309,8 +318,8 @@ impl ContextProfile {
TranscriptEntryKind::User => "transcript_user",
TranscriptEntryKind::ManualApproval
| TranscriptEntryKind::ProtectedMessage
| TranscriptEntryKind::Message => "transcript_message",
TranscriptEntryKind::Tool => "transcript_tool",
| TranscriptEntryKind::Message => TRANSCRIPT_MESSAGE,
TranscriptEntryKind::Tool => TRANSCRIPT_TOOL,
};
// User and approval entries bypass fixed limits. A shorter heartbeat
// reference, for example, is deduplication rather than a budget cut.
@@ -130,9 +130,10 @@ fn profiles_preserve_distinct_retention_and_original_numbering() {
observation.component,
observation.original_bytes,
observation.retained_bytes,
observation.is_omitted_transcript_entry(),
))
.collect::<Vec<_>>(),
vec![("transcript_message", "working".len(), 0)],
vec![("transcript_message", "working".len(), 0, true)],
);
}
@@ -22,7 +22,8 @@ pub struct GuardianV2ModelConfig {
/// Deprecated and ignored; asynchronous classification always uses conversations.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub async_classifier_mode: Option<AsyncClassifierMode>,
/// Reset retained async history when the next request exceeds this token estimate.
/// Soft reset limit for retained async history. If a fresh review reaches this limit,
/// projected input may grow up to 20,000 tokens beyond that review's reported usage.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub async_classifier_conversation_token_limit: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]