Keep one-shot command timeouts active after approval decisions (#64781)

## Why

Recording a declined command can delay tool-result delivery. When
one-shot commands shared that pause for runtime limits, a sibling
command could keep running past its configured `timeout_ms`.

## What changed

Track command timeouts separately from tool-result delivery. A proposed
command holds result delivery through setup and resolution, while its
approval prompt pauses command timeouts only while a decision is
pending. A running one-shot command can then time out while its result
is still held, with its terminal ID remaining addressable until result
collection finishes.

## Testing

Cover the pause states before, during, and after the approval prompt.
Exercise both a sibling command that times out and one that exits
normally while a decline is being recorded, checking terminal access
and the exit status in the eventual tool result.

GitOrigin-RevId: d359bfc99fb9c23e6c61e94d75040cd6c1b09c49
This commit is contained in:
jif
2026-11-30 18:16:01 +00:00
committed by copyberry
parent 1b06a7002e
commit e3694f5cba
6 changed files with 268 additions and 69 deletions
+43 -17
View File
@@ -3,13 +3,44 @@ use std::sync::Mutex;
use tokio::sync::watch;
/// Coordinates user elicitations that pause tool-result delivery for a session.
///
/// Registrations are counted so concurrent elicitations keep the session paused until all of them
/// finish. Consumers can subscribe to pause timeout progress or wait before returning an already
/// captured result.
/// Most elicitations pause both result delivery and command timeouts. A command
/// proposal holds delivery through setup and resolution. Its prompt pauses
/// one-shot runtime limits while awaiting a decision.
#[derive(Clone)]
pub(crate) struct ElicitationService {
pub(crate) tool_results: Pause,
pub(crate) command_timeouts: Pause,
}
pub(crate) struct ElicitationRegistration {
_command_timeouts: PauseGuard,
_tool_results: PauseGuard,
}
impl ElicitationService {
pub(crate) fn new() -> Self {
Self {
tool_results: Pause::new(),
command_timeouts: Pause::new(),
}
}
pub(crate) fn register(&self) -> ElicitationRegistration {
ElicitationRegistration {
_tool_results: self.tool_results.register(),
_command_timeouts: self.command_timeouts.register(),
}
}
pub(crate) async fn wait_until_clear(&self) {
let mut paused = self.tool_results.subscribe();
let _ = paused.wait_for(|paused| !*paused).await;
}
}
/// Notifies subscribers only when the first registration arrives or the last one drops.
#[derive(Clone)]
pub(crate) struct Pause {
inner: Arc<Inner>,
}
@@ -23,12 +54,12 @@ struct State {
outstanding: i64,
}
pub(crate) struct ElicitationRegistration {
service: ElicitationService,
pub(crate) struct PauseGuard {
service: Pause,
}
impl ElicitationService {
pub(crate) fn new() -> Self {
impl Pause {
fn new() -> Self {
let (paused, _paused_rx) = watch::channel(false);
Self {
inner: Arc::new(Inner {
@@ -38,9 +69,9 @@ impl ElicitationService {
}
}
pub(crate) fn register(&self) -> ElicitationRegistration {
pub(crate) fn register(&self) -> PauseGuard {
self.increment();
ElicitationRegistration {
PauseGuard {
service: self.clone(),
}
}
@@ -67,11 +98,6 @@ impl ElicitationService {
self.inner.paused.subscribe()
}
pub(crate) async fn wait_until_clear(&self) {
let mut paused = self.subscribe();
let _ = paused.wait_for(|paused| !*paused).await;
}
fn decrement(&self) {
let mut state = self
.inner
@@ -89,7 +115,7 @@ impl ElicitationService {
}
}
impl Drop for ElicitationRegistration {
impl Drop for PauseGuard {
fn drop(&mut self) {
self.service.decrement();
}
@@ -16,6 +16,7 @@ use codex_protocol::request_permissions::RequestPermissionProfile;
use codex_protocol::request_permissions::RequestPermissionsResponse;
use codex_protocol::request_user_input::RequestUserInputArgs;
use codex_protocol::request_user_input::RequestUserInputResponse;
use futures::FutureExt;
use pretty_assertions::assert_eq;
use tokio::sync::watch;
use tokio_util::sync::CancellationToken;
@@ -78,11 +79,12 @@ async fn command_approval_holds_an_elicitation_until_response(capture: bool, pro
let (session, mut turn_context, events) = make_session_and_context_with_rx().await;
let (timing, timing_start) = start_timing(&mut turn_context, capture);
*session.active_turn.lock().await = Some(ActiveTurn::default());
let mut pause_state = session.subscribe_elicitation_pause_state();
let pause_state = session.subscribe_elicitation_pause_state();
let timeout_pause = session.services.elicitations.command_timeouts.subscribe();
#[allow(deprecated)]
let cwd = turn_context.cwd.clone();
let request = tokio::spawn({
let mut request = Box::pin({
let prompt_id = prompt_id.to_owned();
let session = session.clone();
let turn_context = turn_context.clone();
@@ -113,11 +115,20 @@ async fn command_approval_holds_an_elicitation_until_response(capture: bool, pro
}
});
{
// Stop setup before it can register a prompt.
let _turn = session.active_turn.lock().await;
assert!(request.as_mut().now_or_never().is_none());
assert!(*pause_state.borrow());
assert!(!*timeout_pause.borrow());
}
let request = tokio::spawn(request);
let start = events.recv().await.expect("command start");
assert!(matches!(start.msg, EventMsg::ItemStarted(_)));
let event = events.recv().await.expect("approval event");
assert!(matches!(event.msg, EventMsg::ExecApprovalRequest(_)));
wait_until_held(&mut pause_state).await;
assert!(*pause_state.borrow());
assert!(*timeout_pause.borrow());
session
.notify_approval(prompt_id, ReviewDecision::Approved)
.await;
@@ -125,7 +136,8 @@ async fn command_approval_holds_an_elicitation_until_response(capture: bool, pro
request.await.expect("approval task"),
ReviewDecision::Approved
);
wait_until_released(&mut pause_state).await;
assert!(!*pause_state.borrow());
assert!(!*timeout_pause.borrow());
assert_user_wait(&timing, timing_start, capture);
let EventMsg::ItemCompleted(event) = events.recv().await.expect("command completion").msg
+11 -3
View File
@@ -1667,7 +1667,7 @@ impl Session {
}
pub(crate) fn subscribe_elicitation_pause_state(&self) -> watch::Receiver<bool> {
self.services.elicitations.subscribe()
self.services.elicitations.tool_results.subscribe()
}
pub(crate) fn mark_interrupted(&self) {
@@ -3470,7 +3470,13 @@ impl Session {
) -> ReviewDecision {
let (network_approval_context, turn_binding) = network_approval.unzip();
let user_wait_owner = self.user_wait_timing_owner(turn_context, timing_call_id);
let _elicitation = self.services.elicitations.register();
let elicitations = &self.services.elicitations;
let _delivery = elicitations.tool_results.register();
let pause_timeouts = || elicitations.command_timeouts.register();
// An approval for a running process (e.g. network access) can block it
// throughout the request. A proposed command only needs the prompt's pause.
let proposing_command = command_approval.is_some();
let _execution_pause = (!proposing_command).then(pause_timeouts);
// command-level approvals use `call_id`.
// `approval_id` identifies subcommand callbacks and stdin writes.
let effective_approval_id = approval_id.clone().unwrap_or_else(|| call_id.clone());
@@ -3536,7 +3542,7 @@ impl Session {
.as_deref_mut()
.map(std::mem::take)
.unwrap_or_default();
let serving_turn = if command_approval.is_some() && request.starts_command() {
let serving_turn = if proposing_command && request.starts_command() {
let Some(state) = self
.active_turn
.lock()
@@ -3589,6 +3595,7 @@ impl Session {
turn_id: turn_context.sub_id.clone(),
command,
},
proposing_command.then(pause_timeouts),
);
let prompt = ts.track_prompt(
request
@@ -3651,6 +3658,7 @@ impl Session {
turn_id: turn_context.sub_id.clone(),
command: Default::default(),
},
/*timeout_pause*/ None,
)
}
None => None,
+20 -6
View File
@@ -21,6 +21,7 @@ use tokio::sync::oneshot;
use super::TurnTokenUsage;
use crate::agent::types::AgentExecutionGuard;
use crate::elicitation::PauseGuard;
use crate::session::PendingUserInput;
use crate::session::SamplingInterrupt;
use crate::session::TurnInputQueue;
@@ -159,7 +160,12 @@ pub(crate) struct PendingRequestPermissions {
pub(crate) turn_context: Arc<TurnContext>,
}
type PendingApprovals = SyncMutex<HashMap<String, PendingApproval>>;
struct RegisteredApproval {
approval: PendingApproval,
_timeout_pause: Option<PauseGuard>,
}
type PendingApprovals = SyncMutex<HashMap<String, RegisteredApproval>>;
/// Remove the pending approval from its original registry if the caller goes away.
pub(crate) struct ApprovalPrompt<'a> {
@@ -178,7 +184,7 @@ impl Drop for ApprovalPrompt<'_> {
// A retry can already have a live waiter under the same command ID.
if approvals
.get(self.approval_id)
.is_some_and(|pending| pending.sender.is_closed())
.is_some_and(|entry| entry.approval.sender.is_closed())
{
approvals.remove(self.approval_id);
}
@@ -216,12 +222,20 @@ impl TurnState {
pub(crate) fn insert_pending_approval(
&mut self,
key: String,
pending: PendingApproval,
approval: PendingApproval,
timeout_pause: Option<PauseGuard>,
) -> Option<PendingApproval> {
self.pending_approvals
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(key, pending)
.insert(
key,
RegisteredApproval {
approval,
_timeout_pause: timeout_pause,
},
)
.map(|entry| entry.approval)
}
pub(crate) fn remove_pending_approval(
@@ -234,11 +248,11 @@ impl TurnState {
.lock()
.unwrap_or_else(PoisonError::into_inner);
if let Some(expected) = expected_turn_id
&& approvals.get(key)?.turn_id != expected
&& approvals.get(key)?.approval.turn_id != expected
{
return None;
}
approvals.remove(key)
approvals.remove(key).map(|entry| entry.approval)
}
pub(crate) fn clear_pending_waiters(&mut self) {
@@ -701,21 +701,36 @@ impl UnifiedExecProcessManager {
let deadline = start
.checked_add(wait)
.ok_or_else(|| UnifiedExecError::process_failed("timeout_ms is too large".into()))?;
let collected_output = Self::collect_output_until_deadline(
let elicitations = &context.session.services.elicitations;
let collect = Self::collect_output_until_deadline(
process.output_handles(),
(!attribution_interrupted).then(|| context.session.subscribe_elicitation_pause_state()),
(!attribution_interrupted).then(|| elicitations.tool_results.subscribe()),
deadline,
)
.await;
if let Some(completion) = completion.as_mut()
&& !process.has_exited()
{
completion.timed_out = true;
process.mark_timed_out();
if let Err(err) = process.terminate_confirmed().await {
process.fail_and_terminate(err.to_string());
);
let collected_output = if let Some(completion) = completion.as_mut() {
// Keep the collector and terminal registered while result delivery is
// paused. A live one-shot still has its own execution deadline.
let pause = elicitations.command_timeouts.subscribe();
tokio::pin!(collect);
let output = tokio::select! {
biased;
output = &mut collect => Some(output),
true = Self::running_at_deadline(&process, pause, deadline) => None,
};
if !process.has_exited() {
completion.timed_out = true;
process.mark_timed_out();
if let Err(err) = process.terminate_confirmed().await {
process.fail_and_terminate(err.to_string());
}
}
}
match output {
Some(output) => output,
None => collect.await,
}
} else {
collect.await
};
let wall_time = Instant::now().saturating_duration_since(start);
let original_token_count = usize::try_from(approx_tokens_from_byte_count(
@@ -1638,12 +1653,13 @@ impl UnifiedExecProcessManager {
let mut collected = HeadTailBuffer::default();
let mut post_exit_deadline: Option<Instant> = None;
let stop_reason = loop {
Self::extend_deadlines_while_paused(
&mut pause_state,
&mut deadline,
&mut post_exit_deadline,
)
.await;
if let Some(receiver) = pause_state.as_mut() {
let paused_for = Self::wait_while_paused(receiver).await;
deadline += paused_for;
if let Some(post_exit) = post_exit_deadline.as_mut() {
*post_exit += paused_for;
}
}
// 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();
@@ -1707,30 +1723,31 @@ impl UnifiedExecProcessManager {
collected
}
async fn extend_deadlines_while_paused(
pause_state: &mut Option<watch::Receiver<bool>>,
deadline: &mut Instant,
post_exit_deadline: &mut Option<Instant>,
) {
let Some(receiver) = pause_state.as_mut() else {
return;
};
if !*receiver.borrow() {
return;
}
let paused_at = Instant::now();
while *receiver.borrow() {
if receiver.changed().await.is_err() {
break;
async fn running_at_deadline(
process: &UnifiedExecProcess,
mut pause: watch::Receiver<bool>,
mut deadline: Instant,
) -> bool {
loop {
deadline += Self::wait_while_paused(&mut pause).await;
tokio::select! {
biased;
_ = pause.changed() => {}
_ = tokio::time::sleep_until(deadline) => break,
}
}
// A remote leader can report exit before its output finishes replaying.
// The collector's own deadline bounds that drain.
!process.has_exited() && !process.exit_reported()
}
let paused_for = paused_at.elapsed();
*deadline += paused_for;
if let Some(post_exit_deadline) = post_exit_deadline.as_mut() {
*post_exit_deadline += paused_for;
async fn wait_while_paused(receiver: &mut watch::Receiver<bool>) -> Duration {
if !*receiver.borrow_and_update() {
return Duration::ZERO;
}
let paused_at = Instant::now();
let _ = receiver.wait_for(|paused| !*paused).await;
paused_at.elapsed()
}
async fn wait_for_pause_change(pause_state: Option<&watch::Receiver<bool>>) {
@@ -1,4 +1,4 @@
//! Exercises interruption while a one-shot command's completion is waiting to reach history.
//! Exercises interruption and sibling timeouts while a command completion is waiting to reach history.
use std::sync::Arc;
use std::time::Duration;
@@ -36,8 +36,10 @@ use codex_protocol::user_input::UserInput;
use codex_rollout::RolloutRecorder;
use core_test_support::responses;
use core_test_support::skip_if_no_network;
use core_test_support::test_codex::TestCodexHarness;
use core_test_support::test_codex::test_codex;
use core_test_support::wait_for_event;
use core_test_support::wait_for_event_match;
use pretty_assertions::assert_eq;
use serde_json::json;
use tokio::sync::Notify;
@@ -472,3 +474,123 @@ async fn shutdown_during_launch_failure_preserves_the_failed_command() -> Result
request.single_request();
Ok(())
}
#[test_case::test_case("exec sleep 60", 500, 124; "running shell times out")]
#[test_case::test_case("exit 0", 30_000, 0; "exited shell retains terminal control")]
#[tokio::test]
async fn sibling_finishes_while_a_decline_is_being_recorded(
command: &str,
timeout_ms: u64,
expected_exit: i32,
) -> Result<()> {
skip_if_no_network!(Ok(()));
core_test_support::skip_if_target_windows!(Ok(()), "runs a POSIX sleep command");
let gate = Arc::new(PauseCommandCompletion::default());
let mut extensions = ExtensionRegistryBuilder::<Config>::new();
extensions.turn_lifecycle_contributor(gate.clone());
let builder = test_codex()
.with_extensions(Arc::new(extensions.build()))
.with_cloud_config_bundle(
CloudConfigBundleFixture::loader_with_enterprise_requirement(
r#"
[features]
unified_exec = false
shell_tool = true
[[rules.prefix_rules]]
pattern = [{ token = "echo" }]
decision = "prompt"
"#,
),
)
.with_config(|config| {
config.approvals_reviewer = ApprovalsReviewer::User;
config.permissions.approval_policy = Constrained::allow_any(AskForApproval::OnRequest);
config
.permissions
.set_permission_profile(PermissionProfile::Disabled)
.expect("disable sandboxing");
});
let harness = TestCodexHarness::with_auto_env_builder(builder).await?;
let codex = &harness.test().codex;
let requests = responses::mount_sse_sequence(
harness.server(),
vec![
responses::sse(vec![
responses::ev_exec_command_call_with_args(CALL_ID, &json!({"cmd": "echo pending"})),
responses::ev_exec_command_call_with_args(
"sibling",
&json!({
"cmd": format!("while [ ! -f go ]; do sleep 0.01; done; {command}"),
"timeout_ms": timeout_ms,
"login": false
}),
),
responses::ev_completed("parallel"),
]),
responses::sse(vec![responses::ev_completed("done")]),
],
)
.await;
// Keep the sibling from timing out before the decline reaches the gate.
codex.increment_out_of_band_elicitation_count().await?;
codex
.start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text {
text: "run the commands".into(),
text_elements: Vec::new(),
}]))
.await?;
let decision = wait_for_event_match(codex, |event| match event {
EventMsg::ExecApprovalRequest(prompt) if prompt.call_id == CALL_ID => {
Some(Op::ExecApproval {
id: prompt.effective_approval_id(),
turn_id: Some(prompt.turn_id.clone()),
decision: ReviewDecision::denied("declined"),
})
}
_ => None,
})
.await;
codex.submit(decision).await?;
gate.entered.notified().await;
let wait_for_terminals = async |count| {
timeout(Duration::from_secs(10), async {
loop {
let terminals = codex.list_background_terminals().await;
if terminals.len() == count {
break terminals;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
};
// Let the shell proceed once it has a terminal ID.
let terminal = wait_for_terminals(1)
.await?
.pop()
.context("expected the sibling's terminal")?;
harness.write_file("go", "").await?;
codex.decrement_out_of_band_elicitation_count().await?;
// Keep the ID addressable until the collector delivers its result.
wait_for_terminals(0).await?;
assert!(
codex
.terminate_background_terminal(terminal.process_id.parse()?)
.await
);
gate.release.notify_one();
wait_for_event(codex, |event| matches!(event, EventMsg::TurnComplete(_))).await;
let output = requests.requests()[1]
.function_call_output_text("sibling")
.context("sibling command output")?;
assert!(
output.contains(&format!("Process exited with code {expected_exit}\n")),
"{output}"
);
Ok(())
}