From ebd5c2fddc2ec215c7ab1108564bc209907c7fee Mon Sep 17 00:00:00 2001 From: jif Date: Tue, 24 Nov 2026 15:06:50 +0000 Subject: [PATCH] Make unified exec output closure race-safe (#63664) ## Why The output collector could miss a closure notification while starting its post-exit wait. It could also see an empty buffer just before the producer appended its final chunk and closed the stream. ## What changed Use a dedicated `CancellationToken` to signal when the output producer is done. The collector samples closure before draining the buffer so that closure during the drain wakes it for another pass. The streaming watcher flushes queued chunks when it observes closure, and sandbox denial checks can proceed immediately when output is already closed. ## Testing Update the bounded collection test to verify that closure alone wakes the post-exit collector and that the final bytes survive repeated drains. GitOrigin-RevId: 4b94a018d784664031f326ec360d27fcf166bbda --- .../core/src/unified_exec/async_watcher.rs | 39 ++------- codex-rs/core/src/unified_exec/process.rs | 78 ++++------------- .../core/src/unified_exec/process_manager.rs | 57 ++++--------- .../src/unified_exec/process_manager_tests.rs | 83 ++++++++----------- .../core/src/unified_exec/process_tests.rs | 10 +-- 5 files changed, 73 insertions(+), 194 deletions(-) diff --git a/codex-rs/core/src/unified_exec/async_watcher.rs b/codex-rs/core/src/unified_exec/async_watcher.rs index 49ae8b2cf2..9de79e60ab 100644 --- a/codex-rs/core/src/unified_exec/async_watcher.rs +++ b/codex-rs/core/src/unified_exec/async_watcher.rs @@ -1,7 +1,6 @@ use codex_protocol::openai_models::CatalogModel; use std::pin::Pin; use std::sync::Arc; -use std::sync::atomic::Ordering; use tokio::sync::Mutex; use tokio::time::Duration; @@ -11,7 +10,6 @@ use tokio::time::Sleep; use super::SharedPluginMetricsSidecar; use super::UnifiedExecContext; use super::process::OutputBuffers; -use super::process::OutputHandles; use super::process::UnifiedExecProcess; use super::take_plugin_metrics_sidecar; use crate::exec::MAX_EXEC_OUTPUT_DELTAS_PER_CALL; @@ -58,11 +56,7 @@ pub(crate) fn start_streaming_output(process: &UnifiedExecProcess, context: &Uni let mut receiver = process.output_receiver(); let output_drained = process.output_drained_notify(); let exit_token = process.cancellation_token(); - let OutputHandles { - output_closed, - output_closed_notify, - .. - } = process.output_handles().clone(); + let output_closed = process.output_handles().output_closed.clone(); let emitter = Emitter { remaining_deltas: MAX_EXEC_OUTPUT_DELTAS_PER_CALL, @@ -80,19 +74,8 @@ pub(crate) fn start_streaming_output(process: &UnifiedExecProcess, context: &Uni }; let mut grace_sleep: Option>> = None; - let output_closed_notified = output_closed_notify.notified(); - tokio::pin!(output_closed_notified); - let mut output_complete = false; loop { - // Register before checking the atomic so a close between the check - // and the select cannot miss the notification. - output_closed_notified.as_mut().enable(); - if grace_sleep.is_some() && output_closed.load(Ordering::Acquire) { - output_complete = true; - break; - } - tokio::select! { _ = exit_token.cancelled(), if grace_sleep.is_none() => { let deadline = Instant::now() + TRAILING_OUTPUT_GRACE; @@ -107,20 +90,13 @@ pub(crate) fn start_streaming_output(process: &UnifiedExecProcess, context: &Uni break; } - _ = &mut output_closed_notified, if grace_sleep.is_some() => { - output_closed_notified.set(output_closed_notify.notified()); - } + _ = output_closed.cancelled(), if grace_sleep.is_some() => break, received = receiver.recv() => { let chunk = match received { Ok(chunk) => chunk, - Err(RecvError::Lagged(_)) => { - continue; - }, - Err(RecvError::Closed) => { - output_complete = true; - break; - } + Err(RecvError::Lagged(_)) => continue, + Err(RecvError::Closed) => break, }; output.push(chunk).await; @@ -128,11 +104,8 @@ pub(crate) fn start_streaming_output(process: &UnifiedExecProcess, context: &Uni } } - output_complete |= output_closed.load(Ordering::Acquire); - if output_complete { - // Output producers publish all chunks before setting output_closed - // with Release ordering, so the Acquire above makes this a final - // safe drain. + // Closure can win the select while the receiver still has queued chunks. + if output_closed.is_cancelled() { loop { let chunk = match receiver.try_recv() { Ok(chunk) => chunk, diff --git a/codex-rs/core/src/unified_exec/process.rs b/codex-rs/core/src/unified_exec/process.rs index fb5fceb079..3fdd1c6a2c 100644 --- a/codex-rs/core/src/unified_exec/process.rs +++ b/codex-rs/core/src/unified_exec/process.rs @@ -60,26 +60,14 @@ impl OutputBuffers { pub(crate) struct OutputHandles { pub(crate) output_buffer: Arc>>, pub(crate) output_notify: Arc, - pub(crate) output_closed: Arc, - pub(crate) output_closed_notify: Arc, + /// Cancelled once the producer can no longer append or broadcast output. + pub(crate) output_closed: CancellationToken, pub(crate) cancellation_token: CancellationToken, pub(super) drain_policy: OutputDrainPolicy, /// The initial exec call returned or was cancelled, so background draining may begin. pub(crate) collection_finished: CancellationToken, } -struct OutputTaskGuard { - output_closed: Arc, - output_closed_notify: Arc, -} - -impl Drop for OutputTaskGuard { - fn drop(&mut self) { - self.output_closed.store(true, Ordering::Release); - self.output_closed_notify.notify_waiters(); - } -} - /// Controls whether process exit can start the collectors' bounded output drain. #[derive(Clone, Copy, PartialEq, Eq)] pub(super) enum OutputDrainPolicy { @@ -133,8 +121,7 @@ impl UnifiedExecProcess { let output = OutputHandles { output_buffer: Arc::new(Mutex::new(OutputBuffers::default())), output_notify: Arc::new(Notify::new()), - output_closed: Arc::new(AtomicBool::new(false)), - output_closed_notify: Arc::new(Notify::new()), + output_closed: CancellationToken::new(), cancellation_token: CancellationToken::new(), drain_policy, collection_finished: CancellationToken::new(), @@ -307,21 +294,10 @@ impl UnifiedExecProcess { } pub(super) async fn check_for_sandbox_denial(&self) -> Result<(), UnifiedExecError> { - // A closed output stream cannot provide any more denial context. - if !self.output.output_closed.load(Ordering::Acquire) { - let closed = self.output.output_closed_notify.notified(); - tokio::pin!(closed); - closed.as_mut().enable(); - // Recheck after registering so closure cannot be lost before we wait. - if !self.output.output_closed.load(Ordering::Acquire) { - let _ = tokio::time::timeout(Duration::from_millis(20), async { - tokio::select! { - _ = self.output.output_notify.notified() => {} - _ = &mut closed => {} - } - }) - .await; - } + tokio::select! { + _ = self.output.output_closed.cancelled() => {} + _ = self.output.output_notify.notified() => {} + _ = tokio::time::sleep(Duration::from_millis(20)) => {} } let aggregated = self.snapshot_output().await; @@ -478,7 +454,6 @@ impl UnifiedExecProcess { output_buffer, output_notify, output_closed, - output_closed_notify, cancellation_token, collection_finished, .. @@ -486,11 +461,8 @@ impl UnifiedExecProcess { let process = started.process; let mut events = process.subscribe_events(); let mut state_rx = state_tx.subscribe(); + let close_output = output_closed.drop_guard(); tokio::spawn(async move { - let _output_task_guard = OutputTaskGuard { - output_closed: Arc::clone(&output_closed), - output_closed_notify: Arc::clone(&output_closed_notify), - }; let drain = async { collection_finished.cancelled().await; let _ = state_rx.wait_for(|state| state.has_exited).await; @@ -519,9 +491,6 @@ impl UnifiedExecProcess { state_tx.send_modify(|state| { state.failed("exec-server process event stream closed".to_string()); }); - output_closed.store(true, Ordering::Release); - output_closed_notify.notify_waiters(); - cancellation_token.cancel(); break; } }; @@ -556,9 +525,6 @@ impl UnifiedExecProcess { Ok(response) => response, Err(err) => { state_tx.send_modify(|state| state.failed(err.to_string())); - output_closed.store(true, Ordering::Release); - output_closed_notify.notify_waiters(); - cancellation_token.cancel(); break; } }; @@ -582,9 +548,6 @@ impl UnifiedExecProcess { last_seq = last_seq.max(next_seq.saturating_sub(1)); if let Some(message) = failure { state_tx.send_modify(|state| state.failed(message)); - output_closed.store(true, Ordering::Release); - output_closed_notify.notify_waiters(); - cancellation_token.cancel(); break; } if sandbox_denied || exited { @@ -595,15 +558,12 @@ impl UnifiedExecProcess { } }); } + if closed || final_drain { + break; + } if exited && output_drain_policy == OutputDrainPolicy::BoundedAfterExit { cancellation_token.cancel(); } - if closed || final_drain { - output_closed.store(true, Ordering::Release); - output_closed_notify.notify_waiters(); - cancellation_token.cancel(); - break; - } continue; } @@ -644,26 +604,21 @@ impl UnifiedExecProcess { if seq <= last_seq { continue; } - output_closed.store(true, Ordering::Release); - output_closed_notify.notify_waiters(); - cancellation_token.cancel(); break; } ExecProcessEvent::Failed(message) => { state_tx.send_modify(|state| state.failed(message)); - output_closed.store(true, Ordering::Release); - output_closed_notify.notify_waiters(); - cancellation_token.cancel(); break; } } } + drop(close_output); + cancellation_token.cancel(); if final_drain { tokio::spawn(async move { let _ = process.terminate().await; }); } - cancellation_token.cancel(); }) } @@ -677,14 +632,11 @@ impl UnifiedExecProcess { output_buffer, output_notify, output_closed, - output_closed_notify, .. } = output_handles; + let close_output = output_closed.drop_guard(); tokio::spawn(async move { - let _output_task_guard = OutputTaskGuard { - output_closed: Arc::clone(&output_closed), - output_closed_notify: Arc::clone(&output_closed_notify), - }; + let _close_output = close_output; let mut stdout_open = true; let mut stderr_open = true; while stdout_open || stderr_open { diff --git a/codex-rs/core/src/unified_exec/process_manager.rs b/codex-rs/core/src/unified_exec/process_manager.rs index 94ce167d3f..ff4c6cdf57 100644 --- a/codex-rs/core/src/unified_exec/process_manager.rs +++ b/codex-rs/core/src/unified_exec/process_manager.rs @@ -594,10 +594,7 @@ impl UnifiedExecProcessManager { // Persist live sessions and remote output that remains pollable after an early exit. let process_stored = (!process.has_exited() && process.exit_code().is_none()) || (process.output_handles().drain_policy == OutputDrainPolicy::WaitForOutputClosure - && !process - .output_handles() - .output_closed - .load(Ordering::Acquire)); + && !process.output_handles().output_closed.is_cancelled()); let mut initial_exec_command_guard = InitialExecCommandGuard { active: None, metrics_sidecar, @@ -1139,7 +1136,7 @@ impl UnifiedExecProcessManager { if retention == OutputRetention::UntilCollected && output.drain_policy == OutputDrainPolicy::WaitForOutputClosure && !entry.process.termination_requested.load(Ordering::Acquire) - && (!output.output_closed.load(Ordering::Acquire) + && (!output.output_closed.is_cancelled() || output .output_buffer .try_lock() @@ -1537,12 +1534,10 @@ impl UnifiedExecProcessManager { output_buffer, output_notify, output_closed, - output_closed_notify, cancellation_token, .. } = output; let mut collected = HeadTailBuffer::default(); - let mut exit_signal_received = cancellation_token.is_cancelled(); let mut post_exit_deadline: Option = None; let stop_reason = loop { Self::extend_deadlines_while_paused( @@ -1551,22 +1546,14 @@ impl UnifiedExecProcessManager { &mut post_exit_deadline, ) .await; - let drained_output: HeadTailBuffer; - let has_drained_output: bool; - let mut wait_for_output = None; - { - let mut guard = output_buffer.lock().await; - drained_output = std::mem::take(&mut guard.pending); - has_drained_output = - drained_output.retained_bytes() > 0 || drained_output.omitted_bytes() > 0; - if !has_drained_output { - wait_for_output = Some(output_notify.notified()); - } - } - - if !has_drained_output { - exit_signal_received |= cancellation_token.is_cancelled(); - if exit_signal_received && output_closed.load(Ordering::Acquire) { + // Subscribe before draining. If closure races the drain, wake and + // drain again so the last chunk cannot land between an empty read and exit. + let notified = output_notify.notified(); + let closed = output_closed.is_cancelled(); + let drained_output = std::mem::take(&mut output_buffer.lock().await.pending); + if drained_output.total_bytes() == 0 { + let exit_signal_received = cancellation_token.is_cancelled(); + if exit_signal_received && closed { break StopReason::OutputClosed; } let remaining = deadline.saturating_duration_since(Instant::now()); @@ -1582,26 +1569,18 @@ impl UnifiedExecProcessManager { if close_wait_remaining == Duration::ZERO { break StopReason::PostExitDeadline; } - let notified = wait_for_output.unwrap_or_else(|| output_notify.notified()); - let closed = output_closed_notify.notified(); - tokio::pin!(notified); - tokio::pin!(closed); tokio::select! { - _ = &mut notified => {} - _ = &mut closed => {} + _ = notified => {} + _ = output_closed.cancelled() => {} _ = tokio::time::sleep(close_wait_remaining) => break StopReason::PostExitDeadline, _ = Self::wait_for_pause_change(pause_state.as_ref()) => {} } continue; } - let notified = wait_for_output.unwrap_or_else(|| output_notify.notified()); - tokio::pin!(notified); - let exit_notified = cancellation_token.cancelled(); - tokio::pin!(exit_notified); tokio::select! { - _ = &mut notified => {} - _ = &mut exit_notified => exit_signal_received = true, + _ = notified => {} + _ = cancellation_token.cancelled() => {} _ = tokio::time::sleep(remaining) => break StopReason::Deadline, _ = Self::wait_for_pause_change(pause_state.as_ref()) => {} } @@ -1610,7 +1589,6 @@ impl UnifiedExecProcessManager { collected.push_buffer(drained_output); - exit_signal_received |= cancellation_token.is_cancelled(); if Instant::now() >= deadline { break StopReason::Deadline; } @@ -1625,11 +1603,8 @@ impl UnifiedExecProcessManager { StopReason::PostExitDeadline => "post_exit_deadline", }, ); - span.record( - "exit_signaled", - exit_signal_received || cancellation_token.is_cancelled(), - ); - span.record("output_closed", output_closed.load(Ordering::Acquire)); + span.record("exit_signaled", cancellation_token.is_cancelled()); + span.record("output_closed", output_closed.is_cancelled()); span.record("outcome", "completed"); collected } 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 66363515f8..b467b9ecbf 100644 --- a/codex-rs/core/src/unified_exec/process_manager_tests.rs +++ b/codex-rs/core/src/unified_exec/process_manager_tests.rs @@ -377,61 +377,49 @@ fn initial_exec_yield_time_has_no_platform_floor() { ); } -#[tokio::test] +#[tokio::test(start_paused = true)] async fn output_collection_stays_bounded_across_repeated_drains() { - let chunks: [&[u8]; 4] = [b"01234567", b"89ABCDEF", b"ghijklmnopq", b"rs"]; - let output_buffer = Arc::new(tokio::sync::Mutex::new(OutputBuffers::<10>::default())); - let output_notify = Arc::new(Notify::new()); - let output_closed = Arc::new(AtomicBool::new(false)); - let output_closed_notify = Arc::new(Notify::new()); - let cancellation_token = CancellationToken::new(); let output = OutputHandles { - output_buffer: Arc::clone(&output_buffer), - output_notify: Arc::clone(&output_notify), - output_closed: Arc::clone(&output_closed), - output_closed_notify: Arc::clone(&output_closed_notify), - cancellation_token: cancellation_token.clone(), + output_buffer: Arc::new(tokio::sync::Mutex::new(OutputBuffers::<10>::default())), + output_notify: Arc::new(Notify::new()), + output_closed: CancellationToken::new(), + cancellation_token: CancellationToken::new(), collection_finished: CancellationToken::new(), drain_policy: OutputDrainPolicy::BoundedAfterExit, }; - let collect = UnifiedExecProcessManager::collect_output_until_deadline( &output, /*pause_state*/ None, Instant::now() + Duration::from_secs(5), ); - let produce = async { - for chunk in chunks { - output_buffer - .lock() - .await - .push_chunk(ExecOutputStream::Stdout, chunk); - output_notify.notify_one(); - tokio::time::timeout(Duration::from_secs(1), async { - loop { - if output_buffer.lock().await.pending.retained_bytes() == 0 { - break; - } - tokio::task::yield_now().await; - } - }) - .await - .expect("collector should drain each chunk"); - } + tokio::pin!(collect); - output_closed.store(true, Ordering::Release); - cancellation_token.cancel(); - output_closed_notify.notify_waiters(); - output_notify.notify_waiters(); - }; - - let (collected, ()) = tokio::join!(collect, produce); - let mut expected = HeadTailBuffer::<10>::default(); + let chunks: [&[u8]; 3] = [b"01234567", b"89ABCDEF", b"ghijklmnopq"]; for chunk in chunks { - expected.push_chunk(chunk); + output + .output_buffer + .lock() + .await + .push_chunk(ExecOutputStream::Stdout, chunk); + output.output_notify.notify_waiters(); + assert!(futures::poll!(collect.as_mut()).is_pending()); + assert_eq!(output.output_buffer.lock().await.pending.total_bytes(), 0); } - assert_eq!(collected, expected); - assert_eq!(output_buffer.lock().await.transcript, expected); + + // Closure alone must wake the post-exit wait and drain the last bytes. + output.cancellation_token.cancel(); + assert!(futures::poll!(collect.as_mut()).is_pending()); + output + .output_buffer + .lock() + .await + .push_chunk(ExecOutputStream::Stdout, b"rs"); + output.output_closed.cancel(); + + let mut expected = HeadTailBuffer::<10>::default(); + expected.push_chunk(b"0123456789ABCDEFghijklmnopqrs"); + assert_eq!(collect.await, expected); + assert_eq!(output.output_buffer.lock().await.transcript, expected); } #[tokio::test] @@ -444,20 +432,17 @@ async fn output_collection_preserves_omissions_from_drained_buffer() { expected.push_chunk(b"overflow"); let output_buffer = Arc::new(tokio::sync::Mutex::new(buffered_output)); let output_notify = Arc::new(Notify::new()); - let output_closed = Arc::new(AtomicBool::new(true)); - let output_closed_notify = Arc::new(Notify::new()); - let cancellation_token = CancellationToken::new(); - cancellation_token.cancel(); let output = OutputHandles { output_buffer, output_notify, - output_closed, - output_closed_notify, - cancellation_token, + output_closed: CancellationToken::new(), + cancellation_token: CancellationToken::new(), collection_finished: CancellationToken::new(), drain_policy: OutputDrainPolicy::BoundedAfterExit, }; + output.output_closed.cancel(); + output.cancellation_token.cancel(); let collected = UnifiedExecProcessManager::collect_output_until_deadline( &output, /*pause_state*/ None, diff --git a/codex-rs/core/src/unified_exec/process_tests.rs b/codex-rs/core/src/unified_exec/process_tests.rs index 4145d50589..c1cb66987e 100644 --- a/codex-rs/core/src/unified_exec/process_tests.rs +++ b/codex-rs/core/src/unified_exec/process_tests.rs @@ -212,15 +212,12 @@ async fn remote_lifecycle_updates_preserve_recovered_exit_state(write_status: Wr // A rejected write first reports exit without a status. The final read then // recovers the executor's actual exit code and sandbox-denial classification. - let closed = process.output_handles().output_closed_notify.notified(); - tokio::pin!(closed); - closed.as_mut().enable(); process.output_handles().collection_finished.cancel(); assert!(matches!( process.write(b"hello").await, Err(UnifiedExecError::WriteToStdin) )); - closed.await; + process.output_handles().output_closed.cancelled().await; assert!(matches!( process.write(b"hello").await, @@ -314,11 +311,8 @@ async fn closed_output_is_classified_without_waiting_for_more_output() { .lock() .await .push_chunk(ExecOutputStream::Stderr, b"permission denied"); - let closed = output.output_closed_notify.notified(); - tokio::pin!(closed); - closed.as_mut().enable(); process.terminate_confirmed().await.expect("terminate"); - closed.await; + output.output_closed.cancelled().await; let start = tokio::time::Instant::now(); let result = process.check_for_sandbox_denial().await;