1use super::*;
2
3const 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 let result = self.child.wait().await;
45 self.retire_registration();
46 #[cfg(any(unix, windows))]
47 self.registration_channel.take();
48 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 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 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 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 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
206pub(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
228pub(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 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 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 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 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 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 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
666pub(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
745pub(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
810pub(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}