Skip to main content

subc_daemon/supervise/
restart.rs

1use super::*;
2
3#[cfg(test)]
4#[derive(Debug, Default)]
5pub(super) struct ReloadExitRecordGate {
6    pub(super) reached: tokio::sync::Notify,
7    pub(super) resume: tokio::sync::Notify,
8}
9
10impl SupervisedModule {
11    pub async fn restart(&self, drain_timeout_ms: Option<u64>) -> Result<(), SuperviseError> {
12        self.restart_requested(drain_timeout_ms, None).await
13    }
14
15    pub(crate) async fn restart_requested(
16        &self,
17        drain_timeout_ms: Option<u64>,
18        requester: Option<Principal>,
19    ) -> Result<(), SuperviseError> {
20        let queued_at = Instant::now();
21        let received_at_generation = lock_snapshot(&self.inner.snapshot)?.spawn_generation;
22        let (reply_tx, reply_rx) = oneshot::channel();
23        self.inner
24            .commands
25            .send(SupervisorCommand::Restart {
26                requester,
27                drain_timeout_ms,
28                received_at_generation,
29                queued_at,
30                reply: reply_tx,
31            })
32            .await
33            .map_err(|_| SuperviseError::CommandClosed {
34                module_id: self.inner.module_id.clone(),
35            })?;
36        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
37            module_id: self.inner.module_id.clone(),
38        })?
39    }
40}
41
42impl SupervisedModule {
43    pub async fn reload(&self) -> Result<(), SuperviseError> {
44        self.reload_requested(None).await
45    }
46
47    pub(crate) async fn reload_requested(
48        &self,
49        requester: Option<Principal>,
50    ) -> Result<(), SuperviseError> {
51        let (reply_tx, reply_rx) = oneshot::channel();
52        self.inner
53            .commands
54            .send(SupervisorCommand::Reload {
55                requester,
56                reply: reply_tx,
57            })
58            .await
59            .map_err(|_| SuperviseError::CommandClosed {
60                module_id: self.inner.module_id.clone(),
61            })?;
62        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
63            module_id: self.inner.module_id.clone(),
64        })?
65    }
66
67    pub async fn set_enabled(&self, enabled: bool) -> Result<bool, SuperviseError> {
68        self.set_enabled_requested(enabled, None).await
69    }
70
71    pub(crate) async fn set_enabled_requested(
72        &self,
73        enabled: bool,
74        requester: Option<Principal>,
75    ) -> Result<bool, SuperviseError> {
76        self.set_enabled_with_budget_policy(enabled, requester, true)
77            .await
78    }
79
80    pub(crate) async fn release_config_hold(&self) -> Result<bool, SuperviseError> {
81        self.set_enabled_with_budget_policy(true, None, false).await
82    }
83}
84
85impl SupervisedModule {
86    async fn set_enabled_with_budget_policy(
87        &self,
88        enabled: bool,
89        requester: Option<Principal>,
90        reset_budget: bool,
91    ) -> Result<bool, SuperviseError> {
92        let (reply_tx, reply_rx) = oneshot::channel();
93        self.inner
94            .commands
95            .send(SupervisorCommand::SetEnabled {
96                requester,
97                enabled,
98                reset_budget,
99                reply: reply_tx,
100            })
101            .await
102            .map_err(|_| SuperviseError::CommandClosed {
103                module_id: self.inner.module_id.clone(),
104            })?;
105        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
106            module_id: self.inner.module_id.clone(),
107        })?
108    }
109}
110
111pub(super) async fn restart_child(
112    spec: &ModuleSpec,
113    runtime: &SupervisorRuntimeConfig,
114    registry: &Registry,
115    process_liveness: &SupervisorProcessLiveness,
116    snapshot: &SharedSnapshot,
117    child: &mut Option<SupervisedChild>,
118    drain_timeout: Duration,
119) -> Result<(), SuperviseError> {
120    restart_child_with_budget_policy(
121        spec,
122        runtime,
123        registry,
124        process_liveness,
125        snapshot,
126        child,
127        drain_timeout,
128        true,
129    )
130    .await
131}
132
133#[allow(clippy::too_many_arguments)]
134pub(super) async fn restart_child_with_budget_policy(
135    spec: &ModuleSpec,
136    runtime: &SupervisorRuntimeConfig,
137    registry: &Registry,
138    process_liveness: &SupervisorProcessLiveness,
139    snapshot: &SharedSnapshot,
140    child: &mut Option<SupervisedChild>,
141    drain_timeout: Duration,
142    reset_budget: bool,
143) -> Result<(), SuperviseError> {
144    // Restart cycles a running module; it must not silently start a disabled one.
145    if !lock_snapshot(snapshot)?.enabled {
146        return Err(SuperviseError::Disabled {
147            module_id: spec.module_id.clone(),
148        });
149    }
150    let stop_notice = begin_forwarding_drain_with_timeout(
151        spec,
152        runtime,
153        registry,
154        snapshot,
155        None,
156        RouteCloseReason::Restart,
157        drain_timeout,
158    )
159    .await?;
160
161    if child.is_some() {
162        drain_optional_child(
163            &spec.module_id,
164            spec.protocol,
165            stop_notice,
166            registry,
167            runtime.forwarding.as_deref(),
168            snapshot,
169            &runtime.terminal_ring,
170            &runtime.spawn_events,
171            child,
172            drain_timeout,
173            ModuleState::Restarting,
174            Some(true),
175            &FailureContext::operator(),
176        )
177        .await?;
178    } else {
179        update_snapshot(snapshot, Some(&spec.module_id), |state| {
180            state.enabled = true;
181            state.state = ModuleState::Restarting;
182            clear_current_process_facts(state);
183        })?;
184        release_dead_registration(
185            registry,
186            runtime.forwarding.as_deref(),
187            snapshot,
188            &spec.module_id,
189            &runtime.failure_context(false),
190        )
191        .await?;
192    }
193
194    if reset_budget {
195        reset_restart_count(snapshot, &spec.module_id)?;
196    }
197    process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
198    schedule_respawn(
199        runtime,
200        snapshot,
201        &spec.module_id,
202        runtime.restart_policy.backoff,
203        RespawnKind::Spawn,
204        false,
205    )
206}
207
208pub(super) async fn reload_child(
209    spec: &ModuleSpec,
210    runtime: &SupervisorRuntimeConfig,
211    registry: &Registry,
212    process_liveness: &SupervisorProcessLiveness,
213    snapshot: &SharedSnapshot,
214    child: &mut Option<SupervisedChild>,
215) -> Result<(), SuperviseError> {
216    // Reload cycles a running module; it must not silently start a disabled one.
217    if !lock_snapshot(snapshot)?.enabled {
218        return Err(SuperviseError::Disabled {
219            module_id: spec.module_id.clone(),
220        });
221    }
222    let stop_notice = begin_forwarding_drain(
223        spec,
224        runtime,
225        registry,
226        snapshot,
227        Some(true),
228        RouteCloseReason::Reload,
229    )
230    .await?;
231
232    if child.is_some() {
233        drain_optional_child(
234            &spec.module_id,
235            spec.protocol,
236            stop_notice,
237            registry,
238            runtime.forwarding.as_deref(),
239            snapshot,
240            &runtime.terminal_ring,
241            &runtime.spawn_events,
242            child,
243            runtime.drain_timeout,
244            ModuleState::Restarting,
245            Some(true),
246            &FailureContext::operator(),
247        )
248        .await?;
249    } else {
250        update_snapshot(snapshot, Some(&spec.module_id), |state| {
251            state.enabled = true;
252            state.state = ModuleState::Restarting;
253            clear_current_process_facts(state);
254        })?;
255        release_dead_registration(
256            registry,
257            runtime.forwarding.as_deref(),
258            snapshot,
259            &spec.module_id,
260            &runtime.failure_context(false),
261        )
262        .await?;
263    }
264
265    reset_restart_count(snapshot, &spec.module_id)?;
266    process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
267    schedule_respawn(
268        runtime,
269        snapshot,
270        &spec.module_id,
271        runtime.restart_policy.backoff,
272        RespawnKind::Reload,
273        false,
274    )
275}
276
277pub(super) async fn finish_reload_child(
278    spec: &ModuleSpec,
279    runtime: &SupervisorRuntimeConfig,
280    registry: &Registry,
281    process_liveness: &SupervisorProcessLiveness,
282    snapshot: &SharedSnapshot,
283    child: &mut Option<SupervisedChild>,
284) -> Result<(), SuperviseError> {
285    process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
286    let next_child = match spawn_and_mark_running_async(spec, runtime, snapshot).await {
287        Ok(next_child) => next_child,
288        Err(error @ SuperviseError::ConfigDeliveryDeferred { .. }) => {
289            defer_config_spawn(
290                spec,
291                runtime,
292                snapshot,
293                RespawnKind::Reload,
294                &runtime.failure_context(runtime.recovery_is_daemon),
295            )?;
296            return Err(error);
297        }
298        Err(error @ SuperviseError::ConfigHeld { .. }) => {
299            let failure = runtime.failure_context(runtime.recovery_is_daemon);
300            if try_park_config_attempt(spec, runtime, snapshot, &failure, None)? {
301                return Err(error);
302            }
303            defer_config_spawn(spec, runtime, snapshot, RespawnKind::Reload, &failure)?;
304            return Err(SuperviseError::ConfigDeliveryDeferred {
305                module_id: spec.module_id.clone(),
306            });
307        }
308        Err(err) => {
309            return handle_reload_spawn_failure(
310                spec,
311                runtime,
312                process_liveness,
313                snapshot,
314                child,
315                format!("new child failed to spawn: {err}"),
316            )
317            .await;
318        }
319    };
320    *child = Some(next_child);
321
322    let wait_outcome = {
323        let active_child = child.as_mut().expect("new reload child was just stored");
324        wait_for_registration_after_reload(
325            registry,
326            &spec.module_id,
327            snapshot,
328            active_child,
329            REGISTRY_RELEASE_TIMEOUT,
330        )
331        .await?
332    };
333
334    match wait_outcome {
335        RegistrationWaitOutcome::Registered => {
336            child
337                .as_mut()
338                .expect("registered reload child")
339                .registration_deadline = None;
340            debug!(module_id = %spec.module_id, "supervised module reloaded and registered");
341            Ok(())
342        }
343        RegistrationWaitOutcome::Exited(exit_report) => {
344            if let Some(active_child) = child.as_mut() {
345                active_child.drain_stderr(&spec.module_id).await;
346            }
347            // Keep the exited child's roster guard until its terminal is written.
348            // Shutdown waits on that guard, not on the child Option used for respawn.
349            let mut exited_child = child.take().expect("exited reload child is still stored");
350            #[cfg(test)]
351            if let Some(gate) = &runtime.test_reload_exit_record_gate {
352                gate.reached.notify_one();
353                gate.resume.notified().await;
354            }
355            let result = handle_reload_child_registration_failure(
356                spec,
357                runtime,
358                registry,
359                process_liveness,
360                snapshot,
361                child,
362                ReloadRegistrationFailure {
363                    exit_report: registration_failure_exit_report(exit_report),
364                    cleanup_detail: exited_child.exit_cleanup_detail(None),
365                    reason: exited_child
366                        .spawn_failure
367                        .clone()
368                        .unwrap_or_else(|| "new child exited before registering".to_string()),
369                },
370            )
371            .await;
372            exited_child
373                .finish_exit(false)
374                .await
375                .map_err(|source| SuperviseError::Wait {
376                    module_id: spec.module_id.clone(),
377                    source,
378                })?;
379            result
380        }
381        RegistrationWaitOutcome::TimedOut => {
382            let mut timed_out_child = child
383                .take()
384                .expect("timed-out reload child is still running");
385            timed_out_child
386                .start_kill()
387                .map_err(|source| SuperviseError::Kill {
388                    module_id: spec.module_id.clone(),
389                    source,
390                })?;
391            let status = timed_out_child
392                .wait()
393                .await
394                .map_err(|source| SuperviseError::Wait {
395                    module_id: spec.module_id.clone(),
396                    source,
397                })?;
398            timed_out_child.drain_stderr(&spec.module_id).await;
399            let result = handle_reload_child_registration_failure(
400                spec,
401                runtime,
402                registry,
403                process_liveness,
404                snapshot,
405                child,
406                ReloadRegistrationFailure {
407                    exit_report: registration_failure_exit_report(classify_reaped_child_exit(
408                        snapshot,
409                        &timed_out_child,
410                        &status,
411                    )),
412                    cleanup_detail: timed_out_child.exit_cleanup_detail(None),
413                    reason: format!(
414                        "new child did not register within {:?}",
415                        REGISTRY_RELEASE_TIMEOUT
416                    ),
417                },
418            )
419            .await;
420            timed_out_child
421                .finish_exit(false)
422                .await
423                .map_err(|source| SuperviseError::Wait {
424                    module_id: spec.module_id.clone(),
425                    source,
426                })?;
427            result
428        }
429    }
430}
431
432#[allow(clippy::too_many_arguments)]
433pub(super) async fn set_child_enabled(
434    spec: &ModuleSpec,
435    runtime: &SupervisorRuntimeConfig,
436    registry: &Registry,
437    process_liveness: &SupervisorProcessLiveness,
438    snapshot: &SharedSnapshot,
439    child: &mut Option<SupervisedChild>,
440    enabled: bool,
441    failure: &FailureContext,
442) -> Result<bool, SuperviseError> {
443    set_child_enabled_with_budget_policy(
444        spec,
445        runtime,
446        registry,
447        process_liveness,
448        snapshot,
449        child,
450        enabled,
451        failure,
452        true,
453    )
454    .await
455}
456
457#[allow(clippy::too_many_arguments)]
458pub(super) async fn set_child_enabled_with_budget_policy(
459    spec: &ModuleSpec,
460    runtime: &SupervisorRuntimeConfig,
461    registry: &Registry,
462    process_liveness: &SupervisorProcessLiveness,
463    snapshot: &SharedSnapshot,
464    child: &mut Option<SupervisedChild>,
465    enabled: bool,
466    failure: &FailureContext,
467    reset_budget: bool,
468) -> Result<bool, SuperviseError> {
469    let (current_enabled, current_state, respawn_pending) = {
470        let state = lock_snapshot(snapshot)?;
471        (state.enabled, state.state, state.respawn_pending)
472    };
473    // `start` (enable on an already-enabled module) heals TERMINAL states instead
474    // of no-op'ing: a module whose restart budget exhausted (Failed) or that exited
475    // clean (Stopped) has no live process and no other in-band recovery — the
476    // operator's start is the explicit recovery act and resets the budget. Without
477    // this arm the only revival was subc-probe --supervisor-restart in a terminal,
478    // which the 2026-07-14 aft outage proved is a trap when the failed module is
479    // the one providing every agent's shell.
480    let revive_terminal = enabled
481        && current_enabled
482        && child.is_none()
483        && (matches!(current_state, ModuleState::Failed | ModuleState::Stopped)
484            || (current_state == ModuleState::Restarting && !respawn_pending));
485    if current_enabled == enabled && !revive_terminal {
486        return Ok(false);
487    }
488
489    if enabled {
490        update_snapshot(snapshot, Some(&spec.module_id), |state| {
491            state.enabled = true;
492            state.state = ModuleState::Starting;
493            clear_current_process_facts(state);
494        })?;
495        #[cfg(test)]
496        if runtime.test_seed_stale_facts_before_enable_spawn {
497            update_snapshot(snapshot, Some(&spec.module_id), |state| {
498                state.process_alive = true;
499                state.pid = Some(41);
500                state.spawned_at_ms = Some(42);
501                state.spawned_from = Some(PathBuf::from("/spawned/module"));
502                state.spawned_file_identity = Some(SpawnedFileIdentity {
503                    device: 43,
504                    inode: 44,
505                    #[cfg(windows)]
506                    windows_image: None,
507                });
508            })?;
509        }
510        release_dead_registration(
511            registry,
512            runtime.forwarding.as_deref(),
513            snapshot,
514            &spec.module_id,
515            failure,
516        )
517        .await?;
518        if reset_budget {
519            reset_restart_count(snapshot, &spec.module_id)?;
520        }
521        process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
522        let next_child = match spawn_and_mark_running_async(spec, runtime, snapshot).await {
523            Ok(next_child) => next_child,
524            Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
525                defer_config_spawn(spec, runtime, snapshot, RespawnKind::Spawn, failure)?;
526                return Ok(true);
527            }
528            Err(error @ SuperviseError::ConfigHeld { .. }) => {
529                if let Err(parking_error) = hold_config_spawn(spec, runtime, snapshot, failure) {
530                    process_liveness.untrack_if_current(&spec.module_id, snapshot);
531                    return Err(parking_error);
532                }
533                return Err(error);
534            }
535            Err(err) => {
536                fail_snapshot(snapshot, Some(&spec.module_id), None, failure);
537                process_liveness.untrack_if_current(&spec.module_id, snapshot);
538                return Err(err);
539            }
540        };
541        *child = Some(next_child);
542        debug!(module_id = %spec.module_id, "supervised module enabled");
543        Ok(true)
544    } else {
545        update_snapshot(snapshot, Some(&spec.module_id), |state| {
546            state.config_hold_parked = false;
547            state.config_hold_daemon_initiated = false;
548            state.config_hold_approval = None;
549        })?;
550        let stop_notice = begin_forwarding_drain_if_configured(
551            spec,
552            runtime,
553            registry,
554            snapshot,
555            Some(false),
556            RouteCloseReason::Disable,
557        )
558        .await?;
559        drain_optional_child(
560            &spec.module_id,
561            spec.protocol,
562            stop_notice,
563            registry,
564            runtime.forwarding.as_deref(),
565            snapshot,
566            &runtime.terminal_ring,
567            &runtime.spawn_events,
568            child,
569            runtime.drain_timeout,
570            ModuleState::Disabled,
571            Some(false),
572            failure,
573        )
574        .await?;
575        debug!(module_id = %spec.module_id, "supervised module disabled");
576        Ok(true)
577    }
578}