Fix cleanup when unified exec startup is canceled (#64833)

## Why

Canceling a remote command during the early-exit grace period could
drop the process before handoff and run ordinary termination. That
bypasses the exec server's startup cleanup, which also disables
recovery for the abandoned session.

## What changed

Track whether each process has been handed off or abandoned. Dropping
a live process before handoff abandons startup once. Processes handed
off to the process store or to a one-shot caller retain normal
termination on drop.

## Testing

Add regression tests for cancellation during the early-exit grace
period, dropping an explicitly abandoned process, and normal cleanup
after registration or one-shot handoff.

GitOrigin-RevId: 2276ba15e50a2345da21e7841ab9015b572786ac
This commit is contained in:
jif
2026-12-01 00:26:27 +00:00
committed by copyberry
parent 6dab58d9f7
commit 51bcfc3768
6 changed files with 207 additions and 7 deletions
+12 -1
View File
@@ -21,7 +21,14 @@ use crate::tools::context::ExecCommandToolOutput;
pub(super) struct Completion<'a> {
pub timeout: Duration,
pub timed_out: bool,
pub process: &'a OnceLock<Arc<UnifiedExecProcess>>,
process: &'a OnceLock<Arc<UnifiedExecProcess>>,
}
impl Completion<'_> {
pub(super) fn publish_process(&self, process: &Arc<UnifiedExecProcess>) {
let _ = self.process.set(Arc::clone(process));
process.mark_managed();
}
}
impl UnifiedExecProcessManager {
@@ -123,3 +130,7 @@ impl UnifiedExecProcessManager {
result
}
}
#[cfg(test)]
#[path = "oneshot_tests.rs"]
mod tests;
@@ -0,0 +1,30 @@
#![cfg(test)]
use super::*;
use crate::unified_exec::process_tests::Cleanup;
use crate::unified_exec::process_tests::remote_process_with_cleanup;
use codex_exec_server::WriteStatus;
use pretty_assertions::assert_eq;
#[tokio::test(start_paused = true)]
async fn dropping_a_published_one_shot_uses_normal_termination() {
let (process, mut observed) = remote_process_with_cleanup(
WriteStatus::Accepted,
/*terminate_error*/ None,
/*sandbox_type*/ None,
)
.await;
let process = Arc::new(process);
let slot = OnceLock::new();
let completion = Completion {
timeout: Duration::from_secs(1),
timed_out: false,
process: &slot,
};
completion.publish_process(&process);
drop(process);
drop(slot.into_inner().expect("one-shot should own the process"));
assert_eq!(observed.recv().await, Some(Cleanup::Terminate));
assert_eq!(observed.recv().await, None);
}
+22 -1
View File
@@ -1,6 +1,7 @@
#![allow(clippy::module_inception)]
use std::sync::Arc;
use std::sync::OnceLock;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use tokio::sync::Mutex;
@@ -83,10 +84,18 @@ enum ProcessHandle {
ExecServer(Arc<dyn ExecProcess>),
}
/// Before handoff, dropping the caller must abandon a live process, including
/// during the early-exit grace period.
enum StartupHandoff {
Managed,
Abandoned,
}
/// Unified wrapper over directly spawned PTY sessions and exec-server-backed
/// processes.
pub(crate) struct UnifiedExecProcess {
process_handle: ProcessHandle,
startup_handoff: OnceLock<StartupHandoff>,
output_tx: broadcast::Sender<Vec<u8>>,
output: OutputHandles,
output_drained: Arc<Notify>,
@@ -132,6 +141,7 @@ impl UnifiedExecProcess {
Self {
process_handle,
startup_handoff: OnceLock::new(),
output_tx,
output,
output_drained,
@@ -249,7 +259,14 @@ impl UnifiedExecProcess {
self.finish_termination();
}
pub(super) fn mark_managed(&self) {
self.startup_handoff.get_or_init(|| StartupHandoff::Managed);
}
pub(super) fn abandon_start(&self) {
if self.startup_handoff.set(StartupHandoff::Abandoned).is_err() {
return;
}
match &self.process_handle {
ProcessHandle::Local(handle) => handle.terminate(),
ProcessHandle::ExecServer(handle) => Arc::clone(handle).abandon_start(),
@@ -682,6 +699,10 @@ impl UnifiedExecProcess {
impl Drop for UnifiedExecProcess {
fn drop(&mut self) {
self.terminate();
match self.startup_handoff.get() {
Some(StartupHandoff::Abandoned) => {}
None if !self.exit_reported() => self.abandon_start(),
None | Some(StartupHandoff::Managed) => self.terminate(),
}
}
}
@@ -545,7 +545,7 @@ impl UnifiedExecProcessManager {
} = attempt;
let process = Arc::new(process);
if let Some(completion) = completion.as_ref() {
let _ = completion.process.set(Arc::clone(&process));
completion.publish_process(&process);
}
let network_denial_monitor = deferred_network_approval
.as_ref()
@@ -1315,6 +1315,7 @@ impl UnifiedExecProcessManager {
let pruned_entry = store.and_then(|mut store| {
let pruned_entry = Self::prune_processes_if_needed(&mut store);
store.processes.insert(process_id, entry);
process.mark_managed();
pruned_entry
});
let watcher = exit_watcher(
@@ -3,6 +3,8 @@ use crate::sandboxing::ExecOptions;
use crate::tools::handlers::unified_exec::preparation::ExecCommandLifetime;
use crate::tools::handlers::unified_exec::preparation::ParsedExecCommand;
use crate::unified_exec::clamp_yield_time;
use crate::unified_exec::process_tests::Cleanup;
use crate::unified_exec::process_tests::remote_process_with_cleanup;
use codex_exec_server::ExecOutputStream;
use codex_network_proxy::ManagedNetworkSandboxContext;
use codex_network_proxy::NetworkProxyConfig;
@@ -578,6 +580,69 @@ async fn late_network_denial_grace_observes_cancellation_after_exit() -> anyhow:
Ok(())
}
#[tokio::test(start_paused = true)]
async fn dropping_a_registered_remote_process_uses_normal_termination() {
let (session, turn, _events) = crate::session::tests::make_session_and_context_with_rx().await;
let manager = &session.services.unified_exec_manager;
let context = UnifiedExecContext::new(
Arc::clone(&session),
crate::session::step_context::StepContext::for_test(Arc::clone(&turn)),
CancellationToken::new(),
"call".to_string(),
);
let environment = turn
.initial_environments
.primary()
.expect("primary environment");
let (process, mut observed) = remote_process_with_cleanup(
codex_exec_server::WriteStatus::StdinClosed,
/*terminate_error*/ None,
/*sandbox_type*/ None,
)
.await;
let process = Arc::new(process);
let process_id = manager.allocate_process_id().await;
start_streaming_output(&process, &context);
UnifiedExecProcessManager::handoff_to_exit_watcher(
Some(manager.process_store.lock().await),
/*pending_begin*/ None::<std::future::Ready<()>>,
Arc::clone(&process),
&context,
&["command".to_string()],
"command".to_string(),
environment.cwd().clone(),
environment.selection.environment_id.clone(),
super::super::TerminalPermissions::for_launch(
environment,
&turn,
super::super::TerminalSandboxSource::Native,
crate::sandboxing::SandboxPermissions::UseDefault,
/*additional_permissions*/ None,
/*internal_permissions*/ None,
),
/*plugin_attribution*/ None,
Instant::now(),
process_id,
/*tty*/ false,
/*network_approval*/ None,
/*network_denial_monitor*/ None,
/*publication*/ None,
/*metrics_sidecar*/ None,
Arc::clone(&process.output_handles().output_buffer),
Arc::new(AtomicBool::new(false)),
);
// A rejected write ends collection without an exit report from the executor.
assert!(matches!(
process.write(b"input").await,
Err(UnifiedExecError::WriteToStdin)
));
drop(process);
manager.release_process_id(process_id).await;
assert_eq!(observed.recv().await, Some(Cleanup::Terminate));
assert_eq!(observed.recv().await, None);
}
#[tokio::test]
async fn failed_initial_end_for_unstored_process_uses_fallback_output() {
let (session, turn, rx_event) = crate::session::tests::make_session_and_context_with_rx().await;
@@ -18,14 +18,22 @@ use pretty_assertions::assert_eq;
use std::collections::VecDeque;
use std::sync::Arc;
use tokio::sync::Mutex;
use tokio::sync::mpsc;
use tokio::sync::watch;
#[derive(Debug, PartialEq, Eq)]
pub(super) enum Cleanup {
Terminate,
AbandonStart,
}
struct MockExecProcess {
process_id: ProcessId,
write_response: WriteResponse,
read_responses: Mutex<VecDeque<ReadResponse>>,
terminate_error: Option<String>,
wake_tx: watch::Sender<u64>,
cleanup: mpsc::UnboundedSender<Cleanup>,
}
impl MockExecProcess {
@@ -47,6 +55,7 @@ impl MockExecProcess {
}
async fn terminate(&self) -> Result<(), ExecServerError> {
let _ = self.cleanup.send(Cleanup::Terminate);
if let Some(message) = &self.terminate_error {
return Err(ExecServerError::Protocol(message.clone()));
}
@@ -87,14 +96,19 @@ impl ExecProcess for MockExecProcess {
fn terminate(&self) -> ExecProcessFuture<'_, ()> {
Box::pin(MockExecProcess::terminate(self))
}
fn abandon_start(self: Arc<Self>) {
let _ = self.cleanup.send(Cleanup::AbandonStart);
}
}
pub(super) async fn remote_process(
fn remote_start(
write_status: WriteStatus,
terminate_error: Option<String>,
sandbox_type: impl Into<Option<codex_sandboxing::SandboxType>>,
) -> UnifiedExecProcess {
) -> (StartedExecProcess, mpsc::UnboundedReceiver<Cleanup>) {
let (wake_tx, _wake_rx) = watch::channel(0);
let (cleanup, observed) = mpsc::unbounded_channel();
let started = StartedExecProcess {
process: Arc::new(MockExecProcess {
process_id: "test-process".to_string().into(),
@@ -104,13 +118,70 @@ pub(super) async fn remote_process(
read_responses: Mutex::new(VecDeque::new()),
terminate_error,
wake_tx,
cleanup,
}),
sandbox_type: sandbox_type.into(),
};
UnifiedExecProcess::from_exec_server_started(started, OutputDrainPolicy::WaitForOutputClosure)
(started, observed)
}
pub(super) async fn remote_process(
write_status: WriteStatus,
terminate_error: Option<String>,
sandbox_type: impl Into<Option<codex_sandboxing::SandboxType>>,
) -> UnifiedExecProcess {
remote_process_with_cleanup(write_status, terminate_error, sandbox_type)
.await
.expect("remote process should start")
.0
}
pub(super) async fn remote_process_with_cleanup(
write_status: WriteStatus,
terminate_error: Option<String>,
sandbox_type: impl Into<Option<codex_sandboxing::SandboxType>>,
) -> (UnifiedExecProcess, mpsc::UnboundedReceiver<Cleanup>) {
let (started, observed) = remote_start(write_status, terminate_error, sandbox_type);
let process = UnifiedExecProcess::from_exec_server_started(
started,
OutputDrainPolicy::WaitForOutputClosure,
)
.await
.expect("remote process should start");
(process, observed)
}
#[tokio::test]
async fn dropping_remote_start_during_exit_grace_abandons_it_once() {
let (started, mut observed) = remote_start(
WriteStatus::Accepted,
/*terminate_error*/ None,
/*sandbox_type*/ None,
);
let mut starting = Box::pin(UnifiedExecProcess::from_exec_server_started(
started,
OutputDrainPolicy::WaitForOutputClosure,
));
assert!(futures::poll!(&mut starting).is_pending());
drop(starting);
assert_eq!(observed.recv().await, Some(Cleanup::AbandonStart));
assert_eq!(observed.recv().await, None);
}
#[tokio::test(start_paused = true)]
async fn dropping_explicitly_abandoned_remote_start_does_not_clean_up_twice() {
let (process, mut observed) = remote_process_with_cleanup(
WriteStatus::Accepted,
/*terminate_error*/ None,
/*sandbox_type*/ None,
)
.await;
process.abandon_start();
assert_eq!(observed.try_recv(), Ok(Cleanup::AbandonStart));
drop(process);
assert_eq!(observed.recv().await, None);
}
#[tokio::test]
@@ -202,6 +273,7 @@ async fn remote_lifecycle_updates_preserve_recovered_exit_state(write_status: Wr
}])),
terminate_error: None,
wake_tx,
cleanup: mpsc::unbounded_channel().0,
}),
sandbox_type: Some(codex_sandboxing::SandboxType::None),
},