Files
codex/codex-rs/ext/guardian-v2/src/sync_reviewer/mod.rs
T
jif 18d7ace221 Move Guardian reviewer lifecycle into the extension (#45537)
## Why

Guardian reviews must stop when their parent shuts down or their history is reset. Shutdown must also finish reviewer cleanup before closing the parent's persistent history, including when a review is waiting to retry after a rate limit.

## What changed

- Let the Guardian extension own reviewer startup, prewarming, and shutdown through `ThreadManager`, tracking and joining outstanding work during teardown.
- Cancel reviews on history reset or parent shutdown and reject decisions returned after cancellation, including cached extension decisions.
- Keep background prewarm previews from overwriting the active turn's model metadata.

## Testing

Extend regression coverage to verify reviewer cleanup after parent shutdown, prompt shutdown during a 60-second Guardian retry with the network request denied, and preservation of active model review requirements during prewarming.

GitOrigin-RevId: 05efc369b9a1642a10365eac8a09da77f3f6e28c
2026-09-14 22:58:51 +00:00

188 lines
7.8 KiB
Rust

//! Runs Guardian agents through ThreadManager and owns their background tasks.
//! Context stays in the temporary core adapter. Parent stop joins all reviewer
//! work before the parent closes its history, including partial startup.
use std::sync::Arc;
use std::sync::Weak;
use codex_core::ThreadManager;
use codex_core::config::Config;
use codex_core::config::Constrained;
use codex_core::guardian_review::GuardianReviewSession;
use codex_extension_api::ExtensionFuture;
use codex_extension_api::ExtensionRegistryBuilder;
use codex_extension_api::SessionIsolation;
use codex_extension_api::ThreadLifecycleContributor;
use codex_extension_api::ThreadReadyInput;
use codex_extension_api::ThreadStartInput;
use codex_extension_api::ThreadStopInput;
use codex_guardian_reviewer::ReviewerPool;
use codex_guardian_reviewer::ReviewerTasks;
use codex_protocol::ThreadId;
use codex_protocol::config_types::ApprovalsReviewer;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::InternalSessionSource;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::ThreadSource;
/// Owns reviewer agents through the same thread manager as the parent conversation.
#[derive(Clone, Debug)]
pub struct GuardianExtension {
thread_manager: Weak<ThreadManager>,
}
impl GuardianExtension {
pub fn new(thread_manager: Weak<ThreadManager>) -> Self {
Self { thread_manager }
}
}
impl ThreadLifecycleContributor<Config> for GuardianExtension {
fn on_thread_start<'a>(
&'a self,
input: ThreadStartInput<'a, Config>,
) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
if input.session_source.is_internal() {
return;
}
let manager = self.thread_manager.clone();
let runtime = input.thread_store.get_or_init(ReviewerTasks::default);
input.thread_store.get_or_init(|| {
ReviewerPool::<GuardianReviewSession>::new(
move |context, key, kind, snapshot, cancel| {
let manager = manager.clone();
let runtime = Arc::clone(&runtime);
Box::pin(async move {
let history_reset = context.history_reset.clone();
// Register before checking cancellation so parent stop also joins
// a spawn racing with shutdown.
let _task = runtime.tasks.token();
anyhow::ensure!(
!runtime.cancellation.is_cancelled()
&& !cancel.is_cancelled()
&& !history_reset.is_cancelled(),
"Guardian is stopping"
);
let manager = manager.upgrade().ok_or_else(|| {
anyhow::anyhow!("thread manager is no longer available")
})?;
let (mut options, state) = context.thread_options(snapshot).await;
if matches!(
kind,
codex_analytics::GuardianReviewSessionKind::EphemeralForked
) {
options.config.ephemeral = true;
}
options.config.permissions.approval_policy =
Constrained::allow_only(AskForApproval::Never);
options.session_source =
Some(SessionSource::Internal(InternalSessionSource::Guardian));
options.thread_source = Some(ThreadSource::GuardianReview);
options
.thread_extension_init
.insert(SessionIsolation::Isolated);
let parent_cancel = runtime.cancellation.clone();
let session_cancel = cancel.clone();
let until = async move {
let _cancel_on_exit = cancel.clone().drop_guard();
tokio::select! {
_ = cancel.cancelled() => {}
_ = history_reset.cancelled() => {}
_ = parent_cancel.cancelled() => {}
}
};
let spawned = manager
.start_thread_until(options, until, &runtime.tasks)
.await?;
Ok(context
.bind_thread(&spawned.thread, key, state, session_cancel)
.await)
})
},
)
});
})
}
fn on_thread_ready<'a>(
&'a self,
input: ThreadReadyInput<'a, Config>,
) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
if input.session_source.is_internal()
|| !matches!(
input.config.permissions.approval_policy.value(),
AskForApproval::OnRequest | AskForApproval::Granular(_)
)
|| input.config.approvals_reviewer != ApprovalsReviewer::AutoReview
{
return;
}
let Some(runtime) = input.thread_store.get::<ReviewerTasks>() else {
return;
};
let task = runtime.tasks.token();
if runtime.cancellation.is_cancelled() {
return;
}
let Some(manager) = self.thread_manager.upgrade() else {
return;
};
let Ok(thread_id) = ThreadId::from_string(input.thread_store.level_id()) else {
return;
};
let Ok(parent) = manager.get_thread(thread_id).await else {
return;
};
let Some(pool) = input
.thread_store
.get::<ReviewerPool<GuardianReviewSession>>()
else {
return;
};
let cancel = runtime.cancellation.clone();
tokio::spawn(async move {
let _task = task;
let prepare = async {
let context =
codex_core::guardian_review::prepare_review_prewarm(&parent).await?;
let key = context.reuse_key(/*previous*/ None);
pool.prewarm(Arc::new(context), key).await
};
tokio::select! {
_ = cancel.cancelled() => {}
result = prepare => {
if let Err(error) = result {
tracing::warn!("failed to prewarm Guardian reviewer: {error:#}");
}
}
}
});
})
}
fn on_thread_stop<'a>(&'a self, input: ThreadStopInput<'a>) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
if let Some(runtime) = input.thread_store.get::<ReviewerTasks>() {
runtime.cancellation.cancel();
if let Some(pool) = input
.thread_store
.get::<ReviewerPool<GuardianReviewSession>>()
{
pool.shutdown().await;
}
runtime.tasks.close();
runtime.tasks.wait().await;
}
})
}
}
pub fn install(
registry: &mut ExtensionRegistryBuilder<Config>,
thread_manager: Weak<ThreadManager>,
) {
registry.thread_lifecycle_contributor(Arc::new(GuardianExtension::new(thread_manager)));
}