Finish approved remote one-shot commands after startup interruption (#64367)

## Why

Interrupting an approved one-shot command while remote plugin attribution
is pending can stall session shutdown and leave the command without a
terminal record. An open elicitation can also delay output collection.

## What changed

On interruption, skip the pending remote attribution lookup and optional
plugin metrics read, and bypass the elicitation pause during output
collection. Keep session history open until the command's terminal event
is published, including when the exit watcher publishes it.

## Testing

Extend the remote startup interruption test to cover resumable commands
and approved one-shots. Verify process termination and session shutdown
with the attribution request still pending, and check that the approved
one-shot records exactly one failed completion with an unrelated
elicitation still open.

GitOrigin-RevId: e9b78290544d634797876119006540150a7672b1
This commit is contained in:
jif
2026-11-27 18:55:47 +00:00
committed by copyberry
parent 18c09f20ce
commit 187f00e805
6 changed files with 115 additions and 28 deletions
@@ -95,10 +95,11 @@ impl CommandApproval {
Ok(())
}
/// Release the proposal when execution takes over completion.
/// Its original start time is used for the legacy begin event.
pub(crate) fn handoff(&mut self) -> Option<i64> {
self.0.take().map(|command| command.started_at_ms)
/// Transfer the legacy begin timestamp and shutdown token to execution.
pub(crate) fn handoff(&mut self) -> Option<(i64, TaskTrackerToken)> {
self.0
.take()
.map(|command| (command.started_at_ms, command.publication))
}
pub(crate) async fn fail(&mut self) {
@@ -66,7 +66,7 @@ pub(super) async fn with_launch_failure_events(
let call_id = ctx.call_id.clone();
let message = message.clone();
// The failure write is registered, so the proposal can release its shutdown token.
let proposal_started_at_ms = command_approval.handoff();
let (proposal_started_at_ms, _) = command_approval.handoff().unzip();
// Dropping the join handle on cancellation leaves both lifecycle events running.
let publish = async move {
let model_context = step_context.model_context();
@@ -6,6 +6,7 @@ use tokio::sync::Mutex;
use tokio::time::Duration;
use tokio::time::Instant;
use tokio::time::Sleep;
use tokio_util::task::task_tracker::TaskTrackerToken;
use super::SharedPluginMetricsSidecar;
use super::UnifiedExecContext;
@@ -138,6 +139,7 @@ pub(crate) fn spawn_exit_watcher(
output_buffer: Arc<Mutex<OutputBuffers>>,
started_at: Instant,
network_denial_monitor: Option<tokio::task::JoinHandle<()>>,
publication: Option<TaskTrackerToken>,
plugin_metrics_sidecar: Option<SharedPluginMetricsSidecar>,
) {
let session_ref = Arc::clone(&context.session);
@@ -150,6 +152,7 @@ pub(crate) fn spawn_exit_watcher(
let interaction_lock = process.interaction_lock();
tokio::spawn(async move {
let _publication = publication;
exit_token.cancelled().await;
output_drained.notified().await;
// Deferred network denial deliberately remains observable for a short
@@ -109,6 +109,7 @@ async fn completed_output_preserves_bytes_before_subscription(
output_buffer,
Instant::now(),
/*network_denial_monitor*/ None,
/*publication*/ None,
/*plugin_metrics_sidecar*/ None,
);
stdout_tx.send(late_output.to_vec())?;
@@ -325,6 +326,7 @@ async fn exit_watcher_waits_for_late_network_denial_before_classifying_end() ->
output_buffer,
Instant::now(),
Some(network_denial_monitor),
/*publication*/ None,
/*plugin_metrics_sidecar*/ None,
);
@@ -11,6 +11,7 @@ use tokio::sync::watch;
use tokio::time::Duration;
use tokio::time::Instant;
use tokio_util::sync::CancellationToken;
use tokio_util::task::task_tracker::TaskTrackerToken;
use uuid::Uuid;
use super::oneshot::Completion;
@@ -538,7 +539,7 @@ impl UnifiedExecProcessManager {
let UnifiedExecAttempt {
mut command_approval,
process,
metrics_sidecar,
mut metrics_sidecar,
permissions,
} = attempt;
let process = Arc::new(process);
@@ -559,13 +560,24 @@ impl UnifiedExecProcessManager {
/*turn_diff_tracker*/ None,
);
event_ctx.model_context = Some(&model_context);
let mut attribution_interrupted = false;
let plugin_attribution = if prepared.turn_environment.environment().is_remote() {
let file_system = prepared.turn_environment.environment().get_filesystem();
context
let lookup = context
.step_context
.turn
.plugin_attribution_for_executor_command(command, &cwd, file_system.as_ref())
.await
.plugin_attribution_for_executor_command(command, &cwd, file_system.as_ref());
// A canceled one-shot still drives execution to its terminal event.
tokio::select! {
biased;
_ = context.cancellation_token.cancelled(), if completion.is_some() => {
attribution_interrupted = true;
// Reading the optional metrics file would wait on the same filesystem.
metrics_sidecar = None;
None
}
attribution = lookup => attribution,
}
} else {
cwd.to_abs_path().ok().and_then(|cwd| {
context
@@ -581,7 +593,11 @@ impl UnifiedExecProcessManager {
Some(request.process_id.to_string()),
plugin_attribution.clone(),
);
event_ctx.proposal_started_at_ms = command_approval.handoff();
let (started_at_ms, publication) = command_approval.handoff().unzip();
event_ctx.proposal_started_at_ms = started_at_ms;
// If interrupted during startup, keep history open until this task or
// the exit watcher publishes the approved one-shot's terminal item.
let mut publication = publication.filter(|_| attribution_interrupted);
emitter.emit(event_ctx, ToolEventStage::Begin).await;
// Serialize remote collection with later polls and final transcript publication.
@@ -619,6 +635,7 @@ impl UnifiedExecProcessManager {
prepared.tty,
deferred_network_approval.clone(),
network_denial_monitor,
publication.take(),
initial_exec_command_guard.metrics_sidecar.take(),
Arc::clone(&output_buffer),
Arc::clone(&initial_exec_command_active),
@@ -639,7 +656,7 @@ impl UnifiedExecProcessManager {
.ok_or_else(|| UnifiedExecError::process_failed("timeout_ms is too large".into()))?;
let collected_output = Self::collect_output_until_deadline(
process.output_handles(),
Some(context.session.subscribe_elicitation_pause_state()),
(!attribution_interrupted).then(|| context.session.subscribe_elicitation_pause_state()),
deadline,
)
.await;
@@ -1209,6 +1226,7 @@ impl UnifiedExecProcessManager {
tty: bool,
network_approval: Option<DeferredNetworkApproval>,
network_denial_monitor: Option<tokio::task::JoinHandle<()>>,
publication: Option<TaskTrackerToken>,
metrics_sidecar: Option<PluginMetricsSidecar>,
output_buffer: Arc<tokio::sync::Mutex<OutputBuffers>>,
initial_exec_command_active: Arc<AtomicBool>,
@@ -1246,6 +1264,7 @@ impl UnifiedExecProcessManager {
output_buffer,
started_at,
network_denial_monitor,
publication,
plugin_metrics_sidecar,
);
// Install the watcher before cancellable cleanup, and outside the process-store lock.
@@ -10,6 +10,7 @@ use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use codex_config::test_support::CloudConfigBundleFixture;
use codex_core::TurnInputRequest;
use codex_exec_server::ExecParams;
use codex_history::RolloutItem;
use codex_network_proxy::NetworkProxyConfig;
use codex_network_proxy::environment_policy_from_config;
use codex_protocol::config_types::ApprovalsReviewer;
@@ -20,9 +21,11 @@ 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::protocol::ThreadSettingsOverrides;
use codex_protocol::sandbox::SandboxType;
use codex_protocol::user_input::UserInput;
use codex_rollout::RolloutRecorder;
use core_test_support::responses::ev_assistant_message;
use core_test_support::responses::ev_completed;
use core_test_support::responses::ev_function_call;
@@ -37,6 +40,7 @@ use core_test_support::test_codex::environment_config_for_selection;
use core_test_support::test_codex::test_codex;
use core_test_support::test_codex::turn_permission_fields;
use core_test_support::wait_for_event;
use core_test_support::wait_for_event_match;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
@@ -443,18 +447,24 @@ async fn respond_to_setup_or_hook_request(
send_exec_server_json(websocket, json!({"id": request["id"], "result": result})).await;
}
#[test_case(AskForApproval::Never, ""; "resumable")]
#[test_case(AskForApproval::UnlessTrusted, "[features]\nunified_exec = false\nshell_tool = true\n"; "approved_one_shot")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn interrupt_during_exec_startup_terminates_unregistered_process() -> Result<()> {
async fn interrupt_during_exec_startup_terminates_unregistered_process(
approval_policy: AskForApproval,
requirements: &str,
) -> Result<()> {
let server = start_mock_server().await;
let listener = TcpListener::bind("127.0.0.1:0").await?;
let exec_server_url = format!("ws://{}", listener.local_addr()?);
let home = Arc::new(tempfile::TempDir::new()?);
super::super::plugins::write_remote_plugin_script_and_config(home.as_ref());
let call_id = "interrupted-startup";
let _response = core_test_support::responses::mount_sse_once(
&server,
sse(vec![
ev_function_call(
"interrupted-startup",
call_id,
"exec_command",
&json!({
"cmd": "/bin/sh /opt/plugins/cache/openai-curated-remote/sample/1.2.3/scripts/run.sh",
@@ -465,7 +475,6 @@ async fn interrupt_during_exec_startup_terminates_unregistered_process() -> Resu
]),
).await;
let (startup_blocked, blocked) = tokio::sync::oneshot::channel();
let (terminated, termination) = tokio::sync::oneshot::channel();
let exec_server =
tokio::spawn(async move {
let mut websocket = accept_initialized_exec_server(listener).await;
@@ -483,8 +492,8 @@ async fn interrupt_during_exec_startup_terminates_unregistered_process() -> Resu
})).await;
}
Some("process/start") => {
let params: ExecParams =
serde_json::from_value(request["params"].clone()).unwrap();
let params: ExecParams = serde_json::from_value(request["params"].clone())
.expect("process start");
assert!(
params.network_proxy.is_some(),
"the command needs a network observer"
@@ -505,8 +514,8 @@ async fn interrupt_during_exec_startup_terminates_unregistered_process() -> Resu
.take()
.expect("one blocked lookup")
.send(())
.unwrap();
// Leave this RPC pending until the tool call is interrupted.
.expect("notify test of blocked lookup");
// Leave this RPC pending through session shutdown.
}
Some("process/read") => {
send_exec_server_json(
@@ -522,7 +531,7 @@ async fn interrupt_during_exec_startup_terminates_unregistered_process() -> Resu
Some("process/terminate") => {
assert_eq!(
request["params"]["processId"],
json!(started_process.unwrap())
json!(started_process.expect("process started before termination"))
);
send_exec_server_json(
&mut websocket,
@@ -531,8 +540,7 @@ async fn interrupt_during_exec_startup_terminates_unregistered_process() -> Resu
}),
)
.await;
terminated.send(()).unwrap();
return;
return websocket;
}
_ => respond_to_setup_or_hook_request(&mut websocket, &request).await,
}
@@ -540,6 +548,10 @@ async fn interrupt_during_exec_startup_terminates_unregistered_process() -> Resu
});
let test = test_codex()
.with_home(home)
.with_history_mode(ThreadHistoryMode::Paginated)
.with_cloud_config_bundle(
CloudConfigBundleFixture::loader_with_enterprise_requirement(requirements),
)
.with_auth(codex_login::CodexAuth::create_dummy_chatgpt_auth_for_testing())
.with_exec_server_url(exec_server_url)
.with_config(|config| {
@@ -547,7 +559,7 @@ async fn interrupt_during_exec_startup_terminates_unregistered_process() -> Resu
config
.permissions
.set_permission_profile(PermissionProfile::workspace_write())
.unwrap();
.expect("set workspace-write profile");
config.project_doc_max_bytes = 0;
config.approvals_reviewer = ApprovalsReviewer::User;
#[cfg(windows)]
@@ -556,7 +568,12 @@ async fn interrupt_during_exec_startup_terminates_unregistered_process() -> Resu
// The existing fake executor provides a deterministic RPC boundary for interruption.
.build(&server)
.await?;
let selection = test.codex.environment_selections().await.pop().unwrap();
let selection = test
.codex
.environment_selections()
.await
.pop()
.context("remote environment")?;
let mut config = environment_config_for_selection(&test.config, &selection);
config.network_policy = Some(environment_policy_from_config(
&NetworkProxyConfig {
@@ -573,23 +590,68 @@ async fn interrupt_during_exec_startup_terminates_unregistered_process() -> Resu
text_elements: Vec::new(),
}])
.with_thread_settings(ThreadSettingsOverrides {
approval_policy: Some(AskForApproval::Never),
approval_policy: Some(approval_policy),
..Default::default()
}),
)
.await?;
if approval_policy == AskForApproval::UnlessTrusted {
let approval = wait_for_event_match(&test.codex, |event| match event {
EventMsg::ExecApprovalRequest(prompt) if prompt.starts_command() => {
Some(Op::ExecApproval {
id: prompt.effective_approval_id(),
turn_id: Some(prompt.turn_id.clone()),
decision: ReviewDecision::Approved,
})
}
_ => None,
})
.await;
test.codex.submit(approval).await?;
}
timeout(STARTUP_TIMEOUT, blocked)
.await
.context("startup did not reach attribution")??;
if approval_policy == AskForApproval::UnlessTrusted {
// Keep an unrelated prompt open through shutdown.
test.codex.increment_out_of_band_elicitation_count().await?;
}
test.codex.submit(Op::Interrupt).await?;
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::TurnAborted(_))
})
.await;
let cleanup = timeout(Duration::from_secs(/*secs*/ 5), termination).await;
exec_server.abort();
let _ = exec_server.await;
cleanup.context("interruption left an unregistered process running")??;
// Keep the connection open so disconnecting cannot unblock the lookup.
let _connection = timeout(Duration::from_secs(/*secs*/ 5), exec_server)
.await
.context("interruption left an unregistered process running")??;
timeout(
Duration::from_secs(/*secs*/ 5),
test.codex.shutdown_and_wait(),
)
.await
.context("shutdown stalled after process termination")??;
if approval_policy == AskForApproval::UnlessTrusted {
let path = test.codex.rollout_path().context("rollout path")?;
let (items, _, parse_errors) = RolloutRecorder::load_rollout_items(&path).await?;
assert_eq!(parse_errors, 0);
let statuses = items
.iter()
.filter_map(|item| match item {
RolloutItem::EventMsg {
event: EventMsg::ItemCompleted(event),
..
} => match &event.item {
TurnItem::CommandExecution(command) if command.id == call_id => {
Some(&command.status)
}
_ => None,
},
_ => None,
})
.collect::<Vec<_>>();
assert_eq!(statuses, [&CommandExecutionStatus::Failed]);
}
Ok(())
}