Skip to main content

mj_controller/controller/
worker_restart.rs

1//! Replacing a session's worker process in place.
2//!
3//! Two things ask for this: a checkpoint whose ACP turn will not finish, and a
4//! session whose worker predates the controller now talking to it. Both stop
5//! the worker, install the binary this controller would provision, start it
6//! and reconnect, so the sequence lives here once and each caller supplies
7//! only what it tells the operator.
8
9use std::time::Duration;
10
11use anyhow::{Context, Result, bail};
12
13use crate::session_manager::{SessionManagerControl, StandaloneSession};
14use crate::targets::{self, CommandExecutor, CommandSpec};
15use mj_core::relay::RelayExecutionState;
16
17use super::Controller;
18use super::readiness::{connect_started_worker_with_timeout, wait_for_native_session};
19use super::worker_binary::{
20    install_staged_worker_binary, prepare_managed_harness_for_upgrade,
21    replace_installed_worker_binary, replace_installed_worker_launch_config,
22    stage_worker_binary_for_upgrade, start_worker, stop_worker_after_target_recovery,
23    worker_binary_for, worker_probe_diagnosis,
24};
25
26/// How long a restarted worker has to recover its journal, bind `control.sock`
27/// and report an idle ACP session. Journal recovery over a long transcript
28/// runs before the socket exists, so this has to outlast it.
29const WORKER_RESTART_TIMEOUT: Duration = Duration::from_secs(300);
30
31/// How long a quiet session's upgrade waits for its actor and its lease.
32const UPGRADE_LEASE_TIMEOUT: Duration = Duration::from_secs(5);
33
34/// The worker was stopped so it could be replaced, and no worker came back:
35/// the binary swap, start, connect, or ACP readiness after it failed. The
36/// session has no live worker until something restarts one.
37#[derive(Debug)]
38pub struct WorkerRestartLeftNoWorker;
39
40impl WorkerRestartLeftNoWorker {
41    /// Whether a failed operation left the session without a live worker.
42    ///
43    /// The marker is carried by the error, not by its text. Callers wrap
44    /// restart errors in further context, and `anyhow`'s downcast walks those
45    /// layers, so added context does not hide it.
46    #[must_use]
47    pub fn marks(error: &anyhow::Error) -> bool {
48        error.downcast_ref::<Self>().is_some()
49    }
50}
51
52impl std::fmt::Display for WorkerRestartLeftNoWorker {
53    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        formatter.write_str("the worker restart left the session without a live worker")
55    }
56}
57
58impl std::error::Error for WorkerRestartLeftNoWorker {}
59
60/// After a restarted worker has answered once, only a dead transport proves
61/// the worker is gone again; any other failure leaves a live worker behind.
62fn mark_if_transport_died(error: anyhow::Error) -> anyhow::Error {
63    if crate::worker_client::RelayTransportDead::marks(&error) {
64        error.context(WorkerRestartLeftNoWorker)
65    } else {
66        error
67    }
68}
69
70/// What one restart tells the operator at each step. The steps are identical;
71/// only the reason differs, and a diagnostic that named the wrong reason would
72/// send someone looking in the wrong place.
73pub(super) struct WorkerRestartMessages {
74    pub stop: &'static str,
75    pub replace: &'static str,
76    pub start: &'static str,
77    pub connect: &'static str,
78    pub project_memory: &'static str,
79    pub native_session: &'static str,
80}
81
82pub(super) struct InstalledWorkerRestart<'a> {
83    pub backend: &'a targets::TargetLocator,
84    pub worker_root: &'a str,
85    pub reconnect: &'a CommandSpec,
86    pub launch: Option<&'a mj_core::worker_launch::WorkerLaunchConfig>,
87    pub prepared: bool,
88    pub messages: &'a WorkerRestartMessages,
89}
90
91/// A wedged ACP turn is being killed so a checkpoint barrier can be admitted.
92pub(super) const RESTART_FOR_CHECKPOINT: WorkerRestartMessages = WorkerRestartMessages {
93    stop: "stop wedged Mjolnir worker before retrying checkpoint",
94    replace: "replace Mjolnir worker binary before retrying checkpoint",
95    start: "start Mjolnir worker after interrupting a wedged ACP turn",
96    connect: "connect to Mjolnir worker after restarting it for checkpoint",
97    project_memory: "project memory will not be synchronized after checkpoint worker restart",
98    native_session: "wait for ACP session after restarting the worker for checkpoint",
99};
100
101/// A quiet session is being moved onto the worker binary this controller
102/// would install.
103const RESTART_FOR_UPGRADE: WorkerRestartMessages = WorkerRestartMessages {
104    stop: "stop the Mjolnir worker before installing the current binary",
105    replace: "install the current Mjolnir worker binary",
106    start: "start Mjolnir worker on the current binary",
107    connect: "connect to Mjolnir worker after upgrading its binary",
108    project_memory: "project memory will not be synchronized after the worker upgrade",
109    native_session: "wait for ACP session after upgrading the worker",
110};
111
112/// What an upgrade attempt found. Nothing here is a failure: a worker that is
113/// already current and a session that started working again are both ordinary.
114#[derive(Debug, Clone, PartialEq, Eq)]
115pub enum WorkerUpgradeOutcome {
116    /// The worker was replaced and the managed session now speaks to one
117    /// running this build.
118    Upgraded { build: String },
119    /// The worker already runs the binary this controller would install.
120    AlreadyCurrent { build: String },
121    /// The session was working when the upgrade reached it. A worker restart
122    /// would have killed that work, so nothing was touched.
123    Deferred,
124}
125
126impl WorkerUpgradeOutcome {
127    /// The build the session's worker runs now, or `None` when the attempt
128    /// stood down without establishing one.
129    #[must_use]
130    pub fn build(&self) -> Option<&str> {
131        match self {
132            Self::Upgraded { build } | Self::AlreadyCurrent { build } => Some(build),
133            Self::Deferred => None,
134        }
135    }
136}
137
138/// Whether a worker that reported `reported` in hello is running `installed`,
139/// the binary this controller would provision.
140///
141/// A worker that reported nothing is not: the field postdates it, so its
142/// binary does too.
143fn worker_runs_installed_build(reported: Option<&str>, installed: &str) -> bool {
144    reported.is_some_and(|reported| reported == installed)
145}
146
147impl Controller {
148    /// Replace a session's worker with the binary this controller would
149    /// install, when the session is quiet and its worker is a different build.
150    ///
151    /// `reported_build` is the digest the worker gave the observer that asked
152    /// for this. It only saves work: a match returns before anything is leased.
153    /// The decision that matters is taken again under the lease, against a
154    /// snapshot read from the worker itself, because a session can start
155    /// working between an observation and this call.
156    pub async fn upgrade_session_worker(
157        &self,
158        session_id: &str,
159        executor: &(impl CommandExecutor + Sync),
160        manager: &SessionManagerControl,
161        reported_build: Option<&str>,
162    ) -> Result<WorkerUpgradeOutcome> {
163        let (backend, worker_root) = self.worker_placement(session_id)?;
164        let reconnect = targets::reconnect_plan(&backend, session_id)?
165            .commands
166            .into_iter()
167            .next()
168            .context("reconnect plan is empty")?;
169        let binary = worker_binary_for(&backend, executor)
170            .context("resolve the worker binary this controller would install")?;
171        let installed = mj_core::worker_launch::worker_executable_digest(&binary)?;
172        if worker_runs_installed_build(reported_build, &installed) {
173            return Ok(WorkerUpgradeOutcome::AlreadyCurrent { build: installed });
174        }
175
176        // Preparation can download a managed harness. Keep the old worker and
177        // its controls available for all of it; reserve only for the swap.
178        let launch = self.current_worker_launch_config(session_id, &backend)?;
179        prepare_managed_harness_for_upgrade(executor, &backend, session_id, &binary, &launch)
180            .context("prepare the current managed harness before replacing the worker")?;
181        stage_worker_binary_for_upgrade(executor, &backend, session_id, &binary)
182            .context("stage the current worker while the old worker remains available")?;
183        let handle = manager
184            .wait_for_session(session_id, UPGRADE_LEASE_TIMEOUT)
185            .await?;
186        let harness = self.state.sessions[session_id].harness_kind;
187        let Some(mut lease) =
188            super::IdleWorkspaceLease::acquire_for_upgrade(&handle, harness).await?
189        else {
190            return Ok(WorkerUpgradeOutcome::Deferred);
191        };
192        if !lease.verify_for_upgrade().await? {
193            return Ok(WorkerUpgradeOutcome::Deferred);
194        }
195        install_staged_worker_binary(executor, &backend, session_id)
196            .context("install the prepared worker under its idle reservation")?;
197        replace_installed_worker_launch_config(executor, &backend, session_id, &launch)
198            .context("install the worker launch configuration under its idle reservation")?;
199
200        let restarted = self
201            .restart_worker_with_installed_binary(
202                session_id,
203                executor,
204                InstalledWorkerRestart {
205                    backend: &backend,
206                    worker_root: &worker_root,
207                    reconnect: &reconnect,
208                    launch: Some(&launch),
209                    prepared: true,
210                    messages: &RESTART_FOR_UPGRADE,
211                },
212            )
213            .await;
214        match restarted {
215            Ok(connection) => {
216                lease.finish_replacement(connection);
217                Ok(WorkerUpgradeOutcome::Upgraded { build: installed })
218            }
219            Err(error) => {
220                // Dropping the lease returns the actor to reconnecting on its
221                // own, which is the recovery for a half-finished restart.
222                drop(lease);
223                Err(error)
224            }
225        }
226    }
227
228    /// Stop the worker, install the binary this controller would provision,
229    /// start it and reconnect to the session it recovers.
230    pub(super) async fn restart_worker_with_installed_binary(
231        &self,
232        session_id: &str,
233        executor: &(impl CommandExecutor + Sync),
234        restart: InstalledWorkerRestart<'_>,
235    ) -> Result<StandaloneSession> {
236        let InstalledWorkerRestart {
237            backend,
238            worker_root,
239            reconnect,
240            launch,
241            prepared,
242            messages,
243        } = restart;
244        // A failed stop may leave the old worker alive, so it stays outside the
245        // marker below: only steps after a successful stop can leave the
246        // session with no worker at all.
247        stop_worker_after_target_recovery(executor, backend, session_id, worker_root)
248            .context(messages.stop)?;
249        // Everything up to the first successful connection either fails with no
250        // worker running or cannot tell: the marker covers all of it.
251        let mut connection = async {
252            // Copy through hel.next and rename. scp/cp onto a still-mapped hel
253            // fails with ETXTBSY ("dest open ... Failure") even after SIGKILL,
254            // and prepare_worker_files writes that path in place.
255            if !prepared {
256                let binary = worker_binary_for(backend, executor)?;
257                replace_installed_worker_binary(executor, backend, session_id, &binary)
258                    .context(messages.replace)?;
259                if let Some(launch) = launch {
260                    replace_installed_worker_launch_config(executor, backend, session_id, launch)
261                        .context("install the current Mjolnir worker launch configuration")?;
262                }
263            }
264            start_worker(executor, backend, worker_root).context(messages.start)?;
265            // Journal recovery runs before the daemon binds control.sock. A long
266            // kimi session can take well over the ordinary 30s startup window.
267            match connect_started_worker_with_timeout(
268                reconnect,
269                session_id,
270                executor,
271                backend,
272                worker_root,
273                WORKER_RESTART_TIMEOUT,
274            )
275            .await
276            {
277                Ok(connection) => Ok(connection),
278                Err(error) => Err(
279                    worker_probe_diagnosis(executor, backend, worker_root, error)
280                        .context(messages.connect),
281                ),
282            }
283        }
284        .await
285        .map_err(|error| error.context(WorkerRestartLeftNoWorker))?;
286        let project_memory = match self.project_memory_sync_target(session_id) {
287            Ok(target) => Some(target),
288            Err(error) => {
289                tracing::warn!(
290                    session_id,
291                    error = format!("{error:#}"),
292                    "{}",
293                    messages.project_memory
294                );
295                None
296            }
297        };
298        connection.set_project_memory_target(project_memory);
299        // A worker answered, so a failure from here on only means "no worker"
300        // when the transport to it died again.
301        async {
302            let checkpoint_only = connection.sync().await?.operational.checkpoint_only;
303            if let Some(launch) = launch {
304                anyhow::ensure!(
305                    checkpoint_only
306                        == (launch.run_mode
307                            == mj_core::worker_launch::WorkerRunMode::CheckpointOnly),
308                    "restarted worker did not enter the requested execution mode"
309                );
310            }
311            if checkpoint_only {
312                return Ok(());
313            }
314            wait_for_native_session(&mut connection, executor)
315                .await
316                .context(messages.native_session)?;
317            wait_for_idle_projection(&mut connection, WORKER_RESTART_TIMEOUT)
318                .await
319                .context("wait for ACP to go idle after worker restart")
320        }
321        .await
322        .map_err(mark_if_transport_died)?;
323        Ok(connection)
324    }
325}
326
327/// Wait until a restarted worker's projection stops moving and reports idle.
328///
329/// Three stable polls, not one: a worker that has just recovered its journal
330/// can report idle between two events it is still applying. "Idle" is the
331/// shared predicate, not the bare execution flag, so a foreground tool or a
332/// turn the projection has not caught up with keeps the restart from being
333/// declared ready underneath it. A synchronized active goal is the one
334/// deliberate exception: the restarted worker is meant to continue it.
335async fn wait_for_idle_projection(relay: &mut StandaloneSession, timeout: Duration) -> Result<()> {
336    let deadline = tokio::time::Instant::now() + timeout;
337    let mut last_ordinal = None;
338    let mut stable_polls = 0_u8;
339    loop {
340        let snapshot = relay.sync().await?;
341        let ordinal = snapshot.operational.latest_ordinal;
342        let goal_active =
343            snapshot.operational.goal.synchronized() && snapshot.operational.goal.active();
344        let idle = snapshot.operational.native_session_is_ready()
345            && (!snapshot.operational.has_work_in_flight() || goal_active);
346        if idle && (goal_active || last_ordinal == Some(ordinal)) {
347            stable_polls = stable_polls.saturating_add(1);
348            if stable_polls >= 3 {
349                return Ok(());
350            }
351        } else {
352            stable_polls = 0;
353        }
354        last_ordinal = Some(ordinal);
355        if snapshot.operational.execution == RelayExecutionState::Closed {
356            bail!("ACP runtime stopped before becoming idle");
357        }
358        if tokio::time::Instant::now() >= deadline {
359            bail!(
360                "ACP runtime did not become idle after worker restart (execution={:?}, ordinal={ordinal})",
361                snapshot.operational.execution
362            );
363        }
364        tokio::time::sleep(Duration::from_millis(200)).await;
365    }
366}
367
368#[cfg(test)]
369mod tests {
370    #[test]
371    fn a_dead_transport_after_reconnect_marks_the_restart_as_leaving_no_worker() {
372        let died = anyhow::Error::new(crate::worker_client::RelayTransportDead::new(
373            "relay proxy disconnected during attach",
374        ))
375        .context("wait for ACP session after restarting the worker for checkpoint");
376        assert!(super::WorkerRestartLeftNoWorker::marks(
377            &super::mark_if_transport_died(died)
378        ));
379
380        let slow = anyhow::anyhow!("timed out waiting for the ACP session")
381            .context("wait for ACP session after restarting the worker for checkpoint");
382        let slow = super::mark_if_transport_died(slow);
383        assert!(!super::WorkerRestartLeftNoWorker::marks(&slow), "{slow:#}");
384    }
385
386    use super::*;
387
388    #[cfg(unix)]
389    use std::sync::Mutex;
390
391    #[cfg(unix)]
392    use crate::targets::CommandOutput;
393
394    /// Fails every command after the first, so a restart gets past its stop and
395    /// then loses the worker it was replacing.
396    #[cfg(unix)]
397    struct StopSucceedsThenFails {
398        executed: Mutex<Vec<String>>,
399    }
400
401    #[cfg(unix)]
402    impl CommandExecutor for StopSucceedsThenFails {
403        fn execute(&self, command: &CommandSpec) -> Result<CommandOutput> {
404            let mut executed = self.executed.lock().expect("executed commands");
405            executed.push(command.program.clone());
406            if executed.len() == 1 {
407                return Ok(CommandOutput {
408                    status: 0,
409                    stdout: Vec::new(),
410                    stderr: Vec::new(),
411                });
412            }
413            Ok(CommandOutput {
414                status: 1,
415                stdout: Vec::new(),
416                stderr: b"no such target".to_vec(),
417            })
418        }
419    }
420
421    #[cfg(unix)]
422    struct FailingStop;
423
424    #[cfg(unix)]
425    impl CommandExecutor for FailingStop {
426        fn execute(&self, _command: &CommandSpec) -> Result<CommandOutput> {
427            Ok(CommandOutput {
428                status: 1,
429                stdout: Vec::new(),
430                stderr: b"permission denied".to_vec(),
431            })
432        }
433    }
434
435    #[cfg(unix)]
436    fn bare_restart_controller() -> Controller {
437        Controller {
438            config: mj_core::config::Config::default(),
439            state: mj_core::state::State::default(),
440        }
441    }
442
443    #[cfg(unix)]
444    async fn restart_error(
445        session_id: &str,
446        executor: &(impl CommandExecutor + Sync),
447    ) -> anyhow::Error {
448        let worker_root = format!("/tmp/mjolnir-restart-test/{session_id}");
449        let backend = targets::TargetLocator::LocalBare {
450            worker_root: worker_root.clone(),
451        };
452        let reconnect = CommandSpec::new("unused", std::iter::empty::<&str>());
453        let result = bare_restart_controller()
454            .restart_worker_with_installed_binary(
455                session_id,
456                executor,
457                InstalledWorkerRestart {
458                    backend: &backend,
459                    worker_root: &worker_root,
460                    reconnect: &reconnect,
461                    launch: None,
462                    prepared: false,
463                    messages: &RESTART_FOR_CHECKPOINT,
464                },
465            )
466            .await;
467        match result {
468            Ok(_) => panic!("a failing executor unexpectedly restarted the worker"),
469            Err(error) => error,
470        }
471    }
472
473    #[cfg(unix)]
474    #[tokio::test]
475    async fn a_restart_that_could_not_stop_the_worker_leaves_it_running() {
476        let error = restart_error("0123456789abcdef0123456789abcdef", &FailingStop).await;
477
478        assert!(
479            !WorkerRestartLeftNoWorker::marks(&error),
480            "a failed stop may leave the old worker alive: {error:#}"
481        );
482    }
483
484    #[cfg(unix)]
485    #[tokio::test]
486    async fn a_restart_that_stopped_the_worker_and_then_failed_is_marked() {
487        let executor = StopSucceedsThenFails {
488            executed: Mutex::new(Vec::new()),
489        };
490
491        let error = restart_error("0123456789abcdef0123456789abcdef", &executor).await;
492
493        assert!(
494            WorkerRestartLeftNoWorker::marks(&error),
495            "the worker was stopped and nothing replaced it: {error:#}"
496        );
497        assert!(
498            executor.executed.lock().expect("executed commands").len() > 1,
499            "the restart should have failed after its stop, not during it"
500        );
501    }
502
503    /// The three answers hello can produce, and what each means for the
504    /// worker's binary.
505    #[test]
506    fn only_a_matching_reported_build_counts_as_current() {
507        let installed = "a".repeat(64);
508
509        assert!(worker_runs_installed_build(Some(&installed), &installed));
510        assert!(!worker_runs_installed_build(
511            Some(&"b".repeat(64)),
512            &installed
513        ));
514        assert!(
515            !worker_runs_installed_build(None, &installed),
516            "a worker too old to report a build is older than this controller"
517        );
518    }
519}