mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:50:52 +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:
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user