mirror of
https://github.com/openai/codex.git
synced 2026-11-24 23:20:47 +00:00
Preserve Guardian review evidence when callers are cancelled (#63693)
## Why Cancelling a turn or tool call could drop a pending history write or lose an answer the session had already accepted. A missing write leaves Guardian unable to confirm that its review history is complete. ## What changed Let the session finish tracked evidence writes in queue order after the caller is cancelled, and drain those writes on shutdown. Record verified `request_user_input` answers at acceptance before waking the tool. Continue persisting evidence after an earlier write goes unconfirmed, while still reporting the history gap to Guardian. ## Testing Regression tests cover initial and retried reviews waiting for a revocation after caller cancellation, and an accepted answer reaching history before the turn interruption even with an earlier unconfirmed write. GitOrigin-RevId: b8e212d34686bbc793002a34f5a97834a900a342
This commit is contained in:
@@ -18,9 +18,11 @@ pub struct PendingReviewWrites {
|
||||
pending: Mutex<Vec<watch::Receiver<bool>>>,
|
||||
}
|
||||
|
||||
/// Receipt for one history append. Dropping it without confirmation leaves the
|
||||
/// evidence unavailable to reviews for the lifetime of this root.
|
||||
pub(crate) struct ReviewWrite(watch::Sender<bool>);
|
||||
/// An evidence write that the session must finish. After a failed append, we
|
||||
/// still preserve later writes, but can no longer confirm a complete history.
|
||||
pub(crate) struct ReviewWrite {
|
||||
receipt: Option<watch::Sender<bool>>,
|
||||
}
|
||||
|
||||
impl ReviewWrite {
|
||||
/// Record under the session lock so a reviewer cannot see the new revision
|
||||
@@ -35,21 +37,19 @@ impl ReviewWrite {
|
||||
};
|
||||
let before = history.guardian_revisions();
|
||||
let result = record(history);
|
||||
let write = if history.guardian_revisions() != before {
|
||||
writes.begin()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let write = (history.guardian_revisions() != before).then(|| writes.begin());
|
||||
(result, write)
|
||||
}
|
||||
|
||||
pub(crate) fn confirm(self) {
|
||||
self.0.send_replace(true);
|
||||
if let Some(receipt) = self.receipt {
|
||||
receipt.send_replace(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PendingReviewWrites {
|
||||
fn begin(&self) -> Option<ReviewWrite> {
|
||||
fn begin(&self) -> ReviewWrite {
|
||||
let mut pending = self.pending.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
pending.retain(|write| !*write.borrow());
|
||||
// A dropped or failed append leaves a gap for this root's lifetime.
|
||||
@@ -57,11 +57,13 @@ impl PendingReviewWrites {
|
||||
.iter()
|
||||
.any(|write| write.has_changed().is_err() && !*write.borrow())
|
||||
{
|
||||
return None;
|
||||
return ReviewWrite { receipt: None };
|
||||
}
|
||||
let (appended, write) = watch::channel(/*init*/ false);
|
||||
pending.push(write);
|
||||
Some(ReviewWrite(appended))
|
||||
ReviewWrite {
|
||||
receipt: Some(appended),
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait for writes already visible to this review. Later instructions are
|
||||
|
||||
@@ -300,7 +300,7 @@ async fn should_install_mcp_dependencies(
|
||||
sess.notify_user_input_response(sub_id, empty.clone()).await;
|
||||
empty
|
||||
}
|
||||
response = response_fut => response.map(|accepted| accepted.response).unwrap_or_else(|| RequestUserInputResponse {
|
||||
response = response_fut => response.unwrap_or_else(|| RequestUserInputResponse {
|
||||
answers: HashMap::new(),
|
||||
}),
|
||||
};
|
||||
|
||||
@@ -1957,7 +1957,7 @@ pub(crate) async fn request_mcp_tool_user_approval(
|
||||
.await;
|
||||
let cancellation_reason = response
|
||||
.as_ref()
|
||||
.and_then(|accepted| accepted.response.answers.get(&question_id))
|
||||
.and_then(|response| response.answers.get(&question_id))
|
||||
.filter(|answer| {
|
||||
answer
|
||||
.answers
|
||||
@@ -1971,10 +1971,7 @@ pub(crate) async fn request_mcp_tool_user_approval(
|
||||
.then_some(McpApprovalCancellationReason::Interrupted)
|
||||
});
|
||||
(
|
||||
parse_mcp_tool_approval_response(
|
||||
response.map(|accepted| accepted.response),
|
||||
&question_id,
|
||||
),
|
||||
parse_mcp_tool_approval_response(response, &question_id),
|
||||
cancellation_reason,
|
||||
)
|
||||
};
|
||||
|
||||
@@ -319,6 +319,8 @@ pub(crate) use self::input_queue::SubmittedAdditionalContext;
|
||||
pub(crate) use self::input_queue::TurnInput;
|
||||
pub(crate) use self::input_queue::TurnInputQueue;
|
||||
pub(crate) use self::input_queue::UserInputMetadata;
|
||||
use self::retained_context::AcceptedUserInputResponse;
|
||||
pub(crate) use self::retained_context::PendingUserInput;
|
||||
use self::review::spawn_review_thread;
|
||||
use self::session::AppServerClientMetadata;
|
||||
use self::session::Session;
|
||||
@@ -346,7 +348,6 @@ use crate::mcp::McpThreadIdentity;
|
||||
use crate::rollout::map_session_init_error;
|
||||
use crate::session::startup_prewarm::SessionStartupPrewarmHandle;
|
||||
use crate::shell;
|
||||
use crate::state::AcceptedUserInputResponse;
|
||||
use crate::state::AutoCompactWindowIds;
|
||||
use crate::state::AutoCompactWindowSnapshot;
|
||||
use crate::state::PendingApproval;
|
||||
@@ -3745,48 +3746,76 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
#[expect(
|
||||
clippy::await_holding_invalid_type,
|
||||
reason = "active turn checks and turn state updates must remain atomic"
|
||||
)]
|
||||
pub(crate) async fn request_user_input(
|
||||
&self,
|
||||
turn_context: &TurnContext,
|
||||
call_id: String,
|
||||
args: RequestUserInputArgs,
|
||||
) -> Option<AcceptedUserInputResponse> {
|
||||
) -> Option<RequestUserInputResponse> {
|
||||
self.prompt_user(turn_context, call_id, args, /*verify*/ false)
|
||||
.await
|
||||
}
|
||||
|
||||
#[expect(
|
||||
clippy::await_holding_invalid_type,
|
||||
reason = "active turn checks and turn state updates must remain atomic"
|
||||
)]
|
||||
pub(crate) async fn prompt_user(
|
||||
&self,
|
||||
turn_context: &TurnContext,
|
||||
call_id: String,
|
||||
args: RequestUserInputArgs,
|
||||
verify: bool,
|
||||
) -> Option<RequestUserInputResponse> {
|
||||
let user_wait_owner = self.user_wait_timing_owner(turn_context, Some(&call_id));
|
||||
let _elicitation = self.services.elicitations.register();
|
||||
let sub_id = turn_context.sub_id.clone();
|
||||
let elicitation = self.services.elicitations.register();
|
||||
let sub_id = &turn_context.sub_id;
|
||||
let (tx_response, rx_response) = oneshot::channel();
|
||||
let event_id = sub_id.clone();
|
||||
let prompt = RequestUserInputEvent {
|
||||
call_id,
|
||||
turn_id: sub_id.clone(),
|
||||
questions: args.questions,
|
||||
is_blocking: args.is_blocking,
|
||||
auto_resolution_ms: args.auto_resolution_ms,
|
||||
};
|
||||
// Only a tracked root takes ownership of the prompt before the tool resumes.
|
||||
let mut verify_on_return = verify.then(|| prompt.clone());
|
||||
let verify_on_accept = verify_on_return.take_if(|_| self.pending_review_writes.is_some());
|
||||
let prev_entry = {
|
||||
let mut active = self.active_turn.lock().await;
|
||||
match active.as_mut() {
|
||||
Some(at) => {
|
||||
let mut ts = at.turn_state.lock().await;
|
||||
ts.insert_pending_user_input(sub_id, tx_response)
|
||||
ts.insert_pending_user_input(
|
||||
sub_id.clone(),
|
||||
PendingUserInput {
|
||||
tx_response,
|
||||
verify_on_accept,
|
||||
},
|
||||
)
|
||||
}
|
||||
None => None,
|
||||
}
|
||||
};
|
||||
if prev_entry.is_some() {
|
||||
warn!("Overwriting existing pending user input for sub_id: {event_id}");
|
||||
warn!("Overwriting existing pending user input for sub_id: {sub_id}");
|
||||
}
|
||||
|
||||
let event = EventMsg::RequestUserInput(RequestUserInputEvent {
|
||||
call_id,
|
||||
turn_id: turn_context.sub_id.clone(),
|
||||
questions: args.questions,
|
||||
is_blocking: args.is_blocking,
|
||||
auto_resolution_ms: args.auto_resolution_ms,
|
||||
});
|
||||
turn_context
|
||||
.turn_metadata_state
|
||||
.mark_user_input_requested_during_turn();
|
||||
let _user_wait = self.start_user_wait_timing(turn_context, user_wait_owner.as_deref());
|
||||
self.send_event(turn_context, event).await;
|
||||
rx_response.await.ok()
|
||||
let user_wait = self.start_user_wait_timing(turn_context, user_wait_owner.as_deref());
|
||||
self.send_event(turn_context, EventMsg::RequestUserInput(prompt))
|
||||
.await;
|
||||
let mut accepted = rx_response.await.ok()?;
|
||||
drop(user_wait);
|
||||
drop(elicitation);
|
||||
if let Some(recording) = accepted.recording.take() {
|
||||
let _ = recording.await;
|
||||
} else if let Some(event) = accepted.verified_answer(verify_on_return) {
|
||||
self.record_retained_context(event).await;
|
||||
}
|
||||
Some(accepted.response)
|
||||
}
|
||||
|
||||
#[expect(
|
||||
@@ -3804,7 +3833,13 @@ impl Session {
|
||||
Some(at) => {
|
||||
let sender = at.turn_state.lock().await.remove_pending_user_input(sub_id);
|
||||
match sender {
|
||||
Some(sender) => Some((sender, self.reserve_user_input_order().await)),
|
||||
Some(pending)
|
||||
if pending.verify_on_accept.is_some()
|
||||
&& pending.tx_response.is_closed() =>
|
||||
{
|
||||
return;
|
||||
}
|
||||
Some(pending) => Some((pending, self.reserve_user_input_order().await)),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
@@ -3812,13 +3847,17 @@ impl Session {
|
||||
}
|
||||
};
|
||||
match entry {
|
||||
Some((tx_response, acceptance_order)) => {
|
||||
tx_response
|
||||
.send(AcceptedUserInputResponse {
|
||||
response,
|
||||
acceptance_order,
|
||||
})
|
||||
.ok();
|
||||
Some((pending, acceptance_order)) => {
|
||||
let mut accepted = AcceptedUserInputResponse {
|
||||
response,
|
||||
acceptance_order,
|
||||
recording: None,
|
||||
};
|
||||
// Publish tracked evidence before waking the cancellable tool waiter.
|
||||
if let Some(event) = accepted.verified_answer(pending.verify_on_accept) {
|
||||
accepted.recording = self.start_retained_context(event).await;
|
||||
}
|
||||
let _ = pending.tx_response.send(accepted);
|
||||
}
|
||||
None => {
|
||||
warn!("No pending user input found for sub_id: {sub_id}");
|
||||
@@ -4187,20 +4226,21 @@ impl Session {
|
||||
let has_user_turn_boundary = items
|
||||
.iter()
|
||||
.any(|envelope| crate::context_manager::is_user_turn_boundary(&envelope.item));
|
||||
// Thread settings precede the first accepted input. Keep the persistence lock
|
||||
// through its seal, and clear the pending flag only after the seal succeeds.
|
||||
let realtime_settings_guard = if realtime.is_some()
|
||||
// Prepare settings before publishing tracked evidence so there is no await
|
||||
// between recording the revision and handing the append to the session.
|
||||
let prepare_before_recording = realtime.is_some() || self.pending_review_writes.is_some();
|
||||
let mut early_guard = if prepare_before_recording
|
||||
&& has_user_turn_boundary
|
||||
&& self.reference_context_item().await.is_none()
|
||||
{
|
||||
Some(thread_settings::acquire_persistence_lock(self).await)
|
||||
Some(thread_settings::acquire_owned_persistence_lock(self).await)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let realtime_initial_settings = realtime_settings_guard.is_some()
|
||||
let initial_settings_pending = early_guard.is_some()
|
||||
&& self.reference_context_item().await.is_none()
|
||||
&& self.state.lock().await.initial_settings_pending();
|
||||
let realtime_settings_event = if realtime_initial_settings {
|
||||
let mut early_settings = if initial_settings_pending {
|
||||
Some(thread_settings::applied_event(self).await)
|
||||
} else {
|
||||
None
|
||||
@@ -4262,13 +4302,10 @@ impl Session {
|
||||
&turn_context.sub_id,
|
||||
envelope,
|
||||
prepared,
|
||||
realtime_settings_event,
|
||||
early_settings.take(),
|
||||
policy,
|
||||
)
|
||||
.await?;
|
||||
if realtime_initial_settings {
|
||||
state.take_initial_settings_pending();
|
||||
}
|
||||
response_items = vec![envelope.item.clone()];
|
||||
items = vec![envelope];
|
||||
} else if matches!(&realtime, Some(RealtimeRecord::Chunk)) {
|
||||
@@ -4281,23 +4318,24 @@ impl Session {
|
||||
.record_realtime_chunk_input(
|
||||
&mut state,
|
||||
envelope.clone(),
|
||||
realtime_settings_event,
|
||||
early_settings.take(),
|
||||
policy,
|
||||
)
|
||||
.await?;
|
||||
if realtime_initial_settings {
|
||||
state.take_initial_settings_pending();
|
||||
}
|
||||
response_items = vec![envelope.item];
|
||||
} else {
|
||||
state
|
||||
.pending_audio_duration_ids
|
||||
.extend(file_audio::file_ids(&items).cloned());
|
||||
(_, review_write) = ReviewWrite::record(
|
||||
let (_, write) = ReviewWrite::record(
|
||||
self.pending_review_writes.as_deref(),
|
||||
&mut state.history,
|
||||
|history| history.record_annotated_items(&mut items, policy),
|
||||
);
|
||||
review_write = write.and_then(|write| self.track_review_write(write));
|
||||
}
|
||||
if initial_settings_pending {
|
||||
state.take_initial_settings_pending();
|
||||
}
|
||||
state
|
||||
.current_time_reminder
|
||||
@@ -4319,30 +4357,39 @@ impl Session {
|
||||
if let Some(RealtimeRecord::Handoff(prepared)) = &realtime {
|
||||
self.finish_realtime_handoff(prepared, &items[0]).await;
|
||||
} else if !matches!(&realtime, Some(RealtimeRecord::Chunk)) {
|
||||
let settings_guard =
|
||||
if has_user_turn_boundary && self.reference_context_item().await.is_none() {
|
||||
Some(thread_settings::acquire_persistence_lock(self).await)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let settings_guard = if !prepare_before_recording
|
||||
&& has_user_turn_boundary
|
||||
&& self.reference_context_item().await.is_none()
|
||||
{
|
||||
Some(thread_settings::acquire_persistence_lock(self).await)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let initial_settings = if settings_guard.is_some()
|
||||
&& self.reference_context_item().await.is_none()
|
||||
&& self.state.lock().await.take_initial_settings_pending()
|
||||
{
|
||||
Some(thread_settings::applied_event(self).await)
|
||||
} else {
|
||||
None
|
||||
early_settings
|
||||
};
|
||||
let rollout_items = initial_settings
|
||||
.into_iter()
|
||||
.map(RolloutItem::EventMsg)
|
||||
.chain(items.into_iter().map(RolloutItem::ResponseItem))
|
||||
.collect::<Vec<_>>();
|
||||
self.persist_rollout_items_with_ack(&rollout_items, review_write)
|
||||
.await;
|
||||
if let Some(write) = review_write {
|
||||
if let Some(recording) =
|
||||
self.start_review_write(rollout_items, write, early_guard.take())
|
||||
{
|
||||
let _ = recording.await;
|
||||
}
|
||||
} else {
|
||||
self.persist_rollout_items(&rollout_items).await;
|
||||
}
|
||||
drop(settings_guard);
|
||||
}
|
||||
drop(realtime_settings_guard);
|
||||
drop(early_guard);
|
||||
if turn_context.config.memories.disable_on_external_context
|
||||
&& let Some(item) = response_items
|
||||
.iter()
|
||||
@@ -5556,13 +5603,30 @@ impl Session {
|
||||
.await
|
||||
}
|
||||
|
||||
#[tracing::instrument(name = "persist_rollout_items", level = "trace", skip_all, fields(item_count = items.len()))]
|
||||
async fn persist_rollout_items_with_ack(
|
||||
&self,
|
||||
items: &[RolloutItem],
|
||||
write: Option<ReviewWrite>,
|
||||
) -> bool {
|
||||
if let Some(live_thread) = self.live_thread()
|
||||
Self::append_rollout_items(
|
||||
self.live_thread(),
|
||||
&self.services.local_agent_runtime,
|
||||
self.thread_id,
|
||||
items,
|
||||
write,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[tracing::instrument(name = "persist_rollout_items", level = "trace", skip_all, fields(item_count = items.len()))]
|
||||
async fn append_rollout_items(
|
||||
live_thread: Option<&LiveThread>,
|
||||
runtime: &crate::agent::control::LocalAgentRuntime,
|
||||
thread_id: ThreadId,
|
||||
items: &[RolloutItem],
|
||||
write: Option<ReviewWrite>,
|
||||
) -> bool {
|
||||
if let Some(live_thread) = live_thread
|
||||
&& let Err(e) = live_thread
|
||||
.append_items_with_ack(items, move || {
|
||||
if let Some(write) = write {
|
||||
@@ -5572,17 +5636,12 @@ impl Session {
|
||||
.await
|
||||
{
|
||||
error!("failed to record rollout items: {e:#}");
|
||||
if self
|
||||
.services
|
||||
.local_agent_runtime
|
||||
.suspension_root()
|
||||
.is_some()
|
||||
{
|
||||
self.services.local_agent_runtime.record_shutdown_failure(
|
||||
if runtime.suspension_root().is_some() {
|
||||
runtime.record_shutdown_failure(
|
||||
crate::thread_manager::AgentTreeShutdownFailure::operation_failed(
|
||||
"tree_suspension",
|
||||
"append_history",
|
||||
Some(self.thread_id),
|
||||
Some(thread_id),
|
||||
crate::thread_manager::thread_store_error_kind(&e),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -18,10 +18,17 @@ use codex_history::ResponseItemEnvelope;
|
||||
use codex_history::RetainedContextEvent;
|
||||
use codex_history::RetainedUserMessage;
|
||||
use codex_history::RolloutItem;
|
||||
use codex_history::VerifiedAnswer;
|
||||
use codex_history::VerifiedQuestionAnswer;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_protocol::request_user_input::RequestUserInputEvent;
|
||||
use codex_protocol::request_user_input::RequestUserInputResponse;
|
||||
use codex_thread_store::PersistContext;
|
||||
use codex_utils_output_truncation::TruncationPolicy;
|
||||
use futures::FutureExt;
|
||||
use tokio::sync::OwnedSemaphorePermit;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::sync::watch;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio_util::task::TaskTracker;
|
||||
@@ -31,6 +38,65 @@ use super::Session;
|
||||
use super::TurnContext;
|
||||
use super::thread_settings;
|
||||
|
||||
pub(crate) struct PendingUserInput {
|
||||
pub(super) tx_response: oneshot::Sender<AcceptedUserInputResponse>,
|
||||
pub(super) verify_on_accept: Option<RequestUserInputEvent>,
|
||||
}
|
||||
|
||||
pub(super) struct AcceptedUserInputResponse {
|
||||
pub(super) response: RequestUserInputResponse,
|
||||
/// Order reserved when the host accepts this response.
|
||||
pub(super) acceptance_order: u64,
|
||||
/// Dropping the waiter detaches the session's history append.
|
||||
pub(super) recording: Option<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl AcceptedUserInputResponse {
|
||||
pub(super) fn verified_answer(
|
||||
&self,
|
||||
prompt: Option<RequestUserInputEvent>,
|
||||
) -> Option<RetainedContextEvent> {
|
||||
let prompt = prompt?;
|
||||
let questions = prompt
|
||||
.questions
|
||||
.into_iter()
|
||||
.filter_map(|question| {
|
||||
let response = self.response.answers.get(&question.id)?;
|
||||
let answers = response
|
||||
.answers
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.filter(|answer| !answer.trim().is_empty())
|
||||
.collect::<Vec<_>>();
|
||||
if answers.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut question_text = question.question;
|
||||
for option in question
|
||||
.options
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|option| response.answers.contains(&option.label))
|
||||
{
|
||||
question_text.push_str(&format!("\n{}: {}", option.label, option.description));
|
||||
}
|
||||
Some(VerifiedQuestionAnswer {
|
||||
question: question_text,
|
||||
answer: answers.join("\n"),
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
(!questions.is_empty()).then_some(RetainedContextEvent::VerifiedAnswer {
|
||||
answer: VerifiedAnswer {
|
||||
turn_id: prompt.turn_id,
|
||||
call_id: prompt.call_id,
|
||||
questions,
|
||||
},
|
||||
acceptance_order: Some(self.acceptance_order),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Only unrecorded starts need a reservation; abandoned entries expire with the turn.
|
||||
#[derive(Default)]
|
||||
pub(super) struct PendingAssistantMessageOrders(pub(super) Mutex<HashMap<String, u64>>);
|
||||
@@ -156,22 +222,76 @@ impl Session {
|
||||
pending.clone()
|
||||
}
|
||||
|
||||
pub(crate) async fn record_retained_context(&self, mut event: RetainedContextEvent) {
|
||||
pub(crate) async fn record_retained_context(&self, event: RetainedContextEvent) {
|
||||
if let Some(recording) = self.start_retained_context(event).await {
|
||||
let _ = recording.await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn start_retained_context(
|
||||
&self,
|
||||
mut event: RetainedContextEvent,
|
||||
) -> Option<JoinHandle<()>> {
|
||||
// Share the checkpoint persistence lock so a fact cannot land on the wrong side
|
||||
// of the checkpoint/suffix boundary. Ephemeral threads use the same live state.
|
||||
let _guard = thread_settings::acquire_persistence_lock(self).await;
|
||||
let (recorded, write) = {
|
||||
let guard = thread_settings::acquire_owned_persistence_lock(self).await;
|
||||
let write = {
|
||||
let mut state = self.state.lock().await;
|
||||
ReviewWrite::record(
|
||||
let (recorded, write) = ReviewWrite::record(
|
||||
self.pending_review_writes.as_deref(),
|
||||
&mut state.history,
|
||||
|history| history.record_retained_context_for_persistence(&mut event),
|
||||
)
|
||||
);
|
||||
if !recorded {
|
||||
return None;
|
||||
}
|
||||
write.and_then(|write| self.track_review_write(write))
|
||||
};
|
||||
if recorded {
|
||||
self.persist_rollout_items_with_ack(&[RolloutItem::RetainedContext(event)], write)
|
||||
.await;
|
||||
let item = RolloutItem::RetainedContext(event);
|
||||
if let Some(write) = write {
|
||||
return self.start_review_write(vec![item], write, Some(guard));
|
||||
}
|
||||
self.persist_rollout_items(&[item]).await;
|
||||
None
|
||||
}
|
||||
|
||||
/// Under the state lock, enroll this append in the same shutdown drain as
|
||||
/// confirmed Code Mode deliveries. A closed session cannot admit more work.
|
||||
pub(super) fn track_review_write(
|
||||
&self,
|
||||
write: ReviewWrite,
|
||||
) -> Option<(ReviewWrite, TaskTrackerToken)> {
|
||||
self.track_code_mode_message().map(|token| (write, token))
|
||||
}
|
||||
|
||||
/// Call before yielding after admission. Start in caller order, then let the
|
||||
/// session finish the append even if the caller drops its join handle.
|
||||
pub(super) fn start_review_write(
|
||||
&self,
|
||||
items: Vec<RolloutItem>,
|
||||
(write, token): (ReviewWrite, TaskTrackerToken),
|
||||
settings: Option<OwnedSemaphorePermit>,
|
||||
) -> Option<JoinHandle<()>> {
|
||||
let live_thread = self.live_thread().cloned();
|
||||
let runtime = self.services.local_agent_runtime.clone();
|
||||
let thread_id = self.thread_id;
|
||||
let mut append = Box::pin(async move {
|
||||
let _token = token;
|
||||
let _settings = settings;
|
||||
Self::append_rollout_items(
|
||||
live_thread.as_ref(),
|
||||
&runtime,
|
||||
thread_id,
|
||||
&items,
|
||||
Some(write),
|
||||
)
|
||||
.await;
|
||||
});
|
||||
// Reserve the writer's queue position even if this poll exhausted its Tokio budget.
|
||||
tokio::task::unconstrained(append.as_mut())
|
||||
.now_or_never()
|
||||
.is_none()
|
||||
.then(|| tokio::spawn(append))
|
||||
}
|
||||
|
||||
pub(crate) fn track_code_mode_message(&self) -> Option<TaskTrackerToken> {
|
||||
|
||||
@@ -2,12 +2,20 @@ use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_history::RetainedContextEntry;
|
||||
use codex_history::RetainedContextEvent;
|
||||
use codex_history::RetainedUserMessage;
|
||||
use codex_history::RolloutItem;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use core_test_support::responses::user_message_item;
|
||||
use futures::FutureExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use test_case::test_case;
|
||||
|
||||
use super::thread_settings;
|
||||
use crate::guardian_review::PendingReviewWrites;
|
||||
use crate::guardian_review::ReviewPreparationError;
|
||||
use crate::rollout::recorder::RolloutRecorder;
|
||||
use crate::session::tests::attach_thread_persistence;
|
||||
use crate::session::tests::make_session_and_context;
|
||||
|
||||
@@ -39,6 +47,82 @@ async fn guardian_waits_for_detached_confirmed_delivery() {
|
||||
recording.await.expect("delivery task finished");
|
||||
}
|
||||
|
||||
#[test_case(false; "complete history")]
|
||||
#[test_case(true; "earlier write unconfirmed")]
|
||||
#[tokio::test]
|
||||
async fn guardian_retains_an_accepted_answer_when_the_tool_is_cancelled(
|
||||
earlier_write_unconfirmed: bool,
|
||||
) -> anyhow::Result<()> {
|
||||
let (mut session, turn) = make_session_and_context().await;
|
||||
let writes = Arc::new(PendingReviewWrites::default());
|
||||
session.pending_review_writes = Some(Arc::clone(&writes));
|
||||
if earlier_write_unconfirmed {
|
||||
// Without a live writer the instruction is recorded but its receipt goes unconfirmed.
|
||||
session
|
||||
.record_conversation_items(&turn, turn.model_info(), &[user_message_item("Wait.")])
|
||||
.await;
|
||||
}
|
||||
let path = attach_thread_persistence(&mut session).await;
|
||||
*session.active_turn.lock().await = Some(Default::default());
|
||||
let (tx, events) = async_channel::unbounded();
|
||||
session.tx_event = tx;
|
||||
let args = serde_json::from_value(json!({
|
||||
"questions": [{"id": "publish", "header": "Release", "question": "May I publish?"}],
|
||||
"isBlocking": true,
|
||||
}))?;
|
||||
let mut request =
|
||||
Box::pin(session.prompt_user(&turn, "ask".into(), args, /*verify*/ true));
|
||||
tokio::select! {
|
||||
_ = &mut request => panic!("tool completed before the answer"),
|
||||
event = events.recv() => assert!(matches!(event.unwrap().msg, EventMsg::RequestUserInput(_))),
|
||||
}
|
||||
let response = serde_json::from_value(json!({"answers": {"publish": {"answers": ["No"]}}}))?;
|
||||
// Hold the writer. Accepting the answer must leave the session free to process Stop.
|
||||
let flush = tokio::task::unconstrained(session.live_thread().unwrap().flush());
|
||||
tokio::pin!(flush);
|
||||
assert!(futures::poll!(&mut flush).is_pending());
|
||||
tokio::task::unconstrained(session.notify_user_input_response(&turn.sub_id, response))
|
||||
.now_or_never()
|
||||
.expect("answer handling blocked on the writer");
|
||||
drop(request);
|
||||
|
||||
// Queue the interrupt before the detached task gets a turn on this runtime.
|
||||
let interrupt = [RolloutItem::EventMsg(EventMsg::TurnAborted(
|
||||
serde_json::from_value(json!({"turn_id": turn.sub_id, "reason": "interrupted"}))?,
|
||||
))];
|
||||
let append = tokio::task::unconstrained(session.persist_rollout_items(&interrupt));
|
||||
let (appended, flushed) = tokio::join!(biased; append, flush);
|
||||
flushed?;
|
||||
assert!(appended);
|
||||
session.drain_code_mode_messages().await;
|
||||
if earlier_write_unconfirmed {
|
||||
assert_eq!(
|
||||
writes.wait().await,
|
||||
Err(ReviewPreparationError::HistoryWriteUnconfirmed)
|
||||
);
|
||||
} else {
|
||||
writes.wait().await?;
|
||||
}
|
||||
|
||||
let history = RolloutRecorder::get_rollout_history(&path).await?;
|
||||
let events = history
|
||||
.get_rollout_items()
|
||||
.iter()
|
||||
.filter_map(|item| match item {
|
||||
RolloutItem::RetainedContext(RetainedContextEvent::VerifiedAnswer {
|
||||
answer, ..
|
||||
}) => Some(answer.questions[0].answer.as_str()),
|
||||
RolloutItem::EventMsg {
|
||||
event: EventMsg::TurnAborted(_),
|
||||
..
|
||||
} => Some("interrupted"),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(events, ["No", "interrupted"]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shutdown_retains_an_admitted_delivery_until_persistence_finishes() {
|
||||
let (session, _) = make_session_and_context().await;
|
||||
|
||||
@@ -90,7 +90,7 @@ pub(crate) struct Session {
|
||||
pub(super) initial_context_publication: Semaphore,
|
||||
/// Orders accepted settings commits and their persisted events with compaction checkpoints.
|
||||
/// Keep this separate from `state` so storage I/O does not block runtime state access.
|
||||
pub(super) thread_settings_persistence: Semaphore,
|
||||
pub(super) thread_settings_persistence: Arc<Semaphore>,
|
||||
pub(super) code_mode_message_tasks: CodeModeMessageTasks,
|
||||
/// Serializes rebuild/apply cycles for the running proxy; each cycle
|
||||
/// rebuilds from the current SessionState while holding this lock.
|
||||
@@ -2045,7 +2045,7 @@ impl Session {
|
||||
agent_status,
|
||||
state: Mutex::new(state),
|
||||
initial_context_publication: Semaphore::new(/*permits*/ 1),
|
||||
thread_settings_persistence: Semaphore::new(/*permits*/ 1),
|
||||
thread_settings_persistence: Arc::new(Semaphore::new(/*permits*/ 1)),
|
||||
code_mode_message_tasks: CodeModeMessageTasks::default(),
|
||||
managed_network_proxy_refresh_lock: Semaphore::new(/*permits*/ 1),
|
||||
features: config.features.clone(),
|
||||
|
||||
@@ -6851,7 +6851,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) {
|
||||
agent_status: agent_status_tx,
|
||||
state: Mutex::new(state),
|
||||
initial_context_publication: Semaphore::new(/*permits*/ 1),
|
||||
thread_settings_persistence: Semaphore::new(/*permits*/ 1),
|
||||
thread_settings_persistence: Arc::new(Semaphore::new(/*permits*/ 1)),
|
||||
code_mode_message_tasks: Default::default(),
|
||||
managed_network_proxy_refresh_lock: Semaphore::new(/*permits*/ 1),
|
||||
features: config.features.clone(),
|
||||
@@ -9220,7 +9220,7 @@ where
|
||||
agent_status: agent_status_tx,
|
||||
state: Mutex::new(state),
|
||||
initial_context_publication: Semaphore::new(/*permits*/ 1),
|
||||
thread_settings_persistence: Semaphore::new(/*permits*/ 1),
|
||||
thread_settings_persistence: Arc::new(Semaphore::new(/*permits*/ 1)),
|
||||
code_mode_message_tasks: Default::default(),
|
||||
managed_network_proxy_refresh_lock: Semaphore::new(/*permits*/ 1),
|
||||
features: config.features.clone(),
|
||||
|
||||
@@ -19,6 +19,7 @@ use codex_protocol::protocol::ThreadSettingsSnapshot;
|
||||
use codex_thread_store::ThreadStoreError;
|
||||
use codex_thread_store::ThreadStoreResult;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::OwnedSemaphorePermit;
|
||||
use tokio::sync::SemaphorePermit;
|
||||
|
||||
impl Session {
|
||||
@@ -157,6 +158,14 @@ pub(super) async fn acquire_persistence_lock(session: &Session) -> SemaphorePerm
|
||||
.unwrap_or_else(|_| unreachable!("thread settings persistence semaphore is never closed"))
|
||||
}
|
||||
|
||||
/// Keep checkpoint ordering when a history write outlives its caller.
|
||||
pub(super) async fn acquire_owned_persistence_lock(session: &Session) -> OwnedSemaphorePermit {
|
||||
Arc::clone(&session.thread_settings_persistence)
|
||||
.acquire_owned()
|
||||
.await
|
||||
.unwrap_or_else(|_| unreachable!("thread settings persistence semaphore is never closed"))
|
||||
}
|
||||
|
||||
/// Applies persistent settings and emits the resulting thread-owned snapshot.
|
||||
pub(super) async fn apply_update(
|
||||
session: &Session,
|
||||
|
||||
@@ -13,7 +13,6 @@ pub(crate) use auto_compact_window::AutoCompactWindowSnapshot;
|
||||
pub(crate) use service::SessionServices;
|
||||
pub(crate) use session::ReasoningEffortPin;
|
||||
pub(crate) use session::SessionState;
|
||||
pub(crate) use turn::AcceptedUserInputResponse;
|
||||
pub(crate) use turn::ActiveTurn;
|
||||
pub(crate) use turn::MailboxDeliveryPhase;
|
||||
pub(crate) use turn::PendingApproval;
|
||||
|
||||
@@ -15,13 +15,13 @@ use codex_diagnostics::GaugeGuard;
|
||||
use codex_protocol::dynamic_tools::DynamicToolResponse;
|
||||
use codex_protocol::request_permissions::RequestPermissionProfile;
|
||||
use codex_protocol::request_permissions::RequestPermissionsResponse;
|
||||
use codex_protocol::request_user_input::RequestUserInputResponse;
|
||||
use codex_rmcp_client::ElicitationResponse;
|
||||
use rmcp::model::RequestId;
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
use super::TurnTokenUsage;
|
||||
use crate::agent::types::AgentExecutionGuard;
|
||||
use crate::session::PendingUserInput;
|
||||
use crate::session::SamplingInterrupt;
|
||||
use crate::session::TurnInput;
|
||||
use crate::session::TurnInputQueue;
|
||||
@@ -112,7 +112,7 @@ pub(crate) struct RunningTask {
|
||||
pub(crate) struct TurnState {
|
||||
pending_approvals: Arc<PendingApprovals>,
|
||||
pending_request_permissions: HashMap<String, PendingRequestPermissions>,
|
||||
pending_user_input: HashMap<String, oneshot::Sender<AcceptedUserInputResponse>>,
|
||||
pending_user_input: HashMap<String, PendingUserInput>,
|
||||
pending_elicitations: HashMap<(String, RequestId), oneshot::Sender<ElicitationResponse>>,
|
||||
pending_dynamic_tools: HashMap<String, oneshot::Sender<DynamicToolResponse>>,
|
||||
pub(crate) pending_input: TurnInputQueue,
|
||||
@@ -148,13 +148,6 @@ impl PendingApproval {
|
||||
}
|
||||
}
|
||||
|
||||
/// Host receipt metadata follows the response through the asynchronous tool waiter.
|
||||
pub(crate) struct AcceptedUserInputResponse {
|
||||
pub(crate) response: RequestUserInputResponse,
|
||||
/// Order reserved when the host accepts this response.
|
||||
pub(crate) acceptance_order: u64,
|
||||
}
|
||||
|
||||
pub(crate) struct PendingRequestPermissions {
|
||||
pub(crate) tx_response: oneshot::Sender<RequestPermissionsResponse>,
|
||||
pub(crate) requested_permissions: RequestPermissionProfile,
|
||||
@@ -273,15 +266,12 @@ impl TurnState {
|
||||
pub(crate) fn insert_pending_user_input(
|
||||
&mut self,
|
||||
key: String,
|
||||
tx: oneshot::Sender<AcceptedUserInputResponse>,
|
||||
) -> Option<oneshot::Sender<AcceptedUserInputResponse>> {
|
||||
self.pending_user_input.insert(key, tx)
|
||||
pending: PendingUserInput,
|
||||
) -> Option<PendingUserInput> {
|
||||
self.pending_user_input.insert(key, pending)
|
||||
}
|
||||
|
||||
pub(crate) fn remove_pending_user_input(
|
||||
&mut self,
|
||||
key: &str,
|
||||
) -> Option<oneshot::Sender<AcceptedUserInputResponse>> {
|
||||
pub(crate) fn remove_pending_user_input(&mut self, key: &str) -> Option<PendingUserInput> {
|
||||
self.pending_user_input.remove(key)
|
||||
}
|
||||
|
||||
|
||||
@@ -13,9 +13,6 @@ use crate::tools::handlers::request_user_input_spec::request_user_input_unavaila
|
||||
use crate::tools::registry::CoreToolRuntime;
|
||||
use crate::tools::registry::ToolExecutor;
|
||||
use codex_features::Feature;
|
||||
use codex_history::RetainedContextEvent;
|
||||
use codex_history::VerifiedAnswer;
|
||||
use codex_history::VerifiedQuestionAnswer;
|
||||
use codex_protocol::config_types::ModeKind;
|
||||
use codex_protocol::request_user_input::RequestUserInputArgs;
|
||||
use codex_tools::ToolName;
|
||||
@@ -83,9 +80,10 @@ impl RequestUserInputHandler {
|
||||
is_blocking: mode == ModeKind::Plan,
|
||||
auto_resolution_ms: None,
|
||||
};
|
||||
let questions = args.questions.clone();
|
||||
let accepted = session
|
||||
.request_user_input(turn.as_ref(), call_id.to_string(), args)
|
||||
// Retain answers even while an older checkpoint needs compatibility review.
|
||||
let verify = turn.config.features.enabled(Feature::GuardianApproval);
|
||||
let response = session
|
||||
.prompt_user(turn.as_ref(), call_id.into(), args, verify)
|
||||
.await
|
||||
.ok_or_else(|| {
|
||||
FunctionCallError::RespondToModel(format!(
|
||||
@@ -93,58 +91,11 @@ impl RequestUserInputHandler {
|
||||
))
|
||||
})?;
|
||||
|
||||
let response = accepted.response;
|
||||
|
||||
let content = serde_json::to_string(&response).map_err(|err| {
|
||||
FunctionCallError::Fatal(format!(
|
||||
"failed to serialize {REQUEST_USER_INPUT_TOOL_NAME} response: {err}"
|
||||
))
|
||||
})?;
|
||||
// Persist answers even while an older checkpoint needs compatibility review.
|
||||
if turn.config.features.enabled(Feature::GuardianApproval) {
|
||||
let user_input = questions
|
||||
.iter()
|
||||
.filter_map(|question| {
|
||||
let response = response.answers.get(&question.id)?;
|
||||
let answers = response
|
||||
.answers
|
||||
.iter()
|
||||
.filter(|answer| !answer.trim().is_empty())
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
if answers.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut question_text = question.question.clone();
|
||||
for option in question
|
||||
.options
|
||||
.iter()
|
||||
.flatten()
|
||||
.filter(|option| response.answers.contains(&option.label))
|
||||
{
|
||||
question_text
|
||||
.push_str(&format!("\n{}: {}", option.label, option.description));
|
||||
}
|
||||
Some(VerifiedQuestionAnswer {
|
||||
question: question_text,
|
||||
answer: answers.join("\n"),
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if !user_input.is_empty() {
|
||||
session
|
||||
.record_retained_context(RetainedContextEvent::VerifiedAnswer {
|
||||
answer: VerifiedAnswer {
|
||||
turn_id: turn.sub_id.clone(),
|
||||
call_id: call_id.into(),
|
||||
questions: user_input,
|
||||
},
|
||||
acceptance_order: Some(accepted.acceptance_order),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(boxed_tool_output(FunctionToolOutput::from_text(
|
||||
content,
|
||||
/*success*/ Some(true),
|
||||
|
||||
@@ -38,12 +38,12 @@ use tokio::sync::mpsc::error::TryRecvError;
|
||||
#[path = "../tests/common/board_host.rs"]
|
||||
mod board_host;
|
||||
|
||||
#[test_case::test_case(false; "queued revocation")]
|
||||
#[test_case::test_case(true; "interrupted revocation")]
|
||||
#[test_case::test_case(false; "caller cancelled before recorder admission")]
|
||||
#[test_case::test_case(true; "caller cancelled with projection blocked")]
|
||||
#[tokio::test]
|
||||
async fn initial_cutoff_and_retry_wait_for_live_revocation(interrupt: bool) -> anyhow::Result<()> {
|
||||
use codex_core::guardian_review::ReviewPreparationError;
|
||||
|
||||
async fn initial_cutoff_and_retry_wait_for_live_revocation(
|
||||
during_projection: bool,
|
||||
) -> anyhow::Result<()> {
|
||||
core_test_support::skip_if_no_network!(Ok(()));
|
||||
let server = start_mock_server().await;
|
||||
let test = test_codex()
|
||||
@@ -62,8 +62,12 @@ async fn initial_cutoff_and_retry_wait_for_live_revocation(interrupt: bool) -> a
|
||||
.thread_extension_data()
|
||||
.get::<PendingReviewWrites>()
|
||||
.context("root write tracker")?;
|
||||
let (evidence, mut writer) =
|
||||
RootEvidence::new(Default::default(), history.clone(), cursor, writes);
|
||||
let (evidence, mut writer) = RootEvidence::new(
|
||||
Default::default(),
|
||||
history.clone(),
|
||||
cursor.clone(),
|
||||
writes.clone(),
|
||||
);
|
||||
let before = test.codex.guardian_authorization_version().await;
|
||||
|
||||
// A local flush holds the writer lock while awaiting the recorder task.
|
||||
@@ -89,47 +93,52 @@ async fn initial_cutoff_and_retry_wait_for_live_revocation(interrupt: bool) -> a
|
||||
}) => result?,
|
||||
}
|
||||
let initial = evidence.capture_cutoff();
|
||||
let retry = evidence.request_through(/*cutoff*/ None);
|
||||
let retry = evidence.request_catch_up();
|
||||
tokio::pin!(initial, retry);
|
||||
assert!(futures::poll!(&mut initial).is_pending());
|
||||
assert!(futures::poll!(&mut retry).is_pending());
|
||||
// Release the writer without polling the revocation again. Both reviews
|
||||
// must still depend on that append, even though a flush can now succeed.
|
||||
flush.await?;
|
||||
if interrupt {
|
||||
drop(revoke);
|
||||
let (initial, retry) = tokio::join!(initial, retry);
|
||||
for error in [
|
||||
initial.err(),
|
||||
retry.err(),
|
||||
evidence.capture_cutoff().await.err(),
|
||||
] {
|
||||
assert_eq!(
|
||||
error
|
||||
.context("accepted interrupted write")?
|
||||
.downcast::<ReviewPreparationError>()?,
|
||||
ReviewPreparationError::HistoryWriteUnconfirmed,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
let (saved, cutoff, routed) = tokio::join!(revoke, initial, retry);
|
||||
saved?;
|
||||
let cutoff = cutoff?;
|
||||
let routed = routed?;
|
||||
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."
|
||||
);
|
||||
assert_eq!(capture.snapshot.cutoff(), cutoff);
|
||||
capture.finish();
|
||||
assert_eq!(routed.await?, cutoff);
|
||||
batches.next().await?;
|
||||
// Exercise a shared capture before admission and a lone retry during projection.
|
||||
if !during_projection {
|
||||
assert!(futures::poll!(&mut initial).is_pending());
|
||||
}
|
||||
assert!(futures::poll!(&mut retry).is_pending());
|
||||
|
||||
if during_projection {
|
||||
assert!(test.codex.state_db().is_some());
|
||||
let db = codex_state::open_thread_history_db(test.config.sqlite_config()).await?;
|
||||
let lock = db.begin_with("BEGIN IMMEDIATE").await?;
|
||||
flush.await?;
|
||||
// Read the complete canonical record without flushing or waiting for SQLite.
|
||||
tokio::select! {
|
||||
result = &mut revoke => anyhow::bail!("revocation finished with projection blocked: {result:?}"),
|
||||
result = tokio::time::timeout(Duration::from_secs(/*secs*/ 10), async {
|
||||
while cursor.capture(history.as_ref()).await?.records().is_empty() {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
anyhow::Ok(())
|
||||
}) => result??,
|
||||
}
|
||||
drop(revoke);
|
||||
assert!(writes.wait().now_or_never().is_none());
|
||||
lock.rollback().await?;
|
||||
} else {
|
||||
drop(revoke);
|
||||
assert!(writes.wait().now_or_never().is_none());
|
||||
flush.await?;
|
||||
}
|
||||
let routed = retry.await?;
|
||||
let cutoff = initial.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."
|
||||
);
|
||||
assert_eq!(capture.snapshot.cutoff(), cutoff);
|
||||
capture.finish();
|
||||
assert_eq!(routed.await?, cutoff);
|
||||
earlier.await?;
|
||||
batches.next().await?;
|
||||
assert!(batches.next().now_or_never().is_none());
|
||||
test.codex.shutdown_and_wait().await?;
|
||||
Ok(())
|
||||
|
||||
Reference in New Issue
Block a user