Skip to main content

subc_daemon/supervise/
drain.rs

1use super::*;
2
3/// How long a drain waits for already-dispatched requests to finalize before
4/// the child is torn down. Sized for TOOL-SCALE work (bash, inspect, builds),
5/// not RPC-scale: the original 2s value silently cut nearly every real tool
6/// call at the fence, making the wait-for-finalize design decorative for the
7/// workloads it existed for. Quiescence short-circuits, so an idle module
8/// restarts immediately regardless of this value; the budget is spent only
9/// when a genuine in-flight request is worth finishing. Per-module override:
10/// `drain_timeout_ms` in subc.jsonc; per-restart override: the operator's
11/// `supervisor.restart{drain_timeout_ms}` (0 = cut now, for wedge bounces
12/// where a stuck request will never settle).
13pub const DEFAULT_DRAIN_TIMEOUT: Duration = Duration::from_secs(30);
14
15/// How long a drain waits after one busy-gauge probe completes before it asks
16/// again.
17///
18/// A drain re-probes on this short interval of its own rather than on the
19/// module's health cadence. The default cadence (30 s) equals the default
20/// drain ceiling, so a cadence-paced drain that found the module busy at its
21/// first probe never asked a second time: it waited out the whole ceiling and
22/// forced GOODBYE even after the gauges had read zero. The interval is counted
23/// from the moment the previous probe finished, and probes run one at a time,
24/// so a slow module is never asked more often than it can answer. Periodic
25/// health checks outside a drain keep using the configured cadence.
26const 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    /// The flag [`Self::begin_daemon_shutdown`] sets, for the control handler's
40    /// capability-requirement log to read.
41    pub(crate) fn daemon_shutdown_flag(&self) -> crate::child_roster::DaemonShutdownFlag {
42        self.child_roster.shutdown_flag()
43    }
44
45    /// The first step of an announced daemon shutdown, before the notice and
46    /// before any connection is closed.
47    ///
48    /// Sets the daemon-shutdown flag first: from here on no module is
49    /// respawned (crash restart, operator restart, or swap), and every child
50    /// exit is recorded as `daemon_shutdown` rather than as a crash, whether
51    /// the module exits on the EOF this shutdown gives it or is signalled by a
52    /// service manager that kills the whole cgroup. Queues the journal marker
53    /// without waiting for disk I/O.
54    #[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    /// Announce a cut while established connections can still carry replies.
63    /// These budgets bound the attempt to deliver notices and the wait for
64    /// routes to drain; neither guarantees delivery or child completion, and
65    /// they are local policy, not an estimate of launchd's unknown kill ceiling.
66    #[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        // `begin_daemon_shutdown` only queued the shutdown marker. Let it reach
75        // the journal before any module hears the notice, so a module that
76        // looks at the journal on the notice already finds it. A stalled
77        // writer costs at most MARKER_BUDGET; the notice goes out regardless.
78        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            // Only an announced restart promises that modules are coming back.
135            // Client route notices retain their existing reconnect semantics.
136            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        // A quiet forwarding table is not proof that queued notices reached the
180        // socket. Wait for writer flush acknowledgements before testing quiescence.
181        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                // Store the measurement before the task returns: quiescence
215                // may be reached just as the deadline stops the join loop from
216                // collecting results. Unfinished or failed waits report false.
217                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        // Measure only the forwarding drain, not child teardown or the caller's
232        // signal delivery and process-reaping delays.
233        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    /// The last step of a graceful daemon shutdown, after the notice and the
242    /// drain: send every registered module a module GOODBYE, the same planned
243    /// stop signal `ck module stop` gives, then close every connection so each
244    /// subc module sees EOF and starts its own teardown, then end every
245    /// supervised child that has not exited
246    /// by its own deadline (its drain budget, capped). Modules lead their own
247    /// process groups, so a
248    /// service manager's group kill no longer reaches them; without this a
249    /// child that does not stop on EOF (every `protocol: "none"` child, which
250    /// has no connection) would outlive the daemon. Every wait is bounded (see
251    /// `child_roster`), and `escalate` resolving (a second SIGTERM) cuts them.
252    #[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                // The operator asked to stop waiting: queue the GOODBYEs but
267                // do not wait for them to be written.
268                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        // If the second SIGTERM arrived during GOODBYE delivery, `escalate` has
283        // already completed and must not be polled again; the child shutdown
284        // wait is told it is escalated and gets a future that never fires.
285        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    /// Drain the module and stop monitoring it.
307    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/// What one health answer said about one declared busy gauge.
402#[derive(Debug, Clone, PartialEq, Eq)]
403pub(super) enum GaugeVerdict {
404    /// The gauge read 0: this gauge is not what holds the drain.
405    Zero,
406    /// The gauge read a positive count.
407    NonZero(u64),
408    /// The gauge was present but not a non-negative integer (`0.0`, a string,
409    /// a negative number). It counts as busy, because the daemon cannot tell
410    /// it is idle. Carries the value as JSON text, cut to a short prefix.
411    NotACount(String),
412    /// The health answer had no metrics object, or one without this gauge.
413    Missing,
414    /// The probe produced no health answer to read; carries the probe error's
415    /// evidence label (`no-answer` for a probe that timed out).
416    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
437/// The longest JSON text kept for a gauge value that is not a count, so a
438/// module reporting a large object as a gauge cannot flood the drain log.
439const GAUGE_VALUE_TEXT_LIMIT: usize = 32;
440
441/// Read each declared gauge out of one health answer's metrics.
442pub(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
470/// The drain's overall reading of one health answer: omitted when any
471/// declared gauge is missing, quiescent only when every gauge reads 0.
472pub(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/// One declared gauge's history over a drain: the latest verdict on it, and
486/// the latest value actually read for it (which a later failed probe or
487/// missing gauge does not erase). Times are offsets from the start of the
488/// drain's wait.
489#[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/// What a drain's busy-gauge probes saw, kept so that a drain which runs to
496/// its ceiling can say in its timeout line which declared gauge held it and
497/// why. Without it, a gauge that read busy, a gauge the module never
498/// reported, and a probe that never got an answer all looked the same: a
499/// drain that ended at its ceiling with nothing in flight.
500#[derive(Debug, Clone, Default, PartialEq, Eq)]
501pub(super) struct DrainGaugeTrace {
502    /// Health probes the drain sent.
503    pub(super) probes: u32,
504    /// Each declared gauge, in declaration order.
505    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    /// Record one probe's verdicts, one per declared gauge, `at` into the drain.
520    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
534/// Renders as `gauge: latest verdict @ offset; last value @ offset` for each
535/// declared gauge, separated by ` | `. A value is shown as its verdict
536/// (`zero`, `non_zero(n)`, `not_a_count(json)`), so it says both what was read
537/// and whether that counted as busy.
538impl 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
572/// [`declared_busy_gauges`] for the registration a connection holds, in any
573/// slot: after cutover the incumbent is no longer the id's active
574/// registration, and its own manifest is the one that names its gauges.
575fn 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                // An invalid Busy anchor is fail-safe: the empty name cannot be
607                // present in a conforming health report, so this drain stays busy.
608                gauges.push(String::new());
609            }
610        }
611    }
612    Ok(gauges)
613}
614
615/// Wait for `endpoint` to have nothing in flight and, when the module declares
616/// busy gauges, for a health probe to report them quiet. The probe is addressed
617/// by `scope`: a swap's superseded incumbent must be asked about its own
618/// gauges, and by module id the probe would reach the promoted candidate.
619/// While the gauges read busy, the probe repeats every
620/// [`DRAIN_BUSY_REPROBE_INTERVAL`] until they read quiet or `deadline` passes.
621/// Every probe's reading of each gauge is recorded in `trace`, for the caller's
622/// timeout line.
623#[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                        // Once per drain: a module that never reports a gauge
659                        // it declared would otherwise say so on every probe.
660                        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            // Counted from the probe's completion: the probe above was awaited,
691            // so no second probe can start while one is still outstanding.
692            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
716/// The wait between drain busy-gauge probes: the larger of
717/// [`DRAIN_BUSY_REPROBE_INTERVAL`] and [`REGISTRY_RELEASE_POLL`], the
718/// drain's own in-flight poll interval.
719pub(super) fn drain_busy_reprobe_interval() -> Duration {
720    DRAIN_BUSY_REPROBE_INTERVAL.max(REGISTRY_RELEASE_POLL)
721}
722
723/// Logs why a drain gave up: the drain waited its full timeout without the
724/// module going quiet, and teardown is being forced.
725///
726/// The line names two kinds of evidence, because a bare "timed out" hides
727/// causes that need different fixes:
728/// - `holdouts`: the requests and routes still open when the timeout hit,
729///   and on which connections. One stuck call is a module bug; a held stream
730///   on every session is a module that should end its streams when it
731///   receives `module.draining`.
732/// - `gauges`: for each busy gauge the module declares, its latest reading
733///   and how many probes ran. This separates a module that kept reporting
734///   itself busy, one whose health answer never contained the gauge, and one
735///   that never answered the probes, which otherwise all look like a timeout
736///   with nothing in flight.
737pub(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        // `module_channel:corr`, so the module can find each held request
753        // in its own log; capped, so `held_requests` is the full count.
754        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
766/// The `route.closed` `drained` value implied by a quiescence-wait outcome.
767///
768/// `Ok` is always honest and passed straight through -- the wait actually measured
769/// in-flight state. `Err` means the wait produced no measurement at all (the
770/// forwarding table's lock was poisoned), so `false` is reported as the one honest
771/// constant: the drain did not complete. Never recomputed from route state, never a
772/// third "unknown" value -- the caller must still send a well-formed `route.closed`.
773pub(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
894/// The channel-0 GOODBYE that tells a module its stop is planned.
895fn 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/// Send every registered module connection its module GOODBYE at daemon
918/// shutdown, then request that connection's close.
919///
920/// A module tells a planned stop from a lost daemon by whether a GOODBYE came
921/// before EOF, so the GOODBYE must reach the socket before the close. A close
922/// request does not wait for the connection's queued frames: its writer gets a
923/// bounded grace after the close, is aborted if it overruns it, and the daemon
924/// process may exit before that grace ends. So with `wait_for_flush`, each
925/// connection is closed only after its writer has acknowledged writing the
926/// GOODBYE, or once a short shared budget runs out, so one module that is not
927/// reading cannot hold up the others or the shutdown. Without it the GOODBYEs
928/// are only queued, for a shutdown the operator has told to stop waiting.
929/// A connection that is already gone is skipped.
930#[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    // Every task ends by the shared deadline, so this wait is bounded too.
980    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    // A channel is shut down synchronously after its drain. Its final frame
993    // must reach the socket writer first; queue admission alone can lose it.
994    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/// Which process a forwarding drain addresses.
1028#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1029pub(super) enum DrainScope {
1030    /// Whatever endpoint is active for the module id: every plain stop,
1031    /// restart and reload. Also moves the module's state to `Draining`.
1032    Active,
1033    /// One specific endpoint: a swap's incumbent after cutover. Draining it by
1034    /// module id would resolve to the promoted candidate and leave neither
1035    /// process routable. The module's state is left alone, since the promoted
1036    /// candidate is what it describes and that process is running.
1037    Endpoint(crate::ModuleEndpointId),
1038}
1039
1040/// Whether a child being drained has already been asked to stop by the time
1041/// its drain wait starts.
1042///
1043/// The drain wait is the same budget whatever this says. What it decides is
1044/// whether the supervisor must ask by signal before that wait begins: a child
1045/// that nobody asked will sit out the whole budget and then be SIGKILLed,
1046/// healthy or not.
1047#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1048pub(super) enum StopNotice {
1049    /// The module was sent `module.draining` and a module GOODBYE over its own
1050    /// registered connection, and stops itself.
1051    SentOverConnection,
1052    /// The forwarding drain found no registered connection for the module: a
1053    /// subc child spawned moments ago that has not sent HELLO yet, or a
1054    /// `protocol: "none"` child, which never registers.
1055    NoConnection,
1056    /// This path sends nothing over the module's connection: the supervisor has
1057    /// no forwarding table, or the caller stops the child without a forwarding
1058    /// drain.
1059    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
1113/// Like [`begin_forwarding_drain_if_configured`] but with an explicit drain
1114/// budget, for paths where the operator overrides the module's configured one
1115/// (`supervisor.restart{drain_timeout_ms}`).
1116pub(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    // Admission gate first: route.open/commit and route REQUEST admission are closed
1173    // before the first quiescence check, so the outstanding count can only fall.
1174    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    // The instant admission closed, and how long taking the forwarding write
1181    // lock to close it took. The timeout line reports only the quiescence
1182    // wait, so without this a drain that started late looked like one that
1183    // started on time.
1184    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        // Nothing was sent: the module has no registered connection to carry
1204        // `module.draining` or a GOODBYE. The caller must not assume the child
1205        // was asked to stop.
1206        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        // `route.closing` was just sent above: from here on every return path,
1233        // including an early one, MUST send `route.closed` before propagating
1234        // anything else. A client holds `closing` as a promise that a verdict is
1235        // coming; leaving early without `closed` strands it waiting forever, since
1236        // `closing` carries no timeout of its own.
1237        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            // Read before teardown releases the routes.
1259            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        // `route.closed` has now been sent unconditionally above. From here the
1286        // remaining steps are cleanup (route + module GOODBYE) rather than a
1287        // promise the client is waiting on, but a lock-poisoned
1288        // `release_module_endpoint_routes` would otherwise skip the module
1289        // GOODBYE silently too -- send it before propagating the error.
1290        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        // The drain's happy path was previously silent: every emission above is
1308        // best-effort with only its failure arm logged, so "were consumers told"
1309        // was unprovable from the daemon log (surfaced by a 30-minute consumer
1310        // hang where the open question was exactly whether teardown notice went
1311        // out). One summary line makes that class decidable in one grep.
1312        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    let protocol = child.protocol;
1396    child.retire_registration();
1397    update_snapshot(snapshot, Some(module_id), |state| {
1398        state.state = ModuleState::Draining;
1399        state.draining_to_replace = final_state == ModuleState::Restarting;
1400        if let Some(enabled) = enabled {
1401            state.enabled = enabled;
1402        }
1403    })?;
1404
1405    // The wait below is the same budget in every case; what differs is
1406    // whether anything has ASKED the child to stop before it starts. Only a
1407    // forwarding drain that reached the module's registered connection has
1408    // (`module.draining`, then a module GOODBYE). Every other child was told
1409    // nothing: a `protocol: "none"` module, which never registers; a subc
1410    // module spawned moments ago that has not sent HELLO yet; or a stop that
1411    // runs no forwarding drain. Without a signal the budget is only a delay
1412    // in front of SIGKILL -- and the not-yet-registered child is the worst
1413    // case, because it registers into a module that is already draining,
1414    // is never told, and is killed while healthy.
1415    if stop_notice != StopNotice::SentOverConnection {
1416        if protocol == ModuleProtocol::Subc && stop_notice == StopNotice::NoConnection {
1417            info!(
1418                module_id,
1419                pid = child.pid,
1420                budget_ms = u64::try_from(drain_timeout.as_millis()).unwrap_or(u64::MAX),
1421                "module has no connection yet; requesting stop by signal"
1422            );
1423        }
1424        request_graceful_stop(module_id, &child);
1425    }
1426
1427    let drain_timeout = child.group_drain_budget(drain_timeout, stop_notice);
1428    let exit_report = match timeout(drain_timeout, child.wait()).await {
1429        Ok(Ok(status)) => classify_reaped_child_exit(snapshot, &child, &status),
1430        Ok(Err(source)) => {
1431            fail_after_wait_error(
1432                module_id,
1433                snapshot,
1434                terminal_ring,
1435                spawn_events,
1436                format!("failed to wait during drain: {source}"),
1437                failure,
1438            );
1439            return Err(SuperviseError::Wait {
1440                module_id: module_id.to_string(),
1441                source,
1442            });
1443        }
1444        Err(_) => {
1445            // Mirror the sibling arm above: state is already `Draining`, and an
1446            // error propagated from here would strand it there -- a state
1447            // `set_enabled(true)` cannot heal (`revive_terminal` matches only
1448            // `Failed | Stopped`), leaving an operator Restart as the only exit.
1449            // `Failed` before `?` keeps the module operator-visible and
1450            // revivable. Trigger is an ESRCH race (process exits between the
1451            // drain timeout firing and the kill) or a post-kill wait failure
1452            // (issue #34).
1453            //
1454            // Logged because the kill is otherwise visible only as signal 9 in
1455            // the terminal ring, and the budget it follows can be long enough
1456            // that consumers see a stretch of refusals with no stated cause.
1457            warn!(
1458                module_id,
1459                pid = child.pid,
1460                budget_ms = u64::try_from(drain_timeout.as_millis()).unwrap_or(u64::MAX),
1461                reason = ?final_state,
1462                ?stop_notice,
1463                "drain budget expired before the module exited; killing it"
1464            );
1465            let kill =
1466                if final_state == ModuleState::Restarting && child.child.container().is_some() {
1467                    child.kill_leader()
1468                } else {
1469                    child.start_kill()
1470                };
1471            kill.map_err(|source| {
1472                fail_after_wait_error(
1473                    module_id,
1474                    snapshot,
1475                    terminal_ring,
1476                    spawn_events,
1477                    format!("failed to kill during drain: {source}"),
1478                    failure,
1479                );
1480                SuperviseError::Kill {
1481                    module_id: module_id.to_string(),
1482                    source,
1483                }
1484            })?;
1485            let status = child.wait().await.map_err(|source| {
1486                fail_after_wait_error(
1487                    module_id,
1488                    snapshot,
1489                    terminal_ring,
1490                    spawn_events,
1491                    format!("failed to wait after drain kill: {source}"),
1492                    failure,
1493                );
1494                SuperviseError::Wait {
1495                    module_id: module_id.to_string(),
1496                    source,
1497                }
1498            })?;
1499            classify_reaped_child_exit(snapshot, &child, &status)
1500        }
1501    };
1502
1503    child.drain_stderr(module_id).await;
1504    let detail =
1505        child.exit_cleanup_detail(lock_snapshot(snapshot)?.drain_disposition_detail.take());
1506    publish_after_terminal_record(
1507        module_id,
1508        || {
1509            record_terminal_with_detail(
1510                module_id,
1511                terminal_ring,
1512                spawn_events,
1513                &exit_report,
1514                terminal_disposition(final_state),
1515                detail,
1516            )
1517        },
1518        || {
1519            update_snapshot(snapshot, Some(module_id), |state| {
1520                state.state = final_state;
1521                if final_state == ModuleState::Failed {
1522                    state.failed_retry.failed_at = Some(Instant::now());
1523                }
1524                if let Some(enabled) = enabled {
1525                    state.enabled = enabled;
1526                }
1527                clear_current_process_facts(state);
1528                state.last_exit = Some(exit_report.clone());
1529                if exit_report.kind == ExitKind::DeliberateSeverance {
1530                    state.lifetime_restarts += 1;
1531                }
1532            })
1533        },
1534    )?;
1535    let released =
1536        release_dead_registration(registry, forwarding, snapshot, module_id, failure).await;
1537    child
1538        .finish_exit(
1539            released.is_ok()
1540                && final_state == ModuleState::Restarting
1541                && child.spawn_failure.is_none(),
1542        )
1543        .await
1544        .map_err(|source| SuperviseError::Wait {
1545            module_id: module_id.to_owned(),
1546            source,
1547        })?;
1548    released
1549}
1550
1551/// Ask a child that nothing else has asked to stop, by signal.
1552///
1553/// A registered subc module is asked over its own connection: the drain sends
1554/// `route.closing`/`route.closed` to its consumers, a GOODBYE per route, then a
1555/// module GOODBYE, and the module stops itself. A module that speaks no subc
1556/// wire receives none of that, and neither does a subc module that has not
1557/// registered yet, so for them the drain budget would be pure delay in front of
1558/// a SIGKILL -- and for a process with a store to flush (JetStream is the
1559/// reason `protocol: "none"` exists) a SIGKILL turns every ordinary teardown
1560/// into a recovery on the next start.
1561///
1562/// NEVER CALLED FOR A MODULE THAT WAS TOLD OVER ITS CONNECTION, and that is a
1563/// rule rather than an optimisation: that module's graceful stop is already
1564/// running by the time its child is drained, and a signal would race it.
1565///
1566/// Best-effort by construction. A child that has already exited is the ordinary
1567/// case rather than an error (the kill lands on a reaped or exiting pid), so a
1568/// failure is logged at debug and the wait-then-kill below still decides the
1569/// outcome.
1570#[cfg(unix)]
1571pub(super) fn request_graceful_stop(module_id: &str, child: &SupervisedChild) {
1572    if let Some(group) = &child.child.plain_group {
1573        if let Err(error) = group.signal(rustix::process::Signal::TERM) {
1574            debug!(module_id, %error, "group TERM was not delivered; the drain wait and kill still apply");
1575        }
1576        return;
1577    }
1578    let Some(pid) = child
1579        .id()
1580        .and_then(|pid| i32::try_from(pid).ok())
1581        .filter(|pid| *pid > 1)
1582        .and_then(rustix::process::Pid::from_raw)
1583    else {
1584        debug!(
1585            module_id,
1586            "no pid to signal for teardown; falling through to the drain wait"
1587        );
1588        return;
1589    };
1590    match rustix::process::kill_process(pid, rustix::process::Signal::TERM) {
1591        Ok(()) => debug!(
1592            module_id,
1593            "sent SIGTERM to a module nothing else asked to stop"
1594        ),
1595        Err(err) => debug!(
1596            module_id,
1597            error = %err,
1598            "SIGTERM to module failed; the drain wait and kill still apply"
1599        ),
1600    }
1601}
1602
1603/// Windows has no SIGTERM and no portable stand-in for one. The graceful stops
1604/// Windows does offer need cooperation this supervisor cannot assume: a console
1605/// control event requires sharing a console with the child, and `WM_CLOSE`
1606/// requires the child to pump a message loop. A supervised server process does
1607/// neither, so there is nothing to send and teardown is the wait followed by the
1608/// kill. Emulating a signal here would mean inventing a stop protocol, which is
1609/// the thing `protocol: "none"` exists to avoid.
1610#[cfg(not(unix))]
1611pub(super) fn request_graceful_stop(module_id: &str, _child: &SupervisedChild) {
1612    debug!(
1613        module_id,
1614        "no graceful stop signal exists on this platform; teardown of a module nothing asked to stop waits, then kills"
1615    );
1616}
1617
1618pub(super) fn terminal_disposition(final_state: ModuleState) -> TerminalDisposition {
1619    match final_state {
1620        ModuleState::Stopped => TerminalDisposition::Stopped,
1621        ModuleState::Disabled => TerminalDisposition::Disabled,
1622        ModuleState::Restarting => TerminalDisposition::Restarting,
1623        ModuleState::Failed => TerminalDisposition::Failed,
1624        ModuleState::Starting
1625        | ModuleState::Running
1626        | ModuleState::Unresponsive
1627        | ModuleState::Draining => {
1628            unreachable!("terminal exits only finish in terminal or restarting states")
1629        }
1630    }
1631}