1use super::*;
2
3pub const DEFAULT_DRAIN_TIMEOUT: Duration = Duration::from_secs(30);
14
15const DRAIN_BUSY_REPROBE_INTERVAL: Duration = Duration::from_millis(250);
27
28impl SupervisedChild {
29 pub(super) fn group_drain_budget(&self, budget: Duration, _notice: StopNotice) -> Duration {
30 #[cfg(unix)]
31 if self.child.plain_group.is_some() && _notice != StopNotice::SentOverConnection {
32 return budget.min(plain_group::TERM_GRACE);
33 }
34 budget
35 }
36}
37
38impl Supervisor {
39 pub(crate) fn daemon_shutdown_flag(&self) -> crate::child_roster::DaemonShutdownFlag {
42 self.child_roster.shutdown_flag()
43 }
44
45 #[cfg(unix)]
55 pub(crate) fn begin_daemon_shutdown(&self) {
56 self.child_roster.close();
57 if let Some(journal) = &self.terminal_journal {
58 journal.stamp_shutdown();
59 }
60 }
61
62 #[cfg(unix)]
67 pub(crate) async fn drain_for_daemon_shutdown(&self) -> Result<(), SuperviseError> {
68 const NOTICE_BUDGET: Duration = Duration::from_millis(500);
69 const DRAIN_BUDGET: Duration = Duration::from_secs(2);
70 const MARKER_BUDGET: Duration = Duration::from_millis(500);
71 let Some(forwarding) = &self.forwarding else {
72 return Ok(());
73 };
74 if let Some(journal) = &self.terminal_journal {
79 if !journal.flush_within(MARKER_BUDGET).await {
80 warn!(
81 "shutdown marker not written within its budget; announcing the shutdown anyway"
82 );
83 }
84 }
85 let notice_started = Instant::now();
86 let modules = forwarding
87 .begin_daemon_drain()
88 .map_err(SuperviseError::Forwarding)?;
89 let deadline_ms =
90 unix_ms_now().saturating_add((NOTICE_BUDGET + DRAIN_BUDGET).as_millis() as u64);
91 let shutdown_reason = self
92 .supervisor_handle
93 .as_ref()
94 .map(SupervisorHandle::take_daemon_shutdown_reason)
95 .unwrap_or(RouteCloseReason::Disable);
96 let mut modules_told = 0;
97 let mut notices = tokio::task::JoinSet::new();
98 let mut drains = Vec::new();
99 for connection in forwarding
100 .module_connections()
101 .map_err(SuperviseError::Forwarding)?
102 {
103 let target = ModuleDrainTarget {
104 endpoint: connection.endpoint,
105 sink: connection.sink,
106 negotiated_ver: connection.negotiated_ver,
107 abandoned_bindings: Vec::new(),
108 excluded_subscriptions: 0,
109 };
110 notices.spawn(async move {
111 (
112 true,
113 send_module_draining(
114 &connection.module_id,
115 shutdown_reason,
116 deadline_ms,
117 &target,
118 true,
119 )
120 .await,
121 )
122 });
123 }
124 for (module_id, endpoint) in modules {
125 let Some(target) = forwarding
126 .begin_endpoint_drain(endpoint, RouteCloseReason::Restart)
127 .map_err(SuperviseError::Forwarding)?
128 else {
129 continue;
130 };
131 let routes = forwarding
132 .endpoint_routes(target.endpoint)
133 .map_err(SuperviseError::Forwarding)?;
134 let mut recipients = Vec::new();
137 let mut clients: Vec<(crate::forwarding::GoodbyeTarget, Vec<u16>)> = Vec::new();
138 for route in routes {
139 let client = route.goodbye_target;
140 if let Some((_, channels)) = clients
141 .iter_mut()
142 .find(|(existing, _)| existing.connection_id == client.connection_id)
143 {
144 channels.push(client.channel);
145 } else {
146 let channel = client.channel;
147 clients.push((client, vec![channel]));
148 }
149 }
150 for (client, mut channels) in clients {
151 channels.sort_unstable();
152 channels.dedup();
153 let closing = serde_json::to_vec(&ClientControlPush::RouteClosing {
154 module_id: module_id.clone(),
155 channels,
156 reason: RouteCloseReason::Restart,
157 })
158 .expect("route closing serializes");
159 recipients.push((client.sink, client.negotiated_ver, closing));
160 }
161 for (sink, version, body) in recipients {
162 notices.spawn(async move {
163 let frame = Frame::build_with_version(
164 version,
165 FrameType::Push,
166 control_flags(),
167 0,
168 0,
169 0,
170 body,
171 )
172 .expect("bounded lifecycle notice frame builds");
173 (false, sink.send_flushed(frame).await.is_ok())
174 });
175 }
176 let gauges = declared_busy_gauges(&self.registry, &module_id)?;
177 drains.push((module_id, target.endpoint, gauges));
178 }
179 let notice_deadline = Instant::now() + NOTICE_BUDGET;
182 while let Ok(Some(result)) = timeout_at(notice_deadline, notices.join_next()).await {
183 match result {
184 Ok((true, true)) => modules_told += 1,
185 Ok((false, true)) => {}
186 result => warn!(?result, "daemon shutdown notice delivery failed"),
187 }
188 }
189 notices.abort_all();
190 info!(
191 ?shutdown_reason,
192 modules_told, "daemon shutdown module notices delivered"
193 );
194 let notice_elapsed = notice_started.elapsed();
195 let drain_started = Instant::now();
196 let deadline = drain_started + DRAIN_BUDGET;
197 let mut waits = tokio::task::JoinSet::new();
198 for (module_id, endpoint, gauges) in drains {
199 let forwarding = Arc::clone(forwarding);
200 let mut runtime = self.runtime_config();
201 runtime.health.cadence = Duration::from_millis(100);
202 waits.spawn(async move {
203 let wait_result = wait_for_forwarding_quiescence(
204 &forwarding,
205 &module_id,
206 &runtime,
207 endpoint,
208 deadline,
209 &gauges,
210 DrainScope::Endpoint(endpoint),
211 &mut DrainGaugeTrace::new(&gauges),
212 )
213 .await;
214 forwarding
218 .record_daemon_drain_result(
219 endpoint,
220 drained_after_quiescence_wait(&wait_result),
221 )
222 .map_err(SuperviseError::Forwarding)?;
223 wait_result
224 });
225 }
226 while let Ok(Some(result)) = timeout_at(deadline, waits.join_next()).await {
227 if !matches!(result, Ok(Ok(true))) {
228 warn!(?result, "daemon shutdown drain did not reach quiescence");
229 }
230 }
231 info!(
234 notice_elapsed_ms = notice_elapsed.as_millis() as u64,
235 drain_elapsed_ms = drain_started.elapsed().as_millis() as u64,
236 "daemon shutdown forwarding drain complete"
237 );
238 Ok(())
239 }
240
241 #[cfg(unix)]
253 pub(crate) async fn end_children_for_daemon_shutdown(
254 &self,
255 already_escalated: bool,
256 escalate: impl std::future::Future<Output = ()>,
257 ) {
258 tokio::pin!(escalate);
259 let mut escalated = already_escalated;
260 if let Some(forwarding) = &self.forwarding {
261 let reason = CloseReason::new(
262 "daemon_shutdown",
263 "the daemon is exiting after its shutdown notice and drain",
264 );
265 if escalated {
266 send_module_goodbyes_for_daemon_shutdown(forwarding, &reason, false).await;
269 } else {
270 tokio::select! {
271 biased;
272 _ = escalate.as_mut() => {
273 info!("second SIGTERM: abandoning module GOODBYE delivery");
274 escalated = true;
275 }
276 _ = send_module_goodbyes_for_daemon_shutdown(forwarding, &reason, true) => {}
277 }
278 }
279 let closed = forwarding.close_all_connections(&reason);
280 debug!(closed, "closed established connections for daemon shutdown");
281 }
282 let escalated_here = escalated && !already_escalated;
286 let remaining_escalate = async move {
287 if escalated_here {
288 std::future::pending::<()>().await;
289 } else {
290 escalate.await;
291 }
292 };
293 crate::child_roster::end_children_for_daemon_shutdown(
294 &self.child_roster,
295 escalated,
296 remaining_escalate,
297 )
298 .await;
299 if let Some(journal) = &self.terminal_journal {
300 journal.flush_shutdown().await;
301 }
302 }
303}
304
305impl SupervisedModule {
306 pub async fn drain(&self) -> Result<(), SuperviseError> {
308 self.stop().await
309 }
310
311 pub(crate) async fn retire_requested(
312 &self,
313 requester: Option<Principal>,
314 ) -> Result<(), SuperviseError> {
315 match self.state()? {
316 ModuleState::Stopped => return Ok(()),
317 ModuleState::Failed
318 if lock_snapshot(&self.inner.snapshot)?
319 .failed_retry
320 .pending
321 .is_none() =>
322 {
323 return Ok(())
324 }
325 ModuleState::Failed
326 | ModuleState::Starting
327 | ModuleState::Running
328 | ModuleState::Unresponsive
329 | ModuleState::Restarting
330 | ModuleState::Draining
331 | ModuleState::Disabled => {}
332 }
333
334 let (reply_tx, reply_rx) = oneshot::channel();
335 self.inner
336 .commands
337 .send(SupervisorCommand::Retire {
338 requester,
339 reply: reply_tx,
340 })
341 .await
342 .map_err(|_| SuperviseError::CommandClosed {
343 module_id: self.inner.module_id.clone(),
344 })?;
345 reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
346 module_id: self.inner.module_id.clone(),
347 })?
348 }
349
350 pub async fn stop(&self) -> Result<(), SuperviseError> {
351 self.stop_requested(None).await
352 }
353
354 pub(crate) async fn stop_requested(
355 &self,
356 requester: Option<Principal>,
357 ) -> Result<(), SuperviseError> {
358 match self.state()? {
359 ModuleState::Stopped => return Ok(()),
360 ModuleState::Failed
361 if lock_snapshot(&self.inner.snapshot)?
362 .failed_retry
363 .pending
364 .is_none() =>
365 {
366 return Ok(())
367 }
368 ModuleState::Failed
369 | ModuleState::Starting
370 | ModuleState::Running
371 | ModuleState::Unresponsive
372 | ModuleState::Restarting
373 | ModuleState::Draining
374 | ModuleState::Disabled => {}
375 }
376
377 let (reply_tx, reply_rx) = oneshot::channel();
378 self.inner
379 .commands
380 .send(SupervisorCommand::Drain {
381 requester,
382 reply: reply_tx,
383 })
384 .await
385 .map_err(|_| SuperviseError::CommandClosed {
386 module_id: self.inner.module_id.clone(),
387 })?;
388 reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
389 module_id: self.inner.module_id.clone(),
390 })?
391 }
392}
393
394#[derive(Debug, Clone, Copy, PartialEq, Eq)]
395pub(super) enum BusyGaugeObservation {
396 Quiescent,
397 Busy,
398 Omitted,
399}
400
401#[derive(Debug, Clone, PartialEq, Eq)]
403pub(super) enum GaugeVerdict {
404 Zero,
406 NonZero(u64),
408 NotACount(String),
412 Missing,
414 ProbeFailed(&'static str),
417}
418
419impl GaugeVerdict {
420 fn reads_quiet(&self) -> bool {
421 matches!(self, Self::Zero)
422 }
423}
424
425impl fmt::Display for GaugeVerdict {
426 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
427 match self {
428 Self::Zero => f.write_str("zero"),
429 Self::NonZero(value) => write!(f, "non_zero({value})"),
430 Self::NotACount(value) => write!(f, "not_a_count({value})"),
431 Self::Missing => f.write_str("missing_from_health_body"),
432 Self::ProbeFailed(kind) => write!(f, "probe_failed({kind})"),
433 }
434 }
435}
436
437const GAUGE_VALUE_TEXT_LIMIT: usize = 32;
440
441pub(super) fn gauge_verdicts(metrics: Option<&Value>, gauges: &[String]) -> Vec<GaugeVerdict> {
443 let metrics = metrics.and_then(Value::as_object);
444 gauges
445 .iter()
446 .map(
447 |gauge| match metrics.and_then(|metrics| metrics.get(gauge)) {
448 None => GaugeVerdict::Missing,
449 Some(value) => match value.as_u64() {
450 Some(0) => GaugeVerdict::Zero,
451 Some(count) => GaugeVerdict::NonZero(count),
452 None => {
453 let mut text = value.to_string();
454 if text.len() > GAUGE_VALUE_TEXT_LIMIT {
455 let mut end = GAUGE_VALUE_TEXT_LIMIT;
456 while !text.is_char_boundary(end) {
457 end -= 1;
458 }
459 text.truncate(end);
460 text.push_str("...");
461 }
462 GaugeVerdict::NotACount(text)
463 }
464 },
465 },
466 )
467 .collect()
468}
469
470pub(super) fn busy_gauge_observation(verdicts: &[GaugeVerdict]) -> BusyGaugeObservation {
473 if verdicts
474 .iter()
475 .any(|verdict| matches!(verdict, GaugeVerdict::Missing))
476 {
477 BusyGaugeObservation::Omitted
478 } else if verdicts.iter().all(GaugeVerdict::reads_quiet) {
479 BusyGaugeObservation::Quiescent
480 } else {
481 BusyGaugeObservation::Busy
482 }
483}
484
485#[derive(Debug, Clone, Default, PartialEq, Eq)]
490pub(super) struct GaugeTrace {
491 pub(super) latest: Option<(GaugeVerdict, Duration)>,
492 pub(super) last_value: Option<(GaugeVerdict, Duration)>,
493}
494
495#[derive(Debug, Clone, Default, PartialEq, Eq)]
501pub(super) struct DrainGaugeTrace {
502 pub(super) probes: u32,
504 pub(super) gauges: Vec<(String, GaugeTrace)>,
506}
507
508impl DrainGaugeTrace {
509 pub(super) fn new(gauges: &[String]) -> Self {
510 Self {
511 probes: 0,
512 gauges: gauges
513 .iter()
514 .map(|gauge| (gauge.clone(), GaugeTrace::default()))
515 .collect(),
516 }
517 }
518
519 fn record(&mut self, verdicts: &[GaugeVerdict], at: Duration) {
521 self.probes = self.probes.saturating_add(1);
522 for ((_, trace), verdict) in self.gauges.iter_mut().zip(verdicts) {
523 trace.latest = Some((verdict.clone(), at));
524 if matches!(
525 verdict,
526 GaugeVerdict::Zero | GaugeVerdict::NonZero(_) | GaugeVerdict::NotACount(_)
527 ) {
528 trace.last_value = Some((verdict.clone(), at));
529 }
530 }
531 }
532}
533
534impl fmt::Display for DrainGaugeTrace {
539 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
540 if self.gauges.is_empty() {
541 return f.write_str("none declared");
542 }
543 for (index, (name, trace)) in self.gauges.iter().enumerate() {
544 if index > 0 {
545 f.write_str(" | ")?;
546 }
547 write!(f, "{name}: ")?;
548 match &trace.latest {
549 Some((verdict, at)) => write!(f, "{verdict} @{}ms", at.as_millis())?,
550 None => f.write_str("never probed")?,
551 }
552 match &trace.last_value {
553 Some((value, at)) => write!(f, "; last value {value} @{}ms", at.as_millis())?,
554 None => f.write_str("; no value ever read")?,
555 }
556 }
557 Ok(())
558 }
559}
560
561pub(crate) fn declared_busy_gauges(
562 registry: &Registry,
563 module_id: &str,
564) -> Result<Vec<String>, SuperviseError> {
565 busy_gauges_of(
566 registry
567 .get_module(module_id)
568 .map_err(SuperviseError::Registry)?,
569 )
570}
571
572fn declared_busy_gauges_for_connection(
576 registry: &Registry,
577 connection_id: ConnectionId,
578) -> Result<Vec<String>, SuperviseError> {
579 busy_gauges_of(
580 registry
581 .get_module_by_connection(connection_id)
582 .map_err(SuperviseError::Registry)?,
583 )
584}
585
586fn busy_gauges_of(
587 registration: Option<crate::registry::ModuleRegistration>,
588) -> Result<Vec<String>, SuperviseError> {
589 let Some(registration) = registration else {
590 return Ok(Vec::new());
591 };
592 let Some(self_signals) = registration.manifest.self_signals else {
593 return Ok(Vec::new());
594 };
595
596 let mut gauges = Vec::new();
597 for declaration in self_signals {
598 if declaration.kind != SelfSignalKind::Busy {
599 continue;
600 }
601 match declaration.anchored_to {
602 SignalAnchor::HealthGauges { gauges: declared } if !declared.is_empty() => {
603 gauges.extend(declared)
604 }
605 _ => {
606 gauges.push(String::new());
609 }
610 }
611 }
612 Ok(gauges)
613}
614
615#[allow(clippy::too_many_arguments)]
624pub(super) async fn wait_for_forwarding_quiescence(
625 forwarding: &ForwardingTable,
626 module_id: &str,
627 runtime: &SupervisorRuntimeConfig,
628 endpoint: crate::ModuleEndpointId,
629 deadline: Instant,
630 busy_gauges: &[String],
631 scope: DrainScope,
632 trace: &mut DrainGaugeTrace,
633) -> Result<bool, SuperviseError> {
634 let wait_started = Instant::now();
635 let mut gauges_quiescent = busy_gauges.is_empty();
636 let mut next_probe_at = wait_started;
637 let mut omission_reported = false;
638
639 loop {
640 let now = Instant::now();
641 if !busy_gauges.is_empty() && now >= next_probe_at && now < deadline {
642 let report = match scope {
643 DrainScope::Active => probe_module_health(module_id, runtime, Some(deadline)).await,
644 DrainScope::Endpoint(endpoint) => {
645 probe_endpoint_health(endpoint, runtime, Some(deadline)).await
646 }
647 };
648 let verdicts = match &report {
649 Ok(report) => gauge_verdicts(report.metrics.as_ref(), busy_gauges),
650 Err(err) => vec![GaugeVerdict::ProbeFailed(err.label()); busy_gauges.len()],
651 };
652 trace.record(&verdicts, wait_started.elapsed());
653 gauges_quiescent = match report {
654 Ok(_) => match busy_gauge_observation(&verdicts) {
655 BusyGaugeObservation::Quiescent => true,
656 BusyGaugeObservation::Busy => false,
657 BusyGaugeObservation::Omitted => {
658 if !omission_reported {
661 forwarding
662 .counters()
663 .increment_drains_with_undeclared_gauge();
664 let missing = busy_gauges
665 .iter()
666 .zip(&verdicts)
667 .filter(|(_, verdict)| matches!(verdict, GaugeVerdict::Missing))
668 .map(|(gauge, _)| gauge.as_str())
669 .collect::<Vec<_>>()
670 .join(",");
671 warn!(
672 module_id,
673 missing_gauges = %missing,
674 "drain health.check answer lacks a declared busy gauge; the drain treats the module as busy until it reports it"
675 );
676 omission_reported = true;
677 }
678 false
679 }
680 },
681 Err(err) => {
682 warn!(
683 module_id,
684 error = %err,
685 "drain health.check did not produce declared busy gauges; treating module as busy"
686 );
687 false
688 }
689 };
690 next_probe_at = Instant::now() + drain_busy_reprobe_interval();
693 }
694
695 let in_flight = forwarding
696 .endpoint_in_flight_count(endpoint)
697 .map_err(SuperviseError::Forwarding)?;
698 if in_flight == 0 && gauges_quiescent {
699 return Ok(true);
700 }
701
702 let now = Instant::now();
703 if now >= deadline {
704 return Ok(false);
705 }
706 let mut wait = deadline
707 .saturating_duration_since(now)
708 .min(REGISTRY_RELEASE_POLL);
709 if !busy_gauges.is_empty() {
710 wait = wait.min(next_probe_at.saturating_duration_since(now));
711 }
712 sleep(wait).await;
713 }
714}
715
716pub(super) fn drain_busy_reprobe_interval() -> Duration {
720 DRAIN_BUSY_REPROBE_INTERVAL.max(REGISTRY_RELEASE_POLL)
721}
722
723pub(super) fn warn_drain_timed_out(
738 module_id: &str,
739 drain_timeout: Duration,
740 reason: RouteCloseReason,
741 holdouts: &crate::forwarding::DrainHoldouts,
742 gauges: &DrainGaugeTrace,
743) {
744 warn!(
745 module_id = %module_id,
746 waited = ?drain_timeout,
747 ?reason,
748 held_requests = holdouts.requests,
749 held_routes = holdouts.routes,
750 total_routes = holdouts.total_routes,
751 top_connections = ?holdouts.top_connections,
752 held = %holdouts
755 .held
756 .iter()
757 .map(|(channel, corr)| format!("{channel}:{corr}"))
758 .collect::<Vec<_>>()
759 .join(","),
760 gauge_probes = gauges.probes,
761 busy_gauges = %gauges,
762 "route drain timed out before request quiescence; forcing teardown"
763 );
764}
765
766pub(super) fn drained_after_quiescence_wait(wait_result: &Result<bool, SuperviseError>) -> bool {
774 match wait_result {
775 Ok(drained) => *drained,
776 Err(_) => false,
777 }
778}
779
780fn send_route_goodbyes(forwarding: &ForwardingTable, released_routes: Vec<GoodbyeTarget>) {
781 for released in released_routes {
782 let frame = match Frame::build_with_version(
783 released.negotiated_ver,
784 FrameType::Goodbye,
785 control_flags(),
786 released.channel,
787 released.epoch,
788 0,
789 Vec::new(),
790 ) {
791 Ok(frame) => frame,
792 Err(err) => {
793 warn!(
794 route_channel = released.channel,
795 error = %err,
796 "failed to build supervisor drain route GOODBYE frame"
797 );
798 continue;
799 }
800 };
801 if !released.close_on_delivery_failure() {
802 crate::forwarding::send_module_route_goodbye(
803 &forwarding.counters(),
804 &released.sink,
805 frame,
806 released.module_id.as_deref(),
807 "supervisor drain",
808 );
809 continue;
810 }
811 if let Err(err) = released.sink.try_send(frame) {
812 warn!(
813 target_connection_id = released.connection_id.get(),
814 route_channel = released.channel,
815 error = %err,
816 "supervisor drain route GOODBYE was not delivered to client; closing target connection"
817 );
818 let _ = forwarding.escalate_client_delivery_failure(
819 released.connection_id,
820 released.channel,
821 released.epoch,
822 CloseReason::new(
823 "route_goodbye_delivery_failed",
824 format!(
825 "failed to enqueue supervisor drain route GOODBYE for channel {}: {err}",
826 released.channel
827 ),
828 ),
829 crate::forwarding::UndeliveredFrame {
830 module_id: released.module_id.as_deref(),
831 sink: &released.sink,
832 },
833 );
834 }
835 }
836}
837
838async fn send_module_draining(
839 module_id: &str,
840 reason: RouteCloseReason,
841 deadline_ms: u64,
842 target: &ModuleDrainTarget,
843 _wait_for_flush: bool,
844) -> bool {
845 let body = match serde_json::to_vec(&ModuleControlCommand::Draining {
846 reason,
847 deadline_ms,
848 }) {
849 Ok(body) => body,
850 Err(err) => {
851 warn!(
852 module_id,
853 error = %err,
854 "failed to encode module draining command"
855 );
856 return false;
857 }
858 };
859 let frame = match Frame::build_with_version(
860 target.negotiated_ver,
861 FrameType::Push,
862 control_flags(),
863 0,
864 0,
865 0,
866 body,
867 ) {
868 Ok(frame) => frame,
869 Err(err) => {
870 warn!(
871 module_id,
872 error = %err,
873 "failed to build module draining command frame"
874 );
875 return false;
876 }
877 };
878 #[cfg(unix)]
879 if _wait_for_flush {
880 return target.sink.send_flushed(frame).await.is_ok();
881 }
882 if let Err(err) = target.sink.try_send(frame) {
883 warn!(
884 module_id,
885 target_connection_id = target.endpoint.connection_id.get(),
886 error = %err,
887 "module draining command was not delivered to peer"
888 );
889 return false;
890 }
891 true
892}
893
894fn module_goodbye_frame(module_id: &str, negotiated_ver: u8) -> Option<Frame> {
896 match Frame::build_with_version(
897 negotiated_ver,
898 FrameType::Goodbye,
899 control_flags(),
900 0,
901 0,
902 0,
903 Vec::new(),
904 ) {
905 Ok(frame) => Some(frame),
906 Err(err) => {
907 warn!(
908 module_id,
909 error = %err,
910 "failed to build module GOODBYE frame"
911 );
912 None
913 }
914 }
915}
916
917#[cfg(unix)]
931async fn send_module_goodbyes_for_daemon_shutdown(
932 forwarding: &Arc<ForwardingTable>,
933 reason: &CloseReason,
934 wait_for_flush: bool,
935) {
936 const GOODBYE_BUDGET: Duration = Duration::from_millis(500);
937 let targets = match forwarding.module_connections() {
938 Ok(targets) => targets,
939 Err(err) => {
940 warn!(error = %err, "could not list module connections for shutdown GOODBYE");
941 return;
942 }
943 };
944 let deadline = Instant::now() + GOODBYE_BUDGET;
945 let mut sends = tokio::task::JoinSet::new();
946 for target in targets {
947 let Some(frame) = module_goodbye_frame(&target.module_id, target.negotiated_ver) else {
948 continue;
949 };
950 if !wait_for_flush {
951 if let Err(err) = target.sink.try_send(frame) {
952 debug!(
953 module_id = %target.module_id,
954 error = %err,
955 "shutdown module GOODBYE was not queued"
956 );
957 }
958 continue;
959 }
960 let forwarding = Arc::clone(forwarding);
961 let reason = reason.clone();
962 sends.spawn(async move {
963 match timeout_at(deadline, target.sink.send_flushed(frame)).await {
964 Ok(Ok(())) => {}
965 Ok(Err(err)) => debug!(
966 module_id = %target.module_id,
967 error = %err,
968 "module connection closed before its shutdown GOODBYE was written"
969 ),
970 Err(_) => warn!(
971 module_id = %target.module_id,
972 budget = ?GOODBYE_BUDGET,
973 "shutdown module GOODBYE was not written within its budget; closing anyway"
974 ),
975 }
976 forwarding.request_connection_close(target.endpoint.connection_id, reason);
977 });
978 }
979 while sends.join_next().await.is_some() {}
981}
982
983async fn send_module_goodbye(
984 module_id: &str,
985 forwarding: &ForwardingTable,
986 target: &ModuleDrainTarget,
987 wait_for_flush: bool,
988) {
989 let Some(frame) = module_goodbye_frame(module_id, target.negotiated_ver) else {
990 return;
991 };
992 let sent = if wait_for_flush {
995 timeout(Duration::from_millis(500), target.sink.send_flushed(frame))
996 .await
997 .map_err(|_| "module GOODBYE flush exceeded 500ms".to_owned())
998 .and_then(|result| result.map_err(|err| err.to_string()))
999 } else {
1000 target.sink.try_send(frame).map_err(|err| err.to_string())
1001 };
1002 if let Err(err) = sent {
1003 warn!(
1004 module_id,
1005 target_connection_id = target.endpoint.connection_id.get(),
1006 error = %err,
1007 "supervisor drain module GOODBYE was not delivered to peer; closing module connection"
1008 );
1009 forwarding.request_connection_close(
1010 target.endpoint.connection_id,
1011 CloseReason::new(
1012 "module_goodbye_delivery_failed",
1013 format!("failed to enqueue supervisor drain module GOODBYE for module '{module_id}': {err}"),
1014 ),
1015 );
1016 }
1017}
1018
1019#[derive(Clone, Copy)]
1020pub(super) struct ForwardingDrainContext<'a> {
1021 pub(super) spec: &'a ModuleSpec,
1022 pub(super) runtime: &'a SupervisorRuntimeConfig,
1023 pub(super) registry: &'a Registry,
1024 pub(super) scope: DrainScope,
1025}
1026
1027#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1029pub(super) enum DrainScope {
1030 Active,
1033 Endpoint(crate::ModuleEndpointId),
1038}
1039
1040#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1048pub(super) enum StopNotice {
1049 SentOverConnection,
1052 NoConnection,
1056 NotSent,
1060}
1061
1062pub(super) async fn begin_forwarding_drain(
1063 spec: &ModuleSpec,
1064 runtime: &SupervisorRuntimeConfig,
1065 registry: &Registry,
1066 snapshot: &SharedSnapshot,
1067 enabled: Option<bool>,
1068 reason: RouteCloseReason,
1069) -> Result<StopNotice, SuperviseError> {
1070 let Some(forwarding) = runtime.forwarding.as_ref() else {
1071 return Err(SuperviseError::ReloadUnavailable {
1072 module_id: spec.module_id.clone(),
1073 reason: "supervisor was not configured with a forwarding table".to_string(),
1074 });
1075 };
1076
1077 begin_forwarding_drain_with(
1078 forwarding,
1079 ForwardingDrainContext {
1080 spec,
1081 runtime,
1082 registry,
1083 scope: DrainScope::Active,
1084 },
1085 snapshot,
1086 enabled,
1087 reason,
1088 runtime.drain_timeout,
1089 )
1090 .await
1091}
1092
1093pub(super) async fn begin_forwarding_drain_if_configured(
1094 spec: &ModuleSpec,
1095 runtime: &SupervisorRuntimeConfig,
1096 registry: &Registry,
1097 snapshot: &SharedSnapshot,
1098 enabled: Option<bool>,
1099 reason: RouteCloseReason,
1100) -> Result<StopNotice, SuperviseError> {
1101 begin_forwarding_drain_with_timeout(
1102 spec,
1103 runtime,
1104 registry,
1105 snapshot,
1106 enabled,
1107 reason,
1108 runtime.drain_timeout,
1109 )
1110 .await
1111}
1112
1113pub(super) async fn begin_forwarding_drain_with_timeout(
1117 spec: &ModuleSpec,
1118 runtime: &SupervisorRuntimeConfig,
1119 registry: &Registry,
1120 snapshot: &SharedSnapshot,
1121 enabled: Option<bool>,
1122 reason: RouteCloseReason,
1123 drain_timeout: Duration,
1124) -> Result<StopNotice, SuperviseError> {
1125 let Some(forwarding) = runtime.forwarding.as_ref() else {
1126 return Ok(StopNotice::NotSent);
1127 };
1128
1129 begin_forwarding_drain_with(
1130 forwarding,
1131 ForwardingDrainContext {
1132 spec,
1133 runtime,
1134 registry,
1135 scope: DrainScope::Active,
1136 },
1137 snapshot,
1138 enabled,
1139 reason,
1140 drain_timeout,
1141 )
1142 .await
1143}
1144
1145pub(super) async fn begin_forwarding_drain_with(
1146 forwarding: &ForwardingTable,
1147 context: ForwardingDrainContext<'_>,
1148 snapshot: &SharedSnapshot,
1149 enabled: Option<bool>,
1150 reason: RouteCloseReason,
1151 drain_timeout: Duration,
1152) -> Result<StopNotice, SuperviseError> {
1153 let ForwardingDrainContext {
1154 spec,
1155 runtime,
1156 registry,
1157 scope,
1158 } = context;
1159 debug_assert_ne!(reason, RouteCloseReason::Crash);
1160 let terminal = matches!(reason, RouteCloseReason::Disable);
1161 let drain_started_at = Instant::now();
1162 let drain_deadline = drain_started_at + drain_timeout;
1163 let deadline_ms =
1164 unix_ms_now().saturating_add(u64::try_from(drain_timeout.as_millis()).unwrap_or(u64::MAX));
1165 let busy_gauges = match scope {
1166 DrainScope::Active => declared_busy_gauges(registry, &spec.module_id)?,
1167 DrainScope::Endpoint(endpoint) => {
1168 declared_busy_gauges_for_connection(registry, endpoint.connection_id)?
1169 }
1170 };
1171
1172 let gate_started = Instant::now();
1175 let drain_target = match scope {
1176 DrainScope::Active => forwarding.begin_module_drain(&spec.module_id, reason),
1177 DrainScope::Endpoint(endpoint) => forwarding.begin_endpoint_drain(endpoint, reason),
1178 }
1179 .map_err(SuperviseError::Forwarding)?;
1180 info!(
1185 module_id = %spec.module_id,
1186 ?reason,
1187 gate_ms = u64::try_from(gate_started.elapsed().as_millis()).unwrap_or(u64::MAX),
1188 connected = drain_target.is_some(),
1189 "module drain began; route admission closed"
1190 );
1191 if scope == DrainScope::Active {
1192 update_snapshot(snapshot, Some(&spec.module_id), |state| {
1193 state.state = ModuleState::Draining;
1194 state.draining_to_replace =
1195 matches!(reason, RouteCloseReason::Restart | RouteCloseReason::Reload);
1196 if let Some(enabled) = enabled {
1197 state.enabled = enabled;
1198 }
1199 })?;
1200 }
1201
1202 let Some(target) = drain_target.as_ref() else {
1203 return Ok(StopNotice::NoConnection);
1207 };
1208 let flush_goodbye = runtime.supervisor_handle.as_ref().is_some_and(|handle| {
1209 handle
1210 .registration_spawn(target.endpoint.connection_id)
1211 .is_some()
1212 });
1213 {
1214 send_module_draining(&spec.module_id, reason, deadline_ms, target, false).await;
1215 #[cfg(feature = "test-support")]
1216 forwarding.wait_before_route_closing_for_test().await;
1217 let routes = forwarding
1218 .endpoint_routes(target.endpoint)
1219 .map_err(SuperviseError::Forwarding)?;
1220 let routes_notified = routes.len();
1221 crate::control::send_route_control_pushes(
1222 forwarding,
1223 routes.clone(),
1224 ClientControlPush::RouteClosing {
1225 module_id: spec.module_id.clone(),
1226 channels: Vec::new(),
1227 reason,
1228 },
1229 );
1230 send_route_goodbyes(forwarding, target.abandoned_bindings.clone());
1231
1232 let mut gauge_trace = DrainGaugeTrace::new(&busy_gauges);
1238 let wait_result = wait_for_forwarding_quiescence(
1239 forwarding,
1240 &spec.module_id,
1241 runtime,
1242 target.endpoint,
1243 drain_deadline,
1244 &busy_gauges,
1245 scope,
1246 &mut gauge_trace,
1247 )
1248 .await;
1249 let drained = drained_after_quiescence_wait(&wait_result);
1250 if let Err(err) = &wait_result {
1251 error!(
1252 module_id = %spec.module_id,
1253 ?reason,
1254 error = %err,
1255 "forwarding quiescence wait failed after route.closing; forcing route.closed(drained: false) so the client is not left waiting on an unfulfilled promise"
1256 );
1257 } else if !drained {
1258 let holdouts = forwarding
1260 .endpoint_drain_holdouts(target.endpoint)
1261 .unwrap_or_default();
1262 warn_drain_timed_out(
1263 &spec.module_id,
1264 drain_timeout,
1265 reason,
1266 &holdouts,
1267 &gauge_trace,
1268 );
1269 }
1270 crate::control::send_route_control_pushes(
1271 forwarding,
1272 routes,
1273 ClientControlPush::RouteClosed {
1274 module_id: spec.module_id.clone(),
1275 channels: Vec::new(),
1276 reason,
1277 drained,
1278 abandoned: target.abandoned_bindings.len() as u32,
1279 excluded_subscriptions: target.excluded_subscriptions,
1280 terminal: Some(terminal),
1281 },
1282 );
1283 wait_result?;
1284
1285 let released_routes = match forwarding.release_module_endpoint_routes(target.endpoint) {
1291 Ok(routes) => routes,
1292 Err(err) => {
1293 warn!(
1294 module_id = %spec.module_id,
1295 ?reason,
1296 error = %err,
1297 "failed to release module endpoint routes after route.closed; module GOODBYE will still be sent"
1298 );
1299 send_module_goodbye(&spec.module_id, forwarding, target, flush_goodbye).await;
1300 return Err(SuperviseError::Forwarding(err));
1301 }
1302 };
1303 let route_goodbye_count = released_routes.len();
1304 send_route_goodbyes(forwarding, released_routes);
1305 send_module_goodbye(&spec.module_id, forwarding, target, flush_goodbye).await;
1306
1307 info!(
1313 module_id = %spec.module_id,
1314 ?reason,
1315 routes_notified,
1316 route_goodbyes = route_goodbye_count,
1317 abandoned_reservations = target.abandoned_bindings.len(),
1318 excluded_subscriptions = target.excluded_subscriptions,
1319 drained,
1320 "module drain complete; consumers notified via route.closing/route.closed pushes and per-route GOODBYE frames"
1321 );
1322 }
1323
1324 Ok(StopNotice::SentOverConnection)
1325}
1326
1327pub(super) fn control_flags() -> Flags {
1328 Flags::new(false, Priority::Passive, false)
1329}
1330
1331#[allow(clippy::too_many_arguments)]
1332pub(super) async fn drain_optional_child(
1333 module_id: &str,
1334 protocol: ModuleProtocol,
1335 stop_notice: StopNotice,
1336 registry: &Registry,
1337 forwarding: Option<&ForwardingTable>,
1338 snapshot: &SharedSnapshot,
1339 terminal_ring: &Arc<Mutex<TerminalRing>>,
1340 spawn_events: &SpawnEventFeed,
1341 child: &mut Option<SupervisedChild>,
1342 drain_timeout: Duration,
1343 final_state: ModuleState,
1344 enabled: Option<bool>,
1345 failure: &FailureContext,
1346) -> Result<(), SuperviseError> {
1347 if let Some(child) = child.take() {
1348 drain_child_to_state(
1349 module_id,
1350 protocol,
1351 stop_notice,
1352 registry,
1353 forwarding,
1354 snapshot,
1355 terminal_ring,
1356 spawn_events,
1357 child,
1358 drain_timeout,
1359 final_state,
1360 enabled,
1361 failure,
1362 )
1363 .await
1364 } else {
1365 update_snapshot(snapshot, Some(module_id), |state| {
1366 state.state = final_state;
1367 if final_state == ModuleState::Failed {
1368 state.failed_retry.failed_at = Some(Instant::now());
1369 }
1370 if let Some(enabled) = enabled {
1371 state.enabled = enabled;
1372 }
1373 clear_current_process_facts(state);
1374 })?;
1375 release_dead_registration(registry, forwarding, snapshot, module_id, failure).await
1376 }
1377}
1378
1379#[allow(clippy::too_many_arguments)]
1380pub(super) async fn drain_child_to_state(
1381 module_id: &str,
1382 _protocol: ModuleProtocol,
1383 stop_notice: StopNotice,
1384 registry: &Registry,
1385 forwarding: Option<&ForwardingTable>,
1386 snapshot: &SharedSnapshot,
1387 terminal_ring: &Arc<Mutex<TerminalRing>>,
1388 spawn_events: &SpawnEventFeed,
1389 mut child: SupervisedChild,
1390 drain_timeout: Duration,
1391 final_state: ModuleState,
1392 enabled: Option<bool>,
1393 failure: &FailureContext,
1394) -> Result<(), SuperviseError> {
1395 drain_child_to_state_inner(
1396 module_id,
1397 stop_notice,
1398 registry,
1399 forwarding,
1400 snapshot,
1401 terminal_ring,
1402 spawn_events,
1403 &mut child,
1404 drain_timeout,
1405 final_state,
1406 enabled,
1407 failure,
1408 None,
1409 &mut false,
1410 )
1411 .await
1412}
1413
1414#[cfg(any(target_os = "linux", target_os = "macos"))]
1415pub(super) const UPGRADE_KILL_GRACE: Duration = Duration::from_secs(2);
1416
1417#[cfg(any(target_os = "linux", target_os = "macos"))]
1419pub(super) async fn drain_for_upgrade(
1420 spec: &ModuleSpec,
1421 runtime: &SupervisorRuntimeConfig,
1422 registry: &Registry,
1423 snapshot: &SharedSnapshot,
1424 child: &mut Option<SupervisedChild>,
1425 stop_notice: StopNotice,
1426) -> Result<(), SuperviseError> {
1427 let failure = runtime.failure_context(true);
1428 let Some(active) = child.as_mut() else {
1429 return drain_optional_child(
1430 &spec.module_id,
1431 spec.protocol,
1432 stop_notice,
1433 registry,
1434 runtime.forwarding.as_deref(),
1435 snapshot,
1436 &runtime.terminal_ring,
1437 &runtime.spawn_events,
1438 child,
1439 runtime.drain_timeout,
1440 ModuleState::Stopped,
1441 None,
1442 &failure,
1443 )
1444 .await;
1445 };
1446 let mut exit_finalized = false;
1447 let result = drain_child_to_state_inner(
1448 &spec.module_id,
1449 stop_notice,
1450 registry,
1451 runtime.forwarding.as_deref(),
1452 snapshot,
1453 &runtime.terminal_ring,
1454 &runtime.spawn_events,
1455 active,
1456 runtime.drain_timeout,
1457 ModuleState::Stopped,
1458 None,
1459 &failure,
1460 Some(UPGRADE_KILL_GRACE),
1461 &mut exit_finalized,
1462 )
1463 .await;
1464 let stuck = matches!(&result, Err(SuperviseError::Wait { source, .. }) if source.kind() == io::ErrorKind::TimedOut);
1465 if exit_finalized || (!stuck && active.child.verified_adoptee().is_some()) {
1468 *child = None;
1469 }
1470 result
1471}
1472
1473#[allow(clippy::too_many_arguments)]
1474async fn drain_child_to_state_inner(
1475 module_id: &str,
1476 stop_notice: StopNotice,
1477 registry: &Registry,
1478 forwarding: Option<&ForwardingTable>,
1479 snapshot: &SharedSnapshot,
1480 terminal_ring: &Arc<Mutex<TerminalRing>>,
1481 spawn_events: &SpawnEventFeed,
1482 child: &mut SupervisedChild,
1483 drain_timeout: Duration,
1484 final_state: ModuleState,
1485 enabled: Option<bool>,
1486 failure: &FailureContext,
1487 kill_grace: Option<Duration>,
1488 exit_finalized: &mut bool,
1489) -> Result<(), SuperviseError> {
1490 let protocol = child.protocol;
1491 #[cfg(any(target_os = "linux", target_os = "macos"))]
1492 if kill_grace.is_none() && final_state != ModuleState::Restarting {
1493 if let Some(guard) = &mut child.roster_guard {
1494 guard.stop_adoption_without_replacement();
1495 }
1496 }
1497 child.retire_registration();
1498 update_snapshot(snapshot, Some(module_id), |state| {
1499 state.state = ModuleState::Draining;
1500 state.draining_to_replace = final_state == ModuleState::Restarting;
1501 if let Some(enabled) = enabled {
1502 state.enabled = enabled;
1503 }
1504 })?;
1505
1506 if stop_notice != StopNotice::SentOverConnection {
1517 if protocol == ModuleProtocol::Subc && stop_notice == StopNotice::NoConnection {
1518 info!(
1519 module_id,
1520 pid = child.pid,
1521 budget_ms = u64::try_from(drain_timeout.as_millis()).unwrap_or(u64::MAX),
1522 "module has no connection yet; requesting stop by signal"
1523 );
1524 }
1525 request_graceful_stop(module_id, child);
1526 }
1527
1528 let drain_timeout = child.group_drain_budget(drain_timeout, stop_notice);
1529 let exit_report = match timeout(drain_timeout, child.wait()).await {
1530 Ok(Ok(status)) => classify_reaped_child_exit(snapshot, child, &status),
1531 Ok(Err(source)) => {
1532 fail_after_wait_error(
1533 module_id,
1534 snapshot,
1535 terminal_ring,
1536 spawn_events,
1537 format!("failed to wait during drain: {source}"),
1538 failure,
1539 );
1540 return Err(SuperviseError::Wait {
1541 module_id: module_id.to_string(),
1542 source,
1543 });
1544 }
1545 Err(_) => {
1546 warn!(
1559 module_id,
1560 pid = child.pid,
1561 budget_ms = u64::try_from(drain_timeout.as_millis()).unwrap_or(u64::MAX),
1562 reason = ?final_state,
1563 ?stop_notice,
1564 "drain budget expired before the module exited; killing it"
1565 );
1566 let kill =
1567 if final_state == ModuleState::Restarting && child.child.container().is_some() {
1568 child.kill_leader()
1569 } else {
1570 child.start_kill()
1571 };
1572 kill.map_err(|source| {
1573 fail_after_wait_error(
1574 module_id,
1575 snapshot,
1576 terminal_ring,
1577 spawn_events,
1578 format!("failed to kill during drain: {source}"),
1579 failure,
1580 );
1581 SuperviseError::Kill {
1582 module_id: module_id.to_string(),
1583 source,
1584 }
1585 })?;
1586 let waited = match kill_grace {
1587 Some(grace) => timeout(grace, child.wait()).await.unwrap_or_else(|_| {
1588 Err(io::Error::new(io::ErrorKind::TimedOut, "upgrade stop did not reap the child within the kill grace; child remains owned"))
1589 }),
1590 None => child.wait().await,
1591 };
1592 let status = waited.map_err(|source| {
1593 fail_after_wait_error(
1594 module_id,
1595 snapshot,
1596 terminal_ring,
1597 spawn_events,
1598 format!("failed to wait after drain kill: {source}"),
1599 failure,
1600 );
1601 SuperviseError::Wait {
1602 module_id: module_id.to_string(),
1603 source,
1604 }
1605 })?;
1606 classify_reaped_child_exit(snapshot, child, &status)
1607 }
1608 };
1609
1610 child.drain_stderr(module_id).await;
1611 let detail =
1612 child.exit_cleanup_detail(lock_snapshot(snapshot)?.drain_disposition_detail.take());
1613 publish_after_terminal_record(
1614 module_id,
1615 || {
1616 record_terminal_with_detail(
1617 module_id,
1618 terminal_ring,
1619 spawn_events,
1620 &exit_report,
1621 terminal_disposition(final_state),
1622 detail,
1623 )
1624 },
1625 || {
1626 update_snapshot(snapshot, Some(module_id), |state| {
1627 state.state = final_state;
1628 if final_state == ModuleState::Failed {
1629 state.failed_retry.failed_at = Some(Instant::now());
1630 }
1631 if let Some(enabled) = enabled {
1632 state.enabled = enabled;
1633 }
1634 clear_current_process_facts(state);
1635 state.last_exit = Some(exit_report.clone());
1636 if exit_report.kind == ExitKind::DeliberateSeverance {
1637 state.lifetime_restarts += 1;
1638 }
1639 })
1640 },
1641 )?;
1642 let released =
1643 release_dead_registration(registry, forwarding, snapshot, module_id, failure).await;
1644 child
1645 .finish_exit(
1646 released.is_ok()
1647 && final_state == ModuleState::Restarting
1648 && child.spawn_failure.is_none(),
1649 )
1650 .await
1651 .map_err(|source| SuperviseError::Wait {
1652 module_id: module_id.to_owned(),
1653 source,
1654 })?;
1655 *exit_finalized = true;
1656 released
1657}
1658
1659#[cfg(unix)]
1679pub(super) fn request_graceful_stop(module_id: &str, child: &SupervisedChild) {
1680 if let Some(group) = &child.child.plain_group {
1681 if let Err(error) = group.signal(rustix::process::Signal::TERM) {
1682 debug!(module_id, %error, "group TERM was not delivered; the drain wait and kill still apply");
1683 }
1684 return;
1685 }
1686 #[cfg(any(target_os = "linux", target_os = "macos"))]
1687 if let Some(verified) = child.child.verified_adoptee() {
1688 if let Err(error) = verified.signal(rustix::process::Signal::TERM) {
1689 debug!(module_id, %error, "verified adopted child TERM was not delivered");
1690 }
1691 return;
1692 }
1693 let Some(pid) = child
1694 .id()
1695 .and_then(|pid| i32::try_from(pid).ok())
1696 .filter(|pid| *pid > 1)
1697 .and_then(rustix::process::Pid::from_raw)
1698 else {
1699 debug!(
1700 module_id,
1701 "no pid to signal for teardown; falling through to the drain wait"
1702 );
1703 return;
1704 };
1705 match rustix::process::kill_process(pid, rustix::process::Signal::TERM) {
1706 Ok(()) => debug!(
1707 module_id,
1708 "sent SIGTERM to a module nothing else asked to stop"
1709 ),
1710 Err(err) => debug!(
1711 module_id,
1712 error = %err,
1713 "SIGTERM to module failed; the drain wait and kill still apply"
1714 ),
1715 }
1716}
1717
1718#[cfg(not(unix))]
1726pub(super) fn request_graceful_stop(module_id: &str, _child: &SupervisedChild) {
1727 debug!(
1728 module_id,
1729 "no graceful stop signal exists on this platform; teardown of a module nothing asked to stop waits, then kills"
1730 );
1731}
1732
1733pub(super) fn terminal_disposition(final_state: ModuleState) -> TerminalDisposition {
1734 match final_state {
1735 ModuleState::Stopped => TerminalDisposition::Stopped,
1736 ModuleState::Disabled => TerminalDisposition::Disabled,
1737 ModuleState::Restarting => TerminalDisposition::Restarting,
1738 ModuleState::Failed => TerminalDisposition::Failed,
1739 ModuleState::Starting
1740 | ModuleState::Running
1741 | ModuleState::Unresponsive
1742 | ModuleState::Draining => {
1743 unreachable!("terminal exits only finish in terminal or restarting states")
1744 }
1745 }
1746}