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