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