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    if stop_notice == StopNotice::DaemonShutdown {
161        return Ok(());
162    }
163
164    if child.is_some() {
165        drain_optional_child(
166            &spec.module_id,
167            spec.protocol,
168            stop_notice,
169            registry,
170            runtime.forwarding.as_deref(),
171            snapshot,
172            &runtime.terminal_ring,
173            &runtime.spawn_events,
174            child,
175            drain_timeout,
176            ModuleState::Restarting,
177            Some(true),
178            &FailureContext::operator(),
179        )
180        .await?;
181    } else {
182        update_snapshot(snapshot, Some(&spec.module_id), |state| {
183            state.enabled = true;
184            state.state = ModuleState::Restarting;
185            clear_current_process_facts(state);
186        })?;
187        release_dead_registration(
188            registry,
189            runtime.forwarding.as_deref(),
190            snapshot,
191            &spec.module_id,
192            &runtime.failure_context(false),
193        )
194        .await?;
195    }
196
197    if reset_budget {
198        reset_restart_count(snapshot, &spec.module_id)?;
199    }
200    process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
201    schedule_respawn(
202        runtime,
203        snapshot,
204        &spec.module_id,
205        runtime.restart_policy.backoff,
206        RespawnKind::Spawn,
207        false,
208    )
209}
210
211pub(super) async fn reload_child(
212    spec: &ModuleSpec,
213    runtime: &SupervisorRuntimeConfig,
214    registry: &Registry,
215    process_liveness: &SupervisorProcessLiveness,
216    snapshot: &SharedSnapshot,
217    child: &mut Option<SupervisedChild>,
218) -> Result<(), SuperviseError> {
219    // Reload cycles a running module; it must not silently start a disabled one.
220    if !lock_snapshot(snapshot)?.enabled {
221        return Err(SuperviseError::Disabled {
222            module_id: spec.module_id.clone(),
223        });
224    }
225    let stop_notice = begin_forwarding_drain(
226        spec,
227        runtime,
228        registry,
229        snapshot,
230        Some(true),
231        RouteCloseReason::Reload,
232    )
233    .await?;
234    if stop_notice == StopNotice::DaemonShutdown {
235        return Err(SuperviseError::CommandClosed {
236            module_id: spec.module_id.clone(),
237        });
238    }
239
240    if child.is_some() {
241        drain_optional_child(
242            &spec.module_id,
243            spec.protocol,
244            stop_notice,
245            registry,
246            runtime.forwarding.as_deref(),
247            snapshot,
248            &runtime.terminal_ring,
249            &runtime.spawn_events,
250            child,
251            runtime.drain_timeout,
252            ModuleState::Restarting,
253            Some(true),
254            &FailureContext::operator(),
255        )
256        .await?;
257    } else {
258        update_snapshot(snapshot, Some(&spec.module_id), |state| {
259            state.enabled = true;
260            state.state = ModuleState::Restarting;
261            clear_current_process_facts(state);
262        })?;
263        release_dead_registration(
264            registry,
265            runtime.forwarding.as_deref(),
266            snapshot,
267            &spec.module_id,
268            &runtime.failure_context(false),
269        )
270        .await?;
271    }
272
273    reset_restart_count(snapshot, &spec.module_id)?;
274    process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
275    schedule_respawn(
276        runtime,
277        snapshot,
278        &spec.module_id,
279        runtime.restart_policy.backoff,
280        RespawnKind::Reload,
281        false,
282    )
283}
284
285pub(super) async fn finish_reload_child(
286    spec: &ModuleSpec,
287    runtime: &SupervisorRuntimeConfig,
288    registry: &Registry,
289    process_liveness: &SupervisorProcessLiveness,
290    snapshot: &SharedSnapshot,
291    child: &mut Option<SupervisedChild>,
292) -> Result<(), SuperviseError> {
293    process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
294    let next_child = match spawn_and_mark_running_async(spec, runtime, snapshot).await {
295        Ok(next_child) => next_child,
296        Err(error @ SuperviseError::ConfigDeliveryDeferred { .. }) => {
297            defer_config_spawn(
298                spec,
299                runtime,
300                snapshot,
301                RespawnKind::Reload,
302                &runtime.failure_context(runtime.recovery_is_daemon),
303            )?;
304            return Err(error);
305        }
306        Err(error @ SuperviseError::ConfigHeld { .. }) => {
307            let failure = runtime.failure_context(runtime.recovery_is_daemon);
308            if try_park_config_attempt(spec, runtime, snapshot, &failure, None)? {
309                return Err(error);
310            }
311            defer_config_spawn(spec, runtime, snapshot, RespawnKind::Reload, &failure)?;
312            return Err(SuperviseError::ConfigDeliveryDeferred {
313                module_id: spec.module_id.clone(),
314            });
315        }
316        Err(err) => {
317            return handle_reload_spawn_failure(
318                spec,
319                runtime,
320                process_liveness,
321                snapshot,
322                child,
323                format!("new child failed to spawn: {err}"),
324            )
325            .await;
326        }
327    };
328    *child = Some(next_child);
329
330    let wait_outcome = {
331        let active_child = child.as_mut().expect("new reload child was just stored");
332        wait_for_registration_after_reload(
333            registry,
334            &spec.module_id,
335            snapshot,
336            active_child,
337            REGISTRY_RELEASE_TIMEOUT,
338        )
339        .await?
340    };
341
342    match wait_outcome {
343        RegistrationWaitOutcome::Registered => {
344            child
345                .as_mut()
346                .expect("registered reload child")
347                .registration_deadline = None;
348            debug!(module_id = %spec.module_id, "supervised module reloaded and registered");
349            Ok(())
350        }
351        RegistrationWaitOutcome::Exited(exit_report) => {
352            containment::note_end_reason(
353                &runtime.child_roster.containment,
354                crate::live_children::ContainerEndReason::SpawnFailed,
355            );
356            if let Some(active_child) = child.as_mut() {
357                active_child.drain_stderr(&spec.module_id).await;
358            }
359            // Keep the exited child's roster guard until its terminal is written.
360            // Shutdown waits on that guard, not on the child Option used for respawn.
361            let mut exited_child = child.take().expect("exited reload child is still stored");
362            #[cfg(test)]
363            if let Some(gate) = &runtime.test_reload_exit_record_gate {
364                gate.reached.notify_one();
365                gate.resume.notified().await;
366            }
367            let result = handle_reload_child_registration_failure(
368                spec,
369                runtime,
370                registry,
371                process_liveness,
372                snapshot,
373                child,
374                ReloadRegistrationFailure {
375                    exit_report: registration_failure_exit_report(exit_report),
376                    cleanup_detail: exited_child.exit_cleanup_detail(None),
377                    reason: exited_child
378                        .spawn_failure
379                        .clone()
380                        .unwrap_or_else(|| "new child exited before registering".to_string()),
381                },
382            )
383            .await;
384            exited_child
385                .finish_exit(false)
386                .await
387                .map_err(|source| SuperviseError::Wait {
388                    module_id: spec.module_id.clone(),
389                    source,
390                })?;
391            result
392        }
393        RegistrationWaitOutcome::TimedOut => {
394            containment::note_end_reason(
395                &runtime.child_roster.containment,
396                crate::live_children::ContainerEndReason::SpawnFailed,
397            );
398            let mut timed_out_child = child
399                .take()
400                .expect("timed-out reload child is still running");
401            timed_out_child
402                .start_kill()
403                .map_err(|source| SuperviseError::Kill {
404                    module_id: spec.module_id.clone(),
405                    source,
406                })?;
407            let status = timed_out_child
408                .wait()
409                .await
410                .map_err(|source| SuperviseError::Wait {
411                    module_id: spec.module_id.clone(),
412                    source,
413                })?;
414            timed_out_child.drain_stderr(&spec.module_id).await;
415            let result = handle_reload_child_registration_failure(
416                spec,
417                runtime,
418                registry,
419                process_liveness,
420                snapshot,
421                child,
422                ReloadRegistrationFailure {
423                    exit_report: registration_failure_exit_report(classify_reaped_child_exit(
424                        snapshot,
425                        &timed_out_child,
426                        &status,
427                    )),
428                    cleanup_detail: timed_out_child.exit_cleanup_detail(None),
429                    reason: format!(
430                        "new child did not register within {:?}",
431                        REGISTRY_RELEASE_TIMEOUT
432                    ),
433                },
434            )
435            .await;
436            timed_out_child
437                .finish_exit(false)
438                .await
439                .map_err(|source| SuperviseError::Wait {
440                    module_id: spec.module_id.clone(),
441                    source,
442                })?;
443            result
444        }
445    }
446}
447
448#[allow(clippy::too_many_arguments)]
449pub(super) async fn set_child_enabled(
450    spec: &ModuleSpec,
451    runtime: &SupervisorRuntimeConfig,
452    registry: &Registry,
453    process_liveness: &SupervisorProcessLiveness,
454    snapshot: &SharedSnapshot,
455    child: &mut Option<SupervisedChild>,
456    enabled: bool,
457    failure: &FailureContext,
458) -> Result<bool, SuperviseError> {
459    set_child_enabled_with_budget_policy(
460        spec,
461        runtime,
462        registry,
463        process_liveness,
464        snapshot,
465        child,
466        enabled,
467        failure,
468        true,
469    )
470    .await
471}
472
473#[allow(clippy::too_many_arguments)]
474pub(super) async fn set_child_enabled_with_budget_policy(
475    spec: &ModuleSpec,
476    runtime: &SupervisorRuntimeConfig,
477    registry: &Registry,
478    process_liveness: &SupervisorProcessLiveness,
479    snapshot: &SharedSnapshot,
480    child: &mut Option<SupervisedChild>,
481    enabled: bool,
482    failure: &FailureContext,
483    reset_budget: bool,
484) -> Result<bool, SuperviseError> {
485    let (current_enabled, current_state, respawn_pending) = {
486        let state = lock_snapshot(snapshot)?;
487        (state.enabled, state.state, state.respawn_pending)
488    };
489    // `start` (enable on an already-enabled module) heals TERMINAL states instead
490    // of no-op'ing: a module whose restart budget exhausted (Failed) or that exited
491    // clean (Stopped) has no live process and no other in-band recovery — the
492    // operator's start is the explicit recovery act and resets the budget. Without
493    // this arm the only revival was subc-probe --supervisor-restart in a terminal,
494    // which the 2026-07-14 aft outage proved is a trap when the failed module is
495    // the one providing every agent's shell.
496    let revive_terminal = enabled
497        && current_enabled
498        && child.is_none()
499        && (matches!(current_state, ModuleState::Failed | ModuleState::Stopped)
500            || (current_state == ModuleState::Restarting && !respawn_pending));
501    if current_enabled == enabled && !revive_terminal {
502        return Ok(false);
503    }
504
505    if enabled {
506        update_snapshot(snapshot, Some(&spec.module_id), |state| {
507            state.enabled = true;
508            state.state = ModuleState::Starting;
509            clear_current_process_facts(state);
510        })?;
511        #[cfg(test)]
512        if runtime.test_seed_stale_facts_before_enable_spawn {
513            update_snapshot(snapshot, Some(&spec.module_id), |state| {
514                state.process_alive = true;
515                state.pid = Some(41);
516                state.spawned_at_ms = Some(42);
517                state.spawned_from = Some(PathBuf::from("/spawned/module"));
518                state.spawned_file_identity = Some(SpawnedFileIdentity {
519                    device: 43,
520                    inode: 44,
521                    #[cfg(windows)]
522                    windows_image: None,
523                });
524            })?;
525        }
526        release_dead_registration(
527            registry,
528            runtime.forwarding.as_deref(),
529            snapshot,
530            &spec.module_id,
531            failure,
532        )
533        .await?;
534        if reset_budget {
535            reset_restart_count(snapshot, &spec.module_id)?;
536        }
537        process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
538        let next_child = match spawn_and_mark_running_async(spec, runtime, snapshot).await {
539            Ok(next_child) => next_child,
540            Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
541                defer_config_spawn(spec, runtime, snapshot, RespawnKind::Spawn, failure)?;
542                return Ok(true);
543            }
544            Err(error @ SuperviseError::ConfigHeld { .. }) => {
545                if let Err(parking_error) = hold_config_spawn(spec, runtime, snapshot, failure) {
546                    process_liveness.untrack_if_current(&spec.module_id, snapshot);
547                    return Err(parking_error);
548                }
549                return Err(error);
550            }
551            Err(err) => {
552                fail_snapshot(snapshot, Some(&spec.module_id), None, failure);
553                process_liveness.untrack_if_current(&spec.module_id, snapshot);
554                return Err(err);
555            }
556        };
557        *child = Some(next_child);
558        debug!(module_id = %spec.module_id, "supervised module enabled");
559        Ok(true)
560    } else {
561        update_snapshot(snapshot, Some(&spec.module_id), |state| {
562            state.config_hold_parked = false;
563            state.config_hold_daemon_initiated = false;
564            state.config_hold_approval = None;
565        })?;
566        let stop_notice = begin_forwarding_drain_if_configured(
567            spec,
568            runtime,
569            registry,
570            snapshot,
571            Some(false),
572            RouteCloseReason::Disable,
573        )
574        .await?;
575        containment::note_end_reason(
576            &runtime.child_roster.containment,
577            crate::live_children::ContainerEndReason::Disable,
578        );
579        drain_optional_child(
580            &spec.module_id,
581            spec.protocol,
582            stop_notice,
583            registry,
584            runtime.forwarding.as_deref(),
585            snapshot,
586            &runtime.terminal_ring,
587            &runtime.spawn_events,
588            child,
589            runtime.drain_timeout,
590            ModuleState::Disabled,
591            Some(false),
592            failure,
593        )
594        .await?;
595        debug!(module_id = %spec.module_id, "supervised module disabled");
596        Ok(true)
597    }
598}