Skip to main content

agentmux_srv_core/backend/blockcontroller/persistent/
eager_resume.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Eager resume: spawning the CLI on controller construction (before the first
5//! message) when a prior session id is on file, so the first turn is not
6//! charged the full cold-start.
7
8use super::*;
9
10#[path = "eager_resume_steps.rs"]
11pub mod steps;
12
13/// Whether the pane's last failure says it was closed for an agent open in another pane (`open_in_other_pane`).
14fn closed_for_another_pane(block_meta: &super::super::super::obj::MetaMapType) -> bool {
15    block_meta.get(core::META_LAST_FAILURE).and_then(|f| f.get("code")).and_then(|c| c.as_str()) == Some("open_in_other_pane")
16}
17
18impl PersistentSubprocessController {
19    /// Atomically claims the exclusive spawn right `decide_send_action`'s
20    /// `BecomeSpawner` branch also claims, or declines if one is already
21    /// held (`stdin_tx` live, another spawn in flight, or a drain in
22    /// progress). `true` means the caller now owns the claim and MUST
23    /// release it — either directly (a decline with no message ever
24    /// delivered) or via `drain_queue_after_successful_spawn`/
25    /// `respawn_once_for_leftover_queue` (a spawn attempt was made).
26    ///
27    /// Split out of `try_eager_resume` specifically so this state
28    /// transition is unit-testable on its own — codex P1 on PR #3513
29    /// (the spawn-claim race) found that PR's first fix, tested only
30    /// end-to-end, left this exact step's own removal undetected by every
31    /// test in the file (confirmed by mutation: deleting the claim block
32    /// entirely still passed all 6 eager-resume tests, since none of them
33    /// exercised `try_eager_resume`'s OWN claim step in isolation).
34    #[cfg(test)]
35    pub(super) fn try_claim_eager_resume_spawn(&self) -> bool {
36        self.try_claim_eager_resume_spawn_for(None)
37    }
38
39    /// [`Self::try_claim_eager_resume_spawn`], and for a config restart's
40    /// replacement (`Some(generation)`) also require that restart's token
41    /// (`config_restart_generation`) in the SAME acquisition that takes the
42    /// claim, and record the claim as that replacement (`restart_spawn_for`).
43    /// The token is not consumed here: `spawn_process` consumes it right
44    /// before starting the child, so a Stop during the credential gate in
45    /// between still cancels the replacement (codex P1s on #3990).
46    pub(super) fn try_claim_eager_resume_spawn_for(&self, restart_generation: Option<u64>) -> bool {
47        let mut inner = self.inner.lock().unwrap();
48        if inner.stdin_tx.is_some() || inner.spawning_in_progress || inner.drain_claim {
49            return false;
50        }
51        if let Some(generation) = restart_generation {
52            if inner.config_restart_generation != Some(generation) {
53                return false;
54            }
55        }
56        inner.restart_spawn_for = restart_generation;
57        inner.spawning_in_progress = true;
58        inner.stop_watch.claim();
59        true
60    }
61
62    /// True when a Stop (or a replacement's stop of this controller, or a pane close) has landed since an eager
63    /// resume claimed its spawn, so the child it is about to start would outlive its pane: nothing could reach it
64    /// through the registry, and it would race the replacement on the same `--resume` session. Always false for
65    /// a spawn that is not an eager resume.
66    pub(super) fn eager_resume_stopped_locked(inner: &PersistentInner) -> bool {
67        inner.stop_watch.stopped()
68    }
69
70    /// `start()`'s eager-resume attempt for a pane with a captured
71    /// `agent:sessionid`. Never returns an error — every failure mode here
72    /// is "fall back to lazy", not "fail the resync"; see `start()`'s own
73    /// doc comment for why.
74    pub(super) fn try_eager_resume(&self, block_meta: &super::super::super::obj::MetaMapType, session_id: &str) -> EagerResumeOutcome {
75        self.try_eager_resume_as(block_meta, session_id, None)
76    }
77
78    /// [`Self::try_eager_resume`], optionally as a config restart's
79    /// replacement: see [`Self::try_claim_eager_resume_spawn_for`].
80    pub(super) fn try_eager_resume_as(
81        &self,
82        block_meta: &super::super::super::obj::MetaMapType,
83        session_id: &str,
84        restart_generation: Option<u64>,
85    ) -> EagerResumeOutcome {
86        let stores = match self.eager_resume_stores(block_meta) {
87            Ok(stores) => stores,
88            Err(declined) => return declined,
89        };
90        let steps::LaunchParts { cli_command, cli_args, working_dir, base_env_vars, resume_flag, session_id_field } =
91            match steps::launch_parts(block_meta) {
92                Ok(parts) => parts,
93                Err(declined) => return declined,
94            };
95        if let Some(declined) = self.declined_by_another_instance(block_meta) {
96            return declined;
97        }
98
99        // Claim exclusivity BEFORE the (possibly slow) identity/env
100        // resolution below, not just before the eventual `spawn_process`
101        // call — codex P1 on PR #3513: the controller is placed in the
102        // global registry before `start()` runs (`resync_controller`'s
103        // "Create new controller" branch), so a concurrent message can
104        // reach `send_message` -> `decide_send_action` while this method is
105        // still resolving the identity gate. Without a claim,
106        // `decide_send_action` sees `stdin_tx: None` and
107        // `spawning_in_progress: false` and becomes ITS OWN spawner —
108        // two processes launched against the same `--resume <sid>`, one
109        // silently overwriting the other's `current_pid`/`stdin_tx`/
110        // `kill_tx` while the first stays alive on the same conversation.
111        // Same exclusivity flag `decide_send_action`'s `BecomeSpawner`
112        // branch claims for a live message — this is the same lock a
113        // concurrent `send_message` acquires, so the check-and-set below is
114        // atomic with respect to it.
115        if !self.try_claim_eager_resume_spawn_for(restart_generation) {
116            return EagerResumeOutcome::DeclinedTo(
117                "already running, another spawn already in flight, or a stop overrode the restart \
118                 — nothing to eagerly resume",
119            );
120        }
121        // The claim's epoch outlives neither this call nor the spawn it guards.
122        let _claim_epoch = EagerClaimEpoch(&self.inner);
123
124        let env_vars = match self.build_gate_env(stores, block_meta, base_env_vars) {
125            Ok(env) => env,
126            Err(gate_err) => return self.refuse_after_gate(&gate_err),
127        };
128
129        let config = PersistentSpawnConfig {
130            cli_command,
131            cli_args,
132            working_dir,
133            env_vars,
134            session_id_field,
135            resume_flag,
136            session_id: session_id.to_string(),
137            message_id: None,
138        };
139        let retry_config = config.clone();
140        match self.spawn_process(config, None) {
141            Ok(()) => self.settle_resumed(retry_config),
142            Err(e) => {
143                tracing::warn!(
144                    block_id = %self.block_id,
145                    error = %e,
146                    "eager-resume declined: spawn failed — falling back to lazy"
147                );
148                self.settle_eager_spawn_failure(&e, retry_config);
149                EagerResumeOutcome::DeclinedTo("spawn failed")
150            }
151        }
152    }
153}
154
155impl PersistentSubprocessController {
156    /// `try_eager_resume`'s spawn-failure settlement, split out so the
157    /// decision is unit-testable without a real child process. Also the
158    /// settlement for a refused *candidate* respawn in
159    /// `respawn_once_for_leftover_queue` (codex P1 on PR #3551, sixth
160    /// round), which fails the same way for the same reason.
161    ///
162    /// Mirrors `release_spawn_claim_and_drain_queue`'s `!spawn_succeeded`
163    /// branch: if something queued during the attempt it needs a live
164    /// process to go to, so hand off to the fallback respawn; otherwise just
165    /// release the claim — there's nothing to drain. Decided under ONE lock
166    /// acquisition, same as the success branch and for the same reason
167    /// (codex P2 on PR #3523): as two, a send arriving in the gap saw the
168    /// claim still held, queued its prompt and returned success, and the
169    /// release then never rechecked — stranding an accepted prompt until
170    /// some unrelated later send happened to become the next spawner.
171    ///
172    /// One failure class is exempt from the fallback (codex P1 on PR
173    /// #3551): `session_held_elsewhere` refusing the `--resume` because the
174    /// same conversation is open — or still closing — in another pane. A
175    /// fresh spawn there would deliver the accepted prompt to a blank
176    /// conversation, bypassing the very guard `spawn_process` just applied.
177    /// Instead: release the claim, DISCARD the queue, keep the session id,
178    /// and tell the user which prompts were not delivered and why.
179    ///
180    /// Discarded, not retained (codex P1 on PR #3551, third round): keeping
181    /// the prompts queued — the credential-gate decline's shape — only
182    /// defers the bypass. The next send would become the spawner, hit the
183    /// same refusal, and `release_spawn_claim_and_drain_queue`'s generic
184    /// failed-spawn path, which knows nothing about WHY, would see the
185    /// leftovers and hand them to `respawn_once_for_leftover_queue` — a
186    /// fresh, blank conversation after all. The only way to make that path
187    /// unable to misread them is for them not to be there.
188    pub(super) fn settle_eager_spawn_failure(&self, err: &str, retry_config: PersistentSpawnConfig) {
189        let ownership_refusal = is_held_elsewhere_error(err);
190        // A Stop that cancelled a config restart's replacement must win over
191        // prompts queued behind it too: the fallback respawn below would start
192        // the agent the user just stopped (codex P1 on #3990).
193        let restart_cancelled = err == RESTART_OVERRIDDEN;
194        // Likewise a Stop or a replacement that landed while an eager resume was starting: the prompts queued
195        // behind it must not start the agent again on a controller that was just stopped or replaced.
196        let stopped_while_starting = err == STOPPED_WHILE_STARTING;
197        let no_fallback = ownership_refusal || restart_cancelled || stopped_while_starting;
198        let (stranded, discarded) = {
199            let mut inner = self.inner.lock().unwrap();
200            let n = inner.pending_send_messages.len();
201            let mut discarded = 0;
202            if n == 0 || no_fallback {
203                inner.spawning_in_progress = false;
204                // In the same acquisition, so a message that spawns next is not judged by this attempt's stop.
205                inner.stop_watch.release();
206            }
207            if no_fallback {
208                discarded = inner.pending_send_messages.len();
209                inner.pending_send_messages.clear();
210            }
211            (n, discarded)
212        };
213        if stranded == 0 {
214            return;
215        }
216        if !no_fallback {
217            // Claim still held: `respawn_once_for_leftover_queue` owns its
218            // release on either outcome.
219            self.respawn_once_for_leftover_queue(retry_config);
220            return;
221        }
222        let why = if restart_cancelled {
223            "this agent was stopped before its config restart finished, so it was not restarted".to_string()
224        } else if stopped_while_starting {
225            "this agent was stopped or replaced while it was being resumed, so it was not resumed".to_string()
226        } else {
227            format!("this agent was not resumed. {err}")
228        };
229        let frame = serde_json::json!({
230            "type": "result",
231            "is_error": true,
232            "subtype": "error_during_execution",
233            "error": {
234                "message": format!(
235                    "[AgentMux] {discarded} queued prompt(s) were not delivered and have been discarded: {why}"
236                )
237            }
238        });
239        self.flush_error_line_now(format!("{frame}\n"));
240    }
241}
242
243impl PersistentSubprocessController {
244    /// Called under `inner` just before `spawn_process` starts the OS child:
245    /// if this spawn is a config restart's replacement and a Stop cleared its
246    /// token since the claim (the claim precedes the credential gate, which
247    /// can be slow), refuse, so no process is started at all. A cheap early
248    /// out only: the token stays live, because a Stop can still land while the
249    /// child is being started, and only [`Self::commit_restart_spawn_locked`],
250    /// in the acquisition that installs the child, decides (codex P1s on
251    /// #3990). Refusing returns an error, so the caller takes its ordinary
252    /// spawn-failure path: the claim is released, and a message a human typed
253    /// meanwhile still gets its own spawn.
254    pub(super) fn restart_spawn_still_permitted_locked(inner: &mut PersistentInner) -> Result<(), String> {
255        if Self::eager_resume_stopped_locked(inner) {
256            inner.restart_spawn_for = None;
257            return Err(STOPPED_WHILE_STARTING.to_string());
258        }
259        let Some(generation) = inner.restart_spawn_for else {
260            return Ok(());
261        };
262        if inner.config_restart_generation != Some(generation) {
263            inner.restart_spawn_for = None;
264            return Err(RESTART_OVERRIDDEN.to_string());
265        }
266        Ok(())
267    }
268
269    /// Called in the SAME `inner` acquisition that installs a freshly started
270    /// child as the live process: consume a config restart's token, or refuse
271    /// if a Stop cleared it while the child was starting. Until this point a
272    /// Stop has no `kill_tx` to reach the new process through, so this is
273    /// where it must win: on refusal the caller kills the child it just
274    /// started and fails the spawn.
275    pub(super) fn commit_restart_spawn_locked(inner: &mut PersistentInner) -> Result<(), String> {
276        if Self::eager_resume_stopped_locked(inner) {
277            inner.restart_spawn_for = None;
278            return Err(STOPPED_WHILE_STARTING.to_string());
279        }
280        let Some(generation) = inner.restart_spawn_for.take() else {
281            return Ok(());
282        };
283        if inner.config_restart_generation != Some(generation) {
284            return Err(RESTART_OVERRIDDEN.to_string());
285        }
286        inner.config_restart_generation = None;
287        Ok(())
288    }
289
290    /// Whether the process of `generation` just ended as a committed config
291    /// restart that nothing has overridden, so its exit handler must bring the
292    /// replacement up. Checked by BOTH exit arms: the process can exit on its
293    /// own right after its last `result` and win the `select!` before the kill
294    /// is consumed (codex P1 on #3990). A read, not a take: the token is
295    /// consumed only right before the replacement's child starts, so a Stop
296    /// until then still wins.
297    pub(super) fn config_restart_due_locked(inner: &PersistentInner, generation: u64) -> bool {
298        inner.spawn_generation == generation && inner.config_restart_generation == Some(generation)
299    }
300
301    /// The second half of a deferred runtime-config restart, run by the old
302    /// process's exit handler once it is gone: resume the same session with the
303    /// config now in block meta, exactly as a restart that found the pane idle
304    /// does (`resync_controller` replaces the controller and `start()`
305    /// eager-resumes). Before this the pane stayed empty "until the next
306    /// message", and a jekt is never that message: automated delivery doesn't
307    /// spawn, and it waits while `restart_pending` is set, so every message to
308    /// the agent queued until a human typed into it
309    /// (`docs/retro/RETRO_DEFERRED_RESTART_NEVER_RESPAWNS_2026_09_29.md`).
310    ///
311    /// Nothing is started for a controller that's no longer this block's (a
312    /// pane closed or replaced in the window), when something already replaced
313    /// the process (any spawn clears the token), or when a Stop overrode the
314    /// restart: the token is consumed only inside the spawn claim, under the
315    /// lock a Stop clears it with. Whenever no replacement comes, the restart
316    /// window is closed anyway, so queued deliveries fall to the no-process
317    /// rules (reported stranded after the watchdog's grace) instead of waiting
318    /// for a spawn that isn't coming.
319    pub(super) fn respawn_after_config_restart(&self, generation: u64) {
320        let is_this_blocks_controller = super::super::get_controller(&self.block_id).is_some_and(|c| {
321            c.as_any()
322                .downcast_ref::<PersistentSubprocessController>()
323                .is_some_and(|c| std::ptr::eq(c, self))
324        });
325        if !is_this_blocks_controller {
326            tracing::info!(
327                block_id = %self.block_id,
328                "config restart: controller no longer serves this block — not respawning"
329            );
330            return;
331        }
332        {
333            let inner = self.inner.lock().unwrap();
334            if inner.stdin_tx.is_some() || inner.spawning_in_progress {
335                return;
336            }
337        }
338        let block_meta = self
339            .mstore
340            .as_ref()
341            .and_then(|s| s.get::<crate::backend::obj::Block>(&self.block_id).ok().flatten())
342            .map(|b| b.meta);
343        let session_id = block_meta
344            .as_ref()
345            .map(|m| crate::backend::obj::meta_get_string(m, core::META_SESSION_ID, ""))
346            .unwrap_or_default();
347        let outcome = match block_meta {
348            Some(ref meta) if !session_id.is_empty() => self.try_eager_resume_as(meta, &session_id, Some(generation)),
349            Some(_) => EagerResumeOutcome::DeclinedTo("no session id on file"),
350            None => EagerResumeOutcome::DeclinedTo("block not found"),
351        };
352        match outcome {
353            EagerResumeOutcome::Spawned => {
354                tracing::info!(
355                    block_id = %self.block_id,
356                    session_id = %session_id,
357                    "config restart: replacement process resumed the session"
358                );
359            }
360            EagerResumeOutcome::DeclinedTo(reason) => {
361                self.close_restart_window_without_process();
362                tracing::warn!(
363                    block_id = %self.block_id,
364                    reason = %reason,
365                    "config restart: could not resume a replacement — the agent waits for its next \
366                     message, and queued deliveries follow the no-process rules"
367                );
368            }
369        }
370    }
371
372    /// End a config restart's quiesce window when no replacement is coming:
373    /// with `restart_pending` (and the restart's own `stop_pending`) left set,
374    /// `deferred_must_wait_locked` holds every queued delivery forever and the
375    /// watchdog never reports it. Leaves them alone if a spawn has meanwhile
376    /// begun, since that spawn clears both itself.
377    pub(super) fn close_restart_window_without_process(&self) {
378        let mut inner = self.inner.lock().unwrap();
379        if inner.stdin_tx.is_none() && !inner.spawning_in_progress {
380            inner.config_restart_generation = None;
381            inner.restart_spawn_for = None;
382            inner.restart_pending = false;
383            inner.stop_pending = false;
384        }
385    }
386}
387
388/// Why a config restart's replacement was abandoned: a Stop landed first.
389pub(super) const RESTART_OVERRIDDEN: &str = "a stop overrode the config restart before its replacement started";
390
391/// Why an eager resume was abandoned after it claimed its spawn: a Stop, a replacement of this controller or a
392/// pane close landed during the credential gate or while the child was starting.
393pub(super) const STOPPED_WHILE_STARTING: &str = "a stop or a replacement landed before the eager resume's process started";
394
395/// What an eager resume needs to know about stops that land while it is between its spawn claim and its child
396/// (the identity and credential gate in the middle can be slow): a Stop, a replacement's stop of the old
397/// controller or a pane close, but not a config restart's own stop, each counts. The count is compared with
398/// the one seen at the claim; a spawn that never claimed is never judged by it.
399#[derive(Default)]
400pub(super) struct StopWatch {
401    stops: u64,
402    claimed_at: Option<u64>,
403}
404
405impl StopWatch {
406    pub(super) fn note_stop(&mut self) {
407        self.stops += 1;
408    }
409
410    /// Records the count as it stands now, at the claim of an eager resume's spawn.
411    pub(super) fn claim(&mut self) {
412        self.claimed_at = Some(self.stops);
413    }
414
415    /// True when a stop has landed since the claim.
416    pub(super) fn stopped(&self) -> bool {
417        self.claimed_at.is_some_and(|at| at != self.stops)
418    }
419
420    pub(super) fn claimed(&self) -> bool {
421        self.claimed_at.is_some()
422    }
423
424    pub(super) fn release(&mut self) {
425        self.claimed_at = None;
426    }
427}
428
429/// Holds an eager resume's claim for the length of the attempt and releases it on every way out, so a later
430/// spawn of another kind is never judged by a stale one.
431struct EagerClaimEpoch<'a>(&'a Mutex<PersistentInner>);
432
433impl Drop for EagerClaimEpoch<'_> {
434    fn drop(&mut self) {
435        if let Ok(mut inner) = self.0.lock() {
436            inner.stop_watch.release();
437        }
438    }
439}