mirror of
https://github.com/openai/codex.git
synced 2026-11-24 23:20:47 +00:00
Wait for pending history writes before Guardian v3 reviews (#63675)
## Why A root-thread instruction can be visible in memory while its history append is still pending. Guardian v3 reads persisted history, so a review can miss a newer instruction that revokes permission for an action. ## What changed Track pending appends for review-relevant root history and wait for confirmation before capturing the evidence cutoff for an initial review or retry. Confirm the append when the thread store accepts the history batch, before updating thread metadata. If an append goes unconfirmed, fail review preparation and prompt the user to reload the root thread and resend any missing instructions. ## Testing Add regression coverage for initial and retry cutoffs waiting on a pending revocation, failed appends of forwarded instructions, and history remaining readable after an acknowledged append followed by a metadata failure. GitOrigin-RevId: b83ca178ca7b58dbc23b1f064b402df30f9689e1
This commit is contained in:
@@ -351,6 +351,13 @@ impl ContextManager {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn guardian_revisions(&self) -> (u64, u64) {
|
||||
(
|
||||
self.user_message_revision,
|
||||
self.guardian_review_context_revision,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn conversation_history_snapshot(&self) -> Arc<dyn ConversationHistorySnapshot> {
|
||||
Arc::new(SharedConversationHistory {
|
||||
items: Arc::clone(&self.items),
|
||||
|
||||
@@ -1,11 +1,86 @@
|
||||
//! Host adapter types and assessment results for synchronous Guardian review.
|
||||
//! The extension supplies agent startup and owns the reviewer pool and its lifecycle.
|
||||
|
||||
use crate::context_manager::ContextManager;
|
||||
pub use crate::guardian::GuardianReviewSession;
|
||||
pub use crate::guardian::GuardianReviewState;
|
||||
pub use crate::guardian::PreparedGuardianContext;
|
||||
pub use crate::guardian::prepare_review_prewarm;
|
||||
pub use crate::mcp_tool_call::conversation_history::conversation_history_tools;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::PoisonError;
|
||||
use tokio::sync::watch;
|
||||
|
||||
/// Tracks root evidence that is visible in memory and still awaiting a history append.
|
||||
/// Only reviewers that read persisted history install this tracker.
|
||||
#[derive(Default)]
|
||||
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>);
|
||||
|
||||
impl ReviewWrite {
|
||||
/// Record under the session lock so a reviewer cannot see the new revision
|
||||
/// before its pending write is registered.
|
||||
pub(crate) fn record<T>(
|
||||
writes: Option<&PendingReviewWrites>,
|
||||
history: &mut ContextManager,
|
||||
record: impl FnOnce(&mut ContextManager) -> T,
|
||||
) -> (T, Option<Self>) {
|
||||
let Some(writes) = writes else {
|
||||
return (record(history), None);
|
||||
};
|
||||
let before = history.guardian_revisions();
|
||||
let result = record(history);
|
||||
let write = if history.guardian_revisions() != before {
|
||||
writes.begin()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
(result, write)
|
||||
}
|
||||
|
||||
pub(crate) fn confirm(self) {
|
||||
self.0.send_replace(true);
|
||||
}
|
||||
}
|
||||
|
||||
impl PendingReviewWrites {
|
||||
fn begin(&self) -> Option<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.
|
||||
if pending
|
||||
.iter()
|
||||
.any(|write| write.has_changed().is_err() && !*write.borrow())
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let (appended, write) = watch::channel(/*init*/ false);
|
||||
pending.push(write);
|
||||
Some(ReviewWrite(appended))
|
||||
}
|
||||
|
||||
/// Wait for writes already visible to this review. Later instructions are
|
||||
/// covered by the reviewer's authorization recheck and its next attempt.
|
||||
pub async fn wait(&self) -> Result<(), ReviewPreparationError> {
|
||||
let pending = {
|
||||
let mut pending = self.pending.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
pending.retain(|write| !*write.borrow());
|
||||
pending.clone()
|
||||
};
|
||||
for mut write in pending {
|
||||
write
|
||||
.wait_for(|appended| *appended)
|
||||
.await
|
||||
.map_err(|_| ReviewPreparationError::HistoryWriteUnconfirmed)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Retrieval guidance for the tools installed in a private verdict session.
|
||||
#[derive(Clone)]
|
||||
@@ -54,6 +129,10 @@ pub struct BoundReviewer {
|
||||
pub enum ReviewPreparationError {
|
||||
#[error("Guardian board evidence is unavailable")]
|
||||
EvidenceUnavailable,
|
||||
#[error(
|
||||
"An instruction may not have been saved. Reload the root thread, check the history and resend any missing instructions before retrying."
|
||||
)]
|
||||
HistoryWriteUnconfirmed,
|
||||
#[error("timed out preparing Guardian review")]
|
||||
PreparationTimedOut,
|
||||
#[error("reviewer is unavailable")]
|
||||
|
||||
@@ -339,6 +339,7 @@ mod rollout_reconstruction_tests;
|
||||
|
||||
use crate::exec_policy::ExecPolicyUpdateError;
|
||||
use crate::guardian::GuardianReviewSessionManager;
|
||||
use crate::guardian_review::ReviewWrite;
|
||||
use crate::mcp::McpEnvironmentScope;
|
||||
use crate::mcp::McpManager;
|
||||
use crate::mcp::McpThreadIdentity;
|
||||
@@ -4208,6 +4209,7 @@ impl Session {
|
||||
.iter()
|
||||
.map(|envelope| envelope.item.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let mut review_write = None;
|
||||
{
|
||||
let mut state = self.state.lock().await;
|
||||
let pending_orders = turn_context
|
||||
@@ -4291,7 +4293,11 @@ impl Session {
|
||||
state
|
||||
.pending_audio_duration_ids
|
||||
.extend(file_audio::file_ids(&items).cloned());
|
||||
state.history.record_annotated_items(&mut items, policy);
|
||||
(_, review_write) = ReviewWrite::record(
|
||||
self.pending_review_writes.as_deref(),
|
||||
&mut state.history,
|
||||
|history| history.record_annotated_items(&mut items, policy),
|
||||
);
|
||||
}
|
||||
state
|
||||
.current_time_reminder
|
||||
@@ -4332,7 +4338,8 @@ impl Session {
|
||||
.map(RolloutItem::EventMsg)
|
||||
.chain(items.into_iter().map(RolloutItem::ResponseItem))
|
||||
.collect::<Vec<_>>();
|
||||
self.persist_rollout_items(&rollout_items).await;
|
||||
self.persist_rollout_items_with_ack(&rollout_items, review_write)
|
||||
.await;
|
||||
drop(settings_guard);
|
||||
}
|
||||
drop(realtime_settings_guard);
|
||||
@@ -5544,10 +5551,25 @@ impl Session {
|
||||
(updates, snapshot)
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "trace", skip_all, fields(item_count = items.len()))]
|
||||
pub(crate) async fn persist_rollout_items(&self, items: &[RolloutItem]) -> bool {
|
||||
self.persist_rollout_items_with_ack(items, /*write*/ None)
|
||||
.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()
|
||||
&& let Err(e) = live_thread.append_items(items).await
|
||||
&& let Err(e) = live_thread
|
||||
.append_items_with_ack(items, move || {
|
||||
if let Some(write) = write {
|
||||
write.confirm();
|
||||
}
|
||||
})
|
||||
.await
|
||||
{
|
||||
error!("failed to record rollout items: {e:#}");
|
||||
if self
|
||||
|
||||
@@ -12,6 +12,7 @@ use std::task::Poll;
|
||||
|
||||
use crate::context::ContextualUserFragment;
|
||||
use crate::context::UserGoalUpdate;
|
||||
use crate::guardian_review::ReviewWrite;
|
||||
use codex_history::CodexHarnessMetadata;
|
||||
use codex_history::ResponseItemEnvelope;
|
||||
use codex_history::RetainedContextEvent;
|
||||
@@ -159,14 +160,16 @@ impl Session {
|
||||
// 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;
|
||||
if self
|
||||
.state
|
||||
.lock()
|
||||
.await
|
||||
.history
|
||||
.record_retained_context_for_persistence(&mut event)
|
||||
{
|
||||
self.persist_rollout_items(&[RolloutItem::RetainedContext(event)])
|
||||
let (recorded, write) = {
|
||||
let mut state = self.state.lock().await;
|
||||
ReviewWrite::record(
|
||||
self.pending_review_writes.as_deref(),
|
||||
&mut state.history,
|
||||
|history| history.record_retained_context_for_persistence(&mut event),
|
||||
)
|
||||
};
|
||||
if recorded {
|
||||
self.persist_rollout_items_with_ack(&[RolloutItem::RetainedContext(event)], write)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
@@ -225,9 +228,11 @@ impl Session {
|
||||
retained_source: None,
|
||||
acceptance_order: state.history.reserve_input_order(),
|
||||
};
|
||||
state
|
||||
.history
|
||||
.record_retained_context_for_persistence(&mut event);
|
||||
let (_, write) = ReviewWrite::record(
|
||||
session.pending_review_writes.as_deref(),
|
||||
&mut state.history,
|
||||
|history| history.record_retained_context_for_persistence(&mut event),
|
||||
);
|
||||
let mut pending = session
|
||||
.code_mode_message_tasks
|
||||
.pending_persistence
|
||||
@@ -235,7 +240,7 @@ impl Session {
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
pending.retain(|recording| recording.has_changed().is_ok());
|
||||
pending.push(pending_recording);
|
||||
(event, boundary)
|
||||
(event, boundary, write)
|
||||
});
|
||||
// Poll while still at the confirmed MCP response boundary. A free state lock
|
||||
// reserves the order now; a busy lock queues this reservation ahead of a
|
||||
@@ -248,14 +253,14 @@ impl Session {
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.spawn(async move {
|
||||
let (event, _boundary) = match reservation {
|
||||
let (event, _boundary, write) = match reservation {
|
||||
Poll::Ready(reservation) => reservation,
|
||||
Poll::Pending => reserve.await,
|
||||
};
|
||||
let _guard = thread_settings::acquire_persistence_lock(&persistence_session).await;
|
||||
// A distinct delivery still belongs in the rollout when the live window is full.
|
||||
persistence_session
|
||||
.persist_rollout_items(&[RolloutItem::RetainedContext(event)])
|
||||
.persist_rollout_items_with_ack(&[RolloutItem::RetainedContext(event)], write)
|
||||
.await;
|
||||
drop(recorded);
|
||||
});
|
||||
|
||||
@@ -7,6 +7,8 @@ use pretty_assertions::assert_eq;
|
||||
use test_case::test_case;
|
||||
|
||||
use super::thread_settings;
|
||||
use crate::guardian_review::PendingReviewWrites;
|
||||
use crate::session::tests::attach_thread_persistence;
|
||||
use crate::session::tests::make_session_and_context;
|
||||
|
||||
fn delivered_message() -> RetainedUserMessage {
|
||||
@@ -20,6 +22,23 @@ fn delivered_message() -> RetainedUserMessage {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn guardian_waits_for_detached_confirmed_delivery() {
|
||||
let (mut session, _) = make_session_and_context().await;
|
||||
attach_thread_persistence(&mut session).await;
|
||||
let writes = Arc::new(PendingReviewWrites::default());
|
||||
session.pending_review_writes = Some(Arc::clone(&writes));
|
||||
let session = Arc::new(session);
|
||||
let checkpoint = thread_settings::acquire_persistence_lock(&session).await;
|
||||
let (recording, _) = session.record_delivered_assistant_message(delivered_message());
|
||||
let waiting = writes.wait();
|
||||
tokio::pin!(waiting);
|
||||
assert!(futures::poll!(waiting.as_mut()).is_pending());
|
||||
drop(checkpoint);
|
||||
waiting.await.expect("confirmed delivery appended");
|
||||
recording.await.expect("delivery task finished");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shutdown_retains_an_admitted_delivery_until_persistence_finishes() {
|
||||
let (session, _) = make_session_and_context().await;
|
||||
|
||||
@@ -16,6 +16,7 @@ use crate::agents_md_manager::SessionInstructions;
|
||||
use crate::config::ConstraintError;
|
||||
use crate::environment_selection::ThreadEnvironments;
|
||||
use crate::environment_selection::TurnEnvironmentSnapshot;
|
||||
use crate::guardian_review::PendingReviewWrites;
|
||||
use crate::hook_mcp_executor::CoreHookMcpExecutor;
|
||||
use crate::mcp_tool_call::McpToolApprovalContext;
|
||||
use crate::responses_metadata::CodexResponsesMetadata;
|
||||
@@ -76,6 +77,8 @@ pub(crate) struct Session {
|
||||
pub(crate) context_ids: ThreadContextIds,
|
||||
pub(crate) agent_runtime: AgentRuntimeServices,
|
||||
pub(crate) outcome_reporting: Option<AgentOutcomeReporting>,
|
||||
/// Installed by a thread-start contributor and fixed for this session's lifetime.
|
||||
pub(super) pending_review_writes: Option<Arc<PendingReviewWrites>>,
|
||||
pub(crate) installation_id: String,
|
||||
pub(super) tx_event: Sender<Event>,
|
||||
/// Installed by Guardian before its first review; forwards items and cancellation without
|
||||
@@ -2035,6 +2038,7 @@ impl Session {
|
||||
context_ids,
|
||||
agent_runtime,
|
||||
outcome_reporting,
|
||||
pending_review_writes: services.thread_extension_data.get(),
|
||||
installation_id,
|
||||
tx_event: tx_event.clone(),
|
||||
parent_observer_event_tx: OnceLock::new(),
|
||||
|
||||
@@ -4777,7 +4777,7 @@ async fn open_thread_persistence(session: &mut Session) -> PathBuf {
|
||||
.expect("thread should have rollout path")
|
||||
}
|
||||
|
||||
async fn attach_thread_persistence(session: &mut Session) -> PathBuf {
|
||||
pub(super) async fn attach_thread_persistence(session: &mut Session) -> PathBuf {
|
||||
let rollout_path = open_thread_persistence(session).await;
|
||||
session
|
||||
.ensure_rollout_materialized(PersistContext::Standard)
|
||||
@@ -6844,6 +6844,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) {
|
||||
context_ids,
|
||||
agent_runtime: crate::agent::host::AgentRuntimeServices::Controller,
|
||||
outcome_reporting: None,
|
||||
pending_review_writes: None,
|
||||
installation_id: "11111111-1111-4111-8111-111111111111".to_string(),
|
||||
tx_event,
|
||||
parent_observer_event_tx: OnceLock::new(),
|
||||
@@ -9212,6 +9213,7 @@ where
|
||||
context_ids,
|
||||
agent_runtime: crate::agent::host::AgentRuntimeServices::Controller,
|
||||
outcome_reporting: None,
|
||||
pending_review_writes: None,
|
||||
installation_id: "11111111-1111-4111-8111-111111111111".to_string(),
|
||||
tx_event,
|
||||
parent_observer_event_tx: OnceLock::new(),
|
||||
|
||||
@@ -2,6 +2,8 @@ use super::*;
|
||||
use crate::config::Constrained;
|
||||
use crate::exec_policy::ExecPolicyManager;
|
||||
use crate::guardian::GUARDIAN_REVIEWER_NAME;
|
||||
use crate::guardian_review::PendingReviewWrites;
|
||||
use crate::guardian_review::ReviewPreparationError;
|
||||
use crate::plugins::plugins_manager_for_config;
|
||||
use crate::sandboxing::SandboxPermissions;
|
||||
use crate::session::step_context::StepContext;
|
||||
@@ -72,6 +74,37 @@ use test_case::test_case;
|
||||
use tokio::time::timeout;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
#[tokio::test]
|
||||
async fn guardian_rejects_failed_append_of_forwarded_user_instructions() {
|
||||
let (mut session, turn) = make_session_and_context().await;
|
||||
attach_thread_persistence(&mut session).await;
|
||||
session.live_thread().unwrap().shutdown().await.unwrap();
|
||||
let writes = Arc::new(PendingReviewWrites::default());
|
||||
session.pending_review_writes = Some(Arc::clone(&writes));
|
||||
let delivery = ResponseItemEnvelope {
|
||||
item: serde_json::from_value(json!({
|
||||
"type": "function_call_output", "id": "delivery",
|
||||
"name": "send_message_to_thread", "namespace": "codex_app", "output": "Inspect."
|
||||
}))
|
||||
.unwrap(),
|
||||
metadata: Some(CodexHarnessMetadata {
|
||||
sender_user_messages: Some(Box::new(codex_history::SenderUserMessages {
|
||||
receiver_turn_id: turn.sub_id.clone(),
|
||||
receiver_message_id: "delivery".to_owned(),
|
||||
text: "Stop the release.".to_owned(),
|
||||
})),
|
||||
..Default::default()
|
||||
}),
|
||||
};
|
||||
session
|
||||
.record_prepared_conversation_items(&turn, turn.model_info(), vec![delivery], Vec::new())
|
||||
.await;
|
||||
assert_eq!(
|
||||
writes.wait().await,
|
||||
Err(ReviewPreparationError::HistoryWriteUnconfirmed)
|
||||
);
|
||||
}
|
||||
|
||||
fn expect_text_output<T>(output: &T) -> String
|
||||
where
|
||||
T: ToolOutput + ?Sized,
|
||||
|
||||
Reference in New Issue
Block a user