mirror of
https://github.com/openai/codex.git
synced 2026-11-26 07:26:11 +00:00
Consolidate Guardian reviewer lifecycle ownership (#45672)
## What changed - Use cancellation guards to tie reusable reviewers and temporary forks to their lifetimes, including when a review future is dropped. Replace cancelled reusable reviewers before reuse. - Share `ReviewerTasks` between the pool and `ThreadManager`, and wait for tracked cleanup during pool shutdown. Remove the separate session shutdown protocol. - Move denial cleanup from core task handling into Guardian's turn start, stop, and abort hooks. Expose `install_reviewer` to register both thread and turn lifecycle contributors together. ## Testing Add an integration test that exercises stale denial cleanup at turn start, completion, and interruption, including starting another turn after interruption. GitOrigin-RevId: 85badb235309c1e1576547d1746f7ee9fc66d545
This commit is contained in:
1 parent
4415f985dc
commit
a113f3e063
15 files changed
+231
-315
No files matched your search
@@ -38,4 +38,5 @@ uuid = { workspace = true }
|
||||
codex-model-provider-info = { workspace = true }
|
||||
core_test_support = { workspace = true }
|
||||
pretty_assertions = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
|
||||
@@ -9,7 +9,7 @@ use codex_login::AuthManager;
|
||||
mod async_scorer;
|
||||
mod sync_reviewer;
|
||||
|
||||
pub use sync_reviewer::GuardianExtension as GuardianReviewerExtension;
|
||||
pub use sync_reviewer::install as install_reviewer;
|
||||
|
||||
/// Installs the guardian contributors into the extension registry.
|
||||
pub fn install(
|
||||
@@ -18,5 +18,5 @@ pub fn install(
|
||||
thread_manager: Weak<ThreadManager>,
|
||||
) {
|
||||
async_scorer::install(registry, auth_manager, thread_manager.clone());
|
||||
sync_reviewer::install(registry, thread_manager);
|
||||
install_reviewer(registry, thread_manager);
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
//! Exercises Guardian registration and denial cleanup through real turns.
|
||||
|
||||
use super::*;
|
||||
use codex_core::TurnInputRequest;
|
||||
use codex_protocol::openai_models::ModelInfo;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::Op;
|
||||
use codex_protocol::protocol::TurnAbortReason;
|
||||
use codex_protocol::user_input::UserInput;
|
||||
use core_test_support::responses::ev_completed;
|
||||
use core_test_support::responses::ev_response_created;
|
||||
use core_test_support::responses::sse;
|
||||
use core_test_support::responses::start_mock_server;
|
||||
use core_test_support::streaming_sse::StreamingSseChunk;
|
||||
use core_test_support::streaming_sse::start_streaming_sse_server;
|
||||
use core_test_support::test_codex::test_codex;
|
||||
use core_test_support::wait_for_event;
|
||||
use core_test_support::wait_for_event_match;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::time::Duration;
|
||||
|
||||
struct StaleDenials(ModelInfo);
|
||||
|
||||
impl TurnLifecycleContributor for StaleDenials {
|
||||
fn on_turn_start<'a>(&'a self, input: TurnStartInput<'a>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let denials = ReviewDenials::for_thread(input.thread_store);
|
||||
for _ in 0..2 {
|
||||
assert_eq!(denials.record_denial(input.turn_id, &self.0).await, None);
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn terminal_turn_clears_extension_owned_denials() -> anyhow::Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
let config = core_test_support::load_default_config_for_test(&home).await;
|
||||
let model = codex_core::test_support::construct_model_info_offline("gpt-5", &config);
|
||||
let mut extensions = ExtensionRegistryBuilder::<Config>::new();
|
||||
// Seed stale state before the production Guardian contributor runs its start hook.
|
||||
extensions.turn_lifecycle_contributor(Arc::new(StaleDenials(model.clone())));
|
||||
let mut releases = Vec::new();
|
||||
let streams = (0..3)
|
||||
.map(|_| {
|
||||
let (release, gate) = tokio::sync::oneshot::channel();
|
||||
releases.push(release);
|
||||
vec![
|
||||
StreamingSseChunk {
|
||||
gate: None,
|
||||
body: sse(vec![ev_response_created("response")]),
|
||||
},
|
||||
StreamingSseChunk {
|
||||
gate: Some(gate),
|
||||
body: sse(vec![ev_completed("response")]),
|
||||
},
|
||||
]
|
||||
})
|
||||
.collect();
|
||||
let (streaming, _) = start_streaming_sse_server(streams).await;
|
||||
let server = start_mock_server().await;
|
||||
let base_url = format!("{}/v1", streaming.uri());
|
||||
let test = test_codex()
|
||||
.with_extensions(Arc::new(extensions.build()))
|
||||
.with_config(move |config| {
|
||||
config.model_provider.base_url = Some(base_url);
|
||||
config.model_provider.supports_websockets = false;
|
||||
})
|
||||
.build_with_auto_env(&server)
|
||||
.await?;
|
||||
let denials = ReviewDenials::for_thread(test.codex.thread_extension_data());
|
||||
|
||||
let mut previous_turn = None;
|
||||
// The third turn also checks that an interrupted turn leaves the next turn usable.
|
||||
for (index, release) in releases.into_iter().enumerate() {
|
||||
test.codex
|
||||
.start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text {
|
||||
text: "Continue.".into(),
|
||||
text_elements: Vec::new(),
|
||||
}]))
|
||||
.await?;
|
||||
let turn_id = wait_for_event_match(&test.codex, |event| match event {
|
||||
EventMsg::TurnStarted(event) => Some(event.turn_id.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
// An interruption event can precede its cleanup. The next turn starts after it.
|
||||
if let Some(previous) = previous_turn.replace(turn_id.clone()) {
|
||||
assert_eq!(denials.record_denial(&previous, &model).await, None);
|
||||
}
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(/*secs*/ 10),
|
||||
streaming.wait_for_request_count(index + 1),
|
||||
)
|
||||
.await?;
|
||||
// Without start cleanup, these denials reach the three-denial limit.
|
||||
for _ in 0..2 {
|
||||
assert_eq!(denials.record_denial(&turn_id, &model).await, None);
|
||||
}
|
||||
if index == 1 {
|
||||
test.codex.submit(Op::Interrupt).await?;
|
||||
wait_for_event(&test.codex, |event| {
|
||||
matches!(event, EventMsg::TurnAborted(event)
|
||||
if event.reason == TurnAbortReason::Interrupted
|
||||
&& event.turn_id.as_deref() == Some(turn_id.as_str()))
|
||||
})
|
||||
.await;
|
||||
drop(release);
|
||||
} else {
|
||||
release.send(()).unwrap();
|
||||
wait_for_event(
|
||||
&test.codex,
|
||||
|event| matches!(event, EventMsg::TurnComplete(event) if event.turn_id == turn_id),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
test.codex.shutdown_and_wait().await?;
|
||||
assert_eq!(
|
||||
denials.record_denial(&previous_turn.unwrap(), &model).await,
|
||||
None
|
||||
);
|
||||
streaming.shutdown().await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -16,6 +16,11 @@ use codex_extension_api::ThreadLifecycleContributor;
|
||||
use codex_extension_api::ThreadReadyInput;
|
||||
use codex_extension_api::ThreadStartInput;
|
||||
use codex_extension_api::ThreadStopInput;
|
||||
use codex_extension_api::TurnAbortInput;
|
||||
use codex_extension_api::TurnLifecycleContributor;
|
||||
use codex_extension_api::TurnStartInput;
|
||||
use codex_extension_api::TurnStopInput;
|
||||
use codex_guardian_reviewer::ReviewDenials;
|
||||
use codex_guardian_reviewer::ReviewerPool;
|
||||
use codex_guardian_reviewer::ReviewerTasks;
|
||||
use codex_protocol::ThreadId;
|
||||
@@ -26,17 +31,11 @@ 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 {
|
||||
#[derive(Debug)]
|
||||
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,
|
||||
@@ -50,6 +49,7 @@ impl ThreadLifecycleContributor<Config> for GuardianExtension {
|
||||
let runtime = input.thread_store.get_or_init(ReviewerTasks::default);
|
||||
input.thread_store.get_or_init(|| {
|
||||
ReviewerPool::<GuardianReviewSession>::new(
|
||||
Arc::clone(&runtime),
|
||||
move |context, key, kind, snapshot, cancel| {
|
||||
let manager = manager.clone();
|
||||
let runtime = Arc::clone(&runtime);
|
||||
@@ -82,14 +82,12 @@ impl ThreadLifecycleContributor<Config> for GuardianExtension {
|
||||
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
|
||||
@@ -164,24 +162,44 @@ impl ThreadLifecycleContributor<Config> for GuardianExtension {
|
||||
|
||||
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;
|
||||
if let Some(pool) = input
|
||||
.thread_store
|
||||
.get::<ReviewerPool<GuardianReviewSession>>()
|
||||
{
|
||||
pool.shutdown().await;
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TurnLifecycleContributor for GuardianExtension {
|
||||
fn on_turn_start<'a>(&'a self, input: TurnStartInput<'a>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(ReviewDenials::clear_turn(input.thread_store, input.turn_id))
|
||||
}
|
||||
fn on_turn_stop<'a>(&'a self, input: TurnStopInput<'a>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(ReviewDenials::clear_turn(
|
||||
input.thread_store,
|
||||
input.turn_store.level_id(),
|
||||
))
|
||||
}
|
||||
fn on_turn_abort<'a>(&'a self, input: TurnAbortInput<'a>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(ReviewDenials::clear_turn(
|
||||
input.thread_store,
|
||||
input.turn_store.level_id(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// Registers the synchronous reviewer and its thread and turn cleanup.
|
||||
pub fn install(
|
||||
registry: &mut ExtensionRegistryBuilder<Config>,
|
||||
thread_manager: Weak<ThreadManager>,
|
||||
) {
|
||||
registry.thread_lifecycle_contributor(Arc::new(GuardianExtension::new(thread_manager)));
|
||||
let extension = Arc::new(GuardianExtension { thread_manager });
|
||||
registry.thread_lifecycle_contributor(extension.clone());
|
||||
registry.turn_lifecycle_contributor(extension);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "lifecycle_tests.rs"]
|
||||
mod tests;
|
||||
Reference in new issue
Block a user