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        let Some(forwarding) = &self.forwarding else {
71            return Ok(());
72        };
73        let notice_started = Instant::now();
74        let modules = forwarding
75            .begin_daemon_drain()
76            .map_err(SuperviseError::Forwarding)?;
77        let deadline_ms =
78            unix_ms_now().saturating_add((NOTICE_BUDGET + DRAIN_BUDGET).as_millis() as u64);
79        let shutdown_reason = self
80            .supervisor_handle
81            .as_ref()
82            .map(SupervisorHandle::take_daemon_shutdown_reason)
83            .unwrap_or(RouteCloseReason::Disable);
84        let mut modules_told = 0;
85        let mut notices = tokio::task::JoinSet::new();
86        let mut drains = Vec::new();
87        for connection in forwarding
88            .module_connections()
89            .map_err(SuperviseError::Forwarding)?
90        {
91            let target = ModuleDrainTarget {
92                endpoint: connection.endpoint,
93                sink: connection.sink,
94                negotiated_ver: connection.negotiated_ver,
95                abandoned_bindings: Vec::new(),
96                excluded_subscriptions: 0,
97            };
98            notices.spawn(async move {
99                (
100                    true,
101                    send_module_draining(
102                        &connection.module_id,
103                        shutdown_reason,
104                        deadline_ms,
105                        &target,
106                        true,
107                    )
108                    .await,
109                )
110            });
111        }
112        for (module_id, endpoint) in modules {
113            let Some(target) = forwarding
114                .begin_endpoint_drain(endpoint, RouteCloseReason::Restart)
115                .map_err(SuperviseError::Forwarding)?
116            else {
117                continue;
118            };
119            let routes = forwarding
120                .endpoint_routes(target.endpoint)
121                .map_err(SuperviseError::Forwarding)?;
122            // Only an announced restart promises that modules are coming back.
123            // Client route notices retain their existing reconnect semantics.
124            let mut recipients = Vec::new();
125            let mut clients: Vec<(crate::forwarding::GoodbyeTarget, Vec<u16>)> = Vec::new();
126            for route in routes {
127                let client = route.goodbye_target;
128                if let Some((_, channels)) = clients
129                    .iter_mut()
130                    .find(|(existing, _)| existing.connection_id == client.connection_id)
131                {
132                    channels.push(client.channel);
133                } else {
134                    let channel = client.channel;
135                    clients.push((client, vec![channel]));
136                }
137            }
138            for (client, mut channels) in clients {
139                channels.sort_unstable();
140                channels.dedup();
141                let closing = serde_json::to_vec(&ClientControlPush::RouteClosing {
142                    module_id: module_id.clone(),
143                    channels,
144                    reason: RouteCloseReason::Restart,
145                })
146                .expect("route closing serializes");
147                recipients.push((client.sink, client.negotiated_ver, closing));
148            }
149            for (sink, version, body) in recipients {
150                notices.spawn(async move {
151                    let frame = Frame::build_with_version(
152                        version,
153                        FrameType::Push,
154                        control_flags(),
155                        0,
156                        0,
157                        0,
158                        body,
159                    )
160                    .expect("bounded lifecycle notice frame builds");
161                    (false, sink.send_flushed(frame).await.is_ok())
162                });
163            }
164            let gauges = declared_busy_gauges(&self.registry, &module_id)?;
165            drains.push((module_id, target.endpoint, gauges));
166        }
167        // A quiet forwarding table is not proof that queued notices reached the
168        // socket. Wait for writer flush acknowledgements before testing quiescence.
169        let notice_deadline = Instant::now() + NOTICE_BUDGET;
170        while let Ok(Some(result)) = timeout_at(notice_deadline, notices.join_next()).await {
171            match result {
172                Ok((true, true)) => modules_told += 1,
173                Ok((false, true)) => {}
174                result => warn!(?result, "daemon shutdown notice delivery failed"),
175            }
176        }
177        notices.abort_all();
178        info!(
179            ?shutdown_reason,
180            modules_told, "daemon shutdown module notices delivered"
181        );
182        let notice_elapsed = notice_started.elapsed();
183        let drain_started = Instant::now();
184        let deadline = drain_started + DRAIN_BUDGET;
185        let mut waits = tokio::task::JoinSet::new();
186        for (module_id, endpoint, gauges) in drains {
187            let forwarding = Arc::clone(forwarding);
188            let mut runtime = self.runtime_config();
189            runtime.health.cadence = Duration::from_millis(100);
190            waits.spawn(async move {
191                let wait_result = wait_for_forwarding_quiescence(
192                    &forwarding,
193                    &module_id,
194                    &runtime,
195                    endpoint,
196                    deadline,
197                    &gauges,
198                    DrainScope::Endpoint(endpoint),
199                    &mut DrainGaugeTrace::new(&gauges),
200                )
201                .await;
202                // Store the measurement before the task returns: quiescence
203                // may be reached just as the deadline stops the join loop from
204                // collecting results. Unfinished or failed waits report false.
205                forwarding
206                    .record_daemon_drain_result(
207                        endpoint,
208                        drained_after_quiescence_wait(&wait_result),
209                    )
210                    .map_err(SuperviseError::Forwarding)?;
211                wait_result
212            });
213        }
214        while let Ok(Some(result)) = timeout_at(deadline, waits.join_next()).await {
215            if !matches!(result, Ok(Ok(true))) {
216                warn!(?result, "daemon shutdown drain did not reach quiescence");
217            }
218        }
219        // Measure only the forwarding drain, not child teardown or the caller's
220        // signal delivery and process-reaping delays.
221        info!(
222            notice_elapsed_ms = notice_elapsed.as_millis() as u64,
223            drain_elapsed_ms = drain_started.elapsed().as_millis() as u64,
224            "daemon shutdown forwarding drain complete"
225        );
226        Ok(())
227    }
228
229    /// The last step of a graceful daemon shutdown, after the notice and the
230    /// drain: send every registered module a module GOODBYE, the same planned
231    /// stop signal `ck module stop` gives, then close every connection so each
232    /// subc module sees EOF and starts its own teardown, then end every
233    /// supervised child that has not exited
234    /// by its own deadline (its drain budget, capped). Modules lead their own
235    /// process groups, so a
236    /// service manager's group kill no longer reaches them; without this a
237    /// child that does not stop on EOF (every `protocol: "none"` child, which
238    /// has no connection) would outlive the daemon. Every wait is bounded (see
239    /// `child_roster`), and `escalate` resolving (a second SIGTERM) cuts them.
240    #[cfg(unix)]
241    pub(crate) async fn end_children_for_daemon_shutdown(
242        &self,
243        already_escalated: bool,
244        escalate: impl std::future::Future<Output = ()>,
245    ) {
246        tokio::pin!(escalate);
247        let mut escalated = already_escalated;
248        if let Some(forwarding) = &self.forwarding {
249            let reason = CloseReason::new(
250                "daemon_shutdown",
251                "the daemon is exiting after its shutdown notice and drain",
252            );
253            if escalated {
254                // The operator asked to stop waiting: queue the GOODBYEs but
255                // do not wait for them to be written.
256                send_module_goodbyes_for_daemon_shutdown(forwarding, &reason, false).await;
257            } else {
258                tokio::select! {
259                    biased;
260                    _ = escalate.as_mut() => {
261                        info!("second SIGTERM: abandoning module GOODBYE delivery");
262                        escalated = true;
263                    }
264                    _ = send_module_goodbyes_for_daemon_shutdown(forwarding, &reason, true) => {}
265                }
266            }
267            let closed = forwarding.close_all_connections(&reason);
268            debug!(closed, "closed established connections for daemon shutdown");
269        }
270        // If the second SIGTERM arrived during GOODBYE delivery, `escalate` has
271        // already completed and must not be polled again; the child shutdown
272        // wait is told it is escalated and gets a future that never fires.
273        let escalated_here = escalated && !already_escalated;
274        let remaining_escalate = async move {
275            if escalated_here {
276                std::future::pending::<()>().await;
277            } else {
278                escalate.await;
279            }
280        };
281        crate::child_roster::end_children_for_daemon_shutdown(
282            &self.child_roster,
283            escalated,
284            remaining_escalate,
285        )
286        .await;
287        if let Some(journal) = &self.terminal_journal {
288            journal.flush_shutdown().await;
289        }
290    }
291}
292
293impl SupervisedModule {
294    /// Drain the module and stop monitoring it.
295    pub async fn drain(&self) -> Result<(), SuperviseError> {
296        self.stop().await
297    }
298
299    pub(crate) async fn retire_requested(
300        &self,
301        requester: Option<Principal>,
302    ) -> Result<(), SuperviseError> {
303        match self.state()? {
304            ModuleState::Stopped => return Ok(()),
305            ModuleState::Failed
306                if lock_snapshot(&self.inner.snapshot)?
307                    .failed_retry
308                    .pending
309                    .is_none() =>
310            {
311                return Ok(())
312            }
313            ModuleState::Failed
314            | ModuleState::Starting
315            | ModuleState::Running
316            | ModuleState::Unresponsive
317            | ModuleState::Restarting
318            | ModuleState::Draining
319            | ModuleState::Disabled => {}
320        }
321
322        let (reply_tx, reply_rx) = oneshot::channel();
323        self.inner
324            .commands
325            .send(SupervisorCommand::Retire {
326                requester,
327                reply: reply_tx,
328            })
329            .await
330            .map_err(|_| SuperviseError::CommandClosed {
331                module_id: self.inner.module_id.clone(),
332            })?;
333        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
334            module_id: self.inner.module_id.clone(),
335        })?
336    }
337
338    pub async fn stop(&self) -> Result<(), SuperviseError> {
339        self.stop_requested(None).await
340    }
341
342    pub(crate) async fn stop_requested(
343        &self,
344        requester: Option<Principal>,
345    ) -> Result<(), SuperviseError> {
346        match self.state()? {
347            ModuleState::Stopped => return Ok(()),
348            ModuleState::Failed
349                if lock_snapshot(&self.inner.snapshot)?
350                    .failed_retry
351                    .pending
352                    .is_none() =>
353            {
354                return Ok(())
355            }
356            ModuleState::Failed
357            | ModuleState::Starting
358            | ModuleState::Running
359            | ModuleState::Unresponsive
360            | ModuleState::Restarting
361            | ModuleState::Draining
362            | ModuleState::Disabled => {}
363        }
364
365        let (reply_tx, reply_rx) = oneshot::channel();
366        self.inner
367            .commands
368            .send(SupervisorCommand::Drain {
369                requester,
370                reply: reply_tx,
371            })
372            .await
373            .map_err(|_| SuperviseError::CommandClosed {
374                module_id: self.inner.module_id.clone(),
375            })?;
376        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
377            module_id: self.inner.module_id.clone(),
378        })?
379    }
380}
381
382#[derive(Debug, Clone, Copy, PartialEq, Eq)]
383pub(super) enum BusyGaugeObservation {
384    Quiescent,
385    Busy,
386    Omitted,
387}
388
389/// What one health answer said about one declared busy gauge.
390#[derive(Debug, Clone, PartialEq, Eq)]
391pub(super) enum GaugeVerdict {
392    /// The gauge read 0: this gauge is not what holds the drain.
393    Zero,
394    /// The gauge read a positive count.
395    NonZero(u64),
396    /// The gauge was present but not a non-negative integer (`0.0`, a string,
397    /// a negative number). It counts as busy, because the daemon cannot tell
398    /// it is idle. Carries the value as JSON text, cut to a short prefix.
399    NotACount(String),
400    /// The health answer had no metrics object, or one without this gauge.
401    Missing,
402    /// The probe produced no health answer to read; carries the probe error's
403    /// evidence label (`no-answer` for a probe that timed out).
404    ProbeFailed(&'static str),
405}
406
407impl GaugeVerdict {
408    fn reads_quiet(&self) -> bool {
409        matches!(self, Self::Zero)
410    }
411}
412
413impl fmt::Display for GaugeVerdict {
414    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
415        match self {
416            Self::Zero => f.write_str("zero"),
417            Self::NonZero(value) => write!(f, "non_zero({value})"),
418            Self::NotACount(value) => write!(f, "not_a_count({value})"),
419            Self::Missing => f.write_str("missing_from_health_body"),
420            Self::ProbeFailed(kind) => write!(f, "probe_failed({kind})"),
421        }
422    }
423}
424
425/// The longest JSON text kept for a gauge value that is not a count, so a
426/// module reporting a large object as a gauge cannot flood the drain log.
427const GAUGE_VALUE_TEXT_LIMIT: usize = 32;
428
429/// Read each declared gauge out of one health answer's metrics.
430pub(super) fn gauge_verdicts(metrics: Option<&Value>, gauges: &[String]) -> Vec<GaugeVerdict> {
431    let metrics = metrics.and_then(Value::as_object);
432    gauges
433        .iter()
434        .map(
435            |gauge| match metrics.and_then(|metrics| metrics.get(gauge)) {
436                None => GaugeVerdict::Missing,
437                Some(value) => match value.as_u64() {
438                    Some(0) => GaugeVerdict::Zero,
439                    Some(count) => GaugeVerdict::NonZero(count),
440                    None => {
441                        let mut text = value.to_string();
442                        if text.len() > GAUGE_VALUE_TEXT_LIMIT {
443                            let mut end = GAUGE_VALUE_TEXT_LIMIT;
444                            while !text.is_char_boundary(end) {
445                                end -= 1;
446                            }
447                            text.truncate(end);
448                            text.push_str("...");
449                        }
450                        GaugeVerdict::NotACount(text)
451                    }
452                },
453            },
454        )
455        .collect()
456}
457
458/// The drain's overall reading of one health answer: omitted when any
459/// declared gauge is missing, quiescent only when every gauge reads 0.
460pub(super) fn busy_gauge_observation(verdicts: &[GaugeVerdict]) -> BusyGaugeObservation {
461    if verdicts
462        .iter()
463        .any(|verdict| matches!(verdict, GaugeVerdict::Missing))
464    {
465        BusyGaugeObservation::Omitted
466    } else if verdicts.iter().all(GaugeVerdict::reads_quiet) {
467        BusyGaugeObservation::Quiescent
468    } else {
469        BusyGaugeObservation::Busy
470    }
471}
472
473/// One declared gauge's history over a drain: the latest verdict on it, and
474/// the latest value actually read for it (which a later failed probe or
475/// missing gauge does not erase). Times are offsets from the start of the
476/// drain's wait.
477#[derive(Debug, Clone, Default, PartialEq, Eq)]
478pub(super) struct GaugeTrace {
479    pub(super) latest: Option<(GaugeVerdict, Duration)>,
480    pub(super) last_value: Option<(GaugeVerdict, Duration)>,
481}
482
483/// What a drain's busy-gauge probes saw, kept so that a drain which runs to
484/// its ceiling can say in its timeout line which declared gauge held it and
485/// why. Without it, a gauge that read busy, a gauge the module never
486/// reported, and a probe that never got an answer all looked the same: a
487/// drain that ended at its ceiling with nothing in flight.
488#[derive(Debug, Clone, Default, PartialEq, Eq)]
489pub(super) struct DrainGaugeTrace {
490    /// Health probes the drain sent.
491    pub(super) probes: u32,
492    /// Each declared gauge, in declaration order.
493    pub(super) gauges: Vec<(String, GaugeTrace)>,
494}
495
496impl DrainGaugeTrace {
497    pub(super) fn new(gauges: &[String]) -> Self {
498        Self {
499            probes: 0,
500            gauges: gauges
501                .iter()
502                .map(|gauge| (gauge.clone(), GaugeTrace::default()))
503                .collect(),
504        }
505    }
506
507    /// Record one probe's verdicts, one per declared gauge, `at` into the drain.
508    fn record(&mut self, verdicts: &[GaugeVerdict], at: Duration) {
509        self.probes = self.probes.saturating_add(1);
510        for ((_, trace), verdict) in self.gauges.iter_mut().zip(verdicts) {
511            trace.latest = Some((verdict.clone(), at));
512            if matches!(
513                verdict,
514                GaugeVerdict::Zero | GaugeVerdict::NonZero(_) | GaugeVerdict::NotACount(_)
515            ) {
516                trace.last_value = Some((verdict.clone(), at));
517            }
518        }
519    }
520}
521
522/// Renders as `gauge: latest verdict @ offset; last value @ offset` for each
523/// declared gauge, separated by ` | `. A value is shown as its verdict
524/// (`zero`, `non_zero(n)`, `not_a_count(json)`), so it says both what was read
525/// and whether that counted as busy.
526impl fmt::Display for DrainGaugeTrace {
527    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
528        if self.gauges.is_empty() {
529            return f.write_str("none declared");
530        }
531        for (index, (name, trace)) in self.gauges.iter().enumerate() {
532            if index > 0 {
533                f.write_str(" | ")?;
534            }
535            write!(f, "{name}: ")?;
536            match &trace.latest {
537                Some((verdict, at)) => write!(f, "{verdict} @{}ms", at.as_millis())?,
538                None => f.write_str("never probed")?,
539            }
540            match &trace.last_value {
541                Some((value, at)) => write!(f, "; last value {value} @{}ms", at.as_millis())?,
542                None => f.write_str("; no value ever read")?,
543            }
544        }
545        Ok(())
546    }
547}
548
549pub(crate) fn declared_busy_gauges(
550    registry: &Registry,
551    module_id: &str,
552) -> Result<Vec<String>, SuperviseError> {
553    busy_gauges_of(
554        registry
555            .get_module(module_id)
556            .map_err(SuperviseError::Registry)?,
557    )
558}
559
560/// [`declared_busy_gauges`] for the registration a connection holds, in any
561/// slot: after cutover the incumbent is no longer the id's active
562/// registration, and its own manifest is the one that names its gauges.
563fn declared_busy_gauges_for_connection(
564    registry: &Registry,
565    connection_id: ConnectionId,
566) -> Result<Vec<String>, SuperviseError> {
567    busy_gauges_of(
568        registry
569            .get_module_by_connection(connection_id)
570            .map_err(SuperviseError::Registry)?,
571    )
572}
573
574fn busy_gauges_of(
575    registration: Option<crate::registry::ModuleRegistration>,
576) -> Result<Vec<String>, SuperviseError> {
577    let Some(registration) = registration else {
578        return Ok(Vec::new());
579    };
580    let Some(self_signals) = registration.manifest.self_signals else {
581        return Ok(Vec::new());
582    };
583
584    let mut gauges = Vec::new();
585    for declaration in self_signals {
586        if declaration.kind != SelfSignalKind::Busy {
587            continue;
588        }
589        match declaration.anchored_to {
590            SignalAnchor::HealthGauges { gauges: declared } if !declared.is_empty() => {
591                gauges.extend(declared)
592            }
593            _ => {
594                // An invalid Busy anchor is fail-safe: the empty name cannot be
595                // present in a conforming health report, so this drain stays busy.
596                gauges.push(String::new());
597            }
598        }
599    }
600    Ok(gauges)
601}
602
603/// Wait for `endpoint` to have nothing in flight and, when the module declares
604/// busy gauges, for a health probe to report them quiet. The probe is addressed
605/// by `scope`: a swap's superseded incumbent must be asked about its own
606/// gauges, and by module id the probe would reach the promoted candidate.
607/// While the gauges read busy, the probe repeats every
608/// [`DRAIN_BUSY_REPROBE_INTERVAL`] until they read quiet or `deadline` passes.
609/// Every probe's reading of each gauge is recorded in `trace`, for the caller's
610/// timeout line.
611#[allow(clippy::too_many_arguments)]
612pub(super) async fn wait_for_forwarding_quiescence(
613    forwarding: &ForwardingTable,
614    module_id: &str,
615    runtime: &SupervisorRuntimeConfig,
616    endpoint: crate::ModuleEndpointId,
617    deadline: Instant,
618    busy_gauges: &[String],
619    scope: DrainScope,
620    trace: &mut DrainGaugeTrace,
621) -> Result<bool, SuperviseError> {
622    let wait_started = Instant::now();
623    let mut gauges_quiescent = busy_gauges.is_empty();
624    let mut next_probe_at = wait_started;
625    let mut omission_reported = false;
626
627    loop {
628        let now = Instant::now();
629        if !busy_gauges.is_empty() && now >= next_probe_at && now < deadline {
630            let report = match scope {
631                DrainScope::Active => probe_module_health(module_id, runtime, Some(deadline)).await,
632                DrainScope::Endpoint(endpoint) => {
633                    probe_endpoint_health(endpoint, runtime, Some(deadline)).await
634                }
635            };
636            let verdicts = match &report {
637                Ok(report) => gauge_verdicts(report.metrics.as_ref(), busy_gauges),
638                Err(err) => vec![GaugeVerdict::ProbeFailed(err.label()); busy_gauges.len()],
639            };
640            trace.record(&verdicts, wait_started.elapsed());
641            gauges_quiescent = match report {
642                Ok(_) => match busy_gauge_observation(&verdicts) {
643                    BusyGaugeObservation::Quiescent => true,
644                    BusyGaugeObservation::Busy => false,
645                    BusyGaugeObservation::Omitted => {
646                        // Once per drain: a module that never reports a gauge
647                        // it declared would otherwise say so on every probe.
648                        if !omission_reported {
649                            forwarding
650                                .counters()
651                                .increment_drains_with_undeclared_gauge();
652                            let missing = busy_gauges
653                                .iter()
654                                .zip(&verdicts)
655                                .filter(|(_, verdict)| matches!(verdict, GaugeVerdict::Missing))
656                                .map(|(gauge, _)| gauge.as_str())
657                                .collect::<Vec<_>>()
658                                .join(",");
659                            warn!(
660                                module_id,
661                                missing_gauges = %missing,
662                                "drain health.check answer lacks a declared busy gauge; the drain treats the module as busy until it reports it"
663                            );
664                            omission_reported = true;
665                        }
666                        false
667                    }
668                },
669                Err(err) => {
670                    warn!(
671                        module_id,
672                        error = %err,
673                        "drain health.check did not produce declared busy gauges; treating module as busy"
674                    );
675                    false
676                }
677            };
678            // Counted from the probe's completion: the probe above was awaited,
679            // so no second probe can start while one is still outstanding.
680            next_probe_at = Instant::now() + drain_busy_reprobe_interval();
681        }
682
683        let in_flight = forwarding
684            .endpoint_in_flight_count(endpoint)
685            .map_err(SuperviseError::Forwarding)?;
686        if in_flight == 0 && gauges_quiescent {
687            return Ok(true);
688        }
689
690        let now = Instant::now();
691        if now >= deadline {
692            return Ok(false);
693        }
694        let mut wait = deadline
695            .saturating_duration_since(now)
696            .min(REGISTRY_RELEASE_POLL);
697        if !busy_gauges.is_empty() {
698            wait = wait.min(next_probe_at.saturating_duration_since(now));
699        }
700        sleep(wait).await;
701    }
702}
703
704/// The wait between drain busy-gauge probes: the larger of
705/// [`DRAIN_BUSY_REPROBE_INTERVAL`] and [`REGISTRY_RELEASE_POLL`], the
706/// drain's own in-flight poll interval.
707pub(super) fn drain_busy_reprobe_interval() -> Duration {
708    DRAIN_BUSY_REPROBE_INTERVAL.max(REGISTRY_RELEASE_POLL)
709}
710
711/// Logs why a drain gave up: the drain waited its full timeout without the
712/// module going quiet, and teardown is being forced.
713///
714/// The line names two kinds of evidence, because a bare "timed out" hides
715/// causes that need different fixes:
716/// - `holdouts`: the requests and routes still open when the timeout hit,
717///   and on which connections. One stuck call is a module bug; a held stream
718///   on every session is a module that should end its streams when it
719///   receives `module.draining`.
720/// - `gauges`: for each busy gauge the module declares, its latest reading
721///   and how many probes ran. This separates a module that kept reporting
722///   itself busy, one whose health answer never contained the gauge, and one
723///   that never answered the probes, which otherwise all look like a timeout
724///   with nothing in flight.
725pub(super) fn warn_drain_timed_out(
726    module_id: &str,
727    drain_timeout: Duration,
728    reason: RouteCloseReason,
729    holdouts: &crate::forwarding::DrainHoldouts,
730    gauges: &DrainGaugeTrace,
731) {
732    warn!(
733        module_id = %module_id,
734        waited = ?drain_timeout,
735        ?reason,
736        held_requests = holdouts.requests,
737        held_routes = holdouts.routes,
738        total_routes = holdouts.total_routes,
739        top_connections = ?holdouts.top_connections,
740        // `module_channel:corr`, so the module can find each held request
741        // in its own log; capped, so `held_requests` is the full count.
742        held = %holdouts
743            .held
744            .iter()
745            .map(|(channel, corr)| format!("{channel}:{corr}"))
746            .collect::<Vec<_>>()
747            .join(","),
748        gauge_probes = gauges.probes,
749        busy_gauges = %gauges,
750        "route drain timed out before request quiescence; forcing teardown"
751    );
752}
753
754/// The `route.closed` `drained` value implied by a quiescence-wait outcome.
755///
756/// `Ok` is always honest and passed straight through -- the wait actually measured
757/// in-flight state. `Err` means the wait produced no measurement at all (the
758/// forwarding table's lock was poisoned), so `false` is reported as the one honest
759/// constant: the drain did not complete. Never recomputed from route state, never a
760/// third "unknown" value -- the caller must still send a well-formed `route.closed`.
761pub(super) fn drained_after_quiescence_wait(wait_result: &Result<bool, SuperviseError>) -> bool {
762    match wait_result {
763        Ok(drained) => *drained,
764        Err(_) => false,
765    }
766}
767
768fn send_route_goodbyes(forwarding: &ForwardingTable, released_routes: Vec<GoodbyeTarget>) {
769    for released in released_routes {
770        let frame = match Frame::build_with_version(
771            released.negotiated_ver,
772            FrameType::Goodbye,
773            control_flags(),
774            released.channel,
775            released.epoch,
776            0,
777            Vec::new(),
778        ) {
779            Ok(frame) => frame,
780            Err(err) => {
781                warn!(
782                    route_channel = released.channel,
783                    error = %err,
784                    "failed to build supervisor drain route GOODBYE frame"
785                );
786                continue;
787            }
788        };
789        if !released.close_on_delivery_failure() {
790            crate::forwarding::send_module_route_goodbye(
791                &forwarding.counters(),
792                &released.sink,
793                frame,
794                released.module_id.as_deref(),
795                "supervisor drain",
796            );
797            continue;
798        }
799        if let Err(err) = released.sink.try_send(frame) {
800            warn!(
801                target_connection_id = released.connection_id.get(),
802                route_channel = released.channel,
803                error = %err,
804                "supervisor drain route GOODBYE was not delivered to client; closing target connection"
805            );
806            let _ = forwarding.escalate_client_delivery_failure(
807                released.connection_id,
808                released.channel,
809                released.epoch,
810                CloseReason::new(
811                    "route_goodbye_delivery_failed",
812                    format!(
813                        "failed to enqueue supervisor drain route GOODBYE for channel {}: {err}",
814                        released.channel
815                    ),
816                ),
817                crate::forwarding::UndeliveredFrame {
818                    module_id: released.module_id.as_deref(),
819                    sink: &released.sink,
820                },
821            );
822        }
823    }
824}
825
826async fn send_module_draining(
827    module_id: &str,
828    reason: RouteCloseReason,
829    deadline_ms: u64,
830    target: &ModuleDrainTarget,
831    _wait_for_flush: bool,
832) -> bool {
833    let body = match serde_json::to_vec(&ModuleControlCommand::Draining {
834        reason,
835        deadline_ms,
836    }) {
837        Ok(body) => body,
838        Err(err) => {
839            warn!(
840                module_id,
841                error = %err,
842                "failed to encode module draining command"
843            );
844            return false;
845        }
846    };
847    let frame = match Frame::build_with_version(
848        target.negotiated_ver,
849        FrameType::Push,
850        control_flags(),
851        0,
852        0,
853        0,
854        body,
855    ) {
856        Ok(frame) => frame,
857        Err(err) => {
858            warn!(
859                module_id,
860                error = %err,
861                "failed to build module draining command frame"
862            );
863            return false;
864        }
865    };
866    #[cfg(unix)]
867    if _wait_for_flush {
868        return target.sink.send_flushed(frame).await.is_ok();
869    }
870    if let Err(err) = target.sink.try_send(frame) {
871        warn!(
872            module_id,
873            target_connection_id = target.endpoint.connection_id.get(),
874            error = %err,
875            "module draining command was not delivered to peer"
876        );
877        return false;
878    }
879    true
880}
881
882/// The channel-0 GOODBYE that tells a module its stop is planned.
883fn module_goodbye_frame(module_id: &str, negotiated_ver: u8) -> Option<Frame> {
884    match Frame::build_with_version(
885        negotiated_ver,
886        FrameType::Goodbye,
887        control_flags(),
888        0,
889        0,
890        0,
891        Vec::new(),
892    ) {
893        Ok(frame) => Some(frame),
894        Err(err) => {
895            warn!(
896                module_id,
897                error = %err,
898                "failed to build module GOODBYE frame"
899            );
900            None
901        }
902    }
903}
904
905/// Send every registered module connection its module GOODBYE at daemon
906/// shutdown, then request that connection's close.
907///
908/// A module tells a planned stop from a lost daemon by whether a GOODBYE came
909/// before EOF, so the GOODBYE must reach the socket before the close. A close
910/// request does not wait for the connection's queued frames: its writer gets a
911/// bounded grace after the close, is aborted if it overruns it, and the daemon
912/// process may exit before that grace ends. So with `wait_for_flush`, each
913/// connection is closed only after its writer has acknowledged writing the
914/// GOODBYE, or once a short shared budget runs out, so one module that is not
915/// reading cannot hold up the others or the shutdown. Without it the GOODBYEs
916/// are only queued, for a shutdown the operator has told to stop waiting.
917/// A connection that is already gone is skipped.
918#[cfg(unix)]
919async fn send_module_goodbyes_for_daemon_shutdown(
920    forwarding: &Arc<ForwardingTable>,
921    reason: &CloseReason,
922    wait_for_flush: bool,
923) {
924    const GOODBYE_BUDGET: Duration = Duration::from_millis(500);
925    let targets = match forwarding.module_connections() {
926        Ok(targets) => targets,
927        Err(err) => {
928            warn!(error = %err, "could not list module connections for shutdown GOODBYE");
929            return;
930        }
931    };
932    let deadline = Instant::now() + GOODBYE_BUDGET;
933    let mut sends = tokio::task::JoinSet::new();
934    for target in targets {
935        let Some(frame) = module_goodbye_frame(&target.module_id, target.negotiated_ver) else {
936            continue;
937        };
938        if !wait_for_flush {
939            if let Err(err) = target.sink.try_send(frame) {
940                debug!(
941                    module_id = %target.module_id,
942                    error = %err,
943                    "shutdown module GOODBYE was not queued"
944                );
945            }
946            continue;
947        }
948        let forwarding = Arc::clone(forwarding);
949        let reason = reason.clone();
950        sends.spawn(async move {
951            match timeout_at(deadline, target.sink.send_flushed(frame)).await {
952                Ok(Ok(())) => {}
953                Ok(Err(err)) => debug!(
954                    module_id = %target.module_id,
955                    error = %err,
956                    "module connection closed before its shutdown GOODBYE was written"
957                ),
958                Err(_) => warn!(
959                    module_id = %target.module_id,
960                    budget = ?GOODBYE_BUDGET,
961                    "shutdown module GOODBYE was not written within its budget; closing anyway"
962                ),
963            }
964            forwarding.request_connection_close(target.endpoint.connection_id, reason);
965        });
966    }
967    // Every task ends by the shared deadline, so this wait is bounded too.
968    while sends.join_next().await.is_some() {}
969}
970
971async fn send_module_goodbye(
972    module_id: &str,
973    forwarding: &ForwardingTable,
974    target: &ModuleDrainTarget,
975    wait_for_flush: bool,
976) {
977    let Some(frame) = module_goodbye_frame(module_id, target.negotiated_ver) else {
978        return;
979    };
980    // A channel is shut down synchronously after its drain. Its final frame
981    // must reach the socket writer first; queue admission alone can lose it.
982    let sent = if wait_for_flush {
983        timeout(Duration::from_millis(500), target.sink.send_flushed(frame))
984            .await
985            .map_err(|_| "module GOODBYE flush exceeded 500ms".to_owned())
986            .and_then(|result| result.map_err(|err| err.to_string()))
987    } else {
988        target.sink.try_send(frame).map_err(|err| err.to_string())
989    };
990    if let Err(err) = sent {
991        warn!(
992            module_id,
993            target_connection_id = target.endpoint.connection_id.get(),
994            error = %err,
995            "supervisor drain module GOODBYE was not delivered to peer; closing module connection"
996        );
997        forwarding.request_connection_close(
998            target.endpoint.connection_id,
999            CloseReason::new(
1000                "module_goodbye_delivery_failed",
1001                format!("failed to enqueue supervisor drain module GOODBYE for module '{module_id}': {err}"),
1002            ),
1003        );
1004    }
1005}
1006
1007#[derive(Clone, Copy)]
1008pub(super) struct ForwardingDrainContext<'a> {
1009    pub(super) spec: &'a ModuleSpec,
1010    pub(super) runtime: &'a SupervisorRuntimeConfig,
1011    pub(super) registry: &'a Registry,
1012    pub(super) scope: DrainScope,
1013}
1014
1015/// Which process a forwarding drain addresses.
1016#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1017pub(super) enum DrainScope {
1018    /// Whatever endpoint is active for the module id: every plain stop,
1019    /// restart and reload. Also moves the module's state to `Draining`.
1020    Active,
1021    /// One specific endpoint: a swap's incumbent after cutover. Draining it by
1022    /// module id would resolve to the promoted candidate and leave neither
1023    /// process routable. The module's state is left alone, since the promoted
1024    /// candidate is what it describes and that process is running.
1025    Endpoint(crate::ModuleEndpointId),
1026}
1027
1028/// Whether a child being drained has already been asked to stop by the time
1029/// its drain wait starts.
1030///
1031/// The drain wait is the same budget whatever this says. What it decides is
1032/// whether the supervisor must ask by signal before that wait begins: a child
1033/// that nobody asked will sit out the whole budget and then be SIGKILLed,
1034/// healthy or not.
1035#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1036pub(super) enum StopNotice {
1037    /// The module was sent `module.draining` and a module GOODBYE over its own
1038    /// registered connection, and stops itself.
1039    SentOverConnection,
1040    /// The forwarding drain found no registered connection for the module: a
1041    /// subc child spawned moments ago that has not sent HELLO yet, or a
1042    /// `protocol: "none"` child, which never registers.
1043    NoConnection,
1044    /// This path sends nothing over the module's connection: the supervisor has
1045    /// no forwarding table, or the caller stops the child without a forwarding
1046    /// drain.
1047    NotSent,
1048}
1049
1050pub(super) async fn begin_forwarding_drain(
1051    spec: &ModuleSpec,
1052    runtime: &SupervisorRuntimeConfig,
1053    registry: &Registry,
1054    snapshot: &SharedSnapshot,
1055    enabled: Option<bool>,
1056    reason: RouteCloseReason,
1057) -> Result<StopNotice, SuperviseError> {
1058    let Some(forwarding) = runtime.forwarding.as_ref() else {
1059        return Err(SuperviseError::ReloadUnavailable {
1060            module_id: spec.module_id.clone(),
1061            reason: "supervisor was not configured with a forwarding table".to_string(),
1062        });
1063    };
1064
1065    begin_forwarding_drain_with(
1066        forwarding,
1067        ForwardingDrainContext {
1068            spec,
1069            runtime,
1070            registry,
1071            scope: DrainScope::Active,
1072        },
1073        snapshot,
1074        enabled,
1075        reason,
1076        runtime.drain_timeout,
1077    )
1078    .await
1079}
1080
1081pub(super) async fn begin_forwarding_drain_if_configured(
1082    spec: &ModuleSpec,
1083    runtime: &SupervisorRuntimeConfig,
1084    registry: &Registry,
1085    snapshot: &SharedSnapshot,
1086    enabled: Option<bool>,
1087    reason: RouteCloseReason,
1088) -> Result<StopNotice, SuperviseError> {
1089    begin_forwarding_drain_with_timeout(
1090        spec,
1091        runtime,
1092        registry,
1093        snapshot,
1094        enabled,
1095        reason,
1096        runtime.drain_timeout,
1097    )
1098    .await
1099}
1100
1101/// Like [`begin_forwarding_drain_if_configured`] but with an explicit drain
1102/// budget, for paths where the operator overrides the module's configured one
1103/// (`supervisor.restart{drain_timeout_ms}`).
1104pub(super) async fn begin_forwarding_drain_with_timeout(
1105    spec: &ModuleSpec,
1106    runtime: &SupervisorRuntimeConfig,
1107    registry: &Registry,
1108    snapshot: &SharedSnapshot,
1109    enabled: Option<bool>,
1110    reason: RouteCloseReason,
1111    drain_timeout: Duration,
1112) -> Result<StopNotice, SuperviseError> {
1113    let Some(forwarding) = runtime.forwarding.as_ref() else {
1114        return Ok(StopNotice::NotSent);
1115    };
1116
1117    begin_forwarding_drain_with(
1118        forwarding,
1119        ForwardingDrainContext {
1120            spec,
1121            runtime,
1122            registry,
1123            scope: DrainScope::Active,
1124        },
1125        snapshot,
1126        enabled,
1127        reason,
1128        drain_timeout,
1129    )
1130    .await
1131}
1132
1133pub(super) async fn begin_forwarding_drain_with(
1134    forwarding: &ForwardingTable,
1135    context: ForwardingDrainContext<'_>,
1136    snapshot: &SharedSnapshot,
1137    enabled: Option<bool>,
1138    reason: RouteCloseReason,
1139    drain_timeout: Duration,
1140) -> Result<StopNotice, SuperviseError> {
1141    let ForwardingDrainContext {
1142        spec,
1143        runtime,
1144        registry,
1145        scope,
1146    } = context;
1147    debug_assert_ne!(reason, RouteCloseReason::Crash);
1148    let terminal = matches!(reason, RouteCloseReason::Disable);
1149    let drain_started_at = Instant::now();
1150    let drain_deadline = drain_started_at + drain_timeout;
1151    let deadline_ms =
1152        unix_ms_now().saturating_add(u64::try_from(drain_timeout.as_millis()).unwrap_or(u64::MAX));
1153    let busy_gauges = match scope {
1154        DrainScope::Active => declared_busy_gauges(registry, &spec.module_id)?,
1155        DrainScope::Endpoint(endpoint) => {
1156            declared_busy_gauges_for_connection(registry, endpoint.connection_id)?
1157        }
1158    };
1159
1160    // Admission gate first: route.open/commit and route REQUEST admission are closed
1161    // before the first quiescence check, so the outstanding count can only fall.
1162    let gate_started = Instant::now();
1163    let drain_target = match scope {
1164        DrainScope::Active => forwarding.begin_module_drain(&spec.module_id, reason),
1165        DrainScope::Endpoint(endpoint) => forwarding.begin_endpoint_drain(endpoint, reason),
1166    }
1167    .map_err(SuperviseError::Forwarding)?;
1168    // The instant admission closed, and how long taking the forwarding write
1169    // lock to close it took. The timeout line reports only the quiescence
1170    // wait, so without this a drain that started late looked like one that
1171    // started on time.
1172    info!(
1173        module_id = %spec.module_id,
1174        ?reason,
1175        gate_ms = u64::try_from(gate_started.elapsed().as_millis()).unwrap_or(u64::MAX),
1176        connected = drain_target.is_some(),
1177        "module drain began; route admission closed"
1178    );
1179    if scope == DrainScope::Active {
1180        update_snapshot(snapshot, Some(&spec.module_id), |state| {
1181            state.state = ModuleState::Draining;
1182            state.draining_to_replace =
1183                matches!(reason, RouteCloseReason::Restart | RouteCloseReason::Reload);
1184            if let Some(enabled) = enabled {
1185                state.enabled = enabled;
1186            }
1187        })?;
1188    }
1189
1190    let Some(target) = drain_target.as_ref() else {
1191        // Nothing was sent: the module has no registered connection to carry
1192        // `module.draining` or a GOODBYE. The caller must not assume the child
1193        // was asked to stop.
1194        return Ok(StopNotice::NoConnection);
1195    };
1196    let flush_goodbye = runtime.supervisor_handle.as_ref().is_some_and(|handle| {
1197        handle
1198            .registration_spawn(target.endpoint.connection_id)
1199            .is_some()
1200    });
1201    {
1202        send_module_draining(&spec.module_id, reason, deadline_ms, target, false).await;
1203        #[cfg(feature = "test-support")]
1204        forwarding.wait_before_route_closing_for_test().await;
1205        let routes = forwarding
1206            .endpoint_routes(target.endpoint)
1207            .map_err(SuperviseError::Forwarding)?;
1208        let routes_notified = routes.len();
1209        crate::control::send_route_control_pushes(
1210            forwarding,
1211            routes.clone(),
1212            ClientControlPush::RouteClosing {
1213                module_id: spec.module_id.clone(),
1214                channels: Vec::new(),
1215                reason,
1216            },
1217        );
1218        send_route_goodbyes(forwarding, target.abandoned_bindings.clone());
1219
1220        // `route.closing` was just sent above: from here on every return path,
1221        // including an early one, MUST send `route.closed` before propagating
1222        // anything else. A client holds `closing` as a promise that a verdict is
1223        // coming; leaving early without `closed` strands it waiting forever, since
1224        // `closing` carries no timeout of its own.
1225        let mut gauge_trace = DrainGaugeTrace::new(&busy_gauges);
1226        let wait_result = wait_for_forwarding_quiescence(
1227            forwarding,
1228            &spec.module_id,
1229            runtime,
1230            target.endpoint,
1231            drain_deadline,
1232            &busy_gauges,
1233            scope,
1234            &mut gauge_trace,
1235        )
1236        .await;
1237        let drained = drained_after_quiescence_wait(&wait_result);
1238        if let Err(err) = &wait_result {
1239            error!(
1240                module_id = %spec.module_id,
1241                ?reason,
1242                error = %err,
1243                "forwarding quiescence wait failed after route.closing; forcing route.closed(drained: false) so the client is not left waiting on an unfulfilled promise"
1244            );
1245        } else if !drained {
1246            // Read before teardown releases the routes.
1247            let holdouts = forwarding
1248                .endpoint_drain_holdouts(target.endpoint)
1249                .unwrap_or_default();
1250            warn_drain_timed_out(
1251                &spec.module_id,
1252                drain_timeout,
1253                reason,
1254                &holdouts,
1255                &gauge_trace,
1256            );
1257        }
1258        crate::control::send_route_control_pushes(
1259            forwarding,
1260            routes,
1261            ClientControlPush::RouteClosed {
1262                module_id: spec.module_id.clone(),
1263                channels: Vec::new(),
1264                reason,
1265                drained,
1266                abandoned: target.abandoned_bindings.len() as u32,
1267                excluded_subscriptions: target.excluded_subscriptions,
1268                terminal: Some(terminal),
1269            },
1270        );
1271        wait_result?;
1272
1273        // `route.closed` has now been sent unconditionally above. From here the
1274        // remaining steps are cleanup (route + module GOODBYE) rather than a
1275        // promise the client is waiting on, but a lock-poisoned
1276        // `release_module_endpoint_routes` would otherwise skip the module
1277        // GOODBYE silently too -- send it before propagating the error.
1278        let released_routes = match forwarding.release_module_endpoint_routes(target.endpoint) {
1279            Ok(routes) => routes,
1280            Err(err) => {
1281                warn!(
1282                    module_id = %spec.module_id,
1283                    ?reason,
1284                    error = %err,
1285                    "failed to release module endpoint routes after route.closed; module GOODBYE will still be sent"
1286                );
1287                send_module_goodbye(&spec.module_id, forwarding, target, flush_goodbye).await;
1288                return Err(SuperviseError::Forwarding(err));
1289            }
1290        };
1291        let route_goodbye_count = released_routes.len();
1292        send_route_goodbyes(forwarding, released_routes);
1293        send_module_goodbye(&spec.module_id, forwarding, target, flush_goodbye).await;
1294
1295        // The drain's happy path was previously silent: every emission above is
1296        // best-effort with only its failure arm logged, so "were consumers told"
1297        // was unprovable from the daemon log (surfaced by a 30-minute consumer
1298        // hang where the open question was exactly whether teardown notice went
1299        // out). One summary line makes that class decidable in one grep.
1300        info!(
1301            module_id = %spec.module_id,
1302            ?reason,
1303            routes_notified,
1304            route_goodbyes = route_goodbye_count,
1305            abandoned_reservations = target.abandoned_bindings.len(),
1306            excluded_subscriptions = target.excluded_subscriptions,
1307            drained,
1308            "module drain complete; consumers notified via route.closing/route.closed pushes and per-route GOODBYE frames"
1309        );
1310    }
1311
1312    Ok(StopNotice::SentOverConnection)
1313}
1314
1315pub(super) fn control_flags() -> Flags {
1316    Flags::new(false, Priority::Passive, false)
1317}
1318
1319#[allow(clippy::too_many_arguments)]
1320pub(super) async fn drain_optional_child(
1321    module_id: &str,
1322    protocol: ModuleProtocol,
1323    stop_notice: StopNotice,
1324    registry: &Registry,
1325    forwarding: Option<&ForwardingTable>,
1326    snapshot: &SharedSnapshot,
1327    terminal_ring: &Arc<Mutex<TerminalRing>>,
1328    spawn_events: &SpawnEventFeed,
1329    child: &mut Option<SupervisedChild>,
1330    drain_timeout: Duration,
1331    final_state: ModuleState,
1332    enabled: Option<bool>,
1333    failure: &FailureContext,
1334) -> Result<(), SuperviseError> {
1335    if let Some(child) = child.take() {
1336        drain_child_to_state(
1337            module_id,
1338            protocol,
1339            stop_notice,
1340            registry,
1341            forwarding,
1342            snapshot,
1343            terminal_ring,
1344            spawn_events,
1345            child,
1346            drain_timeout,
1347            final_state,
1348            enabled,
1349            failure,
1350        )
1351        .await
1352    } else {
1353        update_snapshot(snapshot, Some(module_id), |state| {
1354            state.state = final_state;
1355            if final_state == ModuleState::Failed {
1356                state.failed_retry.failed_at = Some(Instant::now());
1357            }
1358            if let Some(enabled) = enabled {
1359                state.enabled = enabled;
1360            }
1361            clear_current_process_facts(state);
1362        })?;
1363        release_dead_registration(registry, forwarding, snapshot, module_id, failure).await
1364    }
1365}
1366
1367#[allow(clippy::too_many_arguments)]
1368pub(super) async fn drain_child_to_state(
1369    module_id: &str,
1370    _protocol: ModuleProtocol,
1371    stop_notice: StopNotice,
1372    registry: &Registry,
1373    forwarding: Option<&ForwardingTable>,
1374    snapshot: &SharedSnapshot,
1375    terminal_ring: &Arc<Mutex<TerminalRing>>,
1376    spawn_events: &SpawnEventFeed,
1377    mut child: SupervisedChild,
1378    drain_timeout: Duration,
1379    final_state: ModuleState,
1380    enabled: Option<bool>,
1381    failure: &FailureContext,
1382) -> Result<(), SuperviseError> {
1383    let protocol = child.protocol;
1384    child.retire_registration();
1385    update_snapshot(snapshot, Some(module_id), |state| {
1386        state.state = ModuleState::Draining;
1387        state.draining_to_replace = final_state == ModuleState::Restarting;
1388        if let Some(enabled) = enabled {
1389            state.enabled = enabled;
1390        }
1391    })?;
1392
1393    // The wait below is the same budget in every case; what differs is
1394    // whether anything has ASKED the child to stop before it starts. Only a
1395    // forwarding drain that reached the module's registered connection has
1396    // (`module.draining`, then a module GOODBYE). Every other child was told
1397    // nothing: a `protocol: "none"` module, which never registers; a subc
1398    // module spawned moments ago that has not sent HELLO yet; or a stop that
1399    // runs no forwarding drain. Without a signal the budget is only a delay
1400    // in front of SIGKILL -- and the not-yet-registered child is the worst
1401    // case, because it registers into a module that is already draining,
1402    // is never told, and is killed while healthy.
1403    if stop_notice != StopNotice::SentOverConnection {
1404        if protocol == ModuleProtocol::Subc && stop_notice == StopNotice::NoConnection {
1405            info!(
1406                module_id,
1407                pid = child.pid,
1408                budget_ms = u64::try_from(drain_timeout.as_millis()).unwrap_or(u64::MAX),
1409                "module has no connection yet; requesting stop by signal"
1410            );
1411        }
1412        request_graceful_stop(module_id, &child);
1413    }
1414
1415    let drain_timeout = child.group_drain_budget(drain_timeout, stop_notice);
1416    let exit_report = match timeout(drain_timeout, child.wait()).await {
1417        Ok(Ok(status)) => classify_reaped_child_exit(snapshot, &child, &status),
1418        Ok(Err(source)) => {
1419            fail_after_wait_error(
1420                module_id,
1421                snapshot,
1422                terminal_ring,
1423                spawn_events,
1424                format!("failed to wait during drain: {source}"),
1425                failure,
1426            );
1427            return Err(SuperviseError::Wait {
1428                module_id: module_id.to_string(),
1429                source,
1430            });
1431        }
1432        Err(_) => {
1433            // Mirror the sibling arm above: state is already `Draining`, and an
1434            // error propagated from here would strand it there -- a state
1435            // `set_enabled(true)` cannot heal (`revive_terminal` matches only
1436            // `Failed | Stopped`), leaving an operator Restart as the only exit.
1437            // `Failed` before `?` keeps the module operator-visible and
1438            // revivable. Trigger is an ESRCH race (process exits between the
1439            // drain timeout firing and the kill) or a post-kill wait failure
1440            // (issue #34).
1441            //
1442            // Logged because the kill is otherwise visible only as signal 9 in
1443            // the terminal ring, and the budget it follows can be long enough
1444            // that consumers see a stretch of refusals with no stated cause.
1445            warn!(
1446                module_id,
1447                pid = child.pid,
1448                budget_ms = u64::try_from(drain_timeout.as_millis()).unwrap_or(u64::MAX),
1449                reason = ?final_state,
1450                ?stop_notice,
1451                "drain budget expired before the module exited; killing it"
1452            );
1453            let kill =
1454                if final_state == ModuleState::Restarting && child.child.container().is_some() {
1455                    child.kill_leader()
1456                } else {
1457                    child.start_kill()
1458                };
1459            kill.map_err(|source| {
1460                fail_after_wait_error(
1461                    module_id,
1462                    snapshot,
1463                    terminal_ring,
1464                    spawn_events,
1465                    format!("failed to kill during drain: {source}"),
1466                    failure,
1467                );
1468                SuperviseError::Kill {
1469                    module_id: module_id.to_string(),
1470                    source,
1471                }
1472            })?;
1473            let status = child.wait().await.map_err(|source| {
1474                fail_after_wait_error(
1475                    module_id,
1476                    snapshot,
1477                    terminal_ring,
1478                    spawn_events,
1479                    format!("failed to wait after drain kill: {source}"),
1480                    failure,
1481                );
1482                SuperviseError::Wait {
1483                    module_id: module_id.to_string(),
1484                    source,
1485                }
1486            })?;
1487            classify_reaped_child_exit(snapshot, &child, &status)
1488        }
1489    };
1490
1491    child.drain_stderr(module_id).await;
1492    let detail =
1493        child.exit_cleanup_detail(lock_snapshot(snapshot)?.drain_disposition_detail.take());
1494    publish_after_terminal_record(
1495        module_id,
1496        || {
1497            record_terminal_with_detail(
1498                module_id,
1499                terminal_ring,
1500                spawn_events,
1501                &exit_report,
1502                terminal_disposition(final_state),
1503                detail,
1504            )
1505        },
1506        || {
1507            update_snapshot(snapshot, Some(module_id), |state| {
1508                state.state = final_state;
1509                if final_state == ModuleState::Failed {
1510                    state.failed_retry.failed_at = Some(Instant::now());
1511                }
1512                if let Some(enabled) = enabled {
1513                    state.enabled = enabled;
1514                }
1515                clear_current_process_facts(state);
1516                state.last_exit = Some(exit_report.clone());
1517                if exit_report.kind == ExitKind::DeliberateSeverance {
1518                    state.lifetime_restarts += 1;
1519                }
1520            })
1521        },
1522    )?;
1523    let released =
1524        release_dead_registration(registry, forwarding, snapshot, module_id, failure).await;
1525    child
1526        .finish_exit(
1527            released.is_ok()
1528                && final_state == ModuleState::Restarting
1529                && child.spawn_failure.is_none(),
1530        )
1531        .await
1532        .map_err(|source| SuperviseError::Wait {
1533            module_id: module_id.to_owned(),
1534            source,
1535        })?;
1536    released
1537}
1538
1539/// Ask a child that nothing else has asked to stop, by signal.
1540///
1541/// A registered subc module is asked over its own connection: the drain sends
1542/// `route.closing`/`route.closed` to its consumers, a GOODBYE per route, then a
1543/// module GOODBYE, and the module stops itself. A module that speaks no subc
1544/// wire receives none of that, and neither does a subc module that has not
1545/// registered yet, so for them the drain budget would be pure delay in front of
1546/// a SIGKILL -- and for a process with a store to flush (JetStream is the
1547/// reason `protocol: "none"` exists) a SIGKILL turns every ordinary teardown
1548/// into a recovery on the next start.
1549///
1550/// NEVER CALLED FOR A MODULE THAT WAS TOLD OVER ITS CONNECTION, and that is a
1551/// rule rather than an optimisation: that module's graceful stop is already
1552/// running by the time its child is drained, and a signal would race it.
1553///
1554/// Best-effort by construction. A child that has already exited is the ordinary
1555/// case rather than an error (the kill lands on a reaped or exiting pid), so a
1556/// failure is logged at debug and the wait-then-kill below still decides the
1557/// outcome.
1558#[cfg(unix)]
1559pub(super) fn request_graceful_stop(module_id: &str, child: &SupervisedChild) {
1560    if let Some(group) = &child.child.plain_group {
1561        if let Err(error) = group.signal(rustix::process::Signal::TERM) {
1562            debug!(module_id, %error, "group TERM was not delivered; the drain wait and kill still apply");
1563        }
1564        return;
1565    }
1566    let Some(pid) = child
1567        .id()
1568        .and_then(|pid| i32::try_from(pid).ok())
1569        .filter(|pid| *pid > 1)
1570        .and_then(rustix::process::Pid::from_raw)
1571    else {
1572        debug!(
1573            module_id,
1574            "no pid to signal for teardown; falling through to the drain wait"
1575        );
1576        return;
1577    };
1578    match rustix::process::kill_process(pid, rustix::process::Signal::TERM) {
1579        Ok(()) => debug!(
1580            module_id,
1581            "sent SIGTERM to a module nothing else asked to stop"
1582        ),
1583        Err(err) => debug!(
1584            module_id,
1585            error = %err,
1586            "SIGTERM to module failed; the drain wait and kill still apply"
1587        ),
1588    }
1589}
1590
1591/// Windows has no SIGTERM and no portable stand-in for one. The graceful stops
1592/// Windows does offer need cooperation this supervisor cannot assume: a console
1593/// control event requires sharing a console with the child, and `WM_CLOSE`
1594/// requires the child to pump a message loop. A supervised server process does
1595/// neither, so there is nothing to send and teardown is the wait followed by the
1596/// kill. Emulating a signal here would mean inventing a stop protocol, which is
1597/// the thing `protocol: "none"` exists to avoid.
1598#[cfg(not(unix))]
1599pub(super) fn request_graceful_stop(module_id: &str, _child: &SupervisedChild) {
1600    debug!(
1601        module_id,
1602        "no graceful stop signal exists on this platform; teardown of a module nothing asked to stop waits, then kills"
1603    );
1604}
1605
1606pub(super) fn terminal_disposition(final_state: ModuleState) -> TerminalDisposition {
1607    match final_state {
1608        ModuleState::Stopped => TerminalDisposition::Stopped,
1609        ModuleState::Disabled => TerminalDisposition::Disabled,
1610        ModuleState::Restarting => TerminalDisposition::Restarting,
1611        ModuleState::Failed => TerminalDisposition::Failed,
1612        ModuleState::Starting
1613        | ModuleState::Running
1614        | ModuleState::Unresponsive
1615        | ModuleState::Draining => {
1616            unreachable!("terminal exits only finish in terminal or restarting states")
1617        }
1618    }
1619}