Batch Guardian review history cutoffs by root thread (#63673)

## Why

Concurrent Guardian reviews of the same root thread can repeat history
flushes and reads to establish how far to route evidence.

## What changed

Share one flush and durable history position across binding and catch-up
requests queued before capture begins. Requests arriving during capture get
a fresh position so they can account for newer records. A lone catch-up reads
unread records and their end position together, skipping the separate tail
read. Catch-up still waits for evidence to be routed through its cutoff.

## Testing

Cover shared cutoffs and read failures, separate capture for late arrivals,
and a lone retry that picks up a newer revocation without a separate tail
read when another queued request is canceled.

GitOrigin-RevId: ef07231d66bc38d8b244b6ee37ec3d483b54bc0f
This commit is contained in:
felixxia-oai
2026-11-24 16:45:39 +00:00
committed by copyberry
parent 6b7a16fe76
commit e713c4c302
2 changed files with 164 additions and 10 deletions
+87 -10
View File
@@ -1,16 +1,19 @@
//! Order intake requests by source position and acknowledge a request once its history has
//! been routed. The acknowledgement is a lower bound; subsequent board writes remain visible.
//! Share a root history position across queued reviews, then acknowledge each request
//! once its evidence has been routed. Later board writes remain visible.
use std::sync::Arc;
use std::sync::OnceLock;
use anyhow::Context;
use codex_core::guardian_review::ReviewPreparationError;
use codex_guardian_reviewer::ReviewerTasks;
use codex_protocol::ThreadId;
use codex_protocol::protocol::HistoryPosition;
use codex_thread_store::OriginalHistoryRequest;
use codex_thread_store::ThreadStore;
use codex_thread_store::ThreadStoreResult;
use tokio::sync::Mutex;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio::sync::watch;
use crate::EvidenceCursor;
@@ -20,11 +23,21 @@ use crate::EvidenceSnapshot;
#[path = "cutoff_tests.rs"]
mod tests;
enum CutoffKind {
Bind,
CatchUp,
}
struct CutoffRequest {
kind: CutoffKind,
reply: oneshot::Sender<ThreadStoreResult<Option<HistoryPosition>>>,
}
/// Installed on the root thread while its evidence intake is active.
pub struct RootEvidence {
root: ThreadId,
lifetime: Arc<ReviewerTasks>,
history: Arc<dyn ThreadStore>,
cutoffs: mpsc::UnboundedSender<CutoffRequest>,
// Advances on enqueue. The housekeeper independently tracks successful routing.
enqueued: Mutex<EvidenceCursor>,
// A rejected durable record keeps its reason for subsequent reviews of this root.
@@ -38,6 +51,53 @@ pub(super) struct Capture {
routed: watch::Sender<HistoryPosition>,
}
async fn capture_cutoffs(
root: ThreadId,
history: Arc<dyn ThreadStore>,
mut requests: mpsc::UnboundedReceiver<CutoffRequest>,
) {
loop {
let mut batch = Vec::new();
if requests.recv_many(&mut batch, usize::MAX).await == 0 {
return;
}
batch.retain(|request| !request.reply.is_closed());
if batch.is_empty() {
continue;
}
// Seal the group before inspecting history. A later caller may need a
// newer record even if the root's authorization hasn't changed.
let reviewers = batch.len();
let lone_catch_up = reviewers == 1 && matches!(batch[0].kind, CutoffKind::CatchUp);
let cancelled = async {
for request in &mut batch {
request.reply.closed().await;
}
};
let capture = async {
// With no position to share, let enqueue read the unread records
// and their end position together under the cursor lock.
if lone_catch_up {
return Ok(None);
}
tracing::debug!(name: "guardian_v3.cutoff_batch", reviewers, "Capturing Guardian history position");
history.flush_thread(root).await?;
history
.read_original_history(root, OriginalHistoryRequest::Tail)
.await
.map(|history| Some(history.end))
};
let result = tokio::select! {
biased;
() = cancelled => continue,
result = capture => result,
};
for request in batch {
let _ = request.reply.send(result.clone());
}
}
}
fn covers(position: HistoryPosition, cutoff: HistoryPosition) -> anyhow::Result<bool> {
anyhow::ensure!(
position.thread_id == cutoff.thread_id,
@@ -92,11 +152,17 @@ impl RootEvidence {
) -> (Arc<Self>, mpsc::Receiver<Capture>) {
let (pending, requests) = mpsc::channel(1);
let routed = watch::Sender::new(cursor.position());
let (cutoffs, readers) = mpsc::unbounded_channel();
let capture = capture_cutoffs(cursor.thread_id(), Arc::clone(&history), readers);
let cancel = lifetime.cancellation.clone();
lifetime.tasks.spawn(async move {
let _ = cancel.run_until_cancelled(capture).await;
});
(
Arc::new(Self {
root: cursor.thread_id(),
lifetime,
history,
cutoffs,
enqueued: Mutex::new(cursor),
rejection: OnceLock::new(),
pending,
@@ -210,13 +276,20 @@ impl RootEvidence {
impl RootEvidence {
/// Capture only the position. Binding an action does not enqueue any housekeeper work.
pub(super) async fn capture_cutoff(&self) -> anyhow::Result<HistoryPosition> {
self.ensure_active()?;
self.history.flush_thread(self.root).await?;
Ok(self
.history
.read_original_history(self.root, OriginalHistoryRequest::Tail)
self.request_cutoff(CutoffKind::Bind)
.await?
.end)
.context("Guardian binding requires a history position")
}
async fn request_cutoff(&self, kind: CutoffKind) -> anyhow::Result<Option<HistoryPosition>> {
self.ensure_active()?;
let (reply, position) = oneshot::channel();
self.cutoffs
.send(CutoffRequest { kind, reply })
.map_err(|_| ReviewPreparationError::EvidenceUnavailable)?;
Ok(position
.await
.map_err(|_| ReviewPreparationError::EvidenceUnavailable)??)
}
/// Submit a catch-up through the current durable tail and return its delivery acknowledgement.
@@ -230,6 +303,10 @@ impl RootEvidence {
&self,
cutoff: Option<HistoryPosition>,
) -> anyhow::Result<impl Future<Output = anyhow::Result<HistoryPosition>> + Send + use<>> {
let cutoff = match cutoff {
Some(end) => Some(end),
None => self.request_cutoff(CutoffKind::CatchUp).await?,
};
let target = tokio::select! { biased;
_ = self.lifetime.cancellation.cancelled() => anyhow::bail!("Guardian intake stopped"),
result = self.enqueue(cutoff) => result?,
@@ -178,8 +178,20 @@ async fn retries_unavailable_history_and_remembers_rejected_evidence() -> anyhow
let hidden = path.with_extension("unavailable");
tokio::fs::rename(path, &hidden).await?;
let unavailable = evidence.enqueue(/*cutoff*/ None).await;
let mut batches = NamedTraceEvents::subscribe("guardian_v3.cutoff_batch");
let (initial, retry) = tokio::join!(evidence.capture_cutoff(), evidence.request_catch_up());
tokio::fs::rename(hidden, path).await?;
assert!(unavailable.is_err());
assert_eq!(
initial
.err()
.context("expected a failed capture")?
.to_string(),
retry.err().context("expected a failed retry")?.to_string()
);
batches.next().await?;
assert!(batches.next().now_or_never().is_none());
assert_eq!(evidence.capture_cutoff().await?, delivered);
evidence.enqueue(/*cutoff*/ None).await?;
history
@@ -217,6 +229,71 @@ async fn retries_unavailable_history_and_remembers_rejected_evidence() -> anyhow
Ok(())
}
#[tokio::test]
async fn retries_share_a_queued_cutoff_and_skip_the_tail_read_when_alone() -> anyhow::Result<()> {
core_test_support::skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let test = test_codex()
.with_history_mode(ThreadHistoryMode::Paginated)
.build_with_auto_env(&server)
.await?;
let root = test.session_configured.thread_id;
let history = &test.thread_store;
history
.persist_thread(root, PersistContext::Standard)
.await?;
let (evidence, mut writer) = RootEvidence::new(
Default::default(),
history.clone(),
EvidenceCursor::start(root),
);
let mut batches = NamedTraceEvents::subscribe("guardian_v3.cutoff_batch");
// Queue all three before the worker runs on this current-thread runtime.
let mut cancelled = Box::pin(evidence.capture_cutoff());
let mut initial = Box::pin(evidence.capture_cutoff());
let mut retry = Box::pin(evidence.request_catch_up());
assert!(futures::poll!(&mut cancelled).is_pending());
assert!(futures::poll!(&mut initial).is_pending());
assert!(futures::poll!(&mut retry).is_pending());
batches.next().await?;
drop(cancelled);
// A caller arriving after the flush starts needs another capture even at the same tail.
let late = evidence.capture_cutoff().await?;
let bound = initial.await?;
// Only the next, lone retry should see this revocation.
test.codex
.inject_response_items_for_turn(vec![user_message_item("Stop the release.")])
.await?;
let routed = retry.await?;
writer.try_recv()?.finish();
assert_eq!(routed.await?, bound);
assert_eq!(late, bound);
batches.next().await?;
assert!(batches.next().now_or_never().is_none());
// A caller that cancels while queued must not force a tail read for the retry.
let mut cancelled = Box::pin(evidence.capture_cutoff());
assert!(futures::poll!(&mut cancelled).is_pending());
drop(cancelled);
let routed = evidence.request_catch_up().await?;
let capture = writer.try_recv()?;
let [record] = capture.snapshot.records() else {
anyhow::bail!("expected the revocation");
};
assert_eq!(
serde_json::to_value(record)?["original"]["payload"]["content"][0]["text"],
"Stop the release."
);
let end = capture.snapshot.cutoff();
capture.finish();
assert_eq!(routed.await?, end);
assert!(batches.next().now_or_never().is_none());
test.codex.shutdown_and_wait().await?;
Ok(())
}
#[test_case::test_case(false; "on_disk")]
#[test_case::test_case(true; "in_memory")]
#[tokio::test]