Skip to main content

subc_daemon/supervise/
exit.rs

1use super::*;
2
3/// How long a restart waits per pipe for queued capture to finish.
4///
5/// A reader and writer still running at the bound are left running. Stderr
6/// stays in the exited process's section of the ring. Its tail reports
7/// `Incomplete` until EOF has reached the writer, and stays incomplete if
8/// backpressure forced capture to drop lines. Late output from either pipe
9/// can reach the capture file after the successor starts.
10const STDERR_PUMP_DRAIN_TIMEOUT: Duration = Duration::from_millis(250);
11
12impl SupervisedChild {
13    pub(super) fn id(&self) -> Option<u32> {
14        Some(self.pid)
15    }
16
17    pub(super) fn process_identity(&self) -> Option<ProcessIdentity> {
18        self.process_identity
19    }
20
21    pub(super) fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
22        let result = self.child.try_wait();
23        if !matches!(result, Ok(None)) {
24            self.retire_registration();
25            #[cfg(any(unix, windows))]
26            self.registration_channel.take();
27            if let Some(binding) = &self._program_binding {
28                binding.retire();
29            }
30        }
31        result
32    }
33
34    pub(super) async fn wait(&mut self) -> io::Result<ExitStatus> {
35        #[cfg(target_os = "macos")]
36        self.confirm_privacy_exec().await;
37        // The roster entry is NOT released here. A daemon shutdown waits for the
38        // roster to empty and then exits the process, so releasing at the reap
39        // let it exit before the exit handler wrote this child's terminal record
40        // (the stderr drain and snapshot update sit in between), and the
41        // shutdown's own `daemon_shutdown` record was intermittently lost. The
42        // caller releases it after recording the exit (`release_roster`), and
43        // dropping the handle releases it too.
44        let result = self.child.wait().await;
45        self.retire_registration();
46        #[cfg(any(unix, windows))]
47        self.registration_channel.take();
48        // All plain and swap waits pass here. Revoke the reaped child's nonce
49        // before cgroup cleanup, stderr draining or exit observation can await.
50        if let Some(binding) = &self._program_binding {
51            binding.retire();
52        }
53        #[cfg(all(test, target_os = "linux"))]
54        if let Some(binding) = &self._program_binding {
55            binding.pause_after_wait_for_test().await;
56        }
57        result
58    }
59
60    pub(super) async fn finish_exit(&mut self, carry: bool) -> io::Result<()> {
61        self.retire_registration();
62        // Idempotent fallback for cleanup paths that did not call wait.
63        if let Some(binding) = self._program_binding.take() {
64            binding.retire();
65        }
66        if !carry && self.child.container().is_some() {
67            self.child.terminate_container().await;
68        }
69        self.child.reap().await?;
70        #[cfg(target_os = "linux")]
71        self.cleanup_ordinary_cgroup().await;
72        self.release_roster();
73        Ok(())
74    }
75}
76
77impl SupervisedChild {
78    /// Releases the leader's roster entry after recording and finalizing its
79    /// exit. A carried container retains its separate roster entry and, for a
80    /// Unix process group, its unreaped first leader that reserves the group ID.
81    pub(super) fn release_roster(&mut self) {
82        let _guard = self.roster_guard.take();
83        #[cfg(target_os = "linux")]
84        if let (Some(unresolved), Some(guard)) = (self.unresolved_cgroup.take(), _guard) {
85            unresolved.retain(guard);
86        }
87    }
88
89    pub(super) fn exit_cleanup_detail(&self, detail: Option<String>) -> Option<String> {
90        #[cfg(unix)]
91        let detail = if self.late_output_lost {
92            Some(match detail {
93                Some(detail) => {
94                    format!("{detail}; late child output lost: capture pipes did not close")
95                }
96                None => "late child output lost: capture pipes did not close".into(),
97            })
98        } else {
99            detail
100        };
101        #[cfg(target_os = "linux")]
102        if let Some(unresolved) = &self.unresolved_cgroup {
103            return Some(match detail {
104                Some(detail) => format!("{detail}; {}", unresolved.detail()),
105                None => unresolved.detail(),
106            });
107        }
108        detail
109    }
110}
111
112impl SupervisedChild {
113    /// Kill the child and, where containment is available, its process tree.
114    ///
115    /// `Child::kill` is `TerminateProcess` scoped to one pid, so a module with a
116    /// helper process leaked the helper — the Synapse embedding module's CUDA
117    /// worker holds the GPU allocation, so the leak cost VRAM until the next
118    /// restart of something else. Terminating the job reaches grandchildren that
119    /// a tree walk cannot, including one whose parent has already exited and
120    /// been reparented away.
121    ///
122    /// Best-effort like `request_graceful_stop`: a job failure is logged and the
123    /// direct-child kill still decides the outcome, so containment can never
124    /// change whether a module is reported as stopped.
125    pub(super) fn start_kill(&mut self) -> io::Result<()> {
126        self.retire_registration();
127        if let Some(container) = self.child.container() {
128            container.hard_kill();
129            return self.kill_leader();
130        }
131        #[cfg(windows)]
132        if let Some(job) = &self.job {
133            if let Err(error) = job.lock().unwrap_or_else(|p| p.into_inner()).terminate() {
134                debug!(
135                    error = %error,
136                    "job termination failed; the direct-child kill still owns the outcome"
137                );
138            }
139        }
140        #[cfg(target_os = "linux")]
141        kill_module_cgroup(self.cgroup_placement.as_ref(), &self.module_id);
142        self.child.start_kill()
143    }
144
145    pub(super) fn kill_leader(&mut self) -> io::Result<()> {
146        self.retire_registration();
147        self.child.start_kill()
148    }
149
150    pub(super) fn start_admission_kill(&mut self) -> io::Result<()> {
151        self.retire_registration();
152        #[cfg(windows)]
153        let result = {
154            // Preserve the leader's distinctive status before ending the whole
155            // container/job; descendants must not wait for exit finalization.
156            let result = self
157                .spawned_file_identity
158                .as_ref()
159                .and_then(|identity| identity.windows_image.as_ref())
160                .ok_or_else(|| io::Error::other("admission child handle unavailable"))
161                .and_then(|image| {
162                    image.process().terminate_with_exit_code(
163                        admission_exit::WINDOWS_ADMISSION_KILL_EXIT_CODE as u32,
164                    )
165                });
166            if let Some(container) = self.child.container() {
167                container.hard_kill();
168            } else if let Some(job) = &self.job {
169                if let Err(error) = job.lock().unwrap_or_else(|p| p.into_inner()).terminate() {
170                    debug!(%error, "job termination failed after admission leader termination");
171                }
172            }
173            result
174        };
175        #[cfg(not(windows))]
176        let result = self.start_kill().map(|()| true);
177        self.admission_kill_sent |= result?;
178        Ok(())
179    }
180
181    pub(super) async fn drain_stderr(&mut self, module_id: &str) {
182        #[cfg(unix)]
183        if self.child.plain_group.is_some() {
184            self.drain_plain_capture(module_id).await;
185            return;
186        }
187        #[cfg(target_os = "linux")]
188        self.cleanup_ordinary_cgroup().await;
189        if let Some(pump) = self.stdout_pump.take() {
190            settle_stdout_pump(module_id, pump, STDERR_PUMP_DRAIN_TIMEOUT).await;
191        }
192
193        let Some(pump) = self.stderr_pump.take() else {
194            return;
195        };
196        settle_stderr_pump(
197            module_id,
198            &self.stderr_ring,
199            pump,
200            STDERR_PUMP_DRAIN_TIMEOUT,
201        )
202        .await;
203    }
204}
205
206/// Bound the restart's wait. Dropping the completion future does not stop
207/// the reader or the capture writer.
208pub(super) async fn settle_stdout_pump<E: std::fmt::Display>(
209    module_id: &str,
210    pump: impl std::future::Future<Output = Result<(), E>>,
211    bound: Duration,
212) {
213    match timeout(bound, pump).await {
214        Ok(Ok(())) => {}
215        Ok(Err(error)) => {
216            warn!(module_id, error = %error, "stdout pump ended unexpectedly");
217        }
218        Err(_) => {
219            warn!(
220                module_id,
221                waited = ?bound,
222                "stdout of the exited process has not finished capture; the reader and writer continue without delaying restart"
223            );
224        }
225    }
226}
227
228/// Retire an exited process's stderr reader and allow up to `bound` for its
229/// output to reach the ring and sink. A late reader or writer keeps going,
230/// and the tail reads `Incomplete` until it finishes.
231pub(super) async fn settle_stderr_pump<E: std::fmt::Display>(
232    module_id: &str,
233    ring: &Arc<Mutex<StderrRing>>,
234    pump: StderrPump<impl std::future::Future<Output = Result<(), E>>>,
235    bound: Duration,
236) {
237    let lock = || ring.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
238    let StderrPump { task, generation } = pump;
239    lock().retire_pump(generation);
240    match timeout(bound, task).await {
241        Ok(Ok(())) => {}
242        Ok(Err(err)) => {
243            let mut ring = lock();
244            ring.mark_incomplete_from(generation, format!("stderr pump ended unexpectedly: {err}"));
245            ring.finish_pump(generation);
246            warn!(module_id, error = %err, "stderr pump ended before clean EOF");
247        }
248        Err(_) => {
249            lock().mark_pump_late(
250                generation,
251                format!(
252                    "stderr of the exited process had not reached EOF or finished queued capture \
253                     {bound:?} after it was retired; retained lines go in that process's section"
254                ),
255            );
256            warn!(
257                module_id,
258                waited = ?bound,
259                "stderr of the exited process has not finished capture; the reader and writer continue without delaying restart"
260            );
261        }
262    }
263}
264
265impl SupervisorHandle {
266    /// Arm the one-shot marker for the module process that this caller
267    /// deliberately initiated severance against. Generic connection teardown
268    /// must not call this:
269    /// a surviving process would otherwise retain an exemption for a later
270    /// genuine crash.
271    pub fn record_deliberate_severance(&self, module_id: &str) -> Result<bool, SuperviseError> {
272        let Some(module) = self.get(module_id) else {
273            return Ok(false);
274        };
275        let snapshot = lock_snapshot(&module.inner.snapshot)?;
276        let Some((pid, start_time)) = snapshot.pid.zip(snapshot.process_start_time) else {
277            return Ok(false);
278        };
279        drop(snapshot);
280        module.record_deliberate_severance(ProcessIdentity { pid, start_time })
281    }
282}
283
284impl SupervisedModule {
285    pub(crate) fn record_deliberate_severance(
286        &self,
287        identity: ProcessIdentity,
288    ) -> Result<bool, SuperviseError> {
289        let mut snapshot = lock_snapshot(&self.inner.snapshot)?;
290        if snapshot.pid != Some(identity.pid)
291            || snapshot.process_start_time != Some(identity.start_time)
292        {
293            return Ok(false);
294        }
295        snapshot.deliberate_severance = Some(identity);
296        Ok(true)
297    }
298}
299
300#[allow(clippy::too_many_arguments)]
301#[cfg(test)]
302pub(super) async fn on_child_exit(
303    spec: &ModuleSpec,
304    policy: RestartPolicy,
305    registry: &Registry,
306    snapshot: &SharedSnapshot,
307    terminal_ring: &Arc<Mutex<TerminalRing>>,
308    spawn_events: &SpawnEventFeed,
309    roster: &ChildRoster,
310    exit_report: ExitReport,
311    daemon_initiated: bool,
312) -> NextAction {
313    on_child_exit_with_detail(
314        spec,
315        policy,
316        registry,
317        snapshot,
318        terminal_ring,
319        spawn_events,
320        roster,
321        exit_report,
322        daemon_initiated,
323        None,
324    )
325    .await
326}
327
328#[allow(clippy::too_many_arguments)]
329pub(super) async fn on_child_exit_with_detail(
330    spec: &ModuleSpec,
331    policy: RestartPolicy,
332    registry: &Registry,
333    snapshot: &SharedSnapshot,
334    terminal_ring: &Arc<Mutex<TerminalRing>>,
335    spawn_events: &SpawnEventFeed,
336    roster: &ChildRoster,
337    exit_report: ExitReport,
338    daemon_initiated: bool,
339    detail: Option<String>,
340) -> NextAction {
341    // Once the daemon has begun shutting down, no exit is a crash to recover
342    // from: the module is exiting because the daemon is going away (EOF on its
343    // connection, or a service manager signalling the whole cgroup). Record it
344    // as such and never schedule a respawn, which would only start a process
345    // for the shutdown to end again.
346    if roster.is_closed() {
347        return on_child_exit_during_daemon_shutdown(
348            spec,
349            registry,
350            snapshot,
351            terminal_ring,
352            spawn_events,
353            exit_report,
354            detail,
355        )
356        .await;
357    }
358    // Deliberate stops the supervisor asks for (operator stop, disable,
359    // restart, reload, swap, a health restart, a drain that runs out of budget)
360    // takes the child out of the supervise loop and reaps it in
361    // `drain_child_to_state`, and daemon shutdown is handled above. So an exit
362    // that reaches this point is either unrequested or a first-HELLO timeout,
363    // which is deliberately classified as a crash even after a clean TERM exit.
364    //
365    // For a subc-wire module a clean exit is still a stop: those modules are
366    // written to re-raise SIGTERM, so a stray outside signal already reads as a
367    // crash, and exiting 0 is a deliberate choice the module made. A
368    // `protocol: "none"` module is a stock program we cannot change, and many
369    // of them (nats-server among them) exit 0 on SIGTERM. Treating that as a
370    // stop would leave the module down for good after any stray signal, so it
371    // goes through the crash path instead: it spends restart budget, respawns
372    // with the crash backoff, and ends `failed` when the budget runs out.
373    let unrequested_clean_exit_of_protocol_none = exit_report.kind == ExitKind::Clean
374        && running_protocol(spec, snapshot) == ModuleProtocol::None;
375    match exit_report.kind {
376        ExitKind::Clean if !unrequested_clean_exit_of_protocol_none => {
377            info!(
378                module_id = %spec.module_id,
379                exit_code = ?exit_report.code,
380                exit_signal = ?exit_report.signal,
381                "supervised module exited cleanly"
382            );
383            if let Err(err) = publish_after_terminal_record(
384                &spec.module_id,
385                || {
386                    record_terminal_with_detail(
387                        &spec.module_id,
388                        terminal_ring,
389                        spawn_events,
390                        &exit_report,
391                        TerminalDisposition::Stopped,
392                        detail,
393                    )
394                },
395                || {
396                    update_snapshot(snapshot, Some(&spec.module_id), |state| {
397                        state.state = ModuleState::Stopped;
398                        clear_current_process_facts(state);
399                        state.last_exit = Some(exit_report.clone());
400                    })
401                },
402            ) {
403                error!(module_id = %spec.module_id, error = %err, "failed to publish clean module exit");
404            }
405            let registration_released = match wait_for_registration_release(
406                registry,
407                &spec.module_id,
408                REGISTRY_RELEASE_TIMEOUT,
409            )
410            .await
411            {
412                Ok(()) => true,
413                Err(err) => {
414                    warn!(module_id = %spec.module_id, error = %err, "registration still active after clean exit");
415                    false
416                }
417            };
418            NextAction::Stop {
419                registration_released,
420            }
421        }
422        ExitKind::Clean | ExitKind::Crash => {
423            if unrequested_clean_exit_of_protocol_none {
424                warn!(
425                    module_id = %spec.module_id,
426                    exit_code = ?exit_report.code,
427                    exit_signal = ?exit_report.signal,
428                    "protocol-none module exited cleanly without a stop request; handling it as a crash"
429                );
430            } else {
431                warn!(
432                    module_id = %spec.module_id,
433                    exit_code = ?exit_report.code,
434                    exit_signal = ?exit_report.signal,
435                    "supervised module exited abnormally (crash)"
436                );
437            }
438            let mut restart_schedule = None;
439            let mut disposition = TerminalDisposition::Disabled;
440            let mut final_state = ModuleState::Disabled;
441            // Set only when the budget is what stopped the module, so the
442            // terminal record says which limit was hit rather than leaving
443            // `failed` to be read as "crashed once, badly".
444            let mut disposition_detail = lock_snapshot(snapshot)
445                .ok()
446                .and_then(|mut state| state.spawn_failure.take());
447            if let Some(detail) = detail {
448                disposition_detail = Some(
449                    disposition_detail
450                        .map_or_else(|| detail.clone(), |cause| format!("{cause}; {detail}")),
451                );
452            }
453            let now = Instant::now();
454            if let Err(err) = update_snapshot(snapshot, Some(&spec.module_id), |state| {
455                if state.enabled {
456                    if let Some(schedule) = state.next_crash_restart(&policy, now) {
457                        // Route close checks this flag so clients can retry even
458                        // before terminal recording publishes Restarting.
459                        state.respawn_pending = true;
460                        final_state = ModuleState::Restarting;
461                        restart_schedule = Some(schedule);
462                        disposition = TerminalDisposition::Restarting;
463                    } else {
464                        final_state = ModuleState::Failed;
465                        disposition = TerminalDisposition::Failed;
466                        let budget = policy.budget_exhausted_detail();
467                        disposition_detail =
468                            Some(disposition_detail.take().map_or_else(
469                                || budget.clone(),
470                                |cause| format!("{cause}; {budget}"),
471                            ));
472                    }
473                } else {
474                    disposition = TerminalDisposition::Disabled;
475                }
476            }) {
477                error!(module_id = %spec.module_id, error = %err, "failed to record crashed module exit");
478                return NextAction::Stop {
479                    registration_released: false,
480                };
481            }
482            if disposition == TerminalDisposition::Failed {
483                // The window is in the message, not only in the fields: this line
484                // is read in a scrollback where a bare `max_restarts=3` reads as a
485                // lifetime cap and sends the operator looking for three crashes
486                // that never happened together.
487                error!(
488                    module_id = %spec.module_id,
489                    max_restarts = policy.max_restarts,
490                    window_secs = policy.window.as_secs(),
491                    "module stopped: {}",
492                    policy.budget_exhausted_detail()
493                );
494            }
495            if let Err(err) = publish_after_terminal_record(
496                &spec.module_id,
497                || {
498                    record_terminal_with_detail(
499                        &spec.module_id,
500                        terminal_ring,
501                        spawn_events,
502                        &exit_report,
503                        disposition,
504                        disposition_detail,
505                    )
506                },
507                || {
508                    update_snapshot(snapshot, Some(&spec.module_id), |state| {
509                        state.state = final_state;
510                        clear_current_process_facts(state);
511                        if final_state == ModuleState::Failed
512                            && daemon_initiated
513                            && !roster.is_closed()
514                        {
515                            state.failed_retry.schedule(&spec.module_id);
516                        }
517                        state.last_exit = Some(exit_report.clone());
518                    })
519                },
520            ) {
521                error!(module_id = %spec.module_id, error = %err, "failed to publish crashed module exit");
522            }
523
524            if let Some(schedule) = restart_schedule {
525                NextAction::Restart {
526                    schedule: Some(schedule),
527                }
528            } else {
529                let registration_released = match wait_for_registration_release(
530                    registry,
531                    &spec.module_id,
532                    REGISTRY_RELEASE_TIMEOUT,
533                )
534                .await
535                {
536                    Ok(()) => true,
537                    Err(err) => {
538                        warn!(module_id = %spec.module_id, error = %err, "registration still active after failed module");
539                        false
540                    }
541                };
542                NextAction::Stop {
543                    registration_released,
544                }
545            }
546        }
547        ExitKind::DeliberateSeverance => {
548            warn!(
549                module_id = %spec.module_id,
550                exit_code = ?exit_report.code,
551                exit_signal = ?exit_report.signal,
552                "supervised module exited after deliberate connection severance"
553            );
554            let should_restart = match lock_snapshot(snapshot) {
555                Ok(state) => state.enabled,
556                Err(err) => {
557                    error!(module_id = %spec.module_id, error = %err, "failed to read deliberately severed module state");
558                    return NextAction::Stop {
559                        registration_released: false,
560                    };
561                }
562            };
563            let final_state = if should_restart {
564                ModuleState::Restarting
565            } else {
566                ModuleState::Disabled
567            };
568            if let Err(err) = publish_after_terminal_record(
569                &spec.module_id,
570                || {
571                    record_terminal_with_detail(
572                        &spec.module_id,
573                        terminal_ring,
574                        spawn_events,
575                        &exit_report,
576                        terminal_disposition(final_state),
577                        detail,
578                    )
579                },
580                || {
581                    update_snapshot(snapshot, Some(&spec.module_id), |state| {
582                        state.state = final_state;
583                        clear_current_process_facts(state);
584                        state.last_exit = Some(exit_report.clone());
585                        state.lifetime_restarts += 1;
586                    })
587                },
588            ) {
589                error!(module_id = %spec.module_id, error = %err, "failed to publish deliberately severed module exit");
590                return NextAction::Stop {
591                    registration_released: false,
592                };
593            }
594
595            if should_restart {
596                NextAction::Restart { schedule: None }
597            } else {
598                let registration_released = match wait_for_registration_release(
599                    registry,
600                    &spec.module_id,
601                    REGISTRY_RELEASE_TIMEOUT,
602                )
603                .await
604                {
605                    Ok(()) => true,
606                    Err(err) => {
607                        warn!(module_id = %spec.module_id, error = %err, "registration still active after deliberately severed module exit");
608                        false
609                    }
610                };
611                NextAction::Stop {
612                    registration_released,
613                }
614            }
615        }
616    }
617}
618
619async fn on_child_exit_during_daemon_shutdown(
620    spec: &ModuleSpec,
621    registry: &Registry,
622    snapshot: &SharedSnapshot,
623    terminal_ring: &Arc<Mutex<TerminalRing>>,
624    spawn_events: &SpawnEventFeed,
625    exit_report: ExitReport,
626    detail: Option<String>,
627) -> NextAction {
628    info!(
629        module_id = %spec.module_id,
630        exit_code = ?exit_report.code,
631        exit_signal = ?exit_report.signal,
632        exit_kind = ?exit_report.kind,
633        "supervised module exited during daemon shutdown; not restarting it"
634    );
635    if let Err(err) = publish_after_terminal_record(
636        &spec.module_id,
637        || {
638            record_terminal_with_detail(
639                &spec.module_id,
640                terminal_ring,
641                spawn_events,
642                &exit_report,
643                TerminalDisposition::DaemonShutdown,
644                detail,
645            )
646        },
647        || {
648            update_snapshot(snapshot, Some(&spec.module_id), |state| {
649                state.state = ModuleState::Stopped;
650                clear_current_process_facts(state);
651                state.last_exit = Some(exit_report.clone());
652            })
653        },
654    ) {
655        error!(module_id = %spec.module_id, error = %err, "failed to publish module exit during daemon shutdown");
656    }
657    let registration_released =
658        wait_for_registration_release(registry, &spec.module_id, REGISTRY_RELEASE_TIMEOUT)
659            .await
660            .is_ok();
661    NextAction::Stop {
662        registration_released,
663    }
664}
665
666// Keep the status lock out of terminal I/O. Readers may observe the previous
667// state while recording is in progress, but never a completed exit without its
668// history. Journal errors are logged by the journal and retained in the ring;
669// a recording panic still publishes the final state before resuming the unwind.
670pub(super) fn publish_after_terminal_record<T>(
671    module_id: &str,
672    record: impl FnOnce(),
673    publish: impl FnOnce() -> T,
674) -> T {
675    let recorded = std::panic::catch_unwind(std::panic::AssertUnwindSafe(record));
676    let published = publish();
677    if let Err(panic) = recorded {
678        error!(
679            module_id,
680            "terminal recording panicked; published final state before resuming unwind"
681        );
682        std::panic::resume_unwind(panic);
683    }
684    published
685}
686
687pub(super) fn fail_after_wait_error(
688    module_id: &str,
689    snapshot: &SharedSnapshot,
690    terminal_ring: &Arc<Mutex<TerminalRing>>,
691    spawn_events: &SpawnEventFeed,
692    detail: String,
693    failure: &FailureContext,
694) {
695    let report = wait_error_exit_report();
696    publish_after_terminal_record(
697        module_id,
698        || {
699            record_terminal_with_detail(
700                module_id,
701                terminal_ring,
702                spawn_events,
703                &report,
704                TerminalDisposition::Failed,
705                Some(detail),
706            )
707        },
708        || fail_snapshot(snapshot, Some(module_id), Some(report.clone()), failure),
709    );
710}
711
712#[cfg(test)]
713pub(super) fn record_wait_error_terminal(
714    module_id: &str,
715    terminal_ring: &Arc<Mutex<TerminalRing>>,
716    spawn_events: &SpawnEventFeed,
717) {
718    record_terminal(
719        module_id,
720        terminal_ring,
721        spawn_events,
722        &wait_error_exit_report(),
723        TerminalDisposition::Failed,
724    );
725}
726
727#[cfg(test)]
728pub(super) fn record_terminal(
729    module_id: &str,
730    terminal_ring: &Arc<Mutex<TerminalRing>>,
731    spawn_events: &SpawnEventFeed,
732    exit_report: &ExitReport,
733    disposition: TerminalDisposition,
734) {
735    record_terminal_with_detail(
736        module_id,
737        terminal_ring,
738        spawn_events,
739        exit_report,
740        disposition,
741        None,
742    );
743}
744
745/// Copy the ring under its lock; pin and read the journal files without it.
746pub(super) fn durable_terminal_history_of(
747    terminal_ring: &Mutex<TerminalRing>,
748    module_id: &str,
749) -> subc_control::TerminalHistory {
750    let read = terminal_ring
751        .lock()
752        .unwrap_or_else(|p| p.into_inner())
753        .capture_durable_history();
754    read.read(module_id)
755}
756
757pub(super) fn record_terminal_with_detail(
758    module_id: &str,
759    terminal_ring: &Arc<Mutex<TerminalRing>>,
760    spawn_events: &SpawnEventFeed,
761    exit_report: &ExitReport,
762    disposition: TerminalDisposition,
763    disposition_detail: Option<String>,
764) {
765    #[cfg(test)]
766    terminal_history_tests::before_terminal_record(spawn_events);
767    spawn_events.emit_exited(module_id, exit_report.code, exit_report.signal);
768    let record = TerminalRecord {
769        exit_code: exit_report.code,
770        exit_signal: exit_report.signal,
771        at_ms: exit_report.at_ms,
772        disposition,
773        exit_kind: exit_report.kind.into(),
774        disposition_detail,
775    };
776    terminal_ring
777        .lock()
778        .unwrap_or_else(|poisoned| poisoned.into_inner())
779        .record_exit(module_id, record);
780}
781
782pub(super) fn untrack_if_registration_released(
783    process_liveness: &SupervisorProcessLiveness,
784    registry: &Registry,
785    module_id: &str,
786    snapshot: &SharedSnapshot,
787) {
788    match registry.get_module(module_id) {
789        Ok(None) => process_liveness.untrack_if_current(module_id, snapshot),
790        Ok(Some(_)) => {}
791        Err(err) => {
792            warn!(module_id, error = %err, "could not determine whether supervisor liveness can be untracked");
793        }
794    }
795}
796
797pub(super) fn classify_exit(status: &ExitStatus) -> ExitReport {
798    ExitReport {
799        kind: if status.success() {
800            ExitKind::Clean
801        } else {
802            ExitKind::Crash
803        },
804        code: status.code(),
805        signal: exit_signal(status),
806        at_ms: unix_ms_now(),
807    }
808}
809
810/// The terminal record for a module whose `wait()` call itself errored (e.g. the
811/// child was already reaped out-of-band). There is no `ExitStatus` to read a code
812/// or signal from -- `None`/`None` is the honest shape, not a guess -- but the
813/// disposition still must be `Failed` so the terminal ring is not silently missing
814/// an entry, matching what `fail_snapshot` records for this same arm.
815pub(super) fn wait_error_exit_report() -> ExitReport {
816    ExitReport {
817        kind: ExitKind::Crash,
818        code: None,
819        signal: None,
820        at_ms: unix_ms_now(),
821    }
822}
823
824#[cfg(unix)]
825fn exit_signal(status: &ExitStatus) -> Option<i32> {
826    use std::os::unix::process::ExitStatusExt;
827
828    status.signal()
829}
830
831#[cfg(not(unix))]
832fn exit_signal(_status: &ExitStatus) -> Option<i32> {
833    None
834}
835
836pub(super) fn clear_current_process_facts(state: &mut SupervisorSnapshot) {
837    state.legacy_registration_spawn = false;
838    state.registration_declaration = None;
839    state.subtree_target = crate::subtree_resources::Target::Unavailable("not_running");
840    state.failed_retry.healthy_since = None;
841    state.failed_retry.running_since = None;
842    state.waiting_for_previous_pid = None;
843    state.waiting_for_previous_detail = None;
844    state.process_alive = false;
845    state.spawned_protocol = None;
846    state.pid = None;
847    #[cfg(windows)]
848    {
849        state.pipe_consumed = None;
850    }
851    #[cfg(target_os = "macos")]
852    {
853        state.report_ready = None;
854    }
855    state.spawned_at_ms = None;
856    state.exec_outcome = None;
857    state.spawned_from = None;
858    state.launch_spec_digest = None;
859    state.spawned_file_identity = None;
860    state.process_start_time = None;
861    state.deliberate_severance = None;
862}
863
864#[cfg(test)]
865pub(super) fn record_deliberate_severance(
866    snapshot: &SharedSnapshot,
867    identity: ProcessIdentity,
868) -> Result<(), SuperviseError> {
869    update_snapshot(snapshot, None, |state| {
870        state.deliberate_severance = Some(identity);
871    })
872}
873
874pub(super) fn apply_deliberate_severance_marker(
875    snapshot: &SharedSnapshot,
876    exited_identity: Option<ProcessIdentity>,
877    mut exit_report: ExitReport,
878) -> ExitReport {
879    let marker = lock_snapshot(snapshot)
880        .ok()
881        .and_then(|mut state| state.deliberate_severance.take());
882    if marker.is_some() && marker == exited_identity {
883        exit_report.kind = ExitKind::DeliberateSeverance;
884    }
885    exit_report
886}
887
888pub(super) fn classify_reaped_child_exit(
889    snapshot: &SharedSnapshot,
890    child: &SupervisedChild,
891    status: &ExitStatus,
892) -> ExitReport {
893    let _ = update_snapshot(snapshot, None, |state| {
894        state.reaped_pid = Some(child.pid);
895        state.spawn_failure = child.spawn_failure.clone();
896    });
897    if matches!(
898        child.spawn_failure.as_deref(),
899        Some("registration_timeout" | "registration_channel_closed")
900    ) {
901        registration_failure_exit_report(classify_exit(status))
902    } else {
903        apply_deliberate_severance_marker(snapshot, child.process_identity(), classify_exit(status))
904    }
905}
906
907pub(super) fn fail_snapshot(
908    snapshot: &SharedSnapshot,
909    module_id: Option<&str>,
910    last_exit: Option<ExitReport>,
911    failure: &FailureContext,
912) {
913    if let Err(err) = update_snapshot(snapshot, module_id, |state| {
914        state.state = ModuleState::Failed;
915        state.config_hold_parked = false;
916        state.config_hold_daemon_initiated = false;
917        state.config_hold_approval = None;
918        clear_current_process_facts(state);
919        if failure.may_retry() && state.enabled {
920            state.failed_retry.schedule(module_id.unwrap_or("unknown"));
921        } else if failure.shutdown.is_set() {
922            state.failed_retry.cancel();
923        }
924        if let Some(last_exit) = last_exit {
925            state.last_exit = Some(last_exit);
926        }
927    }) {
928        error!(error = %err, "failed to mark supervisor state failed");
929    }
930}