diff --git a/codex-rs/core/src/unified_exec/oneshot.rs b/codex-rs/core/src/unified_exec/oneshot.rs index 5136c9139e..fb6dfc9f59 100644 --- a/codex-rs/core/src/unified_exec/oneshot.rs +++ b/codex-rs/core/src/unified_exec/oneshot.rs @@ -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>, + process: &'a OnceLock>, +} + +impl Completion<'_> { + pub(super) fn publish_process(&self, process: &Arc) { + 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; diff --git a/codex-rs/core/src/unified_exec/oneshot_tests.rs b/codex-rs/core/src/unified_exec/oneshot_tests.rs new file mode 100644 index 0000000000..fb1bd02dad --- /dev/null +++ b/codex-rs/core/src/unified_exec/oneshot_tests.rs @@ -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); +} diff --git a/codex-rs/core/src/unified_exec/process.rs b/codex-rs/core/src/unified_exec/process.rs index b22188e693..7f7d590602 100644 --- a/codex-rs/core/src/unified_exec/process.rs +++ b/codex-rs/core/src/unified_exec/process.rs @@ -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), } +/// 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, output_tx: broadcast::Sender>, output: OutputHandles, output_drained: Arc, @@ -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(), + } } } diff --git a/codex-rs/core/src/unified_exec/process_manager.rs b/codex-rs/core/src/unified_exec/process_manager.rs index 98bf80cbe9..4d485215c2 100644 --- a/codex-rs/core/src/unified_exec/process_manager.rs +++ b/codex-rs/core/src/unified_exec/process_manager.rs @@ -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( diff --git a/codex-rs/core/src/unified_exec/process_manager_tests.rs b/codex-rs/core/src/unified_exec/process_manager_tests.rs index 3e5c580668..5b71b00afb 100644 --- a/codex-rs/core/src/unified_exec/process_manager_tests.rs +++ b/codex-rs/core/src/unified_exec/process_manager_tests.rs @@ -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::>, + 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; diff --git a/codex-rs/core/src/unified_exec/process_tests.rs b/codex-rs/core/src/unified_exec/process_tests.rs index c1cb66987e..270a5f972b 100644 --- a/codex-rs/core/src/unified_exec/process_tests.rs +++ b/codex-rs/core/src/unified_exec/process_tests.rs @@ -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>, terminate_error: Option, wake_tx: watch::Sender, + cleanup: mpsc::UnboundedSender, } 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) { + let _ = self.cleanup.send(Cleanup::AbandonStart); + } } -pub(super) async fn remote_process( +fn remote_start( write_status: WriteStatus, terminate_error: Option, sandbox_type: impl Into>, -) -> UnifiedExecProcess { +) -> (StartedExecProcess, mpsc::UnboundedReceiver) { 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, + sandbox_type: impl Into>, +) -> 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, + sandbox_type: impl Into>, +) -> (UnifiedExecProcess, mpsc::UnboundedReceiver) { + 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), },