diff --git a/codex-rs/app-server/tests/suite/v2/guardian_v3_sync_tests.rs b/codex-rs/app-server/tests/suite/v2/guardian_v3_sync_tests.rs index cbde12f4cb..c6b5ac7436 100644 --- a/codex-rs/app-server/tests/suite/v2/guardian_v3_sync_tests.rs +++ b/codex-rs/app-server/tests/suite/v2/guardian_v3_sync_tests.rs @@ -2,12 +2,16 @@ use super::super::mcp_tool::wait_for_mcp_tool_call_completed; use super::sync_sessions::sync_config; use super::*; +use app_test_support::create_final_assistant_message_sse_response as assistant_response; use codex_app_server_protocol::GuardianApprovalReviewStatus; use codex_app_server_protocol::ItemGuardianApprovalReviewCompletedNotification; +use codex_app_server_protocol::ThreadGoalSetResponse; use codex_app_server_protocol::ThreadHistoryMode; use codex_models_manager::model_info::model_info_from_slug; use codex_state::SqlitePoolWriteExt; use core_test_support::apps_test_server::AppsTestServer; +use core_test_support::streaming_sse::StreamingSseChunk; +use core_test_support::streaming_sse::start_streaming_sse_server; use pretty_assertions::assert_eq; use std::sync::atomic::AtomicBool; use test_case::test_case; @@ -41,10 +45,16 @@ fn received_user_instruction(request: &responses::ResponsesRequest, text: &str) .iter() .any(|source| { let item = &source["original"]["payload"]; + // User goals wrap the objective in a host-generated message. + let is_goal = item["internal_chat_message_metadata_passthrough"] + ["content_item_kinds"][0] == "user.goal"; item["role"] == "user" - && item["content"] - .as_array() - .is_some_and(|parts| parts.iter().any(|part| part["text"] == text)) + && item["content"].as_array().is_some_and(|parts| { + parts.iter().any(|part| { + part["text"] == text + || (is_goal && part["text"].as_str().is_some_and(|s| s.contains(text))) + }) + }) }) }) } @@ -75,8 +85,11 @@ async fn pending_mcp_action_uses_the_configured_reviewer( "I understand the release risk. I explicitly approve this release action."; const FINAL_REVOCATION: &str = "Stop the release again. Do not deploy."; const FIRST_DENIAL_REASON: &str = "The user explicitly stopped this deployment."; + const PENDING_CALL: &str = "release-pending"; let next_call = Arc::new(Mutex::new(None)); let actor_call = Arc::clone(&next_call); + let stale_allow_url = Arc::new(Mutex::new(None::)); + let redirect = Arc::clone(&stale_allow_url); let ask_to_subscribe = AtomicBool::new(uses_board); let deny_first_reapproval = AtomicBool::new(reconsider); let first_final_sample = AtomicBool::new(true); @@ -117,6 +130,9 @@ async fn pending_mcp_action_uses_the_configured_reviewer( responses::ev_completed("subscribe"), ])); } + if let Some(url) = redirect.lock().expect("stale allow URL").take() { + return wiremock::ResponseTemplate::new(/*s*/ 307).insert_header("location", url); + } let final_revocation = received_user_instruction(&request, FINAL_REVOCATION); let denied = if final_revocation { first_final_sample.swap(false, Ordering::SeqCst) @@ -218,6 +234,9 @@ async fn pending_mcp_action_uses_the_configured_reviewer( .with_root_config(r#"auto_review.experimental_conversation_history_prompt = "Legacy conversation-history retrieval instructions.""#) .with_extra_config("[feedback]\nenabled = true"); } + if matches!(case, ReviewCase::V3) { + config = config.enable_feature(Feature::Goals); + } config.write(home.path())?; let mut app = TestAppServer::builder() .with_codex_home(home.path()) @@ -261,6 +280,13 @@ async fn pending_mcp_action_uses_the_configured_reviewer( GuardianApprovalReviewStatus::Denied, )); } + if matches!(case, ReviewCase::V3) { + turns.push(( + PENDING_CALL, + "Proceed with the release.", + GuardianApprovalReviewStatus::Denied, + )); + } let mut previous_reviewer = None; let mut previous_review_id = None; let mut denied_turns = Vec::new(); @@ -276,6 +302,19 @@ async fn pending_mcp_action_uses_the_configured_reviewer( } else { None }; + let held_allow = if call_id == PENDING_CALL { + let (release, gate) = tokio::sync::oneshot::channel(); + let (stream, _) = start_streaming_sse_server(vec![vec![StreamingSseChunk { + gate: Some(gate), + body: assistant_response(r#"{"outcome":"allow","rationale":"Release approved."}"#)?, + }]]) + .await; + *stale_allow_url.lock().expect("stale allow URL") = + Some(format!("{}/v1/responses", stream.uri())); + Some((stream, release)) + } else { + None + }; *next_call.lock().expect("next actor call") = Some(call_id); let id = app .send_turn_start_request(TurnStartParams { @@ -288,6 +327,21 @@ async fn pending_mcp_action_uses_the_configured_reviewer( }) .await?; let started: TurnStartResponse = timeout(TIMEOUT, app.read_response(id)).await??; + if let Some((stream, release)) = held_allow { + timeout(TIMEOUT, stream.wait_for_request_count(/*count*/ 1)).await?; + // A paused user goal updates authorization without starting a turn or waking intake. + let id = app + .send_raw_request( + "thread/goal/set", + Some(json!({ + "threadId": thread.id, "origin": "user", + "status": "paused", "objective": FINAL_REVOCATION, + })), + ) + .await?; + let _: ThreadGoalSetResponse = timeout(TIMEOUT, app.read_response(id)).await??; + release.send(()).expect("release stale allow"); + } if let Some(gate) = gate { app.wait_for_matching_json_log_event( "revocation catch-up", @@ -362,6 +416,23 @@ async fn pending_mcp_action_uses_the_configured_reviewer( if status == GuardianApprovalReviewStatus::Denied { denied_turns.push(review.turn_id); } + if call_id == PENDING_CALL { + let [stale, retry] = assessments.as_slice() else { + anyhow::bail!("expected a stale allow and one retry for {call_id}"); + }; + assert!(!received_user_instruction(stale, FINAL_REVOCATION)); + assert!(received_user_instruction(retry, FINAL_REVOCATION)); + assert_eq!(review.target_item_id.as_deref(), Some(call_id)); + let denied = wait_for_mcp_tool_call_completed(&mut app, call_id).await?; + assert!(matches!( + denied.item.payload, + ThreadItemPayload::McpToolCall { + status: McpToolCallStatus::Failed, error: Some(error), .. + } if error.message.contains(FIRST_DENIAL_REASON) + )); + // Core discards the stale session, so the reuse assertions below don't apply. + continue; + } if prompt == FINAL_REVOCATION { assert_eq!( review.review.rationale.as_deref(), diff --git a/codex-rs/core/src/guardian_review.rs b/codex-rs/core/src/guardian_review.rs index 8a5239c43c..24abf5992b 100644 --- a/codex-rs/core/src/guardian_review.rs +++ b/codex-rs/core/src/guardian_review.rs @@ -36,7 +36,8 @@ pub fn reviewer_headers(config: &crate::config::Config) -> crate::CodexResponses } } -/// A thread's synchronous reviewer. Bind the evidence catch-up to the action before it waits. +/// A thread's synchronous reviewer. Bind its evidence position before the action waits. +/// Routing may hand the action to a human without ever requesting preparation. pub trait AttachedReviewer: Send + Sync { fn bind(self: std::sync::Arc) -> BoundReviewer; } @@ -63,7 +64,8 @@ pub enum ReviewPreparationError { Cancelled, } -/// Reserve the actor's reviewer after routing and delivery have covered the bound action. +/// Reserve the actor's reviewer after routing and delivery have covered this attempt. +/// A retry must cover authorization changes since the previous attempt. pub trait ReviewerPreparation: Send + Sync { fn prepare<'a>( &'a self, diff --git a/codex-rs/ext/guardian-v3/src/actor.rs b/codex-rs/ext/guardian-v3/src/actor.rs index a9901504bc..3e4ba5b65b 100644 --- a/codex-rs/ext/guardian-v3/src/actor.rs +++ b/codex-rs/ext/guardian-v3/src/actor.rs @@ -16,8 +16,10 @@ use codex_guardian_reviewer::SessionDisposition; use codex_message_board::AgentMessageBoard; use codex_protocol::AgentPath; use codex_protocol::ThreadId; +use codex_protocol::protocol::HistoryPosition; use tokio::sync::Mutex; use tokio::sync::OwnedMutexGuard; +use tokio::sync::oneshot; use tokio_util::sync::CancellationToken; use crate::LiveRetrievalBinding; @@ -227,35 +229,54 @@ impl ActorReviewer { } } -/// One intake request shared by all verdict attempts for the same action. +/// The first attempt uses the request-time position. Every later attempt flushes and +/// captures again after core has sampled its new authorization revision. struct BoundActorReview { actor: Arc, - routed: tokio::sync::watch::Receiver>>, + initial: Mutex>>, +} + +struct RequestCutoff { + evidence: Arc, + position: HistoryPosition, + revisions: (u64, u64), +} + +async fn root_revisions(root: &CodexThread) -> (u64, u64) { + let history = root.conversation_history_snapshot().await; + ( + history.user_message_revision(), + history.guardian_review_context_revision(), + ) } impl codex_core::guardian_review::AttachedReviewer for ActorReviewer { fn bind(self: Arc) -> codex_core::guardian_review::BoundReviewer { - let (routed, ready) = tokio::sync::watch::channel(None); + let (mut sender, initial) = oneshot::channel(); let actor = Arc::clone(&self); self.lifetime.tasks.spawn(async move { - // Start capture at request time even if a previous verdict occupies the slot. - let catch_up = async { + let capture = async { let manager = actor.manager.upgrade().context("Guardian host stopped")?; let root = manager.get_thread(actor.root).await?; let evidence = root .thread_extension_data() .get::() .context("Guardian intake unavailable")?; - evidence.request_catch_up().await?.await?; - anyhow::Ok(Arc::downgrade(&evidence)) + let revisions = root_revisions(&root).await; + let position = evidence.capture_cutoff().await?; + anyhow::Ok(RequestCutoff { + evidence, + position, + revisions, + }) }; tokio::select! { biased; - _ = routed.closed() => (), + _ = sender.closed() => (), _ = actor.lifetime.cancellation.cancelled() => (), - result = catch_up => { - if let Ok(evidence) = result { - routed.send_replace(Some(evidence)); + result = capture => { + if let Ok(cutoff) = result { + let _ = sender.send(cutoff); } } } @@ -264,7 +285,7 @@ impl codex_core::guardian_review::AttachedReviewer for ActorReviewer { retrieval: self.retrieval.clone(), preparation: Arc::new(BoundActorReview { actor: self, - routed: ready, + initial: Mutex::new(Some(initial)), }), } } @@ -280,17 +301,50 @@ impl codex_core::guardian_review::ReviewerPreparation for BoundActorReview { Result, ReviewPreparationError>, > { Box::pin(async move { - let mut routed = self.routed.clone(); - let evidence = tokio::select! { + let prepare = async { + let manager = self + .actor + .manager + .upgrade() + .ok_or(ReviewPreparationError::ReviewerUnavailable)?; + let root = manager + .get_thread(self.actor.root) + .await + .map_err(|_| ReviewPreparationError::EvidenceUnavailable)?; + let evidence = root + .thread_extension_data() + .get::() + .ok_or(ReviewPreparationError::EvidenceUnavailable)?; + let initial = self.initial.lock().await.take(); + let cutoff = if let Some(initial) = initial { + let initial = initial + .await + .map_err(|_| ReviewPreparationError::EvidenceUnavailable)?; + if !Arc::ptr_eq(&initial.evidence, &evidence) { + return Err(ReviewPreparationError::EvidenceUnavailable); + } + // Authorization may also advance between binding and routing the first attempt. + (root_revisions(&root).await == initial.revisions).then_some(initial.position) + } else { + None + }; + let ready = evidence + .request_through(cutoff) + .await + .map_err(|_| ReviewPreparationError::EvidenceUnavailable)?; + ready + .await + .map_err(|_| ReviewPreparationError::EvidenceUnavailable)?; + let reviewer = self.actor.reserve(&evidence, setup, cancel).await?; + Ok(Box::new(reviewer) as Box) + }; + tokio::select! { biased; - _ = cancel.cancelled() => return Err(ReviewPreparationError::Cancelled), - _ = setup.history_reset.cancelled() => return Err(ReviewPreparationError::Cancelled), - result = routed.wait_for(Option::is_some) => result.ok().and_then(|value| value.as_ref()?.upgrade()), - }.ok_or(ReviewPreparationError::EvidenceUnavailable)?; - // All matching originals through the requested position are queued. The - // reservation drains this guardian's inbox before submitting the action. - let reviewer = self.actor.reserve(&evidence, setup, cancel).await?; - Ok(Box::new(reviewer) as Box) + _ = self.actor.lifetime.cancellation.cancelled() => Err(ReviewPreparationError::Cancelled), + _ = cancel.cancelled() => Err(ReviewPreparationError::Cancelled), + _ = setup.history_reset.cancelled() => Err(ReviewPreparationError::Cancelled), + result = prepare => result, + } }) } } diff --git a/codex-rs/ext/guardian-v3/src/cutoff.rs b/codex-rs/ext/guardian-v3/src/cutoff.rs index b5eae5133f..8c37074c9e 100644 --- a/codex-rs/ext/guardian-v3/src/cutoff.rs +++ b/codex-rs/ext/guardian-v3/src/cutoff.rs @@ -1,14 +1,17 @@ //! 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. use std::sync::Arc; +use std::sync::OnceLock; use anyhow::Context; 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 tokio::sync::Mutex; use tokio::sync::mpsc; -use tokio::sync::oneshot; +use tokio::sync::watch; use crate::EvidenceCursor; use crate::EvidenceSnapshot; @@ -19,25 +22,65 @@ mod tests; /// Installed on the root thread while its evidence intake is active. pub struct RootEvidence { + root: ThreadId, lifetime: Arc, history: Arc, // Advances on enqueue. The housekeeper independently tracks successful routing. + enqueued: Mutex, // A rejected durable record keeps its reason for subsequent reviews of this root. - enqueued: Mutex>, + rejection: OnceLock, pending: mpsc::Sender, + routed: watch::Sender, } pub(super) struct Capture { pub snapshot: EvidenceSnapshot, - routed: Option>, + routed: watch::Sender, +} + +fn covers(position: HistoryPosition, cutoff: HistoryPosition) -> anyhow::Result { + anyhow::ensure!( + position.thread_id == cutoff.thread_id, + "Guardian cutoff belongs to another root" + ); + if position.end_ordinal_exclusive < cutoff.end_ordinal_exclusive { + return Ok(false); + } + anyhow::ensure!( + position.end_byte_offset >= cutoff.end_byte_offset, + "Guardian cutoff is inconsistent" + ); + Ok(true) +} + +async fn wait_until_routed( + mut routed: watch::Receiver, + target: HistoryPosition, +) -> anyhow::Result { + while !covers(*routed.borrow_and_update(), target)? { + routed + .changed() + .await + .context("Guardian housekeeper stopped")?; + } + Ok(target) } impl Capture { - /// Called by the sole writer only after it published the whole capture to subscriber inboxes. + /// Advance only after the sole writer has published all deliveries through this position. + pub(super) fn routed_through(&self, position: HistoryPosition) { + self.routed.send_if_modified(|current| { + if *current == position { + return false; + } + *current = position; + true + }); + } + + /// Complete a capture, including one with no selected evidence. pub(super) fn finish(self) { - if let Some(reply) = self.routed { - let _ = reply.send(self.snapshot.cutoff()); - } + self.routed_through(self.snapshot.cutoff()); } } @@ -48,12 +91,16 @@ impl RootEvidence { cursor: EvidenceCursor, ) -> (Arc, mpsc::Receiver) { let (pending, requests) = mpsc::channel(1); + let routed = watch::Sender::new(cursor.position()); ( Arc::new(Self { + root: cursor.thread_id(), lifetime, history, - enqueued: Mutex::new(Ok(cursor)), + enqueued: Mutex::new(cursor), + rejection: OnceLock::new(), pending, + routed, }), requests, ) @@ -62,8 +109,8 @@ impl RootEvidence { pub(super) async fn capture_on_activity(self: Arc, mut wakes: mpsc::Receiver<()>) { let capture = async { while wakes.recv().await.is_some() { - if self.enqueue(/*routed*/ None).await.is_err() { - if self.enqueued.lock().await.is_err() { + if self.enqueue(/*cutoff*/ None).await.is_err() { + if self.rejection.get().is_some() { break; } tracing::warn!("Guardian background capture failed; waiting for the next wake"); @@ -78,32 +125,62 @@ impl RootEvidence { } } + fn ensure_active(&self) -> anyhow::Result<()> { + if let Some(reason) = self.rejection.get() { + anyhow::bail!("{reason}"); + } + anyhow::ensure!(!self.pending.is_closed(), "Guardian housekeeper stopped"); + Ok(()) + } + #[expect( clippy::await_holding_invalid_type, reason = "capture and enqueue must agree on source order across concurrent approvals" )] - async fn enqueue( - &self, - routed: Option>, - ) -> anyhow::Result<()> { - let mut enqueued = self.enqueued.lock().await; - let cursor = enqueued - .as_mut() - .map_err(|reason| anyhow::anyhow!("{reason}"))?; - anyhow::ensure!(!self.pending.is_closed(), "Guardian housekeeper stopped"); - self.history.flush_thread(cursor.thread_id()).await?; - let history = cursor.read_history(self.history.as_ref()).await?; + async fn enqueue(&self, cutoff: Option) -> anyhow::Result { + // The writer can reach our cutoff while a newer capture holds the cursor. + let mut cursor = if let Some(end) = cutoff { + tokio::select! { + biased; + ready = wait_until_routed(self.routed.subscribe(), end) => { + self.ensure_active()?; + return ready; + } + cursor = self.enqueued.lock() => cursor, + } + } else { + self.enqueued.lock().await + }; + self.ensure_active()?; + let history = match cutoff { + Some(end) => { + let start = cursor.position(); + if covers(start, end)? { + return Ok(end); + } + self.history + .read_original_history( + cursor.thread_id(), + OriginalHistoryRequest::Range { start, end }, + ) + .await? + } + None => { + self.history.flush_thread(cursor.thread_id()).await?; + cursor.read_history(self.history.as_ref()).await? + } + }; let snapshot = match cursor.snapshot(history) { Ok(snapshot) => snapshot, Err(error) => { tracing::warn!(root_thread_id = %cursor.thread_id(), %error, "Guardian intake rejected stored evidence"); - *enqueued = Err(error.to_string()); + let _ = self.rejection.set(error.to_string()); return Err(error); } }; - // A review must wait for earlier writes even when this capture has no new originals. - if routed.is_none() && !snapshot.source_advanced() { - return Ok(()); + let end = snapshot.cutoff(); + if !snapshot.source_advanced() { + return Ok(end); } // Cancellation before reserving leaves the cursor unchanged. After reservation, // admission and advancing the captured range cannot be interrupted. @@ -122,20 +199,51 @@ impl RootEvidence { "Skipped incomplete Guardian evidence" ); } - permit.send(Capture { snapshot, routed }); - Ok(()) + permit.send(Capture { + snapshot, + routed: self.routed.clone(), + }); + Ok(end) } } impl RootEvidence { - /// Admit the current source boundary while the action is being submitted. A successful - /// reply means all matching deliveries through this point are already in actor inboxes. - pub async fn request_catch_up(&self) -> anyhow::Result> { - let (routed, ready) = oneshot::channel(); - tokio::select! { biased; + /// Capture only the position. Binding an action does not enqueue any housekeeper work. + pub(super) async fn capture_cutoff(&self) -> anyhow::Result { + self.ensure_active()?; + self.history.flush_thread(self.root).await?; + Ok(self + .history + .read_original_history(self.root, OriginalHistoryRequest::Tail) + .await? + .end) + } + + /// Submit a catch-up through the current durable tail and return its delivery acknowledgement. + pub async fn request_catch_up( + &self, + ) -> anyhow::Result> + Send + use<>> { + self.request_through(/*cutoff*/ None).await + } + + pub(super) async fn request_through( + &self, + cutoff: Option, + ) -> anyhow::Result> + Send + use<>> { + let target = tokio::select! { biased; _ = self.lifetime.cancellation.cancelled() => anyhow::bail!("Guardian intake stopped"), - result = self.enqueue(Some(routed)) => result?, - } - Ok(ready) + result = self.enqueue(cutoff) => result?, + }; + let routed = self.routed.subscribe(); + let writer = self.pending.clone(); + let cancel = self.lifetime.cancellation.clone(); + Ok(async move { + tokio::select! { + biased; + _ = cancel.cancelled() => anyhow::bail!("Guardian intake stopped"), + ready = wait_until_routed(routed, target) => ready, + _ = writer.closed() => anyhow::bail!("Guardian housekeeper stopped"), + } + }) } } diff --git a/codex-rs/ext/guardian-v3/src/cutoff_tests.rs b/codex-rs/ext/guardian-v3/src/cutoff_tests.rs index 64b2f31719..0e7cb5ebef 100644 --- a/codex-rs/ext/guardian-v3/src/cutoff_tests.rs +++ b/codex-rs/ext/guardian-v3/src/cutoff_tests.rs @@ -60,7 +60,7 @@ async fn skips_a_partial_delivery_once_across_wakes_and_catch_up() -> anyhow::Re history .persist_thread(root, PersistContext::Standard) .await?; - evidence.enqueue(/*routed*/ None).await?; + evidence.enqueue(/*cutoff*/ None).await?; let first = writer.try_recv()?; assert!(first.snapshot.records().is_empty()); @@ -87,9 +87,27 @@ async fn skips_a_partial_delivery_once_across_wakes_and_catch_up() -> anyhow::Re items, }) .await?; + // A request can go to a human after binding. Capturing its source position alone + // must leave the worker idle, even when there are unread originals. + let bound = evidence.capture_cutoff().await?; + assert!(matches!(writer.try_recv(), Err(TryRecvError::Empty))); + history + .append_items(AppendThreadItemsParams { + thread_id: root, + items: vec![RolloutItem::ResponseItem(ResponseItemEnvelope { + item: user_message_item("Later authorization"), + metadata: Some(CodexHarnessMetadata { + user_input_order: Some(3), + ..Default::default() + }), + })], + }) + .await?; + history.flush_thread(root).await?; let mut warnings = NamedTraceEvents::subscribe("guardian_v3.evidence_skipped"); - evidence.enqueue(/*routed*/ None).await?; - let routed = writer.try_recv()?.snapshot; + evidence.enqueue(Some(bound)).await?; + let capture = writer.try_recv()?; + let routed = &capture.snapshot; let [next] = routed.records() else { anyhow::bail!("expected only the complete delivery") }; @@ -98,14 +116,38 @@ async fn skips_a_partial_delivery_once_across_wakes_and_catch_up() -> anyhow::Re assert_eq!(next.id.ordinal, skipped + 1); warnings.next().await?; - evidence.enqueue(/*routed*/ None).await?; + // A second waiter at the same cutoff shares the writer's progress, even though + // a newer original is already durable. + let ready = evidence.request_through(Some(bound)).await?; assert!(matches!(writer.try_recv(), Err(TryRecvError::Empty))); - - // A review at that very same position still needs a response from the writer. - let mut ready = evidence.request_catch_up().await?; + tokio::pin!(ready); assert!(futures::poll!(&mut ready).is_pending()); - writer.try_recv()?.finish(); - assert_eq!(ready.await?, routed.cutoff()); + let cutoff = routed.cutoff(); + capture.finish(); + assert_eq!(ready.await?, cutoff); + let latest = evidence.request_catch_up().await?; + let later = writer.try_recv()?; + assert_eq!(later.snapshot.records().len(), 1); + assert!(later.snapshot.cutoff().end_ordinal_exclusive > cutoff.end_ordinal_exclusive); + let end = later.snapshot.cutoff(); + { + // A later enqueue may hold the cursor while the queue is full. + let _guard = evidence.enqueued.try_lock()?; + let through = async |target| evidence.request_through(Some(target)).await?.await; + assert_eq!( + through(bound).now_or_never().context("already routed")??, + bound + ); + let waiting = through(end); + tokio::pin!(waiting); + assert!(waiting.as_mut().now_or_never().is_none()); + later.finish(); + assert_eq!( + waiting.now_or_never().context("blocked after routing")??, + end + ); + } + assert_eq!(latest.await?, end); assert!(warnings.next().now_or_never().is_none()); test.codex.shutdown_and_wait().await?; Ok(()) @@ -125,6 +167,7 @@ async fn retries_unavailable_history_and_remembers_rejected_evidence() -> anyhow .persist_thread(root, PersistContext::Standard) .await?; let cursor = EvidenceCursor::from_now(history.as_ref(), root).await?; + let delivered = cursor.position(); let (evidence, _writer) = RootEvidence::new(Default::default(), history.clone(), cursor); let path = test @@ -134,10 +177,10 @@ async fn retries_unavailable_history_and_remembers_rejected_evidence() -> anyhow .context("rollout path")?; let hidden = path.with_extension("unavailable"); tokio::fs::rename(path, &hidden).await?; - let unavailable = evidence.enqueue(/*routed*/ None).await; + let unavailable = evidence.enqueue(/*cutoff*/ None).await; tokio::fs::rename(hidden, path).await?; assert!(unavailable.is_err()); - evidence.enqueue(/*routed*/ None).await?; + evidence.enqueue(/*cutoff*/ None).await?; history .append_items(AppendThreadItemsParams { @@ -148,7 +191,7 @@ async fn retries_unavailable_history_and_remembers_rejected_evidence() -> anyhow }) .await?; let rejected = evidence - .enqueue(/*routed*/ None) + .enqueue(/*cutoff*/ None) .await .err() .context("expected rejected evidence")?; @@ -158,11 +201,19 @@ async fn retries_unavailable_history_and_remembers_rejected_evidence() -> anyhow // A fresh flush would now fail. The review must still get the original rejection. assert!(history.flush_thread(root).await.is_err()); let error = evidence - .request_catch_up() + .capture_cutoff() .await .err() .context("expected a rejected cutoff")?; assert_eq!(error.to_string(), reason); + for cutoff in [None, Some(delivered)] { + let error = evidence + .request_through(cutoff) + .await + .err() + .context("expected a rejected cutoff")?; + assert_eq!(error.to_string(), reason); + } Ok(()) } @@ -325,7 +376,8 @@ async fn catch_up_waits_for_committed_delivery_and_allows_later_posts( .store(true, std::sync::atomic::Ordering::SeqCst); let first_original = append_user_message(2, "Stop the release.").await?; let wait = Duration::from_secs(15); - let mut first = evidence.request_catch_up().await?; + let first = evidence.request_catch_up().await?; + tokio::pin!(first); tokio::time::timeout(wait, host.started.notified()).await?; assert!(futures::poll!(&mut first).is_pending()); assert_eq!(inbox.len(), 0); diff --git a/codex-rs/ext/guardian-v3/src/host.rs b/codex-rs/ext/guardian-v3/src/host.rs index a18d202015..c8eafe819c 100644 --- a/codex-rs/ext/guardian-v3/src/host.rs +++ b/codex-rs/ext/guardian-v3/src/host.rs @@ -207,7 +207,9 @@ impl Host { .route_next(&capture.snapshot, cancellation) .await? != 0 - {} + { + capture.routed_through(housekeeper.cursor().position()); + } capture.finish(); let Some(next) = cancellation .run_until_cancelled(captures.recv()) diff --git a/codex-rs/thread-store/src/local/original_history.rs b/codex-rs/thread-store/src/local/original_history.rs index 9cb5907201..f77ec5fe7a 100644 --- a/codex-rs/thread-store/src/local/original_history.rs +++ b/codex-rs/thread-store/src/local/original_history.rs @@ -62,27 +62,43 @@ pub(super) async fn read( "original history requires a paginated root", )); } - let end_byte_offset = complete_end(&mut file)?; - let end_ordinal_exclusive = { - let mut scanner = ReverseJsonlScanner::new_at(&mut file, end_byte_offset)?; - let Some(ScanOutcome::Parsed(last)) = scanner.scan_next_rollout_line()? else { - return Err(io::Error::other("original history has an invalid tail")); - }; - last.ordinal - .and_then(|ordinal| ordinal.checked_add(1)) - .ok_or_else(|| io::Error::other("original history tail has no next ordinal"))? - }; - let end = HistoryPosition { - thread_id, - end_ordinal_exclusive, - end_byte_offset, + let end = match &request { + OriginalHistoryRequest::Range { end, .. } => { + if end.thread_id != thread_id + || end.end_byte_offset > file.seek(SeekFrom::End(0))? + { + return Err(io::Error::other( + "original history cutoff no longer applies", + )); + } + *end + } + OriginalHistoryRequest::Tail | OriginalHistoryRequest::After(_) => { + let end_byte_offset = complete_end(&mut file)?; + let end_ordinal_exclusive = { + let mut scanner = ReverseJsonlScanner::new_at(&mut file, end_byte_offset)?; + let Some(ScanOutcome::Parsed(last)) = scanner.scan_next_rollout_line()? else { + return Err(io::Error::other("original history has an invalid tail")); + }; + last.ordinal + .and_then(|ordinal| ordinal.checked_add(1)) + .ok_or_else(|| { + io::Error::other("original history tail has no next ordinal") + })? + }; + HistoryPosition { + thread_id, + end_ordinal_exclusive, + end_byte_offset, + } + } }; match request { OriginalHistoryRequest::Tail => Ok(OriginalHistoryRead { items: Vec::new(), end, }), - OriginalHistoryRequest::After(start) => { + OriginalHistoryRequest::After(start) | OriginalHistoryRequest::Range { start, .. } => { if start.thread_id != thread_id || start.end_byte_offset > end.end_byte_offset || start.end_ordinal_exclusive > end.end_ordinal_exclusive diff --git a/codex-rs/thread-store/src/local/original_history_tests.rs b/codex-rs/thread-store/src/local/original_history_tests.rs index 1b2e2372be..e4c85db8b9 100644 --- a/codex-rs/thread-store/src/local/original_history_tests.rs +++ b/codex-rs/thread-store/src/local/original_history_tests.rs @@ -64,6 +64,15 @@ async fn reads_complete_fixed_suffix_and_rejects_truncated_source() later["ordinal"] = json!(2); later["payload"]["content"][0]["text"] = json!("After the cutoff"); writeln!(file, "{later}")?; + let bounded = store + .read_original_history(owner, OriginalHistoryRequest::Range { start, end }) + .await?; + assert_eq!(bounded.end, end); + assert_eq!(bounded.items.len(), 1); + assert_eq!( + serde_json::to_value(&bounded.items[0].item)?, + serde_json::to_value(&read.items[0].item)? + ); assert_eq!(read.end, end); assert_eq!(read.items.len(), 1); assert_eq!(read.items[0].end, end); diff --git a/codex-rs/thread-store/src/original_history.rs b/codex-rs/thread-store/src/original_history.rs index 486311d30b..74cc9e5668 100644 --- a/codex-rs/thread-store/src/original_history.rs +++ b/codex-rs/thread-store/src/original_history.rs @@ -12,6 +12,11 @@ pub enum OriginalHistoryRequest { /// Freeze the current complete tail and read originals after this position. /// Appends beyond that cutoff are excluded from the returned records. After(HistoryPosition), + /// Read only the records between two previously captured positions in this rollout. + Range { + start: HistoryPosition, + end: HistoryPosition, + }, } /// One original record and the exclusive position immediately after it.