mirror of
https://github.com/openai/codex.git
synced 2026-11-19 22:30:42 +00:00
Enforce refreshed Guardian policy on running threads (#62585)
## Why A Guardian policy refresh could leave a thread using its previous restrictions if the new policy disallowed its current model. A refresh could also report success after its managed policy source changed before publication. ## What changed - Use the app server's configuration manager to load Guardian policy from current local and managed configuration. Report an error when the policy source changes before publication or a live thread rejects the update. - Apply updated reviewer and model restrictions even when they block the current model. Keep automatic work queued while the model is blocked and wake it when a later refresh permits it. Allow a new turn to supply a compliant replacement model. ## Testing Regression tests cover policy changes during thread startup and live refresh, queued work resuming after a blocking policy is lifted, and updated policy text reaching Guardian reviews without reconnecting MCP. GitOrigin-RevId: c7d3e119aa409342cc2fa18946ce2b6a4392e0e3
This commit is contained in:
@@ -202,7 +202,7 @@ pub enum ConfigRefreshOutcome {
|
||||
Published,
|
||||
/// The captured owner changed; the caller must reload before retrying.
|
||||
Stale,
|
||||
/// Resolution failed and a configuration disabling enterprise MCP was published.
|
||||
/// Resolution failed. The scope may still have published a fail-closed configuration.
|
||||
Rejected,
|
||||
}
|
||||
|
||||
|
||||
@@ -48,41 +48,35 @@ impl Session {
|
||||
.binding
|
||||
.as_ref()
|
||||
.map(codex_config::CloudConfigBundleBinding::read);
|
||||
match binding
|
||||
if binding
|
||||
.as_ref()
|
||||
.map(|guard| guard.status)
|
||||
.unwrap_or(CloudConfigBundleBindingStatus::Current)
|
||||
.is_some_and(|guard| guard.status != CloudConfigBundleBindingStatus::Current)
|
||||
{
|
||||
CloudConfigBundleBindingStatus::Stale => return ConfigRefreshOutcome::Stale,
|
||||
CloudConfigBundleBindingStatus::Suspended => return ConfigRefreshOutcome::Rejected,
|
||||
CloudConfigBundleBindingStatus::Current => {}
|
||||
return ConfigRefreshOutcome::Rejected;
|
||||
}
|
||||
let mut config = current.as_ref().clone();
|
||||
config.config_layer_stack.apply_guardian_policy(snapshot);
|
||||
let Ok(fallback) = config.config_layer_stack.guardian_config() else {
|
||||
if config.apply_guardian_policy(snapshot).is_err() {
|
||||
return ConfigRefreshOutcome::Rejected;
|
||||
};
|
||||
(config.guardian_policy_config, config.guardian_extra_policy) =
|
||||
crate::config::resolve_guardian_policy_text(
|
||||
config.config_layer_stack.requirements_toml(),
|
||||
Some(&fallback),
|
||||
);
|
||||
}
|
||||
let configuration = &state.session_configuration;
|
||||
let was_blocked = configuration
|
||||
.step_settings
|
||||
.validate(&configuration.step_settings_constraints(&configuration.environments))
|
||||
.is_err();
|
||||
let model = (!configuration.trusted_guardian_reviewer)
|
||||
.then_some(configuration.step_settings.collaboration_mode.model());
|
||||
let requested = config
|
||||
.requested_approvals_reviewer
|
||||
.unwrap_or(configuration.step_settings.approvals_reviewer);
|
||||
let Ok(reviewer) = crate::config::resolve_guardian_reviewer(
|
||||
requested,
|
||||
model,
|
||||
config.config_layer_stack.requirements(),
|
||||
) else {
|
||||
return ConfigRefreshOutcome::Rejected;
|
||||
};
|
||||
let requirements = config.config_layer_stack.requirements();
|
||||
let resolved = crate::config::resolve_guardian_reviewer(requested, model, requirements);
|
||||
// Publish both restrictions even when they rule out the current model.
|
||||
let reviewer = resolved
|
||||
.as_ref()
|
||||
.copied()
|
||||
.unwrap_or_else(|_| requirements.approvals_reviewer.value());
|
||||
config.requested_approvals_reviewer = Some(requested);
|
||||
config.approvals_reviewer = reviewer;
|
||||
config.guardian_policy_revision = snapshot.revision;
|
||||
let previous = Arc::downgrade(current);
|
||||
let config = Arc::new(config);
|
||||
let snapshots = &mut state.guardian_config_snapshots;
|
||||
@@ -100,7 +94,24 @@ impl Session {
|
||||
Arc::make_mut(settings).approvals_reviewer = reviewer;
|
||||
}
|
||||
state.session_configuration.original_config_do_not_use = config;
|
||||
ConfigRefreshOutcome::Published
|
||||
let configuration = &state.session_configuration;
|
||||
let validation = resolved.and_then(|_| {
|
||||
configuration
|
||||
.step_settings
|
||||
.validate(&configuration.step_settings_constraints(&configuration.environments))
|
||||
});
|
||||
match validation {
|
||||
Ok(()) => {
|
||||
if was_blocked && !state.shutting_down {
|
||||
self.input_queue.pending_work_wake.notify_one();
|
||||
}
|
||||
ConfigRefreshOutcome::Published
|
||||
}
|
||||
Err(error) => {
|
||||
warn!(%error, "Guardian policy blocks the current model");
|
||||
ConfigRefreshOutcome::Rejected
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn refresh_runtime_config(
|
||||
|
||||
@@ -3,14 +3,19 @@
|
||||
use super::*;
|
||||
use crate::StartThreadOptions;
|
||||
use crate::ThreadManager;
|
||||
use codex_config::CloudConfigBundlePolicy;
|
||||
use codex_config::CloudConfigBundleSnapshot;
|
||||
use codex_config::loader::load_guardian_policy_snapshot;
|
||||
use codex_config::test_support::CloudConfigBundleFixture;
|
||||
use codex_exec_server::LOCAL_FS;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn guardian_refresh_updates_idle_thread_while_another_thread_is_busy() -> anyhow::Result<()> {
|
||||
struct TestPolicyLoader(AbsolutePathBuf);
|
||||
async fn guardian_refresh_reports_a_suspended_live_update() -> anyhow::Result<()> {
|
||||
struct TestPolicyLoader {
|
||||
home: AbsolutePathBuf,
|
||||
cloud: codex_config::CloudConfigBundleLoader,
|
||||
}
|
||||
impl crate::GuardianPolicyLoader for TestPolicyLoader {
|
||||
fn load_guardian_policy_snapshot(
|
||||
&self,
|
||||
@@ -19,9 +24,9 @@ async fn guardian_refresh_updates_idle_thread_while_another_thread_is_busy() ->
|
||||
Box::pin(async move {
|
||||
load_guardian_policy_snapshot(
|
||||
LOCAL_FS.as_ref(),
|
||||
self.0.as_path(),
|
||||
self.home.as_path(),
|
||||
&LoaderOverrides::without_managed_config_for_tests(),
|
||||
&codex_config::CloudConfigBundleLoader::default(),
|
||||
&self.cloud,
|
||||
revision,
|
||||
)
|
||||
.await
|
||||
@@ -34,13 +39,23 @@ async fn guardian_refresh_updates_idle_thread_while_another_thread_is_busy() ->
|
||||
let mut config = crate::config::test_config().await;
|
||||
config.codex_home = home.path().abs();
|
||||
config.cwd = config.codex_home.clone();
|
||||
let policy = CloudConfigBundlePolicy::default();
|
||||
let mut cloud = CloudConfigBundleSnapshot {
|
||||
bundle: Ok(None),
|
||||
binding: None,
|
||||
config_server: None,
|
||||
};
|
||||
policy.publish_snapshot(&mut cloud);
|
||||
let manager = ThreadManager::with_models_provider_and_home_for_tests(
|
||||
CodexAuth::from_api_key("dummy"),
|
||||
config.model_provider.clone(),
|
||||
config.codex_home.to_path_buf(),
|
||||
Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()),
|
||||
)
|
||||
.with_guardian_policy_loader(Arc::new(TestPolicyLoader(config.codex_home.clone())));
|
||||
.with_guardian_policy_loader(Arc::new(TestPolicyLoader {
|
||||
home: config.codex_home.clone(),
|
||||
cloud: codex_config::CloudConfigBundleLoader::from_snapshot(cloud),
|
||||
}));
|
||||
|
||||
manager
|
||||
.start_thread(StartThreadOptions::new(config.clone()))
|
||||
@@ -50,10 +65,11 @@ async fn guardian_refresh_updates_idle_thread_while_another_thread_is_busy() ->
|
||||
.await?;
|
||||
// The manager lists threads in the registry's iteration order. Lock the first one.
|
||||
let threads = manager.list_thread_ids().await;
|
||||
let [busy, idle] = threads.as_slice() else {
|
||||
let [busy_id, idle] = threads.as_slice() else {
|
||||
panic!("expected two live threads");
|
||||
};
|
||||
let busy = manager.get_thread(*busy).await?;
|
||||
let busy = manager.get_thread(*busy_id).await?;
|
||||
let busy_revision = busy.config().await.guardian_policy_revision;
|
||||
let idle = manager.get_thread(*idle).await?;
|
||||
let startup_revision = idle.config().await.guardian_policy_revision;
|
||||
let (locked, state_locked) = tokio::sync::oneshot::channel();
|
||||
@@ -72,12 +88,34 @@ async fn guardian_refresh_updates_idle_thread_while_another_thread_is_busy() ->
|
||||
}
|
||||
})
|
||||
.await;
|
||||
let changed = CloudConfigBundleFixture::enterprise_requirement(
|
||||
"guardian_policy_config = 'next policy'",
|
||||
)
|
||||
.into_bundle();
|
||||
policy
|
||||
.observe_remote_bundle(&changed)
|
||||
.expect("suspend the cloud binding");
|
||||
let _ = release_state.send(());
|
||||
result
|
||||
});
|
||||
held_state.await?;
|
||||
idle_update.expect("the idle thread should update while the first thread holds its lock");
|
||||
refresh?;
|
||||
assert_eq!(
|
||||
refresh
|
||||
.expect_err("the busy thread skipped the update")
|
||||
.to_string(),
|
||||
"Guardian policy refresh rejected by one or more live threads"
|
||||
);
|
||||
let busy = manager.get_thread(*busy_id).await?;
|
||||
assert_eq!(busy.config().await.guardian_policy_revision, busy_revision);
|
||||
assert_eq!(
|
||||
manager
|
||||
.refresh_guardian_policy()
|
||||
.await
|
||||
.expect_err("the source is still suspended")
|
||||
.to_string(),
|
||||
"Guardian policy source changed before publication"
|
||||
);
|
||||
manager.shutdown_all_threads_bounded(UPDATE_TIMEOUT).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -273,9 +273,18 @@ pub async fn reload_user_config(sess: &Arc<Session>) {
|
||||
pub async fn compact(sess: &Arc<Session>, sub_id: String) {
|
||||
// Stop the old turn before the compact task picks up the next turn's environments.
|
||||
sess.abort_all_tasks(TurnAbortReason::Replaced).await;
|
||||
let turn_context = sess
|
||||
.new_turn_with_default_settings(sub_id, Default::default())
|
||||
.await;
|
||||
let turn_context = if sess.enabled(Feature::TokenBudget) {
|
||||
sess.new_turn_with_default_settings(sub_id, Default::default())
|
||||
.await
|
||||
} else {
|
||||
let Ok((turn_context, _)) = sess
|
||||
.new_turn_with_sub_id(sub_id, Default::default(), Default::default())
|
||||
.await
|
||||
else {
|
||||
return;
|
||||
};
|
||||
turn_context
|
||||
};
|
||||
|
||||
sess.spawn_task(turn_context, Vec::new(), CompactTask).await;
|
||||
}
|
||||
@@ -588,6 +597,10 @@ pub(super) async fn submission_loop(
|
||||
Ok(sub) => *sub,
|
||||
Err(_) => break,
|
||||
},
|
||||
_ = sess.input_queue.pending_work_wake.notified() => {
|
||||
sess.maybe_start_turn_for_pending_work().await;
|
||||
continue;
|
||||
}
|
||||
update = async {
|
||||
match &mut admission_updates {
|
||||
Some(updates) => updates.changed().await,
|
||||
|
||||
@@ -15,6 +15,7 @@ use std::collections::BTreeMap;
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::sync::Notify;
|
||||
use tokio::sync::watch;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tokio_util::task::AbortOnDropHandle;
|
||||
@@ -136,6 +137,7 @@ pub(crate) struct InputQueue {
|
||||
activity_tx: watch::Sender<InputQueueActivity>,
|
||||
controller: Option<(ThreadId, Arc<dyn AgentControl>, watch::Receiver<bool>)>,
|
||||
mailbox_pending_mails: Mutex<VecDeque<PendingMailboxCommunication>>,
|
||||
pub(super) pending_work_wake: Notify,
|
||||
}
|
||||
|
||||
pub(crate) struct PendingMailboxCommunication {
|
||||
@@ -151,6 +153,7 @@ impl InputQueue {
|
||||
activity_tx,
|
||||
controller: None,
|
||||
mailbox_pending_mails: Mutex::new(VecDeque::new()),
|
||||
pending_work_wake: Notify::new(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2424,12 +2424,15 @@ impl Session {
|
||||
app_server_client_name: Option<String>,
|
||||
app_server_client_version: Option<String>,
|
||||
) -> ConstraintResult<()> {
|
||||
self.update_settings(SessionSettingsUpdate {
|
||||
app_server_client_name,
|
||||
app_server_client_version,
|
||||
..Default::default()
|
||||
})
|
||||
.await?;
|
||||
// A new turn may supply a valid replacement for a model blocked by policy.
|
||||
// Recording its client identity must not validate the old model first.
|
||||
let configuration = &mut self.state.lock().await.session_configuration;
|
||||
if let Some(name) = app_server_client_name {
|
||||
configuration.app_server_client_name = Some(name);
|
||||
}
|
||||
if let Some(version) = app_server_client_version {
|
||||
configuration.app_server_client_version = Some(version);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -975,10 +975,15 @@ impl Session {
|
||||
let has_trigger_turn = self.input_queue.has_trigger_turn_mailbox_items().await;
|
||||
let state = self.state.lock().await;
|
||||
let configuration = &state.session_configuration;
|
||||
if !has_trigger_turn
|
||||
if (self.enabled(Feature::WakeOnAgentMessages)
|
||||
&& !has_trigger_turn
|
||||
&& !self.has_outstanding_durable_sleep()
|
||||
&& !TurnStartKind::Automatic
|
||||
.permits_mode(configuration.step_settings.collaboration_mode.mode)
|
||||
.permits_mode(configuration.step_settings.collaboration_mode.mode))
|
||||
|| configuration
|
||||
.step_settings
|
||||
.validate(&configuration.step_settings_constraints(&configuration.environments))
|
||||
.is_err()
|
||||
{
|
||||
*active = None;
|
||||
return None;
|
||||
|
||||
@@ -610,23 +610,8 @@ impl Session {
|
||||
.models_manager
|
||||
.refresh_after_auth_change(self.get_config().await.http_client_factory())
|
||||
.await;
|
||||
let session_configuration = if self.enabled(Feature::WakeOnAgentMessages) {
|
||||
let Some(configuration) = self.pending_work_turn_configuration(&turn_state).await
|
||||
else {
|
||||
return;
|
||||
};
|
||||
Some(configuration)
|
||||
} else {
|
||||
if self
|
||||
.active_turn
|
||||
.lock()
|
||||
.await
|
||||
.as_ref()
|
||||
.is_none_or(|turn| !Arc::ptr_eq(&turn.turn_state, &turn_state))
|
||||
{
|
||||
return;
|
||||
}
|
||||
None
|
||||
let Some(configuration) = self.pending_work_turn_configuration(&turn_state).await else {
|
||||
return;
|
||||
};
|
||||
// Read the routing options now and leave the mail queued until task registration.
|
||||
let wake_options = self.input_queue.pending_wake_options().await;
|
||||
@@ -639,13 +624,9 @@ impl Session {
|
||||
cyber_access_program: start_options.cyber_access_program,
|
||||
helper_admission: triggered.then_some(helper_admission).flatten(),
|
||||
};
|
||||
let turn_context = match session_configuration {
|
||||
Some(configuration) => {
|
||||
self.new_turn_with_configuration(sub_id, configuration, options)
|
||||
.await
|
||||
}
|
||||
None => self.new_turn_with_default_settings(sub_id, options).await,
|
||||
};
|
||||
let turn_context = self
|
||||
.new_turn_with_configuration(sub_id, configuration, options)
|
||||
.await;
|
||||
if let Some(trigger) = start_options.turn_trigger {
|
||||
turn_context.turn_metadata_state.set_turn_trigger(trigger);
|
||||
}
|
||||
|
||||
@@ -143,7 +143,9 @@ impl ThreadRegistry {
|
||||
.as_ref()
|
||||
.is_some_and(|guard| guard.status != CloudConfigBundleBindingStatus::Current)
|
||||
{
|
||||
return Ok(());
|
||||
return Err(std::io::Error::other(
|
||||
"Guardian policy source changed before publication",
|
||||
));
|
||||
}
|
||||
// A startup may have reserved a revision while the refresh was reading.
|
||||
snapshot.revision = state.reserve_guardian_policy_revision()?;
|
||||
|
||||
@@ -20,7 +20,14 @@ use crate::session::tests::make_session_and_context;
|
||||
use crate::tasks::InterruptedTurnHistoryMarker;
|
||||
use crate::tasks::interrupted_turn_history_marker;
|
||||
use crate::windows_sandbox::WindowsSandboxLevelExt;
|
||||
use codex_config::CloudConfigBundleLoader;
|
||||
use codex_config::CloudConfigBundlePolicy;
|
||||
use codex_config::CloudConfigBundleSnapshot;
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_config::loader::load_guardian_policy_snapshot;
|
||||
use codex_config::test_support::CloudConfigBundleFixture;
|
||||
use codex_exec_server::LOCAL_FS;
|
||||
use codex_execpolicy::Decision;
|
||||
use codex_execpolicy::NetworkRuleProtocol;
|
||||
use codex_extension_api::SessionIsolation;
|
||||
@@ -1535,6 +1542,11 @@ async fn code_mode_session_provider_is_shared_across_threads() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn mcp_invalidation_refreshes_threads_that_are_still_starting() {
|
||||
const STARTUP_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const POLICY: &str = "Use the refreshed startup policy.";
|
||||
const LOCAL_POLICY: &str = "Use the latest local requirements.";
|
||||
const REPLACEMENT_POLICY: &str = "Use the current managed bundle.";
|
||||
const CHILD_MODEL: &str = "gpt-5.4";
|
||||
struct BlockingThreadStartup {
|
||||
entered: tokio::sync::Notify,
|
||||
release: tokio::sync::Notify,
|
||||
@@ -1576,6 +1588,7 @@ async fn mcp_invalidation_refreshes_threads_that_are_still_starting() {
|
||||
let temp_dir = tempdir().expect("tempdir");
|
||||
let mut config = test_config().await;
|
||||
// Resolve the model locally before waiting for the MCP lifecycle hook.
|
||||
config.model = Some("gpt-5.5".to_owned());
|
||||
config.model_catalog = Some(
|
||||
codex_models_manager::bundled_models_response().expect("bundled model catalog should load"),
|
||||
);
|
||||
@@ -1583,6 +1596,52 @@ async fn mcp_invalidation_refreshes_threads_that_are_still_starting() {
|
||||
config.cwd = config.codex_home.abs();
|
||||
std::fs::create_dir_all(&config.codex_home).expect("create codex home");
|
||||
|
||||
let policy = CloudConfigBundlePolicy::default();
|
||||
let mut cloud = CloudConfigBundleSnapshot {
|
||||
bundle: Ok(Some(
|
||||
CloudConfigBundleFixture::enterprise_requirement(format!(
|
||||
"guardian_policy_config = {POLICY:?}\nallowed_approvals_reviewers = ['user']\n[auto_review]\nrequired_on_models = [{CHILD_MODEL:?}]"
|
||||
))
|
||||
.into_bundle(),
|
||||
)),
|
||||
config_server: None,
|
||||
binding: None,
|
||||
};
|
||||
policy.publish_snapshot(&mut cloud);
|
||||
struct TestPolicyLoader {
|
||||
home: AbsolutePathBuf,
|
||||
overrides: LoaderOverrides,
|
||||
cloud: tokio::sync::watch::Receiver<CloudConfigBundleSnapshot>,
|
||||
}
|
||||
impl GuardianPolicyLoader for TestPolicyLoader {
|
||||
fn load_guardian_policy_snapshot(
|
||||
&self,
|
||||
revision: u64,
|
||||
) -> BoxFuture<'_, std::io::Result<codex_config::GuardianPolicySnapshot>> {
|
||||
Box::pin(async move {
|
||||
let cloud = CloudConfigBundleLoader::from_snapshot(self.cloud.borrow().clone());
|
||||
load_guardian_policy_snapshot(
|
||||
LOCAL_FS.as_ref(),
|
||||
self.home.as_path(),
|
||||
&self.overrides,
|
||||
&cloud,
|
||||
revision,
|
||||
)
|
||||
.await
|
||||
})
|
||||
}
|
||||
}
|
||||
let (cloud_tx, cloud_rx) = tokio::sync::watch::channel(cloud);
|
||||
let requirements = config.codex_home.join("requirements.toml").to_path_buf();
|
||||
let loader = Arc::new(TestPolicyLoader {
|
||||
home: config.codex_home.clone(),
|
||||
overrides: LoaderOverrides {
|
||||
system_requirements_path: Some(requirements.clone()),
|
||||
..LoaderOverrides::without_managed_config_for_tests()
|
||||
},
|
||||
cloud: cloud_rx,
|
||||
});
|
||||
|
||||
let observer = Arc::new(BlockingThreadStartup {
|
||||
entered: tokio::sync::Notify::new(),
|
||||
release: tokio::sync::Notify::new(),
|
||||
@@ -1593,7 +1652,7 @@ async fn mcp_invalidation_refreshes_threads_that_are_still_starting() {
|
||||
extensions.thread_lifecycle_contributor(observer.clone());
|
||||
extensions.mcp_server_contributor(observer.clone());
|
||||
let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("dummy"));
|
||||
let manager = Arc::new(ThreadManager::new(
|
||||
let manager = ThreadManager::new(
|
||||
&config,
|
||||
crate::build_startup_models(
|
||||
&config,
|
||||
@@ -1612,28 +1671,106 @@ async fn mcp_invalidation_refreshes_threads_that_are_still_starting() {
|
||||
/*agent_graph_store*/ None,
|
||||
/*attestation_provider*/ None,
|
||||
/*external_time_provider*/ None,
|
||||
));
|
||||
);
|
||||
let manager = Arc::new(manager.with_guardian_policy_loader(loader));
|
||||
let starting = tokio::spawn({
|
||||
let manager = Arc::clone(&manager);
|
||||
async move { manager.start_thread(StartThreadOptions::new(config)).await }
|
||||
});
|
||||
|
||||
tokio::time::timeout(Duration::from_secs(5), observer.entered.notified())
|
||||
tokio::time::timeout(STARTUP_TIMEOUT, observer.entered.notified())
|
||||
.await
|
||||
.expect("thread should enter its startup lifecycle");
|
||||
assert!(manager.list_thread_ids().await.is_empty());
|
||||
std::fs::write(
|
||||
&requirements,
|
||||
format!("guardian_extra_policy = {LOCAL_POLICY:?}"),
|
||||
)
|
||||
.unwrap();
|
||||
manager
|
||||
.refresh_guardian_policy()
|
||||
.await
|
||||
.expect("publish Guardian policy while startup is paused");
|
||||
manager.invalidate_mcp_runtimes().await;
|
||||
observer.release.notify_one();
|
||||
starting
|
||||
let started = tokio::time::timeout(STARTUP_TIMEOUT, starting)
|
||||
.await
|
||||
.expect("thread startup must terminate")
|
||||
.expect("thread startup task should finish")
|
||||
.expect("thread should start");
|
||||
tokio::time::timeout(Duration::from_secs(5), observer.refreshed.notified())
|
||||
let inherited = started.thread.config().await;
|
||||
assert_eq!(
|
||||
inherited.guardian_extra_policy.as_deref(),
|
||||
Some(LOCAL_POLICY)
|
||||
);
|
||||
tokio::time::timeout(STARTUP_TIMEOUT, observer.refreshed.notified())
|
||||
.await
|
||||
.expect("invalidation during startup should refresh the newly published thread");
|
||||
let shutdown = manager
|
||||
.shutdown_all_threads_bounded(Duration::from_secs(5))
|
||||
.await;
|
||||
|
||||
// A starting thread cannot register after its Guardian source changes.
|
||||
let bundle = CloudConfigBundleFixture::enterprise_requirement(format!(
|
||||
"guardian_policy_config = {REPLACEMENT_POLICY:?}\nallowed_sandbox_modes = ['read-only']"
|
||||
))
|
||||
.into_bundle();
|
||||
let startup_id = ThreadId::new();
|
||||
let parent_id = started.thread_id;
|
||||
let starting = tokio::spawn({
|
||||
let manager = Arc::clone(&manager);
|
||||
let mut options = StartThreadOptions::new(inherited.as_ref().clone());
|
||||
options.reserved_thread_id = Some(startup_id);
|
||||
async move { manager.start_thread(options).await }
|
||||
});
|
||||
tokio::time::timeout(STARTUP_TIMEOUT, observer.entered.notified())
|
||||
.await
|
||||
.expect("thread should pause before registration");
|
||||
policy.observe_remote_bundle(&bundle);
|
||||
observer.release.notify_one();
|
||||
let result = tokio::time::timeout(STARTUP_TIMEOUT, starting)
|
||||
.await
|
||||
.expect("rejected startup must terminate")
|
||||
.expect("startup task should finish");
|
||||
let Err(error) = result else {
|
||||
panic!("startup should reject the changed Guardian source");
|
||||
};
|
||||
assert!(matches!(
|
||||
error.details(),
|
||||
CodexErrorDetails::InvalidRequest(message)
|
||||
if message.contains("Guardian policy changed during startup")
|
||||
));
|
||||
assert!(!manager.list_thread_ids().await.contains(&startup_id));
|
||||
|
||||
// The child model was blocked by the old policy. Only the background bundle changed.
|
||||
cloud_tx.send_modify(|cloud| {
|
||||
cloud.bundle = Ok(Some(bundle));
|
||||
policy.publish_snapshot(cloud);
|
||||
});
|
||||
let child_source = SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
|
||||
parent_thread_id: parent_id,
|
||||
depth: 1,
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
agent_path: None,
|
||||
});
|
||||
for source in [None, Some(child_source)] {
|
||||
let mut options = StartThreadOptions::new(inherited.as_ref().clone());
|
||||
options.config.model = Some(CHILD_MODEL.to_owned());
|
||||
options.session_source = source;
|
||||
observer.release.notify_one();
|
||||
let recovered = tokio::time::timeout(STARTUP_TIMEOUT, manager.start_thread(options))
|
||||
.await
|
||||
.expect("inherited startup must terminate")
|
||||
.expect("start with current Guardian policy");
|
||||
assert_eq!(
|
||||
recovered
|
||||
.thread
|
||||
.config()
|
||||
.await
|
||||
.guardian_policy_config
|
||||
.as_deref(),
|
||||
Some(REPLACEMENT_POLICY),
|
||||
);
|
||||
}
|
||||
let shutdown = manager.shutdown_all_threads_bounded(STARTUP_TIMEOUT).await;
|
||||
assert!(shutdown.timed_out.is_empty());
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user