Continue interrupted work after managed daemon restarts (#45820)

## Why

Daemon recovery reloads threads but leaves interrupted work unfinished. Resume eligible work automatically from the saved conversation, even without a connected client.

## What changed

- Attempt one new continuation turn immediately after restoration, including in Plan mode. Mark the old turn interrupted and supply recovery context without creating a user message or granting new authorization.
- Require an idle thread, matching permissions, and the same single local environment configured by the thread. Skip completed, aborted, or superseded work and snapshots without environment identity.
- Add `continue_turn_if_idle` with an atomic previous-turn check so newer tasks or standalone settings changes invalidate pending continuation.
- Preserve the output schema, service tier, and root turn ID, and emit a “Resuming interrupted work” warning when continuation starts.

## Testing

Add daemon restart coverage for continuation without a client, Plan mode, permission and environment mismatches, and legacy snapshots. Add core coverage for preserved continuation metadata, absence of user-message events, rejection of superseded continuations, and exclusion of remote execution from recovery snapshots.

GitOrigin-RevId: 2b290b75d9399fc58258bcda2e85c74e9b5b3b09
This commit is contained in:
Eric Traut authored and copyberry committed 2026-09-16 00:54:58 +00:00
1 parent 7c709f0ffd
commit f2b5b81f39
21 files changed
+641 -55

No files matched your search

@@ -0,0 +1,135 @@
//! Attempts one new continuation turn immediately after daemon thread restoration.
//! Completed or superseded work is discarded; recovery never waits for a later idle event.
//! Permissions and the saved local executor selection must match the resumed runtime.
use super::ThreadRequestProcessor;
use codex_app_server_protocol::ThreadEnvironment;
use codex_app_server_transport::daemon_recovery::InterruptedTurn;
use codex_core::TurnInput;
use codex_core::TurnInputRequest;
use codex_core::TurnInputSubmission;
use codex_core::TurnStartOptions;
use codex_core::context::ContextualUserFragment;
use codex_core::context::InternalContextSource;
use codex_core::context::InternalModelContextFragment;
use codex_protocol::ThreadId;
use codex_protocol::protocol::EnvironmentConfigState;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::TurnAbortReason;
use codex_protocol::protocol::TurnAbortedEvent;
use codex_rollout::RolloutItem;
impl ThreadRequestProcessor {
pub(crate) async fn continue_daemon_turn(&self, thread_id: &str, saved: InterruptedTurn) {
let Ok(thread_id) = ThreadId::from_string(thread_id) else {
return;
};
let Ok(thread) = self.thread_manager.get_thread(thread_id).await else {
return;
};
let Some(path) = thread.rollout_path() else {
return;
};
let history = match codex_rollout::RolloutRecorder::load_rollout_items(&path).await {
Ok((history, _, _)) => history,
Err(err) => {
tracing::warn!(%thread_id, %err, "failed to read interrupted turn history");
return;
}
};
// The snapshot has complete recorded input, but the old process may have
// completed or replaced its turn during the shutdown grace period.
let Some(start) = history
.iter()
.rposition(|item| matches!(item, RolloutItem::EventMsg(EventMsg::TurnStarted(_))))
else {
return;
};
if !matches!(&history[start], RolloutItem::EventMsg(EventMsg::TurnStarted(event))
if event.turn_id == saved.turn_id)
|| history[start..].iter().any(|item| match item {
RolloutItem::EventMsg(EventMsg::TurnComplete(event)) => {
event.turn_id == saved.turn_id
}
RolloutItem::EventMsg(EventMsg::TurnAborted(event)) => event
.turn_id
.as_ref()
.is_none_or(|turn_id| turn_id == &saved.turn_id),
_ => false,
})
{
return;
}
let previous_context = history.iter().rev().find_map(|item| match item {
RolloutItem::TurnContext(context)
if context.turn_id.as_ref() == Some(&saved.turn_id) =>
{
Some(context)
}
_ => None,
});
let Some(previous_context) = previous_context else {
return;
};
let config = thread.config_snapshot().await;
let [environment] = config.environment_selections() else {
return;
};
if environment.environment_id != codex_exec_server::LOCAL_ENVIRONMENT_ID
|| environment.config != EnvironmentConfigState::FromThread
|| saved.local_environment.as_ref() != Some(&ThreadEnvironment::from(environment))
{
return;
}
// Recovery must not override a stricter saved or newly configured policy.
if previous_context.permission_profile() != config.permission_profile {
return;
}
let continuation = ContextualUserFragment::into(InternalModelContextFragment::new(
InternalContextSource::from_static("daemon_recovery"),
"The server restarted and interrupted the previous turn. Continue the unfinished work from the saved conversation. Check the current state before repeating actions that may already have completed.",
));
let request = TurnInputRequest::new(TurnInput::ResponseItem(continuation)).on_start(
TurnStartOptions {
turn_trigger: Some("daemon_recovery".to_string()),
final_output_json_schema: saved.output_schema,
service_tier: saved.service_tier,
cyber_access_program: saved.cyber_access_program,
root_turn_id: previous_context.root_turn_id.clone(),
..Default::default()
},
);
// Close the old turn in persisted history before exposing a new running turn.
if let Err(err) = thread
.append_rollout_items(&[RolloutItem::EventMsg(EventMsg::TurnAborted(
TurnAbortedEvent {
turn_id: Some(saved.turn_id.clone()),
reason: TurnAbortReason::Interrupted,
started_at: None,
completed_at: None,
duration_ms: None,
},
))])
.await
{
tracing::warn!(%thread_id, %err, "failed to close interrupted turn history");
return;
}
match thread.continue_turn_if_idle(request, saved.turn_id).await {
Ok(TurnInputSubmission::Started { .. }) => {
crate::extensions::send_thread_warning(
&self.outgoing,
&self.thread_state_manager,
thread_id,
"Resuming interrupted work".to_string(),
)
.await;
}
Ok(TurnInputSubmission::NotSubmitted { reason }) => {
tracing::debug!(%thread_id, ?reason, "recovery continuation was not started");
}
Ok(TurnInputSubmission::Steered { .. }) => unreachable!("continuation cannot steer"),
Err(err) => tracing::warn!(%thread_id, %err, "recovery continuation failed"),
}
}
}
@@ -37,7 +37,7 @@ impl ThreadRequestProcessor {
continue;
}
snapshot.loaded.insert(thread_id.to_string());
if let Some((turn_id, options)) = interrupted {
if let Some((turn_id, options, environment)) = interrupted {
snapshot.interrupted.insert(
thread_id.to_string(),
InterruptedTurn {
@@ -45,6 +45,7 @@ impl ThreadRequestProcessor {
output_schema: options.final_output_json_schema,
service_tier: options.service_tier,
cyber_access_program: options.cyber_access_program,
local_environment: Some((&environment).into()),
},
);
}
@@ -1,3 +1,6 @@
#[path = "daemon_continuation.rs"]
mod daemon_continuation;
#[path = "daemon_snapshot.rs"]
mod daemon_snapshot;
@@ -460,7 +463,7 @@ pub(crate) struct ThreadRequestProcessor {
/// Whether resume attaches a client or restores a cold runtime during daemon startup.
pub(crate) enum ThreadResumeTarget {
Client(ConnectionRequestId),
DaemonRecovery,
DaemonRecovery(Option<codex_app_server_transport::daemon_recovery::InterruptedTurn>),
}
/// Outcome of trying to satisfy a resume request from an already loaded thread.
@@ -3630,11 +3633,15 @@ impl ThreadRequestProcessor {
}
RunningThreadResumeResult::NotRunning(stored_thread) => stored_thread,
},
ThreadResumeTarget::DaemonRecovery => {
ThreadResumeTarget::DaemonRecovery(saved) => {
let thread_id = ThreadId::from_string(&params.thread_id)
.map_err(|err| invalid_request(format!("invalid thread id: {err}")))?;
// Recheck under the same permit as client resume, including after config loading.
if self.thread_manager.get_thread(thread_id).await.is_ok() {
if let Some(saved) = saved {
self.continue_daemon_turn(&params.thread_id, saved.clone())
.await;
}
return Ok(ControlFlow::Break(()));
}
None
@@ -3918,7 +3925,7 @@ impl ThreadRequestProcessor {
ThreadResumeTarget::Client(request_id) => {
self.request_trace_context(request_id).await
}
ThreadResumeTarget::DaemonRecovery => None,
ThreadResumeTarget::DaemonRecovery(_) => None,
},
client_mcp_extensions,
)
@@ -3939,6 +3946,10 @@ impl ThreadRequestProcessor {
codex_thread
.emit_thread_idle_lifecycle_if_idle(ThreadIdleCause::Completed)
.await;
if let ThreadResumeTarget::DaemonRecovery(Some(saved)) = target {
self.continue_daemon_turn(&thread_id.to_string(), saved.clone())
.await;
}
let state = self.thread_state_manager.thread_state(thread_id).await;
self.ensure_listener_task_running(thread_id, Arc::clone(&codex_thread), state)
.await?;
@@ -1150,7 +1150,9 @@ impl TurnRequestProcessor {
None,
None,
),
NotSubmittedReason::PendingTriggerTurn | NotSubmittedReason::PlanMode => (
NotSubmittedReason::PendingTriggerTurn
| NotSubmittedReason::PlanMode
| NotSubmittedReason::Superseded => (
"no active turn to steer".to_string(),
None,
Some(AnalyticsJsonRpcError::TurnSteer(