mirror of
https://github.com/openai/codex.git
synced 2026-11-19 22:30:42 +00:00
Refresh managed Guardian policy across Codex threads (#62496)
## Why A thread can start while managed Guardian policy is being refreshed. Startup and refresh need to coordinate so the thread does not register with policy that the refresh has already superseded. ## What changed Let hosts provide a `GuardianPolicyLoader` to `ThreadManager` for startup and on-demand refresh. Pause thread registration while a refresh loads and publishes policy. If publication overtakes a thread's startup configuration, reload Guardian policy before registering the thread. Apply the published policy to live threads concurrently. Once published, the updates continue even if the refresh caller is canceled. Return an error if any live thread rejects the update. ## Testing Add regression coverage for an idle thread receiving the update while another thread holds its session lock, and for reporting a live thread's rejection of invalid Guardian configuration. GitOrigin-RevId: ca0cfa2a30f0d45c4ac5ded3400e0e18177ede1d
This commit is contained in:
@@ -873,10 +873,14 @@ async fn cancelled_spawn_after_input_admission_discards_child() {
|
||||
});
|
||||
let child = poll_fn(|cx| {
|
||||
assert!(spawn.as_mut().poll(cx).is_pending());
|
||||
let threads = state.threads.try_read().expect("uncontended manager");
|
||||
let threads = state.threads.state.try_read().expect("uncontended manager");
|
||||
// On this single-thread runtime the session loop cannot consume the first
|
||||
// input until this poll returns. Leave spawn waiting for its admission reply.
|
||||
match threads.values().find(|thread| !thread.io.tx_sub.is_empty()) {
|
||||
match threads
|
||||
.threads
|
||||
.values()
|
||||
.find(|thread| !thread.io.tx_sub.is_empty())
|
||||
{
|
||||
Some(child) => Poll::Ready(Arc::clone(child)),
|
||||
None => Poll::Pending,
|
||||
}
|
||||
@@ -1187,10 +1191,10 @@ async fn cancelled_v2_send_finishes_reload_registration() {
|
||||
let mut send = control.send(followup_request("cancelled follow-up"));
|
||||
let (reloaded, pin_blocker) = poll_fn(|cx| {
|
||||
assert!(send.as_mut().poll(cx).is_pending());
|
||||
let Ok(threads) = state.threads.try_read() else {
|
||||
let Ok(threads) = state.threads.state.try_read() else {
|
||||
return Poll::Pending;
|
||||
};
|
||||
let Some(reloaded) = threads.get(&child_id).cloned() else {
|
||||
let Some(reloaded) = threads.threads.get(&child_id).cloned() else {
|
||||
return Poll::Pending;
|
||||
};
|
||||
// On this single-thread runtime, intercept publication before the detached
|
||||
|
||||
@@ -5,9 +5,26 @@ use super::guardian_policy_config_from_requirements;
|
||||
use super::normalize_guardian_policy_config;
|
||||
use codex_config::ConfigRequirements;
|
||||
use codex_config::ConfigRequirementsToml;
|
||||
use codex_config::GuardianPolicySnapshot;
|
||||
use codex_config::config_toml::AutoReviewToml;
|
||||
use codex_protocol::config_types::ApprovalsReviewer;
|
||||
|
||||
impl super::Config {
|
||||
pub(crate) fn apply_guardian_policy(
|
||||
&mut self,
|
||||
snapshot: &GuardianPolicySnapshot,
|
||||
) -> std::io::Result<()> {
|
||||
self.config_layer_stack.apply_guardian_policy(snapshot);
|
||||
let fallback = self.config_layer_stack.guardian_config()?;
|
||||
(self.guardian_policy_config, self.guardian_extra_policy) = resolve_guardian_policy_text(
|
||||
self.config_layer_stack.requirements_toml(),
|
||||
Some(&fallback),
|
||||
);
|
||||
self.guardian_policy_revision = snapshot.revision;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn resolve_guardian_policy_text(
|
||||
requirements: &ConfigRequirementsToml,
|
||||
fallback: Option<&AutoReviewToml>,
|
||||
|
||||
@@ -193,6 +193,7 @@ pub use thread_manager::AgentTreeShutdownFailure;
|
||||
pub use thread_manager::AgentTreeShutdownFailureReason;
|
||||
pub use thread_manager::AgentTreeShutdownReport;
|
||||
pub use thread_manager::ForkSnapshot;
|
||||
pub use thread_manager::GuardianPolicyLoader;
|
||||
pub use thread_manager::InternalSessionParent;
|
||||
pub use thread_manager::LoadedSuspendedAgent;
|
||||
pub use thread_manager::McpRefreshReason;
|
||||
|
||||
@@ -1,11 +1,87 @@
|
||||
//! Runtime-refresh regressions; pure authority resolution is tested with Config.
|
||||
|
||||
use super::*;
|
||||
use crate::StartThreadOptions;
|
||||
use crate::ThreadManager;
|
||||
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);
|
||||
impl crate::GuardianPolicyLoader for TestPolicyLoader {
|
||||
fn load_guardian_policy_snapshot(
|
||||
&self,
|
||||
revision: u64,
|
||||
) -> BoxFuture<'_, std::io::Result<codex_config::GuardianPolicySnapshot>> {
|
||||
Box::pin(async move {
|
||||
load_guardian_policy_snapshot(
|
||||
LOCAL_FS.as_ref(),
|
||||
self.0.as_path(),
|
||||
&LoaderOverrides::without_managed_config_for_tests(),
|
||||
&codex_config::CloudConfigBundleLoader::default(),
|
||||
revision,
|
||||
)
|
||||
.await
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const UPDATE_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
let home = tempfile::tempdir()?;
|
||||
let mut config = crate::config::test_config().await;
|
||||
config.codex_home = home.path().abs();
|
||||
config.cwd = config.codex_home.clone();
|
||||
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())));
|
||||
|
||||
manager
|
||||
.start_thread(StartThreadOptions::new(config.clone()))
|
||||
.await?;
|
||||
manager
|
||||
.start_thread(StartThreadOptions::new(config))
|
||||
.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 {
|
||||
panic!("expected two live threads");
|
||||
};
|
||||
let busy = manager.get_thread(*busy).await?;
|
||||
let idle = manager.get_thread(*idle).await?;
|
||||
let startup_revision = idle.config().await.guardian_policy_revision;
|
||||
let (locked, state_locked) = tokio::sync::oneshot::channel();
|
||||
let (release_state, release) = tokio::sync::oneshot::channel();
|
||||
let held_state = tokio::task::spawn_blocking(move || {
|
||||
let _state = busy.session.state.blocking_lock();
|
||||
let _ = locked.send(());
|
||||
let _ = release.blocking_recv();
|
||||
});
|
||||
state_locked.await?;
|
||||
|
||||
let (refresh, idle_update) = tokio::join!(manager.refresh_guardian_policy(), async {
|
||||
let result = tokio::time::timeout(UPDATE_TIMEOUT, async {
|
||||
while idle.config().await.guardian_policy_revision <= startup_revision {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await;
|
||||
let _ = release_state.send(());
|
||||
result
|
||||
});
|
||||
held_state.await?;
|
||||
idle_update.expect("the idle thread should update while the first thread holds its lock");
|
||||
refresh?;
|
||||
manager.shutdown_all_threads_bounded(UPDATE_TIMEOUT).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mcp_reload_survives_guardian_only_publications() {
|
||||
let (session, _) = make_session_and_context().await;
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
mod managed;
|
||||
mod model_catalog;
|
||||
mod registry;
|
||||
mod shared_instructions;
|
||||
mod shutdown;
|
||||
|
||||
pub use registry::GuardianPolicyLoader;
|
||||
pub use shutdown::AgentTreeShutdown;
|
||||
pub use shutdown::AgentTreeShutdownFailure;
|
||||
pub use shutdown::AgentTreeShutdownFailureReason;
|
||||
@@ -11,6 +13,7 @@ pub use shutdown::LoadedSuspendedAgent;
|
||||
pub use shutdown::SuspendedAgentTree;
|
||||
pub(crate) use shutdown::thread_store_error_kind;
|
||||
|
||||
use self::registry::ThreadRegistry;
|
||||
use crate::CodexAppsToolsCache;
|
||||
use crate::CodexThreadSettingsOverrides;
|
||||
use crate::agent::AgentStatus;
|
||||
@@ -126,7 +129,6 @@ use codex_utils_git_discovery::GitRootDiscovery;
|
||||
use futures::StreamExt;
|
||||
use futures::future::BoxFuture;
|
||||
use futures::stream::FuturesUnordered;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::future::Future;
|
||||
use std::path::PathBuf;
|
||||
@@ -134,8 +136,8 @@ use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::RwLock;
|
||||
use tokio::sync::broadcast;
|
||||
use tokio::sync::watch;
|
||||
use tracing::instrument;
|
||||
use tracing::warn;
|
||||
|
||||
@@ -599,7 +601,8 @@ pub(crate) struct ResumeThreadWithHistoryOptions {
|
||||
/// function to require an `Arc<&Self>`.
|
||||
pub(crate) struct ThreadManagerState {
|
||||
// Eviction updates this registry and residency together, locking the registry first.
|
||||
pub(crate) threads: Arc<RwLock<HashMap<ThreadId, Arc<CodexThread>>>>,
|
||||
pub(crate) threads: ThreadRegistry,
|
||||
guardian_policy_loader: Option<Arc<dyn GuardianPolicyLoader>>,
|
||||
shared_thread_instructions: shared_instructions::SharedThreadInstructionsProviders,
|
||||
thread_created_tx: broadcast::Sender<ThreadId>,
|
||||
thread_id_generator: ThreadIdGenerator,
|
||||
@@ -702,7 +705,8 @@ impl ThreadManager {
|
||||
};
|
||||
Self {
|
||||
state: Arc::new(ThreadManagerState {
|
||||
threads: Arc::new(RwLock::new(HashMap::new())),
|
||||
threads: ThreadRegistry::default(),
|
||||
guardian_policy_loader: None,
|
||||
shared_thread_instructions: Default::default(),
|
||||
thread_created_tx,
|
||||
thread_id_generator: default_thread_id_generator(),
|
||||
@@ -768,6 +772,15 @@ impl ThreadManager {
|
||||
self
|
||||
}
|
||||
|
||||
/// Installs the host loader used to read Guardian policy for startup and refresh.
|
||||
pub fn with_guardian_policy_loader(mut self, loader: Arc<dyn GuardianPolicyLoader>) -> Self {
|
||||
let Some(state) = Arc::get_mut(&mut self.state) else {
|
||||
unreachable!("Guardian policy loader must be set before the thread manager is shared");
|
||||
};
|
||||
state.guardian_policy_loader = Some(loader);
|
||||
self
|
||||
}
|
||||
|
||||
/// Samples host metrics without creating a Codex thread or code-mode session.
|
||||
/// Process-owned providers observe existing children; custom providers retain
|
||||
/// their transport's connection policy.
|
||||
@@ -906,7 +919,8 @@ impl ThreadManager {
|
||||
Self {
|
||||
state: Arc::new(ThreadManagerState {
|
||||
runtime_auth,
|
||||
threads: Arc::new(RwLock::new(HashMap::new())),
|
||||
threads: ThreadRegistry::default(),
|
||||
guardian_policy_loader: None,
|
||||
shared_thread_instructions: Default::default(),
|
||||
thread_created_tx,
|
||||
thread_id_generator: default_thread_id_generator(),
|
||||
@@ -1249,6 +1263,22 @@ impl ThreadManager {
|
||||
self.state.list_thread_ids().await
|
||||
}
|
||||
|
||||
/// Reserves a Guardian policy revision before a host loads thread startup configuration.
|
||||
pub async fn reserve_guardian_policy_revision(&self) -> std::io::Result<u64> {
|
||||
self.state.threads.reserve_guardian_policy_revision().await
|
||||
}
|
||||
|
||||
/// Loads managed Guardian requirements before publishing them to live and starting threads.
|
||||
/// A live thread can reject the update after the policy has been published.
|
||||
pub async fn refresh_guardian_policy(&self) -> std::io::Result<()> {
|
||||
let loader = self
|
||||
.state
|
||||
.guardian_policy_loader
|
||||
.as_deref()
|
||||
.ok_or_else(|| std::io::Error::other("Guardian policy loader is not configured"))?;
|
||||
self.state.threads.refresh_guardian_policy(loader).await
|
||||
}
|
||||
|
||||
pub fn subscribe_thread_created(&self) -> broadcast::Receiver<ThreadId> {
|
||||
self.state.thread_created_tx.subscribe()
|
||||
}
|
||||
@@ -2739,6 +2769,21 @@ impl ThreadManagerState {
|
||||
thread.session.services.mcp_runtime.revoke_ema();
|
||||
}
|
||||
}
|
||||
if !session_source.is_internal()
|
||||
&& let Err(error) = runtime
|
||||
.shutdown
|
||||
.run_until_cancelled(self.threads.prepare_startup_guardian_policy(
|
||||
&mut config,
|
||||
self.guardian_policy_loader.as_deref(),
|
||||
))
|
||||
.await
|
||||
.ok_or(CodexErr::TurnAborted)?
|
||||
{
|
||||
warn!(kind = ?error.kind(), "could not load Guardian policy for startup");
|
||||
return Err(CodexErr::InvalidRequest(
|
||||
"Could not load Guardian policy for thread startup".into(),
|
||||
));
|
||||
}
|
||||
let supplied_thread_instructions =
|
||||
thread_extension_init.remove::<InheritedThreadInstructions>();
|
||||
let supplied_exec_policy = thread_extension_init.remove::<InheritedExecPolicy>();
|
||||
@@ -3059,9 +3104,11 @@ impl ThreadManagerState {
|
||||
warn!(%thread_id, %source_thread_id, %error, "failed to copy fork attachments");
|
||||
}
|
||||
}
|
||||
let finalize_result = self
|
||||
.finalize_thread_spawn(session, io, tracked_session_source, ®istered)
|
||||
.await;
|
||||
let finalize_result = tokio::select! {
|
||||
biased;
|
||||
_ = runtime.shutdown.cancelled() => Err(CodexErr::TurnAborted),
|
||||
result = self.finalize_thread_spawn(session, io, tracked_session_source, ®istered) => result,
|
||||
};
|
||||
let (new_thread, tier_acceptance) = match finalize_result {
|
||||
Ok(registered) => registered,
|
||||
Err(error) => {
|
||||
@@ -3107,7 +3154,7 @@ impl ThreadManagerState {
|
||||
) -> CodexResult<(NewThread, Option<ServiceTierAcceptance>)> {
|
||||
let thread_id = session.thread_id();
|
||||
let event = io.next_event().await?;
|
||||
let session_configured = match event {
|
||||
let mut session_configured = match event {
|
||||
Event {
|
||||
id,
|
||||
msg: EventMsg::SessionConfigured(session_configured),
|
||||
@@ -3117,13 +3164,37 @@ impl ThreadManagerState {
|
||||
}
|
||||
};
|
||||
|
||||
let ema_cancellation = session
|
||||
.get_config()
|
||||
.await
|
||||
let mut startup_config = session.get_config().await;
|
||||
let mcp_ema_cancellation = startup_config
|
||||
.config_layer_stack
|
||||
.mcp_ema_cancellation()
|
||||
.clone();
|
||||
{
|
||||
let policy_changed = "Guardian policy changed during startup; retry starting the thread";
|
||||
let check_guardian = !session_source.is_internal();
|
||||
let mut reload_policy = false;
|
||||
let mut pending_refresh: Option<watch::Receiver<()>> = None;
|
||||
let startup_error = loop {
|
||||
if let Some(mut pending) = pending_refresh.take() {
|
||||
let _ = pending.changed().await;
|
||||
}
|
||||
if std::mem::take(&mut reload_policy) {
|
||||
// A revision orders load starts. Re-read here because the startup may
|
||||
// have read newer local requirements than the published snapshot did.
|
||||
let Ok(snapshot) = self
|
||||
.threads
|
||||
.load_startup_guardian_policy(self.guardian_policy_loader.as_deref())
|
||||
.await
|
||||
else {
|
||||
break policy_changed.to_owned();
|
||||
};
|
||||
if session.refresh_guardian_policy(&snapshot).await
|
||||
!= crate::ConfigRefreshOutcome::Published
|
||||
{
|
||||
break policy_changed.to_owned();
|
||||
}
|
||||
startup_config = session.get_config().await;
|
||||
session_configured.approvals_reviewer = startup_config.approvals_reviewer;
|
||||
}
|
||||
let pending_service_tier = if self.agent_control_factory.is_some()
|
||||
|| matches!(
|
||||
&session.agent_runtime,
|
||||
@@ -3134,9 +3205,31 @@ impl ThreadManagerState {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut threads = self.threads.write().await;
|
||||
if let std::collections::hash_map::Entry::Vacant(e) = threads.entry(thread_id) {
|
||||
ema_cancellation.publish();
|
||||
let mut registry = self.threads.state.write().await;
|
||||
if check_guardian && let Some(wait) = registry.pending_guardian_refresh() {
|
||||
pending_refresh = Some(wait);
|
||||
continue;
|
||||
}
|
||||
let revision = startup_config.guardian_policy_revision;
|
||||
let refresh_crossed_load = registry.published_guardian_revision > revision;
|
||||
if let std::collections::hash_map::Entry::Vacant(entry) =
|
||||
registry.threads.entry(thread_id)
|
||||
{
|
||||
if check_guardian && refresh_crossed_load {
|
||||
reload_policy = true;
|
||||
continue;
|
||||
}
|
||||
// Source validity is held through insertion, after the last await.
|
||||
let binding = (check_guardian && revision != 0)
|
||||
.then(|| startup_config.config_layer_stack.guardian_policy_binding())
|
||||
.flatten()
|
||||
.map(codex_config::CloudConfigBundleBinding::read);
|
||||
if binding.as_ref().is_some_and(|binding| {
|
||||
binding.status != codex_config::CloudConfigBundleBindingStatus::Current
|
||||
}) {
|
||||
break policy_changed.to_owned();
|
||||
}
|
||||
mcp_ema_cancellation.publish();
|
||||
let thread = Arc::new(CodexThread::new(
|
||||
Arc::clone(&session),
|
||||
io,
|
||||
@@ -3146,7 +3239,7 @@ impl ThreadManagerState {
|
||||
));
|
||||
// All registration checks passed; publish the receipt with this insertion.
|
||||
registered.store(true, Ordering::Release);
|
||||
e.insert(thread.clone());
|
||||
entry.insert(Arc::clone(&thread));
|
||||
let tier_acceptance = pending_service_tier.and_then(|(mut state, update)| {
|
||||
state.service_tier_acceptance =
|
||||
crate::agent::host::propagate_config_update(&session, update);
|
||||
@@ -3160,14 +3253,13 @@ impl ThreadManagerState {
|
||||
};
|
||||
return Ok((new_thread, tier_acceptance));
|
||||
}
|
||||
}
|
||||
break format!("thread {thread_id} is already running");
|
||||
};
|
||||
|
||||
if let Err(err) = io.shutdown_and_wait().await {
|
||||
warn!("failed to shut down duplicate thread {thread_id}: {err}");
|
||||
warn!(%thread_id, %err, %startup_error, "failed to shut down rejected thread");
|
||||
}
|
||||
Err(CodexErr::InvalidRequest(format!(
|
||||
"thread {thread_id} is already running"
|
||||
)))
|
||||
Err(CodexErr::InvalidRequest(startup_error))
|
||||
}
|
||||
|
||||
pub(crate) fn notify_thread_created(&self, thread_id: ThreadId) {
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
//! Keeps thread membership and Guardian publication atomic under one registry lock.
|
||||
//! Refresh pauses registration during policy loading. Policy loads and session
|
||||
//! updates happen outside the lock.
|
||||
|
||||
use crate::CodexThread;
|
||||
use crate::ConfigRefreshOutcome;
|
||||
use crate::config::Config;
|
||||
use codex_config::CloudConfigBundleBinding;
|
||||
use codex_config::CloudConfigBundleBindingStatus;
|
||||
use codex_config::GuardianPolicySnapshot;
|
||||
use codex_protocol::ThreadId;
|
||||
use futures::future::BoxFuture;
|
||||
use futures::future::join_all;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::RwLock;
|
||||
use tokio::sync::RwLockMappedWriteGuard;
|
||||
use tokio::sync::RwLockReadGuard;
|
||||
use tokio::sync::RwLockWriteGuard;
|
||||
use tokio::sync::watch;
|
||||
use tracing::warn;
|
||||
|
||||
type LiveThreads = HashMap<ThreadId, Arc<CodexThread>>;
|
||||
|
||||
/// Reads the current managed Guardian requirements using the host's config authority.
|
||||
pub trait GuardianPolicyLoader: Send + Sync {
|
||||
fn load_guardian_policy_snapshot(
|
||||
&self,
|
||||
revision: u64,
|
||||
) -> BoxFuture<'_, std::io::Result<GuardianPolicySnapshot>>;
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct ThreadRegistry {
|
||||
pub(crate) state: RwLock<ThreadRegistryState>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct ThreadRegistryState {
|
||||
pub(crate) threads: LiveThreads,
|
||||
last_guardian_revision: u64,
|
||||
pub(super) published_guardian_revision: u64,
|
||||
guardian_refresh: Option<watch::Receiver<()>>,
|
||||
}
|
||||
|
||||
impl ThreadRegistryState {
|
||||
fn reserve_guardian_policy_revision(&mut self) -> std::io::Result<u64> {
|
||||
self.last_guardian_revision = self
|
||||
.last_guardian_revision
|
||||
.checked_add(1)
|
||||
.ok_or_else(|| std::io::Error::other("Guardian observation revisions exhausted"))?;
|
||||
Ok(self.last_guardian_revision)
|
||||
}
|
||||
|
||||
pub(super) fn pending_guardian_refresh(&self) -> Option<watch::Receiver<()>> {
|
||||
self.guardian_refresh
|
||||
.as_ref()
|
||||
.filter(|confirmation| confirmation.has_changed().is_ok())
|
||||
.cloned()
|
||||
}
|
||||
}
|
||||
|
||||
impl ThreadRegistry {
|
||||
pub(crate) async fn read(&self) -> RwLockReadGuard<'_, LiveThreads> {
|
||||
RwLockReadGuard::map(self.state.read().await, |state| &state.threads)
|
||||
}
|
||||
|
||||
pub(crate) async fn write(&self) -> RwLockMappedWriteGuard<'_, LiveThreads> {
|
||||
RwLockWriteGuard::map(self.state.write().await, |state| &mut state.threads)
|
||||
}
|
||||
|
||||
pub(super) async fn reserve_guardian_policy_revision(&self) -> std::io::Result<u64> {
|
||||
self.state.write().await.reserve_guardian_policy_revision()
|
||||
}
|
||||
|
||||
pub(super) async fn prepare_startup_guardian_policy(
|
||||
&self,
|
||||
config: &mut Config,
|
||||
loader: Option<&dyn GuardianPolicyLoader>,
|
||||
) -> std::io::Result<()> {
|
||||
let stale_binding = config.guardian_policy_revision != 0
|
||||
&& config
|
||||
.config_layer_stack
|
||||
.guardian_policy_binding()
|
||||
.is_some_and(|binding| {
|
||||
binding.read().status != CloudConfigBundleBindingStatus::Current
|
||||
});
|
||||
let refresh_crossed_load =
|
||||
self.state.read().await.published_guardian_revision > config.guardian_policy_revision;
|
||||
let untracked = config.guardian_policy_revision == 0 && loader.is_some();
|
||||
if untracked || stale_binding || refresh_crossed_load {
|
||||
let snapshot = self.load_startup_guardian_policy(loader).await?;
|
||||
config.apply_guardian_policy(&snapshot)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn load_startup_guardian_policy(
|
||||
&self,
|
||||
loader: Option<&dyn GuardianPolicyLoader>,
|
||||
) -> std::io::Result<GuardianPolicySnapshot> {
|
||||
let unavailable = || std::io::Error::other("Guardian policy source changed");
|
||||
let loader = loader.ok_or_else(unavailable)?;
|
||||
let revision = self.reserve_guardian_policy_revision().await?;
|
||||
let snapshot = loader.load_guardian_policy_snapshot(revision).await?;
|
||||
if snapshot
|
||||
.binding
|
||||
.as_ref()
|
||||
.is_some_and(|binding| binding.read().status != CloudConfigBundleBindingStatus::Current)
|
||||
{
|
||||
return Err(unavailable());
|
||||
}
|
||||
Ok(snapshot)
|
||||
}
|
||||
|
||||
pub(super) async fn refresh_guardian_policy(
|
||||
&self,
|
||||
loader: &dyn GuardianPolicyLoader,
|
||||
) -> std::io::Result<()> {
|
||||
// Pause registration before reading. Dropping the sender releases waiters.
|
||||
let (registration_pause, revision) = loop {
|
||||
let mut wait = {
|
||||
let mut state = self.state.write().await;
|
||||
if let Some(wait) = state.pending_guardian_refresh() {
|
||||
wait
|
||||
} else {
|
||||
let revision = state.reserve_guardian_policy_revision()?;
|
||||
let (sender, receiver) = watch::channel(());
|
||||
state.guardian_refresh = Some(receiver);
|
||||
break (sender, revision);
|
||||
}
|
||||
};
|
||||
let _ = wait.changed().await;
|
||||
};
|
||||
let mut snapshot = loader.load_guardian_policy_snapshot(revision).await?;
|
||||
let pending = {
|
||||
let mut state = self.state.write().await;
|
||||
let binding = snapshot
|
||||
.binding
|
||||
.as_ref()
|
||||
.map(CloudConfigBundleBinding::read);
|
||||
if binding
|
||||
.as_ref()
|
||||
.is_some_and(|guard| guard.status != CloudConfigBundleBindingStatus::Current)
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
// A startup may have reserved a revision while the refresh was reading.
|
||||
snapshot.revision = state.reserve_guardian_policy_revision()?;
|
||||
state.published_guardian_revision = snapshot.revision;
|
||||
state
|
||||
.threads
|
||||
.values()
|
||||
.filter(|thread| !thread.session_source.is_internal())
|
||||
.cloned()
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
drop(registration_pause);
|
||||
// Complete updates after registry publication even if the refresh caller is cancelled.
|
||||
let update = tokio::spawn(async move {
|
||||
let snapshot = &snapshot;
|
||||
let rejections = join_all(pending.into_iter().map(|thread| async move {
|
||||
let rejected =
|
||||
thread.refresh_guardian_policy(snapshot).await == ConfigRefreshOutcome::Rejected;
|
||||
if rejected {
|
||||
warn!(thread_id = %thread.session.thread_id(), "Guardian policy refresh rejected for thread");
|
||||
}
|
||||
rejected
|
||||
}))
|
||||
.await;
|
||||
if rejections.into_iter().any(|rejected| rejected) {
|
||||
return Err(std::io::Error::other(
|
||||
"Guardian policy refresh rejected by one or more live threads",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
update.await?
|
||||
}
|
||||
}
|
||||
@@ -65,6 +65,7 @@ use core_test_support::PathExt;
|
||||
use core_test_support::responses::mount_models_once;
|
||||
use core_test_support::responses::strip_response_item_ids_from_json;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::HashMap;
|
||||
use std::time::Duration;
|
||||
use tempfile::tempdir;
|
||||
use wiremock::MockServer;
|
||||
|
||||
@@ -2,10 +2,12 @@ use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use codex_config::CloudConfigBundleLoader;
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_config::loader::load_guardian_policy_snapshot;
|
||||
use codex_config::test_support::CloudConfigBundleFixture;
|
||||
use codex_config::types::WindowsSandboxModeToml;
|
||||
use codex_core::CodexThreadSettingsOverrides;
|
||||
use codex_core::config::ConfigBuilder;
|
||||
use codex_exec_server::LOCAL_FS;
|
||||
use codex_features::Feature;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::permissions::NetworkSandboxPolicy;
|
||||
@@ -94,6 +96,69 @@ async fn session_requires_managed_configuration_from_configured_service() -> Res
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn guardian_refresh_reports_live_thread_rejection() -> Result<()> {
|
||||
struct TestPolicyLoader {
|
||||
home: Arc<TempDir>,
|
||||
bundle: RwLock<CloudConfigBundleLoader>,
|
||||
}
|
||||
impl codex_core::GuardianPolicyLoader for TestPolicyLoader {
|
||||
fn load_guardian_policy_snapshot(
|
||||
&self,
|
||||
revision: u64,
|
||||
) -> futures::future::BoxFuture<'_, std::io::Result<codex_config::GuardianPolicySnapshot>>
|
||||
{
|
||||
let bundle = self.bundle.read().unwrap().clone();
|
||||
Box::pin(async move {
|
||||
load_guardian_policy_snapshot(
|
||||
LOCAL_FS.as_ref(),
|
||||
self.home.path(),
|
||||
&LoaderOverrides::without_managed_config_for_tests(),
|
||||
&bundle,
|
||||
revision,
|
||||
)
|
||||
.await
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
let server = start_mock_server().await;
|
||||
let home = Arc::new(TempDir::new()?);
|
||||
let loader = Arc::new(TestPolicyLoader {
|
||||
home: Arc::clone(&home),
|
||||
bundle: RwLock::new(
|
||||
CloudConfigBundleFixture::loader_with_enterprise_requirement(
|
||||
"guardian_policy_config = 'startup policy'",
|
||||
),
|
||||
),
|
||||
});
|
||||
let test = test_codex()
|
||||
.with_home(home)
|
||||
.with_thread_manager({
|
||||
let loader = Arc::clone(&loader);
|
||||
move |manager| manager.with_guardian_policy_loader(loader)
|
||||
})
|
||||
.build_with_auto_env(&server)
|
||||
.await?;
|
||||
let startup = test.codex.config().await;
|
||||
assert!(startup.guardian_policy_revision > 0);
|
||||
let policy = startup.guardian_policy_config.as_deref();
|
||||
assert_eq!(policy, Some("startup policy"));
|
||||
*loader.bundle.write().unwrap() =
|
||||
CloudConfigBundleFixture::loader_with_enterprise_config("auto_review = false");
|
||||
|
||||
let error = test
|
||||
.thread_manager
|
||||
.refresh_guardian_policy()
|
||||
.await
|
||||
.expect_err("the live thread cannot apply the invalid Guardian fallback");
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"Guardian policy refresh rejected by one or more live threads"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn managed_mxc_opt_out_blocks_preferred_and_explicit_selection() -> Result<()> {
|
||||
for mode in [None, Some("elevated"), Some("mxc")] {
|
||||
|
||||
Reference in New Issue
Block a user