Skip to main content

subc_daemon/control/
supervisor_operations.rs

1use super::*;
2
3pub(super) const DEFAULT_HEALTH_PROBE_TIMEOUT: Duration = Duration::from_secs(5);
4
5pub(super) fn reload_verdict(
6    configured: &Path,
7    spawned_from: Option<&Path>,
8    image: subc_control::RunningImageAgreement,
9) -> PendingReloadVerdict {
10    let path = match spawned_from {
11        Some(spawned_from) if reload_paths_match(configured, spawned_from) => {
12            ReloadPathAgreement::Match
13        }
14        Some(spawned_from) => ReloadPathAgreement::Mismatch {
15            configured: configured.to_path_buf(),
16            spawned_from: spawned_from.to_path_buf(),
17        },
18        None => ReloadPathAgreement::Unavailable {
19            reason: if matches!(
20                image,
21                subc_control::RunningImageAgreement::Unavailable {
22                    reason: subc_control::RunningImageUnavailableReason::NotRunning
23                }
24            ) {
25                ReloadPathUnavailableReason::NotRunning
26            } else {
27                ReloadPathUnavailableReason::SpawnedPathUnavailable
28            },
29        },
30    };
31    PendingReloadVerdict::new(path, image)
32}
33
34pub(super) fn launch_spec_agreement(
35    configured: &crate::supervise::ModuleSpec,
36    running: bool,
37    spawned: Option<&crate::supervise::LaunchSpecDigest>,
38) -> subc_control::LaunchSpecAgreement {
39    use subc_control::{LaunchSpecAgreement as Agreement, LaunchSpecUnavailableReason as Reason};
40    if !running {
41        return Agreement::Unavailable {
42            reason: Reason::NotRunning,
43        };
44    }
45    match spawned {
46        None => Agreement::Unavailable {
47            reason: Reason::SpawnedSpecUnavailable,
48        },
49        Some(digest) if *digest == crate::supervise::LaunchSpecDigest::from_spec(configured) => {
50            Agreement::Match
51        }
52        Some(_) => Agreement::Mismatch,
53    }
54}
55
56fn reload_paths_match(configured: &Path, spawned_from: &Path) -> bool {
57    if configured == spawned_from {
58        return true;
59    }
60    #[cfg(windows)]
61    {
62        // Windows spawn records the resolved verbatim path (\\?\...), while
63        // configuration keeps its original spelling. Resolve both with the OS
64        // instead of stripping prefixes or folding case, which could conflate
65        // distinct names in case-sensitive directories. Different resolved
66        // paths still differ even if their files have identical content.
67        match (
68            std::fs::canonicalize(configured),
69            std::fs::canonicalize(spawned_from),
70        ) {
71            (Ok(configured), Ok(spawned_from)) => configured == spawned_from,
72            _ => false,
73        }
74    }
75    #[cfg(not(windows))]
76    {
77        false
78    }
79}
80
81#[derive(Clone)]
82pub(super) struct DaemonProvenanceFacts {
83    pub(super) build: DaemonBuildProvenance,
84    pub(super) pid: Option<u32>,
85    pub(super) started_at_ms: Option<u64>,
86    pub(super) start_clock: Option<crate::clock::StartClock>,
87    pub(super) executable_path: Option<PathBuf>,
88    pub(super) executable_identity: Option<SpawnedFileIdentity>,
89    pub(super) process_start_time: Option<u64>,
90    pub(super) probe: ExecutableIdentityProbe,
91}
92
93impl Default for DaemonProvenanceFacts {
94    fn default() -> Self {
95        Self {
96            build: DaemonBuildProvenance {
97                build_git_sha: None,
98                build_lock_digest: None,
99            },
100            pid: None,
101            started_at_ms: None,
102            start_clock: None,
103            executable_path: None,
104            executable_identity: None,
105            process_start_time: None,
106            probe: ExecutableIdentityProbe::default(),
107        }
108    }
109}
110
111pub(super) struct ModuleControlRpcGuard {
112    forwarding: Arc<ForwardingTable>,
113    endpoint: ModuleEndpointId,
114    corr: u64,
115    armed: bool,
116}
117
118impl ModuleControlRpcGuard {
119    pub(super) fn new(
120        forwarding: Arc<ForwardingTable>,
121        endpoint: ModuleEndpointId,
122        corr: u64,
123    ) -> Self {
124        Self {
125            forwarding,
126            endpoint,
127            corr,
128            armed: true,
129        }
130    }
131
132    pub(super) fn disarm(&mut self) {
133        self.armed = false;
134    }
135}
136
137impl Drop for ModuleControlRpcGuard {
138    fn drop(&mut self) {
139        if self.armed {
140            let _ = self
141                .forwarding
142                .cancel_module_control_rpc(self.endpoint, self.corr);
143        }
144    }
145}
146
147impl ControlHandler {
148    #[cfg(test)]
149    pub(crate) fn with_health_probe_timeout(mut self, timeout: Duration) -> Self {
150        self.health_probe_timeout = timeout;
151        self
152    }
153}
154
155impl ControlHandler {
156    pub fn with_daemon_provenance(
157        mut self,
158        pid: u32,
159        started_at_ms: u64,
160        executable_path: Option<PathBuf>,
161        build_git_sha: Option<String>,
162        build_lock_digest: Option<String>,
163    ) -> Self {
164        let executable_identity = executable_path.as_deref().and_then(spawned_file_identity);
165        let process_start_time = process_start_time(pid);
166        self.daemon_provenance = DaemonProvenanceFacts {
167            build: DaemonBuildProvenance {
168                build_git_sha,
169                build_lock_digest,
170            },
171            pid: Some(pid),
172            started_at_ms: Some(started_at_ms),
173            start_clock: None,
174            executable_path,
175            executable_identity,
176            process_start_time,
177            probe: ExecutableIdentityProbe::default(),
178        };
179        self
180    }
181
182    pub(crate) fn with_daemon_start_clock(mut self, clock: crate::clock::StartClock) -> Self {
183        self.daemon_provenance.start_clock = Some(clock);
184        self
185    }
186}
187
188impl ControlHandler {
189    #[cfg(test)]
190    pub(super) fn with_provenance_probe_result(
191        mut self,
192        result: subc_control::RunningImageAgreement,
193    ) -> Self {
194        self.provenance_probe_override = Some(result);
195        self
196    }
197}
198
199impl ControlHandler {
200    pub(super) fn log_supervisor_request_received(
201        &self,
202        ctx: &RouteCtx,
203        corr: u64,
204        op: &'static str,
205        module_id: Option<&str>,
206        enabled: Option<bool>,
207    ) -> Result<(), RouterError> {
208        let caller = self.supervisor_requester(ctx, corr)?;
209        let caller = principal_label(&caller);
210        // `Option` fields are recorded only when present, so a request with no
211        // module id (rescan) or no enabled flag simply omits that field.
212        info!(
213            target: "control",
214            op,
215            module_id,
216            enabled,
217            connection_id = ctx.connection_id.get(),
218            caller = %caller,
219            "supervisor request received"
220        );
221        Ok(())
222    }
223
224    pub(super) fn supervisor_requester(
225        &self,
226        ctx: &RouteCtx,
227        corr: u64,
228    ) -> Result<Principal, RouterError> {
229        Ok(self
230            .registry
231            .get_module_by_connection(ctx.connection_id)
232            .map_err(|err| RouterError::backend(0, corr, err.to_string()))?
233            .map(|registration| Principal::Reserved {
234                module_id: registration.manifest.module_id,
235            })
236            .unwrap_or(Principal::Direct))
237    }
238}
239
240impl ControlHandler {
241    pub(super) fn handle_supervisor_spawn_snapshot(
242        &self,
243        frame: Frame,
244    ) -> Result<Vec<Frame>, RouterError> {
245        let response = ClientControlResponse::SupervisorSpawnSnapshot {
246            snapshot: self.supervisor.spawn_snapshot(),
247        };
248        Ok(vec![control_response_body_frame(
249            &frame,
250            &response,
251            "ClientControlResponse::SupervisorSpawnSnapshot",
252        )?])
253    }
254
255    pub(super) fn handle_supervisor_spawn_subscribe(
256        &self,
257        ctx: &RouteCtx,
258        frame: Frame,
259        since: Option<SpawnCursor>,
260    ) -> Result<Vec<Frame>, RouterError> {
261        match self.supervisor.subscribe_spawns(
262            ctx.connection_id,
263            frame.header.corr,
264            response_version(&frame),
265            since,
266            ctx.egress.clone(),
267        ) {
268            Ok(()) => Ok(Vec::new()),
269            Err(SpawnSubscribeRefusal::ForeignIncarnation { current }) => {
270                Ok(vec![control_error_body_frame(
271                    &frame,
272                    ErrorBody {
273                        code: "spawn_cursor_incarnation_mismatch".to_string(),
274                        message: "spawn cursor belongs to a different daemon incarnation"
275                            .to_string(),
276                        detail: Some(serde_json::json!({
277                            "current_daemon_incarnation": current
278                        })),
279                    },
280                )?])
281            }
282            Err(SpawnSubscribeRefusal::TooOld { oldest }) => Ok(vec![control_error_body_frame(
283                &frame,
284                ErrorBody {
285                    code: "spawn_cursor_too_old".to_string(),
286                    message: "spawn cursor predates the retained event ring".to_string(),
287                    detail: Some(serde_json::json!({
288                        "oldest_retained_cursor": oldest
289                    })),
290                },
291            )?]),
292            Err(SpawnSubscribeRefusal::Frame(error)) => Err(RouterError::backend(
293                0,
294                frame.header.corr,
295                format!("failed to open supervisor spawn subscription: {error}"),
296            )),
297        }
298    }
299
300    pub(super) async fn handle_supervisor_list(
301        &self,
302        frame: Frame,
303    ) -> Result<Vec<Frame>, RouterError> {
304        // Status/configuration snapshots may wait on synchronous supervisor
305        // locks. Keep that work off the connection's async runtime thread.
306        let handler = self.clone();
307        let runtime = tokio::runtime::Handle::current();
308        // The blocking pool does not inherit the control request's tracing
309        // subscriber. Preserve it so slow snapshot-lock warnings stay visible.
310        let subscriber = tracing::dispatcher::get_default(Clone::clone);
311        let corr = frame.header.corr;
312        tokio::task::spawn_blocking(move || {
313            runtime.block_on(
314                list_diagnostics::scope(handler.handle_supervisor_list_inner(frame))
315                    .with_subscriber(subscriber),
316            )
317        })
318        .await
319        .map_err(|error| RouterError::backend(0, corr, error.to_string()))?
320    }
321
322    pub(super) async fn handle_supervisor_list_inner(
323        &self,
324        frame: Frame,
325    ) -> Result<Vec<Frame>, RouterError> {
326        use crate::config_gate::runtime::ApprovedDaemonView;
327        let publication = self
328            .config_runtime
329            .as_ref()
330            .and_then(|owner| owner.observed_snapshot().ok());
331        let approved = publication
332            .as_ref()
333            .map(|view| view.approved_daemon.clone())
334            .unwrap_or_else(|| {
335                if self.config_runtime.is_some() {
336                    ApprovedDaemonView::Unavailable
337                } else {
338                    ApprovedDaemonView::NotStamped
339                }
340            });
341        let generation = self
342            .registry
343            .generation()
344            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
345        let supervised = self.supervisor.list();
346        let mut statuses = BTreeMap::new();
347        let mut not_running = BTreeSet::new();
348        for module in &supervised {
349            let status = module.status_for_control("list").map_err(|err| {
350                RouterError::backend(
351                    0,
352                    frame.header.corr,
353                    format!("failed to read supervisor status: {err}"),
354                )
355            })?;
356            if !status.enabled || !status.process_alive {
357                not_running.insert(module.module_id().to_owned());
358            }
359            statuses.insert(module.module_id().to_owned(), status);
360        }
361        // Legacy per-process diagnostics keep their shared optional budget.
362        // The cached tree and accounting export below does not spend it.
363        let mut process_resources = BTreeMap::new();
364        for module in &supervised {
365            process_resources.insert(
366                module.module_id().to_owned(),
367                crate::subtree_resources::read_process(module.clone()).await,
368            );
369        }
370        // Image evidence uses the same optional deadline, but an exhausted
371        // budget must not suppress the committed resource view.
372        let mut image_readings = BTreeMap::new();
373        for module in &supervised {
374            image_readings.insert(
375                module.module_id().to_owned(),
376                module.running_image_agreement().await,
377            );
378        }
379        let readings = self.resource_tracker.list(supervised.clone());
380        let mut modules = Vec::new();
381        for module in supervised {
382            let status = statuses
383                .remove(module.module_id())
384                .expect("each supervised module has a status snapshot");
385            let (configured, _) = module.configuration().map_err(|err| {
386                RouterError::backend(
387                    0,
388                    frame.header.corr,
389                    format!("failed to read module configuration: {err}"),
390                )
391            })?;
392            let next_retry_at_ms = module.next_retry_at_ms().map_err(|err| {
393                RouterError::backend(
394                    0,
395                    frame.header.corr,
396                    format!("failed to read retry time: {err}"),
397                )
398            })?;
399            let image = image_readings
400                .remove(module.module_id())
401                .expect("each supervised module has an image snapshot");
402            let resources = process_resources.remove(module.module_id());
403            let mut verdict =
404                reload_verdict(&configured.program, status.spawned_from.as_deref(), image);
405            verdict.spec = Some(launch_spec_agreement(
406                &configured,
407                status.process_alive,
408                status.launch_spec_digest.as_ref(),
409            ));
410            let pending_reload = Some(verdict);
411            let pending_entry = match &approved {
412                ApprovedDaemonView::Approved { config, .. } => config
413                    .modules
414                    .iter()
415                    .find(|m| m.module_id == module.module_id()),
416                _ => None,
417            };
418            let pending = self
419                .pending_module_fields(
420                    &module,
421                    pending_entry,
422                    false,
423                    Self::registration_channel_in_force(
424                        publication
425                            .as_ref()
426                            .and_then(|view| view.registration_declaration(module.module_id()))
427                            .as_deref(),
428                        pending_entry.map(|entry| entry.registration_channel),
429                    ),
430                    publication.as_deref(),
431                )
432                .map_err(|err| RouterError::backend(0, frame.header.corr, err))?;
433            let script = configured.script.as_ref().map(|entry| {
434                let approved = self
435                    .config_runtime
436                    .as_ref()
437                    .and_then(|owner| owner.approved_script(&status.module_id, &entry.path));
438                crate::supervise::script::status(entry, approved.as_ref())
439            });
440            let configured_enabled = match &approved {
441                ApprovedDaemonView::Approved {
442                    config: approved, ..
443                } => approved
444                    .modules
445                    .iter()
446                    .find(|module| module.module_id == status.module_id)
447                    .map(|module| module.enabled),
448                ApprovedDaemonView::NotStamped => self
449                    .capability_evaluator
450                    .configured_enabled(&status.module_id),
451                ApprovedDaemonView::Unavailable => None,
452            };
453            let admission_refused = status
454                .admission_refused
455                .clone()
456                .filter(|_| status.enabled && !status.process_alive)
457                .filter(|_| {
458                    publication
459                        .as_ref()
460                        .and_then(|view| view.registration_declaration(&status.module_id))
461                        .as_deref()
462                        == Some("undeclared")
463                });
464            #[cfg(windows)]
465            let admission_refused = admission_refused.or_else(|| {
466                (status.enabled && !status.process_alive)
467                    .then_some(status.nonce_pipe_refusal)
468                    .flatten()
469                    .map(str::to_owned)
470            });
471            let accepting_drain = status.state == crate::supervise::ModuleState::Draining
472                && self
473                    .forwarding
474                    .module_is_accepting_drain(&status.module_id)
475                    .map_err(RouterError::Forwarding)?;
476            // Keep the retired field for status consumers that display whether
477            // the daemon puts launch nonces in the environment.
478            let mut entry = SupervisorEntry::new(
479                status.module_id,
480                status.state.to_string(),
481                status.enabled,
482                status.live,
483                status.health.status,
484            )
485            .with_configured_enabled(configured_enabled)
486            .with_script(script)
487            .with_admission_refused(admission_refused)
488            .with_next_retry_at_ms(next_retry_at_ms)
489            .with_launch_nonce_env(Some(!cfg!(any(unix, windows))))
490            .with_launch_nonce_source(status.launch_nonce_source)
491            .with_waiting_for_previous_pid(status.waiting_for_previous_pid)
492            .with_protocol(status.protocol)
493            .with_pending_reload(pending_reload)
494            .with_last_probe_ms(status.health.last_probe_ms)
495            .with_last_exit_code(status.last_exit.as_ref().and_then(|e| e.code))
496            .with_last_exit_signal(status.last_exit.as_ref().and_then(|e| e.signal))
497            .with_last_exit_ms(status.last_exit.as_ref().map(|e| e.at_ms))
498            .with_last_exit_kind(status.last_exit.as_ref().map(|e| e.kind.into()))
499            .with_restart_count(Some(status.restart_count))
500            .with_max_restarts(Some(status.max_restarts))
501            .with_lifetime_restarts(Some(status.lifetime_restarts))
502            .with_spawn_generation(Some(status.spawn_generation))
503            .with_restart_window_secs(Some(status.restart_window.as_secs()))
504            .with_drain_timeout_ms(Some(status.drain_timeout.as_millis() as u64))
505            .with_restart_backoff_ms(Some(status.restart_backoff.as_millis() as u64))
506            .with_restart_max_backoff_ms(Some(status.restart_max_backoff.as_millis() as u64))
507            .with_resources(resources);
508            entry.pending = pending;
509            entry.accepting_drain = accepting_drain.then_some(true);
510            modules.push(entry);
511        }
512        for module in &mut modules {
513            if let Some((tree, hour)) = readings.modules.get(&module.module_id) {
514                module.tree = tree.clone();
515                module.cpu_last_hour = hour.clone();
516            }
517            module.tree_unavailable = readings
518                .reasons
519                .get(&module.module_id)
520                .map(|reason| (*reason).to_owned());
521            if module.tree.is_none() {
522                module.tree_unavailable = Some(
523                    if not_running.contains(&module.module_id) {
524                        "not_running"
525                    } else if let Some(reason) = readings.reasons.get(&module.module_id) {
526                        reason
527                    } else {
528                        "not_yet_measured"
529                    }
530                    .to_owned(),
531                );
532            }
533        }
534        let response = ClientControlResponse::SupervisorList {
535            generation,
536            modules,
537            daemon: readings.daemon,
538            agent_commands: readings.agent_commands,
539        };
540        Ok(vec![control_response_body_frame(
541            &frame,
542            &response,
543            "ClientControlResponse::SupervisorList",
544        )?])
545    }
546
547    pub(super) fn handle_supervisor_stderr_tail(
548        &self,
549        frame: Frame,
550        module_id: String,
551        max_lines: Option<u32>,
552        max_bytes: Option<u32>,
553    ) -> Result<Vec<Frame>, RouterError> {
554        let Some(module) = self.supervisor.get(&module_id) else {
555            return Ok(vec![control_error_frame(
556                &frame,
557                "unknown_module",
558                format!("module_id '{module_id}' is not supervised"),
559            )?]);
560        };
561
562        let snapshot = module.stderr_tail(
563            max_lines.map(|value| value as usize),
564            max_bytes.map(|value| value as usize),
565        );
566
567        let response = ClientControlResponse::SupervisorStderrTail {
568            module_id,
569            tail: StderrTail {
570                capture: match snapshot.capture {
571                    CaptureState::Captured => StderrCaptureState::Captured,
572                    CaptureState::Incomplete { reason } => {
573                        StderrCaptureState::Incomplete { reason }
574                    }
575                    CaptureState::NotCaptured { reason } => {
576                        StderrCaptureState::NotCaptured { reason }
577                    }
578                },
579                entries: snapshot
580                    .entries
581                    .into_iter()
582                    .map(|entry| match entry {
583                        TailEntry::Line {
584                            text,
585                            truncated,
586                            at_ms,
587                        } => StderrTailEntry::Line {
588                            text,
589                            truncated,
590                            at_ms,
591                        },
592                        TailEntry::ProcessStart => StderrTailEntry::ProcessStart,
593                    })
594                    .collect(),
595                dropped_lines: snapshot.dropped_lines,
596            },
597        };
598        Ok(vec![control_response_body_frame(
599            &frame,
600            &response,
601            "ClientControlResponse::SupervisorStderrTail",
602        )?])
603    }
604
605    pub(super) async fn observe_control_wait<F: std::future::Future>(
606        &self,
607        ctx: &RouteCtx,
608        target: Option<&str>,
609        kind: &'static str,
610        future: F,
611    ) -> F::Output {
612        self.counters
613            .observe_reader_wait(
614                || {
615                    let module = self
616                        .forwarding
617                        .module_id_for_connection(ctx.connection_id)
618                        .ok()
619                        .flatten();
620                    let principal = if module.is_some() { "module" } else { "direct" };
621                    (
622                        self.resolve_reader_wait_target(kind, target)
623                            .or(module)
624                            .unwrap_or_else(|| crate::observability::CONTROL_WAIT_BUCKET.into()),
625                        principal.into(),
626                    )
627                },
628                kind,
629                future,
630            )
631            .await
632    }
633
634    /// Resolve the reader-wait module ID only from supervisor or registry
635    /// records; never attribute a wait from the request selector alone.
636    pub(crate) fn resolve_reader_wait_target(
637        &self,
638        op: &str,
639        selector: Option<&str>,
640    ) -> Option<String> {
641        let selector = selector?;
642        match op {
643            ops::SUPERVISOR_TERMINALS | ops::SUPERVISOR_PROVENANCE => self
644                .supervisor
645                .get(selector)
646                .map(|module| module.module_id().to_owned()),
647            ops::SUPERVISOR_HEALTH_PROBE => self
648                .registry
649                .get_module(selector)
650                .ok()
651                .flatten()
652                .map(|registration| registration.manifest.module_id),
653            _ => None,
654        }
655    }
656
657    pub(super) async fn handle_supervisor_terminals(
658        &self,
659        ctx: &RouteCtx,
660        frame: Frame,
661        module_id: String,
662    ) -> Result<Vec<Frame>, RouterError> {
663        let Some(module) = self.supervisor.get(&module_id) else {
664            return Ok(vec![control_error_frame(
665                &frame,
666                "unknown_module",
667                format!("module_id '{module_id}' is not supervised"),
668            )?]);
669        };
670
671        // The journal read runs on a blocking thread: it can be megabytes of
672        // file I/O and must not occupy a runtime worker.
673        let terminals = self
674            .observe_control_wait(
675                ctx,
676                Some(module.module_id()),
677                ops::SUPERVISOR_TERMINALS,
678                module.read_durable_terminal_history(),
679            )
680            .await
681            .map_err(|error| {
682                RouterError::backend(
683                    0,
684                    frame.header.corr,
685                    format!("failed to read terminal history: {error}"),
686                )
687            })?;
688        let response = ClientControlResponse::SupervisorTerminals {
689            module_id,
690            terminals,
691        };
692        Ok(vec![control_response_body_frame(
693            &frame,
694            &response,
695            "ClientControlResponse::SupervisorTerminals",
696        )?])
697    }
698
699    pub(super) fn handle_supervisor_routes(
700        &self,
701        frame: Frame,
702        module_id: Option<String>,
703    ) -> Result<Vec<Frame>, RouterError> {
704        let mut openers = HashMap::new();
705        let modules = self
706            .forwarding
707            .route_census(module_id.as_deref())
708            .map_err(RouterError::Forwarding)?
709            .into_iter()
710            .map(|(module_id, routes)| SupervisorRouteModule {
711                module_id,
712                routes: routes
713                    .into_iter()
714                    .map(|route| SupervisorRoute {
715                        consumer: match route.principal {
716                            Principal::Reserved { module_id } => {
717                                SupervisorRouteConsumer::Reserved { module_id }
718                            }
719                            Principal::Direct | Principal::Unverified => {
720                                SupervisorRouteConsumer::Direct {
721                                    connection_id: route.goodbye_target.connection_id.get(),
722                                }
723                            }
724                        },
725                        age_ms: Instant::now()
726                            .saturating_duration_since(route.bound_at)
727                            .as_millis()
728                            .try_into()
729                            .unwrap_or(u64::MAX),
730                        draining: route.draining,
731                        drain_reason: route.drain_reason,
732                        opener: openers
733                            .entry(route.goodbye_target.connection_id)
734                            .or_insert_with_key(|connection| self.route_opener(*connection))
735                            .clone(),
736                    })
737                    .collect(),
738            })
739            .collect();
740        let response = ClientControlResponse::SupervisorRoutes { modules };
741        Ok(vec![control_response_body_frame(
742            &frame,
743            &response,
744            "ClientControlResponse::SupervisorRoutes",
745        )?])
746    }
747
748    fn route_opener(
749        &self,
750        connection: ConnectionId,
751    ) -> Option<subc_control::SupervisorRouteOpener> {
752        use subc_control::{SupervisorRouteOpener, SupervisorRouteTransport};
753
754        // Several routes may share a connection. Resolve its name once per
755        // reply, outside the lock, so other connections can open and close.
756        let opener = self
757            .route_openers
758            .lock()
759            .unwrap_or_else(|p| p.into_inner())
760            .get(&connection)
761            .cloned()?;
762        let (transport, process) = match opener {
763            RouteOpenerConnection::Local(process) => (SupervisorRouteTransport::Local, process),
764            RouteOpenerConnection::Tcp => (SupervisorRouteTransport::Tcp, None),
765        };
766        Some(SupervisorRouteOpener {
767            connection_id: connection.get(),
768            transport,
769            pid: process.as_ref().map(|process| process.pid()),
770            command: process.and_then(|process| process.short_name()),
771        })
772    }
773
774    fn running_registration_method(
775        &self,
776        module: &str,
777    ) -> Option<subc_control::RegistrationMethod> {
778        let registration = self.registry.get_module(module).ok()??;
779        let connection = registration.connection_id;
780        let channel = self.supervisor.registration_spawn(connection).is_some();
781        let nonce = if channel {
782            None
783        } else {
784            self.hello_launch_nonces
785                .lock()
786                .ok()?
787                .nonce(connection)
788                .map(str::to_owned)
789        };
790        if !channel && nonce.is_none() {
791            return None;
792        }
793        self.supervisor
794            .registration_snapshot_is_current_live(
795                &self.registry,
796                module,
797                connection,
798                nonce.as_deref(),
799            )
800            .then_some(if channel {
801                subc_control::RegistrationMethod::Channel
802            } else {
803                subc_control::RegistrationMethod::Nonce
804            })
805    }
806
807    pub(super) async fn handle_supervisor_provenance(
808        &self,
809        ctx: &RouteCtx,
810        frame: Frame,
811        module_id: Option<String>,
812    ) -> Result<Vec<Frame>, RouterError> {
813        let targeted = module_id.is_some();
814        let selected = if let Some(module_id) = module_id {
815            let Some(module) = self.supervisor.get(&module_id) else {
816                return Ok(vec![control_error_frame(
817                    &frame,
818                    "unknown_module",
819                    format!("module_id '{module_id}' is not supervised"),
820                )?]);
821            };
822            vec![module]
823        } else {
824            self.supervisor.list()
825        };
826
827        let target = targeted.then(|| selected[0].module_id());
828        let declarations = if let Some(owner) = &self.config_runtime {
829            owner
830                .on_blocking(|owner| owner.registration_declarations())
831                .await
832                .ok()
833        } else {
834            None
835        };
836        self.observe_control_wait(ctx, target, ops::SUPERVISOR_PROVENANCE, async {
837            let mut modules = Vec::with_capacity(selected.len());
838            let mut extensions = Vec::with_capacity(selected.len());
839            for module in &selected {
840                let (status, observed_image) = module
841                    .status_and_running_image_agreement()
842                    .await
843                    .map_err(|err| {
844                        RouterError::backend(
845                            0,
846                            frame.header.corr,
847                            format!("failed to read supervisor status: {err}"),
848                        )
849                    })?;
850                let module_declared = self
851                    .registry
852                    .get_module(&status.module_id)
853                    .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
854                    .and_then(|registration| registration.manifest.provenance)
855                    .map(|build| ModuleDeclaredProvenance::Reported { build })
856                    .unwrap_or(ModuleDeclaredProvenance::Unverifiable);
857                #[cfg(test)]
858                let running_image = match &self.provenance_probe_override {
859                    Some(result) => result.clone(),
860                    None => observed_image,
861                };
862                #[cfg(not(test))]
863                let running_image = observed_image;
864                let registration = self.running_registration_method(&status.module_id);
865                let mut extension = subc_control::SupervisorModuleProvenanceExt::new()
866                    .with_registration(registration);
867                extension.registration_declaration = declarations
868                    .as_ref()
869                    .and_then(|entries| entries.get(&status.module_id))
870                    .cloned();
871                if status.process_alive && status.registration_declaration.is_some() {
872                    extension.registration_declaration = status.registration_declaration.clone();
873                }
874                extensions.push(extension);
875                modules.push(SupervisorModuleProvenance {
876                    module_id: status.module_id,
877                    module_declared,
878                    daemon_observed: SupervisorObservedProcess {
879                        launch_nonce_source: status.launch_nonce_source,
880                        pid: status.pid,
881                        spawned_at_ms: status.spawned_at_ms,
882                        spawned_from: status.spawned_from,
883                        running_image,
884                    },
885                });
886            }
887            let daemon = SupervisorDaemonProvenance {
888                daemon_build: self.daemon_provenance.build.clone(),
889                daemon_observed: DaemonObservedProcess {
890                    pid: self.daemon_provenance.pid,
891                    started_at_ms: self
892                        .daemon_provenance
893                        .start_clock
894                        .map(|clock| clock.started_at_ms())
895                        .or(self.daemon_provenance.started_at_ms),
896                    running_image: self
897                        .daemon_provenance
898                        .probe
899                        .observe(
900                            self.daemon_provenance.pid,
901                            self.daemon_provenance.executable_path.as_deref(),
902                            self.daemon_provenance.executable_identity.clone(),
903                            self.daemon_provenance.process_start_time,
904                        )
905                        .await,
906                },
907            };
908            let response = ClientControlResponse::SupervisorProvenance { daemon, modules };
909            let mut response = serde_json::to_value(response)
910                .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?;
911            for (entry, extension) in response["modules"]
912                .as_array_mut()
913                .expect("provenance modules are an array")
914                .iter_mut()
915                .zip(extensions)
916            {
917                extension.write_to(entry).map_err(|error| {
918                    RouterError::backend(0, frame.header.corr, error.to_string())
919                })?;
920            }
921            Ok(vec![control_response_body_frame(
922                &frame,
923                &response,
924                "ClientControlResponse::SupervisorProvenance",
925            )?])
926        })
927        .await
928    }
929
930    pub(super) fn handle_supervisor_health(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
931        self.refresh_capability_requirements();
932        let publication = self
933            .config_runtime
934            .as_ref()
935            .and_then(|owner| owner.observed_snapshot().ok());
936        let generation = self
937            .registry
938            .generation()
939            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
940        let modules = self
941            .supervisor
942            .list()
943            .into_iter()
944            .map(|module| {
945                let status = module.status_for_control("health").map_err(|err| {
946                    RouterError::backend(
947                        0,
948                        frame.header.corr,
949                        format!("failed to read supervisor health: {err}"),
950                    )
951                })?;
952                let module_id = status.module_id;
953                let capability_detail = self
954                    .capability_evaluator
955                    .required_problem_detail(&module_id);
956                let declaration_warning = self.registry.get_module(&module_id).ok().flatten()
957                    .filter(|registration| registration.manifest.registration_channel == Some(false))
958                    .filter(|_| publication.as_ref().and_then(|view| view.registration_declaration(&module_id))
959                        .as_deref().map(|next| if status.process_alive { status.registration_declaration.as_deref().unwrap_or(next) } else { next }) == Some("declared"))
960                    .map(|_| format!("{module_id}: HELLO registration_channel is false despite the approved channel declaration"));
961                let capability_detail = append_capability_problem_detail(capability_detail, declaration_warning);
962                Ok(SupervisorHealthEntry {
963                    module_id,
964                    status: status.health.status,
965                    detail: append_capability_problem_detail(
966                        status.health.detail,
967                        capability_detail,
968                    ),
969                    metrics: status.health.metrics,
970                    consecutive_failures: status.health.consecutive_failures,
971                    late_answer_count: status.health.late_answer_count,
972                    last_late_answer_latency_ms: status.health.last_late_answer_latency_ms,
973                    last_action: status.health.last_action,
974                    last_action_ms: status.health.last_action_ms,
975                    last_probe_ms: status.health.last_probe_ms,
976                })
977            })
978            .collect::<Result<Vec<_>, RouterError>>()?;
979        let response = ClientControlResponse::SupervisorHealth {
980            generation,
981            modules,
982        };
983        Ok(vec![control_response_body_frame(
984            &frame,
985            &response,
986            "ClientControlResponse::SupervisorHealth",
987        )?])
988    }
989
990    pub(super) async fn handle_supervisor_restart(
991        &self,
992        frame: Frame,
993        module_id: String,
994        drain_timeout_ms: Option<u64>,
995        requester: Principal,
996    ) -> Result<Vec<Frame>, RouterError> {
997        let _operation_guard = match self.supervisor.lifecycle_operation(Some(&module_id)).await {
998            Ok(guard) => guard,
999            Err(refusal) => return Ok(vec![control_error_body_frame(&frame, refusal.body())?]),
1000        };
1001        let Some(module) = self.supervisor.get(&module_id) else {
1002            return Ok(vec![control_error_frame(
1003                &frame,
1004                "unknown_module",
1005                format!("module_id '{module_id}' is not supervised"),
1006            )?]);
1007        };
1008
1009        self.route_outages.mark_operator_action(&module_id);
1010        if let Err(err) = module
1011            .restart_requested(drain_timeout_ms, Some(requester))
1012            .await
1013        {
1014            self.route_outages
1015                .operator_action_ended_unrefused(&module_id);
1016            let (code, message) = match err {
1017                _ if err.is_config_gate_error() => ("config_gated", err.to_string()),
1018                crate::supervise::SuperviseError::Disabled { .. } => {
1019                    ("module_disabled", err.to_string())
1020                }
1021                crate::supervise::SuperviseError::SwapInProgress { .. } => {
1022                    ("swap_in_progress", err.to_string())
1023                }
1024                _ => (
1025                    "target_unavailable",
1026                    format!("failed to restart module_id '{module_id}': {err}"),
1027                ),
1028            };
1029            return Ok(vec![control_error_frame(&frame, code, message)?]);
1030        }
1031
1032        let response = ClientControlResponse::SupervisorAck {
1033            module_id,
1034            applied: true,
1035        };
1036        Ok(vec![control_response_body_frame(
1037            &frame,
1038            &response,
1039            "ClientControlResponse::SupervisorAck",
1040        )?])
1041    }
1042
1043    /// `supervisor.swap`. Answered when the swap has cut over or failed, not
1044    /// when the old process has finished draining: a caller whose own lane
1045    /// rides the old process must get its reply before that drain waits on it.
1046    pub(super) async fn handle_supervisor_swap(
1047        &self,
1048        frame: Frame,
1049        module_id: String,
1050        ready_timeout_ms: Option<u64>,
1051        requester: Principal,
1052    ) -> Result<Vec<Frame>, RouterError> {
1053        // The daemon-wide operation lock is held only to resolve the handle,
1054        // not across the swap. The swap can take its whole readiness budget,
1055        // and `supervisor.set_enabled` (ck module stop) takes the same lock:
1056        // holding it here would park an operator's stop behind the swap it is
1057        // meant to abort. A rescan or stop that reaches the module during the
1058        // swap is served by the swap itself (see `supervise_swap`).
1059        let module = {
1060            let _operation_guard = match self.supervisor.lifecycle_operation(Some(&module_id)).await
1061            {
1062                Ok(guard) => guard,
1063                Err(refusal) => return Ok(vec![control_error_body_frame(&frame, refusal.body())?]),
1064            };
1065            self.supervisor.get(&module_id)
1066        };
1067        let Some(module) = module else {
1068            return Ok(vec![control_error_frame(
1069                &frame,
1070                "unknown_module",
1071                format!("module_id '{module_id}' is not supervised"),
1072            )?]);
1073        };
1074
1075        self.route_outages.mark_operator_action(&module_id);
1076        if let Err(err) = module
1077            .swap_requested(ready_timeout_ms.map(Duration::from_millis), Some(requester))
1078            .await
1079        {
1080            self.route_outages
1081                .operator_action_ended_unrefused(&module_id);
1082            use crate::supervise::SuperviseError;
1083            let message = err.to_string();
1084            let error = match err {
1085                SuperviseError::ConfigHeld { .. } => ErrorBody::new("config_gated", message),
1086                SuperviseError::Disabled { .. } => ErrorBody::new("module_disabled", message),
1087                SuperviseError::SwapRefused { reason, .. } => ErrorBody {
1088                    code: "swap_refused".to_string(),
1089                    message,
1090                    detail: Some(serde_json::json!({ "reason": reason.as_str() })),
1091                },
1092                SuperviseError::SwapFailed {
1093                    arm,
1094                    candidate_exit,
1095                    ..
1096                } => ErrorBody {
1097                    code: "swap_failed".to_string(),
1098                    message,
1099                    detail: Some(serde_json::json!({
1100                        "arm": arm.as_str(),
1101                        "candidate_exit_code": candidate_exit.as_ref().and_then(|exit| exit.code),
1102                        "candidate_exit_signal": candidate_exit.as_ref().and_then(|exit| exit.signal),
1103                    })),
1104                },
1105                _ => ErrorBody::new(
1106                    "target_unavailable",
1107                    format!("failed to swap module_id '{module_id}': {message}"),
1108                ),
1109            };
1110            return Ok(vec![control_error_body_frame(&frame, error)?]);
1111        }
1112        // A completed swap kept the incumbent serving until cutover, so it
1113        // usually opened no outage; a mark left behind would make the next,
1114        // unrelated outage read as requested.
1115        self.route_outages
1116            .operator_action_ended_unrefused(&module_id);
1117
1118        let response = ClientControlResponse::SupervisorAck {
1119            module_id,
1120            applied: true,
1121        };
1122        Ok(vec![control_response_body_frame(
1123            &frame,
1124            &response,
1125            "ClientControlResponse::SupervisorAck",
1126        )?])
1127    }
1128
1129    pub(super) async fn handle_supervisor_reload(
1130        &self,
1131        frame: Frame,
1132        module_id: String,
1133        requester: Principal,
1134    ) -> Result<Vec<Frame>, RouterError> {
1135        let _operation_guard = match self.supervisor.lifecycle_operation(Some(&module_id)).await {
1136            Ok(guard) => guard,
1137            Err(refusal) => return Ok(vec![control_error_body_frame(&frame, refusal.body())?]),
1138        };
1139        let Some(module) = self.supervisor.get(&module_id) else {
1140            return Ok(vec![control_error_frame(
1141                &frame,
1142                "unknown_module",
1143                format!("module_id '{module_id}' is not supervised"),
1144            )?]);
1145        };
1146
1147        self.route_outages.mark_operator_action(&module_id);
1148        if let Err(err) = module.reload_requested(Some(requester)).await {
1149            self.route_outages
1150                .operator_action_ended_unrefused(&module_id);
1151            let (code, message) = match err {
1152                _ if err.is_config_gate_error() => ("config_gated", err.to_string()),
1153                crate::supervise::SuperviseError::Disabled { .. } => {
1154                    ("module_disabled", err.to_string())
1155                }
1156                crate::supervise::SuperviseError::SwapInProgress { .. } => {
1157                    ("swap_in_progress", err.to_string())
1158                }
1159                _ => (
1160                    "reload_failed",
1161                    format!("failed to reload module_id '{module_id}': {err}"),
1162                ),
1163            };
1164            return Ok(vec![control_error_frame(&frame, code, message)?]);
1165        }
1166
1167        let response = ClientControlResponse::SupervisorAck {
1168            module_id,
1169            applied: true,
1170        };
1171        Ok(vec![control_response_body_frame(
1172            &frame,
1173            &response,
1174            "ClientControlResponse::SupervisorAck",
1175        )?])
1176    }
1177}
1178
1179impl ControlHandler {
1180    pub(super) async fn handle_supervisor_release_reserved(
1181        &self,
1182        frame: Frame,
1183        module_id: String,
1184    ) -> Result<Vec<Frame>, RouterError> {
1185        let Some(context) = self.rescan.clone() else {
1186            return Ok(vec![control_error_frame(
1187                &frame,
1188                "release_unavailable",
1189                "reserved-id release requires a daemon started with a reloadable config path",
1190            )?]);
1191        };
1192        let _operation_guard = match self.supervisor.lifecycle_operation(Some(&module_id)).await {
1193            Ok(guard) => guard,
1194            Err(refusal) => return Ok(vec![control_error_body_frame(&frame, refusal.body())?]),
1195        };
1196        let approved = if let Some(owner) = &self.config_runtime {
1197            // Observe the file as a proposal, but decide membership solely from
1198            // approved bytes. A proposed re-add must not retain a removed id.
1199            match owner
1200                .on_blocking(|owner| {
1201                    owner.observe_file_proposal()?;
1202                    owner.approved_daemon_configuration()
1203                })
1204                .await
1205            {
1206                Ok(config) => config,
1207                Err(error) => return Ok(vec![config_gate::config_error_frame(&frame, error)?]),
1208            }
1209        } else {
1210            None
1211        };
1212        let loaded = if let Some(approved) = approved {
1213            Ok(Some(approved))
1214        } else {
1215            crate::daemon_config::load(&context.config_path)
1216        };
1217        let loaded = match loaded {
1218            Ok(Some(config)) => config,
1219            Ok(None) => {
1220                return Ok(vec![control_error_frame(
1221                    &frame,
1222                    "invalid_daemon_config",
1223                    format!(
1224                        "daemon config not found at {}; refusing to release reserved module_id '{module_id}'",
1225                        context.config_path.display()
1226                    ),
1227                )?])
1228            }
1229            Err(err) => {
1230                return Ok(vec![control_error_frame(
1231                    &frame,
1232                    "invalid_daemon_config",
1233                    format!("unable to verify reserved-id release against daemon config: {err}"),
1234                )?])
1235            }
1236        };
1237        if loaded
1238            .modules
1239            .iter()
1240            .any(|configured| configured.module_id == module_id)
1241        {
1242            return Ok(vec![control_error_frame(
1243                &frame,
1244                "reserved_module_configured",
1245                format!(
1246                    "module_id '{module_id}' remains configured; remove its config entry and rescan before releasing its reserved id"
1247                ),
1248            )?]);
1249        }
1250        if !self.supervisor.release_retained_reserved_gate(&module_id) {
1251            return Ok(vec![control_error_frame(
1252                &frame,
1253                "reserved_gate_not_retained",
1254                format!(
1255                    "module_id '{module_id}' has no retired reserved-id gate to release; rescan its removed reserved configuration first"
1256                ),
1257            )?]);
1258        }
1259
1260        let response = ClientControlResponse::SupervisorAck {
1261            module_id,
1262            applied: true,
1263        };
1264        Ok(vec![control_response_body_frame(
1265            &frame,
1266            &response,
1267            "ClientControlResponse::SupervisorAck",
1268        )?])
1269    }
1270}
1271
1272impl ControlHandler {
1273    pub(super) async fn handle_supervisor_set_enabled(
1274        &self,
1275        frame: Frame,
1276        module_id: String,
1277        enabled: bool,
1278        requester: Principal,
1279    ) -> Result<Vec<Frame>, RouterError> {
1280        let _operation_guard = match self.supervisor.lifecycle_operation(Some(&module_id)).await {
1281            Ok(guard) => guard,
1282            Err(refusal) => return Ok(vec![control_error_body_frame(&frame, refusal.body())?]),
1283        };
1284        let Some(module) = self.supervisor.get(&module_id) else {
1285            return Ok(vec![control_error_frame(
1286                &frame,
1287                "unknown_module",
1288                format!("module_id '{module_id}' is not supervised"),
1289            )?]);
1290        };
1291
1292        // Enabling counts as well as disabling: a module an operator starts
1293        // is refused until it registers, and that wait was asked for.
1294        self.route_outages.mark_operator_action(&module_id);
1295        let applied = match module.set_enabled_requested(enabled, Some(requester)).await {
1296            Ok(applied) => applied,
1297            Err(err) => {
1298                self.route_outages
1299                    .operator_action_ended_unrefused(&module_id);
1300                return Ok(vec![control_error_frame(
1301                    &frame,
1302                    if err.is_config_gate_error() {
1303                        "config_gated"
1304                    } else {
1305                        "target_unavailable"
1306                    },
1307                    format!("failed to set module_id '{module_id}' enabled={enabled}: {err}"),
1308                )?]);
1309            }
1310        };
1311        if !applied {
1312            // Already in the requested state: nothing was made unavailable,
1313            // so the mark must not outlive this request.
1314            self.route_outages
1315                .operator_action_ended_unrefused(&module_id);
1316        }
1317
1318        self.capability_evaluator.wake_deadline_loop();
1319        self.refresh_capability_requirements();
1320        let response = ClientControlResponse::SupervisorAck { module_id, applied };
1321        Ok(vec![control_response_body_frame(
1322            &frame,
1323            &response,
1324            "ClientControlResponse::SupervisorAck",
1325        )?])
1326    }
1327
1328    pub(super) async fn handle_supervisor_health_probe(
1329        &self,
1330        ctx: &RouteCtx,
1331        frame: Frame,
1332        module_id: String,
1333    ) -> Result<Vec<Frame>, RouterError> {
1334        use crate::supervise::live_upgrade::LifecycleRefusal;
1335
1336        if let Some(refusal) = self.supervisor.lifecycle_refusal(Some(&module_id)) {
1337            return Ok(vec![control_error_body_frame(&frame, refusal.body())?]);
1338        }
1339        if self.forwarding.upgrade_admission.borrow().fenced() {
1340            return Ok(vec![control_error_body_frame(
1341                &frame,
1342                LifecycleRefusal::UpgradeBusy.body(),
1343            )?]);
1344        }
1345        self.refresh_capability_requirements();
1346        let Some(registration) = self
1347            .registry
1348            .get_module(&module_id)
1349            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
1350        else {
1351            return Ok(vec![control_error_frame(
1352                &frame,
1353                "unknown_module",
1354                format!("module_id '{module_id}' is not registered"),
1355            )?]);
1356        };
1357
1358        // This guard's ACCEPT direction is fenced, but only INCIDENTALLY: no test is
1359        // named for it. Making `module_registration_grants_op` return false
1360        // unconditionally reddens five tests, and every one is named for something
1361        // else -- capability relay, probe/bind demultiplexing, supervision-only
1362        // probing. They exercise a successful advertisement check on the way to their
1363        // own subject.
1364        //
1365        // Real protection, fragile in a specific way: narrowing any of those tests to
1366        // focus on its stated subject would silently remove coverage nobody knows
1367        // they are carrying. Recorded here rather than as a sixth test, because the
1368        // useful fact is WHICH tests hold the guard up -- a new test would add
1369        // coverage without telling the next person what the existing ones quietly do.
1370        if !module_registration_grants_op(&registration.control_ops, MODULE_CONTROL_OP_HEALTH_CHECK)
1371        {
1372            return Ok(vec![control_error_frame(
1373                &frame,
1374                "health_not_advertised",
1375                format!("module_id '{module_id}' did not advertise health.check"),
1376            )?]);
1377        }
1378
1379        self.observe_control_wait(
1380            ctx,
1381            Some(&registration.manifest.module_id),
1382            ops::SUPERVISOR_HEALTH_PROBE,
1383            async {
1384                let deadline = Instant::now() + self.health_probe_timeout;
1385                let pending = match self.forwarding.begin_module_control_rpc_for(
1386                    &module_id,
1387                    MODULE_CONTROL_OP_HEALTH_CHECK,
1388                    deadline,
1389                ) {
1390                    Ok(pending) => pending,
1391                    Err(err) => {
1392                        return Ok(vec![control_error_frame(
1393                            &frame,
1394                            forwarding_error_code(&err),
1395                            err.to_string(),
1396                        )?])
1397                    }
1398                };
1399
1400                let PendingModuleControlRpc {
1401                    endpoint,
1402                    module_sink,
1403                    negotiated_ver,
1404                    corr: probe_corr,
1405                    receiver,
1406                } = pending;
1407                let mut guard =
1408                    ModuleControlRpcGuard::new(Arc::clone(&self.forwarding), endpoint, probe_corr);
1409                let probe_body = serde_json::to_vec(&ModuleControlRequest::HealthCheck {})
1410                    .map_err(|err| {
1411                        RouterError::backend(
1412                            0,
1413                            frame.header.corr,
1414                            format!("failed to encode health.check request: {err}"),
1415                        )
1416                    })?;
1417                let probe_frame = Frame::build_with_version(
1418                    negotiated_ver,
1419                    FrameType::Request,
1420                    control_flags(),
1421                    0,
1422                    0,
1423                    probe_corr,
1424                    probe_body,
1425                )
1426                .map_err(RouterError::FrameBuild)?;
1427
1428                // Queue admission and the reply share one deadline, so a module that
1429                // stops reading cannot park the requesting connection's reader forever.
1430                let fenced = RouterError::DaemonUpgrade {
1431                    channel: 0,
1432                    epoch: 0,
1433                    corr: frame.header.corr,
1434                };
1435                match timeout_at(
1436                    deadline,
1437                    module_sink.send_upgrade_fenced(probe_frame, fenced),
1438                )
1439                .await
1440                {
1441                    Ok(Ok(())) => {}
1442                    Ok(Err(RouterError::DaemonUpgrade { .. })) => {
1443                        return Ok(vec![control_error_body_frame(
1444                            &frame,
1445                            LifecycleRefusal::UpgradeBusy.body(),
1446                        )?]);
1447                    }
1448                    Ok(Err(err)) => {
1449                        return Ok(vec![control_error_frame(
1450                            &frame,
1451                            "target_unavailable",
1452                            err.to_string(),
1453                        )?]);
1454                    }
1455                    Err(_) => {
1456                        return Ok(vec![control_error_frame(
1457                            &frame,
1458                            "module_timeout",
1459                            format!(
1460                                "module_id '{module_id}' did not answer health.check within {:?}",
1461                                self.health_probe_timeout
1462                            ),
1463                        )?]);
1464                    }
1465                }
1466
1467                match timeout_at(deadline, receiver).await {
1468                    Ok(Ok(ModuleControlRpcOutcome::RawResponse(_))) => {
1469                        Ok(vec![control_error_frame(
1470                            &frame,
1471                            "invalid_control_body",
1472                            "health.check returned an unexpected config response",
1473                        )?])
1474                    }
1475                    Ok(Ok(ModuleControlRpcOutcome::Response(response))) => {
1476                        guard.disarm();
1477                        let Some(report) = response.health_report() else {
1478                            return Ok(vec![control_error_frame(
1479                                &frame,
1480                                "invalid_control_body",
1481                                "health.check RPC returned a non-health response",
1482                            )?]);
1483                        };
1484                        // Metrics go out whole here. The supervisor's cached snapshot
1485                        // caps this blob (see truncate_health_metrics), and this path
1486                        // exists precisely to answer without that cap -- so applying it
1487                        // here would leave no way to see what the cached view drops.
1488                        let HealthReport {
1489                            status,
1490                            detail,
1491                            metrics,
1492                        } = report;
1493                        let capability_detail = self
1494                            .capability_evaluator
1495                            .required_problem_detail(&module_id);
1496                        let response = ClientControlResponse::SupervisorHealthProbe {
1497                            module_id,
1498                            status,
1499                            detail: append_capability_problem_detail(detail, capability_detail),
1500                            metrics,
1501                        };
1502                        Ok(vec![control_response_body_frame(
1503                            &frame,
1504                            &response,
1505                            "ClientControlResponse::SupervisorHealthProbe",
1506                        )?])
1507                    }
1508                    Ok(Ok(ModuleControlRpcOutcome::Rejected(body))) => {
1509                        guard.disarm();
1510                        // The module refused the health probe with its own body, so
1511                        // the refusal is relayed without the daemon-origin flag
1512                        // (bit 6): a client must not read it as the daemon's own
1513                        // refusal, which it may treat as never forwarded.
1514                        Ok(vec![control_relayed_error_body_frame(&frame, body)?])
1515                    }
1516                    Ok(Ok(ModuleControlRpcOutcome::ModuleGone(message))) => {
1517                        guard.disarm();
1518                        Ok(vec![control_error_frame(
1519                            &frame,
1520                            "target_unavailable",
1521                            message,
1522                        )?])
1523                    }
1524                    Ok(Ok(ModuleControlRpcOutcome::MalformedResponse(message))) => {
1525                        guard.disarm();
1526                        Ok(vec![control_error_frame(
1527                            &frame,
1528                            "invalid_control_body",
1529                            message,
1530                        )?])
1531                    }
1532                    Ok(Ok(ModuleControlRpcOutcome::UnexpectedOp { expected, actual })) => {
1533                        guard.disarm();
1534                        Ok(vec![control_error_frame(
1535                            &frame,
1536                            "invalid_control_body",
1537                            format!("expected module-control op '{expected}', got '{actual}'"),
1538                        )?])
1539                    }
1540                    Ok(Ok(ModuleControlRpcOutcome::DeadlineElapsed)) => {
1541                        guard.disarm();
1542                        Ok(vec![control_error_frame(
1543                            &frame,
1544                            "module_timeout",
1545                            format!(
1546                                "module_id '{module_id}' answered health.check after {:?}",
1547                                self.health_probe_timeout
1548                            ),
1549                        )?])
1550                    }
1551                    Ok(Err(_)) => Ok(vec![control_error_frame(
1552                        &frame,
1553                        "target_unavailable",
1554                        "health.check waiter was canceled before the module responded",
1555                    )?]),
1556                    Err(_) => Ok(vec![control_error_frame(
1557                        &frame,
1558                        "module_timeout",
1559                        format!(
1560                            "module_id '{module_id}' did not answer health.check within {:?}",
1561                            self.health_probe_timeout
1562                        ),
1563                    )?]),
1564                }
1565            },
1566        )
1567        .await
1568    }
1569
1570    pub(super) fn supervisor_status(
1571        &self,
1572        module_id: &str,
1573        corr: u64,
1574    ) -> Result<Option<(crate::supervise::ModuleStatus, bool)>, RouterError> {
1575        self.supervisor
1576            .get(module_id)
1577            .map(|module| {
1578                let warming = module.is_warming_for_control("status").map_err(|err| {
1579                    RouterError::backend(
1580                        0,
1581                        corr,
1582                        format!(
1583                            "failed to read supervisor warming state for module_id '{module_id}': {err}"
1584                        ),
1585                    )
1586                })?;
1587                module.status_for_control("status").map_err(|err| {
1588                    RouterError::backend(
1589                        0,
1590                        corr,
1591                        format!(
1592                            "failed to read supervisor status for module_id '{module_id}': {err}"
1593                        ),
1594                    )
1595                }).map(|status| (status, warming))
1596            })
1597            .transpose()
1598    }
1599}