Interrupt running commands promptly when approval is canceled (#64368)

## Why

Recording a declined command can block on history writes. If turn
cancellation waits for that write, sibling commands can keep running.
The same write can also delay recording results from commands that
already finished.

## What changed

Signal cancellation before recording the declined command and publish
the decline before `TurnAborted`. Start the task's shutdown grace period
after publication so it has time to record completed tool results.

## Testing

Add a regression test that blocks publication of the decline, verifies
that a running sibling stops while publication is blocked, and checks
that another sibling's completed output reaches the next model request.

GitOrigin-RevId: c0b2e40e711ffe5ee46b76b110410518d2191041
This commit is contained in:
jif
2026-11-27 19:08:45 +00:00
committed by copyberry
parent 187f00e805
commit 005a57e890
4 changed files with 218 additions and 28 deletions
@@ -91,6 +91,7 @@ impl Session {
active_turn,
TurnAbortReason::Interrupted,
/*error*/ None,
std::future::ready(()),
)
.await;
}
+10 -6
View File
@@ -195,22 +195,26 @@ impl Session {
return;
};
let decision = pending.validate(decision);
pending.resolve_command(&decision).await;
if decision == ReviewDecision::Abort {
let turn_id = if pending.kind == ExecApprovalKind::HumanCommand {
Some(&pending.turn_id)
Some(pending.turn_id.clone())
} else {
active_turn_id.as_ref()
active_turn_id
};
if let Some(turn_id) = turn_id {
self.abort_turn_if_active(
turn_id,
self.abort_turn_if_active_with_publication(
&turn_id,
TurnAbortReason::Interrupted,
/*error*/ None,
pending.resolve_command(&decision),
)
.await;
pending.reply(decision);
return;
}
} else if let ReviewDecision::ApprovedExecpolicyAmendment {
}
pending.resolve_command(&decision).await;
if let ReviewDecision::ApprovedExecpolicyAmendment {
proposed_execpolicy_amendment,
} = &decision
&& let Err(err) = self
+51 -20
View File
@@ -699,6 +699,7 @@ impl Session {
reason.clone(),
&active_turn.turn_state,
/*error*/ None,
std::future::ready(()),
)
.await;
}
@@ -722,13 +723,28 @@ impl Session {
turn_id: &str,
reason: TurnAbortReason,
error: Option<ErrorEvent>,
) -> bool {
self.abort_turn_if_active_with_publication(turn_id, reason, error, std::future::ready(()))
.await
}
/// Signal the matching task before waiting for an item that must precede TurnAborted.
/// Publish the item even if its turn has already finished.
pub(crate) async fn abort_turn_if_active_with_publication(
self: &Arc<Self>,
turn_id: &str,
reason: TurnAbortReason,
error: Option<ErrorEvent>,
publication: impl Future<Output = ()>,
) -> bool {
let active_turn = self.take_named_active_turn(turn_id, &reason).await;
let Some(active_turn) = active_turn else {
publication.await;
return false;
};
self.finish_turn_abort(active_turn, reason, error).await;
self.finish_turn_abort(active_turn, reason, error, publication)
.await;
true
}
@@ -756,11 +772,20 @@ impl Session {
mut active_turn: ActiveTurn,
reason: TurnAbortReason,
error: Option<ErrorEvent>,
publication: impl Future<Output = ()>,
) {
let task = active_turn.task.take();
if let Some(task) = task {
self.handle_task_abort(task, reason.clone(), &active_turn.turn_state, error)
.await;
self.handle_task_abort(
task,
reason.clone(),
&active_turn.turn_state,
error,
publication,
)
.await;
} else {
publication.await;
}
// Let interrupted tasks observe cancellation before dropping pending approvals, or an
// in-flight approval wait can surface as a model-visible rejection before TurnAborted.
@@ -1193,9 +1218,11 @@ impl Session {
reason: TurnAbortReason,
turn_state: &Mutex<TurnState>,
error: Option<ErrorEvent>,
publication: impl Future<Output = ()>,
) {
let sub_id = task.turn_context.sub_id.clone();
if task.cancellation_token.is_cancelled() {
publication.await;
self.emit_turn_abort_lifecycle(reason, task.turn_context.extension_data.as_ref())
.await;
return;
@@ -1203,23 +1230,26 @@ impl Session {
trace!(task_kind = ?task.kind, sub_id, "aborting running task");
task.cancellation_token.cancel();
if reason == TurnAbortReason::Interrupted
&& task
.turn_context
.config
.features
.enabled(Feature::CodeModeInterrupt)
{
self.services
.code_mode_service
.interrupt_active_cells()
.await;
}
task.turn_context
.turn_metadata_state
.cancel_git_enrichment_task();
let session_task = task.task;
let interrupt = async {
if reason == TurnAbortReason::Interrupted
&& task
.turn_context
.config
.features
.enabled(Feature::CodeModeInterrupt)
{
self.services
.code_mode_service
.interrupt_active_cells()
.await;
}
task.turn_context
.turn_metadata_state
.cancel_git_enrichment_task();
};
// Publication can hold the writer the task needs to drain completed tool results.
// Give the task its full grace period once that writer is available.
tokio::join!(interrupt, publication);
let mut handle = task.handle;
let grace = Duration::from_millis(GRACEFULL_INTERRUPTION_TIMEOUT_MS);
let joined = match tokio::time::timeout(grace, &mut handle).await {
@@ -1229,6 +1259,7 @@ impl Session {
handle.await
}
};
let session_task = task.task;
// A task may finish normally between the deadline and the abort.
if let Err(error) = joined {
warn!(%error, "task {sub_id} did not finish gracefully");
@@ -1,4 +1,4 @@
//! Failed one-shot launches must finish publishing their lifecycle after interruption.
//! Exercises interruption while a one-shot command's completion is waiting to reach history.
use std::sync::Arc;
use std::time::Duration;
@@ -12,18 +12,25 @@ use codex_config::Constrained;
use codex_config::test_support::CloudConfigBundleFixture;
use codex_core::TurnInputRequest;
use codex_core::config::Config;
use codex_extension_api::CommandStartInput;
use codex_extension_api::ExtensionData;
use codex_extension_api::ExtensionFuture;
use codex_extension_api::ExtensionRegistryBuilder;
use codex_extension_api::ToolCallOutcome;
use codex_extension_api::ToolFinishInput;
use codex_extension_api::ToolLifecycleContributor;
use codex_extension_api::ToolLifecycleFuture;
use codex_extension_api::TurnLifecycleContributor;
use codex_features::Feature;
use codex_history::RolloutItem;
use codex_protocol::config_types::ApprovalsReviewer;
use codex_protocol::items::CommandExecutionStatus;
use codex_protocol::items::TurnItem;
use codex_protocol::models::PermissionProfile;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::Op;
use codex_protocol::protocol::ReviewDecision;
use codex_protocol::protocol::ThreadHistoryMode;
use codex_protocol::user_input::UserInput;
use codex_rollout::RolloutRecorder;
@@ -36,7 +43,7 @@ use serde_json::json;
use tokio::sync::Notify;
use tokio::time::timeout;
const CALL_ID: &str = "interrupted-launch-failure";
const CALL_ID: &str = "gated-command";
#[derive(Default)]
struct PauseCommandCompletion {
@@ -63,6 +70,153 @@ impl TurnLifecycleContributor for PauseCommandCompletion {
}
}
#[tokio::test]
async fn cancelling_approval_stops_running_sibling_and_preserves_completed_output() -> Result<()> {
skip_if_no_network!(Ok(()));
core_test_support::skip_if_target_windows!(Ok(()), "runs a POSIX sleep command");
#[derive(Default)]
struct SiblingResults {
completed: Notify,
release_first: Notify,
}
impl ToolLifecycleContributor for SiblingResults {
fn on_command_start<'a>(&'a self, input: CommandStartInput<'a>) -> ToolLifecycleFuture<'a> {
Box::pin(async move {
if input.call_id == CALL_ID {
self.completed.notified().await;
}
})
}
fn on_tool_finish<'a>(&'a self, input: ToolFinishInput<'a>) -> ToolLifecycleFuture<'a> {
Box::pin(async move {
match input.call_id {
"sibling" => self.release_first.notified().await,
"finished" => {
assert_eq!(input.outcome, ToolCallOutcome::Completed { success: true });
self.completed.notify_one();
}
_ => {}
}
})
}
}
let server = responses::start_mock_server().await;
let gate = Arc::new(PauseCommandCompletion::default());
let results = Arc::new(SiblingResults::default());
let mut extensions = ExtensionRegistryBuilder::<Config>::new();
extensions.turn_lifecycle_contributor(gate.clone());
extensions.tool_lifecycle_contributor(results.clone());
let test = test_codex()
.with_extensions(Arc::new(extensions.build()))
.with_cloud_config_bundle(
CloudConfigBundleFixture::loader_with_enterprise_requirement(
"[features]\nunified_exec = false\nshell_tool = true\n",
),
)
.with_config(|config| config.approvals_reviewer = ApprovalsReviewer::User)
.build_with_auto_env(&server)
.await?;
let requests = responses::mount_sse_sequence(
&server,
vec![
responses::sse(vec![
responses::ev_response_created("parallel"),
responses::ev_exec_command_call_with_args(
"sibling",
&json!({"cmd": "sleep 120", "timeout_ms": 120_000}),
),
responses::ev_exec_command_call_with_args(
"finished",
&json!({"cmd": "echo sibling-output", "login": false}),
),
responses::ev_exec_command_call_with_args(
CALL_ID,
&json!({"cmd": "echo pending", "sandbox_permissions": "require_escalated",
"justification": "Run outside the sandbox?"}),
),
responses::ev_completed("parallel"),
]),
responses::sse(vec![responses::ev_completed("follow-up")]),
],
)
.await;
test.codex
.start_or_steer_turn(
TurnInputRequest::user_input(vec![UserInput::Text {
text: "run the commands".to_string(),
text_elements: Vec::new(),
}])
.with_thread_settings(
codex_protocol::protocol::ThreadSettingsOverrides {
approval_policy: Some(AskForApproval::OnRequest),
permission_profile: Some(PermissionProfile::workspace_write()),
..Default::default()
},
),
)
.await?;
let mut started = false;
let mut prompt = None;
while !started || prompt.is_none() {
match test.codex.next_event().await?.msg {
EventMsg::ExecCommandBegin(event) if event.call_id == "sibling" => {
assert!(event.process_id.is_some());
started = true;
}
EventMsg::ExecApprovalRequest(event) if event.call_id == CALL_ID => {
prompt = Some(event)
}
_ => {}
}
}
let prompt = prompt.unwrap();
test.codex
.submit(Op::ExecApproval {
id: prompt.effective_approval_id(),
turn_id: Some(prompt.turn_id),
decision: ReviewDecision::Abort,
})
.await?;
gate.entered.notified().await;
// The sibling should stop even while history is waiting to record the decline.
wait_for_event(
&test.codex,
|event| matches!(event, EventMsg::ExecCommandEnd(end) if end.call_id == "sibling"),
)
.await;
// Results drain in call order. Hold the first result and the decline beyond
// the abort grace period, with the successful second result queued behind it.
tokio::time::pause();
tokio::time::sleep(Duration::from_secs(1)).await;
tokio::time::resume();
results.release_first.notify_one();
gate.release.notify_one();
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::ItemCompleted(completed)
if matches!(&completed.item, TurnItem::CommandExecution(command)
if command.id == CALL_ID && command.status == CommandExecutionStatus::Declined))
})
.await;
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::TurnAborted(_))
})
.await;
test.submit_text_turn("What did the finished command print?")
.await?;
let requests = requests.requests();
assert_eq!(requests.len(), 2);
let output = requests[1]
.function_call_output_text("finished")
.context("finished command output")?;
assert!(output.contains("sibling-output"), "{output}");
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn interrupted_one_shot_launch_failure_completes_and_persists() -> Result<()> {
skip_if_no_network!(Ok(()));