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            // Keep the retired policy field on the wire for one release so
465            // existing status consumers still receive the platform policy.
466            let mut entry = SupervisorEntry::new(
467                status.module_id,
468                status.state.to_string(),
469                status.enabled,
470                status.live,
471                status.health.status,
472            )
473            .with_configured_enabled(configured_enabled)
474            .with_script(script)
475            .with_admission_refused(admission_refused)
476            .with_next_retry_at_ms(next_retry_at_ms)
477            .with_launch_nonce_env(Some(!cfg!(unix)))
478            .with_launch_nonce_source(status.launch_nonce_source)
479            .with_waiting_for_previous_pid(status.waiting_for_previous_pid)
480            .with_protocol(status.protocol)
481            .with_pending_reload(pending_reload)
482            .with_last_probe_ms(status.health.last_probe_ms)
483            .with_last_exit_code(status.last_exit.as_ref().and_then(|e| e.code))
484            .with_last_exit_signal(status.last_exit.as_ref().and_then(|e| e.signal))
485            .with_last_exit_ms(status.last_exit.as_ref().map(|e| e.at_ms))
486            .with_last_exit_kind(status.last_exit.as_ref().map(|e| e.kind.into()))
487            .with_restart_count(Some(status.restart_count))
488            .with_max_restarts(Some(status.max_restarts))
489            .with_lifetime_restarts(Some(status.lifetime_restarts))
490            .with_spawn_generation(Some(status.spawn_generation))
491            .with_restart_window_secs(Some(status.restart_window.as_secs()))
492            .with_drain_timeout_ms(Some(status.drain_timeout.as_millis() as u64))
493            .with_restart_backoff_ms(Some(status.restart_backoff.as_millis() as u64))
494            .with_restart_max_backoff_ms(Some(status.restart_max_backoff.as_millis() as u64))
495            .with_resources(resources);
496            entry.pending = pending;
497            modules.push(entry);
498        }
499        for module in &mut modules {
500            if let Some((tree, hour)) = readings.modules.get(&module.module_id) {
501                module.tree = tree.clone();
502                module.cpu_last_hour = hour.clone();
503            }
504            module.tree_unavailable = readings
505                .reasons
506                .get(&module.module_id)
507                .map(|reason| (*reason).to_owned());
508            if module.tree.is_none() {
509                module.tree_unavailable = Some(
510                    if not_running.contains(&module.module_id) {
511                        "not_running"
512                    } else if let Some(reason) = readings.reasons.get(&module.module_id) {
513                        reason
514                    } else {
515                        "not_yet_measured"
516                    }
517                    .to_owned(),
518                );
519            }
520        }
521        let response = ClientControlResponse::SupervisorList {
522            generation,
523            modules,
524            daemon: readings.daemon,
525            agent_commands: readings.agent_commands,
526        };
527        Ok(vec![control_response_body_frame(
528            &frame,
529            &response,
530            "ClientControlResponse::SupervisorList",
531        )?])
532    }
533
534    pub(super) fn handle_supervisor_stderr_tail(
535        &self,
536        frame: Frame,
537        module_id: String,
538        max_lines: Option<u32>,
539        max_bytes: Option<u32>,
540    ) -> Result<Vec<Frame>, RouterError> {
541        let Some(module) = self.supervisor.get(&module_id) else {
542            return Ok(vec![control_error_frame(
543                &frame,
544                "unknown_module",
545                format!("module_id '{module_id}' is not supervised"),
546            )?]);
547        };
548
549        let snapshot = module.stderr_tail(
550            max_lines.map(|value| value as usize),
551            max_bytes.map(|value| value as usize),
552        );
553
554        let response = ClientControlResponse::SupervisorStderrTail {
555            module_id,
556            tail: StderrTail {
557                capture: match snapshot.capture {
558                    CaptureState::Captured => StderrCaptureState::Captured,
559                    CaptureState::Incomplete { reason } => {
560                        StderrCaptureState::Incomplete { reason }
561                    }
562                    CaptureState::NotCaptured { reason } => {
563                        StderrCaptureState::NotCaptured { reason }
564                    }
565                },
566                entries: snapshot
567                    .entries
568                    .into_iter()
569                    .map(|entry| match entry {
570                        TailEntry::Line {
571                            text,
572                            truncated,
573                            at_ms,
574                        } => StderrTailEntry::Line {
575                            text,
576                            truncated,
577                            at_ms,
578                        },
579                        TailEntry::ProcessStart => StderrTailEntry::ProcessStart,
580                    })
581                    .collect(),
582                dropped_lines: snapshot.dropped_lines,
583            },
584        };
585        Ok(vec![control_response_body_frame(
586            &frame,
587            &response,
588            "ClientControlResponse::SupervisorStderrTail",
589        )?])
590    }
591
592    pub(super) async fn observe_control_wait<F: std::future::Future>(
593        &self,
594        ctx: &RouteCtx,
595        target: Option<&str>,
596        kind: &'static str,
597        future: F,
598    ) -> F::Output {
599        self.counters
600            .observe_reader_wait(
601                || {
602                    let module = self
603                        .forwarding
604                        .module_id_for_connection(ctx.connection_id)
605                        .ok()
606                        .flatten();
607                    let principal = if module.is_some() { "module" } else { "direct" };
608                    (
609                        self.resolve_reader_wait_target(kind, target)
610                            .or(module)
611                            .unwrap_or_else(|| crate::observability::CONTROL_WAIT_BUCKET.into()),
612                        principal.into(),
613                    )
614                },
615                kind,
616                future,
617            )
618            .await
619    }
620
621    /// Resolve the reader-wait module ID only from supervisor or registry
622    /// records; never attribute a wait from the request selector alone.
623    pub(crate) fn resolve_reader_wait_target(
624        &self,
625        op: &str,
626        selector: Option<&str>,
627    ) -> Option<String> {
628        let selector = selector?;
629        match op {
630            ops::SUPERVISOR_TERMINALS | ops::SUPERVISOR_PROVENANCE => self
631                .supervisor
632                .get(selector)
633                .map(|module| module.module_id().to_owned()),
634            ops::SUPERVISOR_HEALTH_PROBE => self
635                .registry
636                .get_module(selector)
637                .ok()
638                .flatten()
639                .map(|registration| registration.manifest.module_id),
640            _ => None,
641        }
642    }
643
644    pub(super) async fn handle_supervisor_terminals(
645        &self,
646        ctx: &RouteCtx,
647        frame: Frame,
648        module_id: String,
649    ) -> Result<Vec<Frame>, RouterError> {
650        let Some(module) = self.supervisor.get(&module_id) else {
651            return Ok(vec![control_error_frame(
652                &frame,
653                "unknown_module",
654                format!("module_id '{module_id}' is not supervised"),
655            )?]);
656        };
657
658        // The journal read runs on a blocking thread: it can be megabytes of
659        // file I/O and must not occupy a runtime worker.
660        let terminals = self
661            .observe_control_wait(
662                ctx,
663                Some(module.module_id()),
664                ops::SUPERVISOR_TERMINALS,
665                module.read_durable_terminal_history(),
666            )
667            .await
668            .map_err(|error| {
669                RouterError::backend(
670                    0,
671                    frame.header.corr,
672                    format!("failed to read terminal history: {error}"),
673                )
674            })?;
675        let response = ClientControlResponse::SupervisorTerminals {
676            module_id,
677            terminals,
678        };
679        Ok(vec![control_response_body_frame(
680            &frame,
681            &response,
682            "ClientControlResponse::SupervisorTerminals",
683        )?])
684    }
685
686    pub(super) fn handle_supervisor_routes(
687        &self,
688        frame: Frame,
689        module_id: Option<String>,
690    ) -> Result<Vec<Frame>, RouterError> {
691        let mut openers = HashMap::new();
692        let modules = self
693            .forwarding
694            .route_census(module_id.as_deref())
695            .map_err(RouterError::Forwarding)?
696            .into_iter()
697            .map(|(module_id, routes)| SupervisorRouteModule {
698                module_id,
699                routes: routes
700                    .into_iter()
701                    .map(|route| SupervisorRoute {
702                        consumer: match route.principal {
703                            Principal::Reserved { module_id } => {
704                                SupervisorRouteConsumer::Reserved { module_id }
705                            }
706                            Principal::Direct | Principal::Unverified => {
707                                SupervisorRouteConsumer::Direct {
708                                    connection_id: route.goodbye_target.connection_id.get(),
709                                }
710                            }
711                        },
712                        age_ms: Instant::now()
713                            .saturating_duration_since(route.bound_at)
714                            .as_millis()
715                            .try_into()
716                            .unwrap_or(u64::MAX),
717                        draining: route.draining,
718                        drain_reason: route.drain_reason,
719                        opener: openers
720                            .entry(route.goodbye_target.connection_id)
721                            .or_insert_with_key(|connection| self.route_opener(*connection))
722                            .clone(),
723                    })
724                    .collect(),
725            })
726            .collect();
727        let response = ClientControlResponse::SupervisorRoutes { modules };
728        Ok(vec![control_response_body_frame(
729            &frame,
730            &response,
731            "ClientControlResponse::SupervisorRoutes",
732        )?])
733    }
734
735    fn route_opener(
736        &self,
737        connection: ConnectionId,
738    ) -> Option<subc_control::SupervisorRouteOpener> {
739        use subc_control::{SupervisorRouteOpener, SupervisorRouteTransport};
740
741        // Several routes may share a connection. Resolve its name once per
742        // reply, outside the lock, so other connections can open and close.
743        let opener = self
744            .route_openers
745            .lock()
746            .unwrap_or_else(|p| p.into_inner())
747            .get(&connection)
748            .cloned()?;
749        let (transport, process) = match opener {
750            RouteOpenerConnection::Local(process) => (SupervisorRouteTransport::Local, process),
751            RouteOpenerConnection::Tcp => (SupervisorRouteTransport::Tcp, None),
752        };
753        Some(SupervisorRouteOpener {
754            connection_id: connection.get(),
755            transport,
756            pid: process.as_ref().map(|process| process.pid()),
757            command: process.and_then(|process| process.short_name()),
758        })
759    }
760
761    fn running_registration_method(
762        &self,
763        module: &str,
764    ) -> Option<subc_control::RegistrationMethod> {
765        let registration = self.registry.get_module(module).ok()??;
766        let connection = registration.connection_id;
767        let channel = self.supervisor.registration_spawn(connection).is_some();
768        let nonce = if channel {
769            None
770        } else {
771            self.hello_launch_nonces
772                .lock()
773                .ok()?
774                .nonce(connection)
775                .map(str::to_owned)
776        };
777        if !channel && nonce.is_none() {
778            return None;
779        }
780        self.supervisor
781            .registration_snapshot_is_current_live(
782                &self.registry,
783                module,
784                connection,
785                nonce.as_deref(),
786            )
787            .then_some(if channel {
788                subc_control::RegistrationMethod::Channel
789            } else {
790                subc_control::RegistrationMethod::Nonce
791            })
792    }
793
794    pub(super) async fn handle_supervisor_provenance(
795        &self,
796        ctx: &RouteCtx,
797        frame: Frame,
798        module_id: Option<String>,
799    ) -> Result<Vec<Frame>, RouterError> {
800        let targeted = module_id.is_some();
801        let selected = if let Some(module_id) = module_id {
802            let Some(module) = self.supervisor.get(&module_id) else {
803                return Ok(vec![control_error_frame(
804                    &frame,
805                    "unknown_module",
806                    format!("module_id '{module_id}' is not supervised"),
807                )?]);
808            };
809            vec![module]
810        } else {
811            self.supervisor.list()
812        };
813
814        let target = targeted.then(|| selected[0].module_id());
815        let declarations = if let Some(owner) = &self.config_runtime {
816            owner
817                .on_blocking(|owner| owner.registration_declarations())
818                .await
819                .ok()
820        } else {
821            None
822        };
823        self.observe_control_wait(ctx, target, ops::SUPERVISOR_PROVENANCE, async {
824            let mut modules = Vec::with_capacity(selected.len());
825            let mut extensions = Vec::with_capacity(selected.len());
826            for module in &selected {
827                let (status, observed_image) = module
828                    .status_and_running_image_agreement()
829                    .await
830                    .map_err(|err| {
831                        RouterError::backend(
832                            0,
833                            frame.header.corr,
834                            format!("failed to read supervisor status: {err}"),
835                        )
836                    })?;
837                let module_declared = self
838                    .registry
839                    .get_module(&status.module_id)
840                    .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
841                    .and_then(|registration| registration.manifest.provenance)
842                    .map(|build| ModuleDeclaredProvenance::Reported { build })
843                    .unwrap_or(ModuleDeclaredProvenance::Unverifiable);
844                #[cfg(test)]
845                let running_image = match &self.provenance_probe_override {
846                    Some(result) => result.clone(),
847                    None => observed_image,
848                };
849                #[cfg(not(test))]
850                let running_image = observed_image;
851                let registration = self.running_registration_method(&status.module_id);
852                let mut extension = subc_control::SupervisorModuleProvenanceExt::new()
853                    .with_registration(registration);
854                extension.registration_declaration = declarations
855                    .as_ref()
856                    .and_then(|entries| entries.get(&status.module_id))
857                    .cloned();
858                if status.process_alive && status.registration_declaration.is_some() {
859                    extension.registration_declaration = status.registration_declaration.clone();
860                }
861                extensions.push(extension);
862                modules.push(SupervisorModuleProvenance {
863                    module_id: status.module_id,
864                    module_declared,
865                    daemon_observed: SupervisorObservedProcess {
866                        launch_nonce_source: status.launch_nonce_source,
867                        pid: status.pid,
868                        spawned_at_ms: status.spawned_at_ms,
869                        spawned_from: status.spawned_from,
870                        running_image,
871                    },
872                });
873            }
874            let daemon = SupervisorDaemonProvenance {
875                daemon_build: self.daemon_provenance.build.clone(),
876                daemon_observed: DaemonObservedProcess {
877                    pid: self.daemon_provenance.pid,
878                    started_at_ms: self
879                        .daemon_provenance
880                        .start_clock
881                        .map(|clock| clock.started_at_ms())
882                        .or(self.daemon_provenance.started_at_ms),
883                    running_image: self
884                        .daemon_provenance
885                        .probe
886                        .observe(
887                            self.daemon_provenance.pid,
888                            self.daemon_provenance.executable_path.as_deref(),
889                            self.daemon_provenance.executable_identity.clone(),
890                            self.daemon_provenance.process_start_time,
891                        )
892                        .await,
893                },
894            };
895            let response = ClientControlResponse::SupervisorProvenance { daemon, modules };
896            let mut response = serde_json::to_value(response)
897                .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?;
898            for (entry, extension) in response["modules"]
899                .as_array_mut()
900                .expect("provenance modules are an array")
901                .iter_mut()
902                .zip(extensions)
903            {
904                extension.write_to(entry).map_err(|error| {
905                    RouterError::backend(0, frame.header.corr, error.to_string())
906                })?;
907            }
908            Ok(vec![control_response_body_frame(
909                &frame,
910                &response,
911                "ClientControlResponse::SupervisorProvenance",
912            )?])
913        })
914        .await
915    }
916
917    pub(super) fn handle_supervisor_health(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
918        self.refresh_capability_requirements();
919        let publication = self
920            .config_runtime
921            .as_ref()
922            .and_then(|owner| owner.observed_snapshot().ok());
923        let generation = self
924            .registry
925            .generation()
926            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
927        let modules = self
928            .supervisor
929            .list()
930            .into_iter()
931            .map(|module| {
932                let status = module.status_for_control("health").map_err(|err| {
933                    RouterError::backend(
934                        0,
935                        frame.header.corr,
936                        format!("failed to read supervisor health: {err}"),
937                    )
938                })?;
939                let module_id = status.module_id;
940                let capability_detail = self
941                    .capability_evaluator
942                    .required_problem_detail(&module_id);
943                let declaration_warning = self.registry.get_module(&module_id).ok().flatten()
944                    .filter(|registration| registration.manifest.registration_channel == Some(false))
945                    .filter(|_| publication.as_ref().and_then(|view| view.registration_declaration(&module_id))
946                        .as_deref().map(|next| if status.process_alive { status.registration_declaration.as_deref().unwrap_or(next) } else { next }) == Some("declared"))
947                    .map(|_| format!("{module_id}: HELLO registration_channel is false despite the approved channel declaration"));
948                let capability_detail = append_capability_problem_detail(capability_detail, declaration_warning);
949                Ok(SupervisorHealthEntry {
950                    module_id,
951                    status: status.health.status,
952                    detail: append_capability_problem_detail(
953                        status.health.detail,
954                        capability_detail,
955                    ),
956                    metrics: status.health.metrics,
957                    consecutive_failures: status.health.consecutive_failures,
958                    late_answer_count: status.health.late_answer_count,
959                    last_late_answer_latency_ms: status.health.last_late_answer_latency_ms,
960                    last_action: status.health.last_action,
961                    last_action_ms: status.health.last_action_ms,
962                    last_probe_ms: status.health.last_probe_ms,
963                })
964            })
965            .collect::<Result<Vec<_>, RouterError>>()?;
966        let response = ClientControlResponse::SupervisorHealth {
967            generation,
968            modules,
969        };
970        Ok(vec![control_response_body_frame(
971            &frame,
972            &response,
973            "ClientControlResponse::SupervisorHealth",
974        )?])
975    }
976
977    pub(super) async fn handle_supervisor_restart(
978        &self,
979        frame: Frame,
980        module_id: String,
981        drain_timeout_ms: Option<u64>,
982        requester: Principal,
983    ) -> Result<Vec<Frame>, RouterError> {
984        let _operation_guard = match self.supervisor.lifecycle_operation(Some(&module_id)).await {
985            Ok(guard) => guard,
986            Err(refusal) => return Ok(vec![control_error_body_frame(&frame, refusal.body())?]),
987        };
988        let Some(module) = self.supervisor.get(&module_id) else {
989            return Ok(vec![control_error_frame(
990                &frame,
991                "unknown_module",
992                format!("module_id '{module_id}' is not supervised"),
993            )?]);
994        };
995
996        self.route_outages.mark_operator_action(&module_id);
997        if let Err(err) = module
998            .restart_requested(drain_timeout_ms, Some(requester))
999            .await
1000        {
1001            self.route_outages
1002                .operator_action_ended_unrefused(&module_id);
1003            let (code, message) = match err {
1004                _ if err.is_config_gate_error() => ("config_gated", err.to_string()),
1005                crate::supervise::SuperviseError::Disabled { .. } => {
1006                    ("module_disabled", err.to_string())
1007                }
1008                crate::supervise::SuperviseError::SwapInProgress { .. } => {
1009                    ("swap_in_progress", err.to_string())
1010                }
1011                _ => (
1012                    "target_unavailable",
1013                    format!("failed to restart module_id '{module_id}': {err}"),
1014                ),
1015            };
1016            return Ok(vec![control_error_frame(&frame, code, message)?]);
1017        }
1018
1019        let response = ClientControlResponse::SupervisorAck {
1020            module_id,
1021            applied: true,
1022        };
1023        Ok(vec![control_response_body_frame(
1024            &frame,
1025            &response,
1026            "ClientControlResponse::SupervisorAck",
1027        )?])
1028    }
1029
1030    /// `supervisor.swap`. Answered when the swap has cut over or failed, not
1031    /// when the old process has finished draining: a caller whose own lane
1032    /// rides the old process must get its reply before that drain waits on it.
1033    pub(super) async fn handle_supervisor_swap(
1034        &self,
1035        frame: Frame,
1036        module_id: String,
1037        ready_timeout_ms: Option<u64>,
1038        requester: Principal,
1039    ) -> Result<Vec<Frame>, RouterError> {
1040        // The daemon-wide operation lock is held only to resolve the handle,
1041        // not across the swap. The swap can take its whole readiness budget,
1042        // and `supervisor.set_enabled` (ck module stop) takes the same lock:
1043        // holding it here would park an operator's stop behind the swap it is
1044        // meant to abort. A rescan or stop that reaches the module during the
1045        // swap is served by the swap itself (see `supervise_swap`).
1046        let module = {
1047            let _operation_guard = match self.supervisor.lifecycle_operation(Some(&module_id)).await
1048            {
1049                Ok(guard) => guard,
1050                Err(refusal) => return Ok(vec![control_error_body_frame(&frame, refusal.body())?]),
1051            };
1052            self.supervisor.get(&module_id)
1053        };
1054        let Some(module) = module else {
1055            return Ok(vec![control_error_frame(
1056                &frame,
1057                "unknown_module",
1058                format!("module_id '{module_id}' is not supervised"),
1059            )?]);
1060        };
1061
1062        self.route_outages.mark_operator_action(&module_id);
1063        if let Err(err) = module
1064            .swap_requested(ready_timeout_ms.map(Duration::from_millis), Some(requester))
1065            .await
1066        {
1067            self.route_outages
1068                .operator_action_ended_unrefused(&module_id);
1069            use crate::supervise::SuperviseError;
1070            let message = err.to_string();
1071            let error = match err {
1072                SuperviseError::ConfigHeld { .. } => ErrorBody::new("config_gated", message),
1073                SuperviseError::Disabled { .. } => ErrorBody::new("module_disabled", message),
1074                SuperviseError::SwapRefused { reason, .. } => ErrorBody {
1075                    code: "swap_refused".to_string(),
1076                    message,
1077                    detail: Some(serde_json::json!({ "reason": reason.as_str() })),
1078                },
1079                SuperviseError::SwapFailed {
1080                    arm,
1081                    candidate_exit,
1082                    ..
1083                } => ErrorBody {
1084                    code: "swap_failed".to_string(),
1085                    message,
1086                    detail: Some(serde_json::json!({
1087                        "arm": arm.as_str(),
1088                        "candidate_exit_code": candidate_exit.as_ref().and_then(|exit| exit.code),
1089                        "candidate_exit_signal": candidate_exit.as_ref().and_then(|exit| exit.signal),
1090                    })),
1091                },
1092                _ => ErrorBody::new(
1093                    "target_unavailable",
1094                    format!("failed to swap module_id '{module_id}': {message}"),
1095                ),
1096            };
1097            return Ok(vec![control_error_body_frame(&frame, error)?]);
1098        }
1099        // A completed swap kept the incumbent serving until cutover, so it
1100        // usually opened no outage; a mark left behind would make the next,
1101        // unrelated outage read as requested.
1102        self.route_outages
1103            .operator_action_ended_unrefused(&module_id);
1104
1105        let response = ClientControlResponse::SupervisorAck {
1106            module_id,
1107            applied: true,
1108        };
1109        Ok(vec![control_response_body_frame(
1110            &frame,
1111            &response,
1112            "ClientControlResponse::SupervisorAck",
1113        )?])
1114    }
1115
1116    pub(super) async fn handle_supervisor_reload(
1117        &self,
1118        frame: Frame,
1119        module_id: String,
1120        requester: Principal,
1121    ) -> Result<Vec<Frame>, RouterError> {
1122        let _operation_guard = match self.supervisor.lifecycle_operation(Some(&module_id)).await {
1123            Ok(guard) => guard,
1124            Err(refusal) => return Ok(vec![control_error_body_frame(&frame, refusal.body())?]),
1125        };
1126        let Some(module) = self.supervisor.get(&module_id) else {
1127            return Ok(vec![control_error_frame(
1128                &frame,
1129                "unknown_module",
1130                format!("module_id '{module_id}' is not supervised"),
1131            )?]);
1132        };
1133
1134        self.route_outages.mark_operator_action(&module_id);
1135        if let Err(err) = module.reload_requested(Some(requester)).await {
1136            self.route_outages
1137                .operator_action_ended_unrefused(&module_id);
1138            let (code, message) = match err {
1139                _ if err.is_config_gate_error() => ("config_gated", err.to_string()),
1140                crate::supervise::SuperviseError::Disabled { .. } => {
1141                    ("module_disabled", err.to_string())
1142                }
1143                crate::supervise::SuperviseError::SwapInProgress { .. } => {
1144                    ("swap_in_progress", err.to_string())
1145                }
1146                _ => (
1147                    "reload_failed",
1148                    format!("failed to reload module_id '{module_id}': {err}"),
1149                ),
1150            };
1151            return Ok(vec![control_error_frame(&frame, code, message)?]);
1152        }
1153
1154        let response = ClientControlResponse::SupervisorAck {
1155            module_id,
1156            applied: true,
1157        };
1158        Ok(vec![control_response_body_frame(
1159            &frame,
1160            &response,
1161            "ClientControlResponse::SupervisorAck",
1162        )?])
1163    }
1164}
1165
1166impl ControlHandler {
1167    pub(super) async fn handle_supervisor_release_reserved(
1168        &self,
1169        frame: Frame,
1170        module_id: String,
1171    ) -> Result<Vec<Frame>, RouterError> {
1172        let Some(context) = self.rescan.clone() else {
1173            return Ok(vec![control_error_frame(
1174                &frame,
1175                "release_unavailable",
1176                "reserved-id release requires a daemon started with a reloadable config path",
1177            )?]);
1178        };
1179        let _operation_guard = match self.supervisor.lifecycle_operation(Some(&module_id)).await {
1180            Ok(guard) => guard,
1181            Err(refusal) => return Ok(vec![control_error_body_frame(&frame, refusal.body())?]),
1182        };
1183        let approved = if let Some(owner) = &self.config_runtime {
1184            // Observe the file as a proposal, but decide membership solely from
1185            // approved bytes. A proposed re-add must not retain a removed id.
1186            match owner
1187                .on_blocking(|owner| {
1188                    owner.observe_file_proposal()?;
1189                    owner.approved_daemon_configuration()
1190                })
1191                .await
1192            {
1193                Ok(config) => config,
1194                Err(error) => return Ok(vec![config_gate::config_error_frame(&frame, error)?]),
1195            }
1196        } else {
1197            None
1198        };
1199        let loaded = if let Some(approved) = approved {
1200            Ok(Some(approved))
1201        } else {
1202            crate::daemon_config::load(&context.config_path)
1203        };
1204        let loaded = match loaded {
1205            Ok(Some(config)) => config,
1206            Ok(None) => {
1207                return Ok(vec![control_error_frame(
1208                    &frame,
1209                    "invalid_daemon_config",
1210                    format!(
1211                        "daemon config not found at {}; refusing to release reserved module_id '{module_id}'",
1212                        context.config_path.display()
1213                    ),
1214                )?])
1215            }
1216            Err(err) => {
1217                return Ok(vec![control_error_frame(
1218                    &frame,
1219                    "invalid_daemon_config",
1220                    format!("unable to verify reserved-id release against daemon config: {err}"),
1221                )?])
1222            }
1223        };
1224        if loaded
1225            .modules
1226            .iter()
1227            .any(|configured| configured.module_id == module_id)
1228        {
1229            return Ok(vec![control_error_frame(
1230                &frame,
1231                "reserved_module_configured",
1232                format!(
1233                    "module_id '{module_id}' remains configured; remove its config entry and rescan before releasing its reserved id"
1234                ),
1235            )?]);
1236        }
1237        if !self.supervisor.release_retained_reserved_gate(&module_id) {
1238            return Ok(vec![control_error_frame(
1239                &frame,
1240                "reserved_gate_not_retained",
1241                format!(
1242                    "module_id '{module_id}' has no retired reserved-id gate to release; rescan its removed reserved configuration first"
1243                ),
1244            )?]);
1245        }
1246
1247        let response = ClientControlResponse::SupervisorAck {
1248            module_id,
1249            applied: true,
1250        };
1251        Ok(vec![control_response_body_frame(
1252            &frame,
1253            &response,
1254            "ClientControlResponse::SupervisorAck",
1255        )?])
1256    }
1257}
1258
1259impl ControlHandler {
1260    pub(super) async fn handle_supervisor_set_enabled(
1261        &self,
1262        frame: Frame,
1263        module_id: String,
1264        enabled: bool,
1265        requester: Principal,
1266    ) -> Result<Vec<Frame>, RouterError> {
1267        let _operation_guard = match self.supervisor.lifecycle_operation(Some(&module_id)).await {
1268            Ok(guard) => guard,
1269            Err(refusal) => return Ok(vec![control_error_body_frame(&frame, refusal.body())?]),
1270        };
1271        let Some(module) = self.supervisor.get(&module_id) else {
1272            return Ok(vec![control_error_frame(
1273                &frame,
1274                "unknown_module",
1275                format!("module_id '{module_id}' is not supervised"),
1276            )?]);
1277        };
1278
1279        // Enabling counts as well as disabling: a module an operator starts
1280        // is refused until it registers, and that wait was asked for.
1281        self.route_outages.mark_operator_action(&module_id);
1282        let applied = match module.set_enabled_requested(enabled, Some(requester)).await {
1283            Ok(applied) => applied,
1284            Err(err) => {
1285                self.route_outages
1286                    .operator_action_ended_unrefused(&module_id);
1287                return Ok(vec![control_error_frame(
1288                    &frame,
1289                    if err.is_config_gate_error() {
1290                        "config_gated"
1291                    } else {
1292                        "target_unavailable"
1293                    },
1294                    format!("failed to set module_id '{module_id}' enabled={enabled}: {err}"),
1295                )?]);
1296            }
1297        };
1298        if !applied {
1299            // Already in the requested state: nothing was made unavailable,
1300            // so the mark must not outlive this request.
1301            self.route_outages
1302                .operator_action_ended_unrefused(&module_id);
1303        }
1304
1305        self.capability_evaluator.wake_deadline_loop();
1306        self.refresh_capability_requirements();
1307        let response = ClientControlResponse::SupervisorAck { module_id, applied };
1308        Ok(vec![control_response_body_frame(
1309            &frame,
1310            &response,
1311            "ClientControlResponse::SupervisorAck",
1312        )?])
1313    }
1314
1315    pub(super) async fn handle_supervisor_health_probe(
1316        &self,
1317        ctx: &RouteCtx,
1318        frame: Frame,
1319        module_id: String,
1320    ) -> Result<Vec<Frame>, RouterError> {
1321        use crate::supervise::live_upgrade::LifecycleRefusal;
1322
1323        if let Some(refusal) = self.supervisor.lifecycle_refusal(Some(&module_id)) {
1324            return Ok(vec![control_error_body_frame(&frame, refusal.body())?]);
1325        }
1326        if self.forwarding.upgrade_admission.borrow().fenced() {
1327            return Ok(vec![control_error_body_frame(
1328                &frame,
1329                LifecycleRefusal::UpgradeBusy.body(),
1330            )?]);
1331        }
1332        self.refresh_capability_requirements();
1333        let Some(registration) = self
1334            .registry
1335            .get_module(&module_id)
1336            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
1337        else {
1338            return Ok(vec![control_error_frame(
1339                &frame,
1340                "unknown_module",
1341                format!("module_id '{module_id}' is not registered"),
1342            )?]);
1343        };
1344
1345        // This guard's ACCEPT direction is fenced, but only INCIDENTALLY: no test is
1346        // named for it. Making `module_registration_grants_op` return false
1347        // unconditionally reddens five tests, and every one is named for something
1348        // else -- capability relay, probe/bind demultiplexing, supervision-only
1349        // probing. They exercise a successful advertisement check on the way to their
1350        // own subject.
1351        //
1352        // Real protection, fragile in a specific way: narrowing any of those tests to
1353        // focus on its stated subject would silently remove coverage nobody knows
1354        // they are carrying. Recorded here rather than as a sixth test, because the
1355        // useful fact is WHICH tests hold the guard up -- a new test would add
1356        // coverage without telling the next person what the existing ones quietly do.
1357        if !module_registration_grants_op(&registration.control_ops, MODULE_CONTROL_OP_HEALTH_CHECK)
1358        {
1359            return Ok(vec![control_error_frame(
1360                &frame,
1361                "health_not_advertised",
1362                format!("module_id '{module_id}' did not advertise health.check"),
1363            )?]);
1364        }
1365
1366        self.observe_control_wait(
1367            ctx,
1368            Some(&registration.manifest.module_id),
1369            ops::SUPERVISOR_HEALTH_PROBE,
1370            async {
1371                let deadline = Instant::now() + self.health_probe_timeout;
1372                let pending = match self.forwarding.begin_module_control_rpc_for(
1373                    &module_id,
1374                    MODULE_CONTROL_OP_HEALTH_CHECK,
1375                    deadline,
1376                ) {
1377                    Ok(pending) => pending,
1378                    Err(err) => {
1379                        return Ok(vec![control_error_frame(
1380                            &frame,
1381                            forwarding_error_code(&err),
1382                            err.to_string(),
1383                        )?])
1384                    }
1385                };
1386
1387                let PendingModuleControlRpc {
1388                    endpoint,
1389                    module_sink,
1390                    negotiated_ver,
1391                    corr: probe_corr,
1392                    receiver,
1393                } = pending;
1394                let mut guard =
1395                    ModuleControlRpcGuard::new(Arc::clone(&self.forwarding), endpoint, probe_corr);
1396                let probe_body = serde_json::to_vec(&ModuleControlRequest::HealthCheck {})
1397                    .map_err(|err| {
1398                        RouterError::backend(
1399                            0,
1400                            frame.header.corr,
1401                            format!("failed to encode health.check request: {err}"),
1402                        )
1403                    })?;
1404                let probe_frame = Frame::build_with_version(
1405                    negotiated_ver,
1406                    FrameType::Request,
1407                    control_flags(),
1408                    0,
1409                    0,
1410                    probe_corr,
1411                    probe_body,
1412                )
1413                .map_err(RouterError::FrameBuild)?;
1414
1415                // Queue admission and the reply share one deadline, so a module that
1416                // stops reading cannot park the requesting connection's reader forever.
1417                let fenced = RouterError::DaemonUpgrade {
1418                    channel: 0,
1419                    epoch: 0,
1420                    corr: frame.header.corr,
1421                };
1422                match timeout_at(
1423                    deadline,
1424                    module_sink.send_upgrade_fenced(probe_frame, fenced),
1425                )
1426                .await
1427                {
1428                    Ok(Ok(())) => {}
1429                    Ok(Err(RouterError::DaemonUpgrade { .. })) => {
1430                        return Ok(vec![control_error_body_frame(
1431                            &frame,
1432                            LifecycleRefusal::UpgradeBusy.body(),
1433                        )?]);
1434                    }
1435                    Ok(Err(err)) => {
1436                        return Ok(vec![control_error_frame(
1437                            &frame,
1438                            "target_unavailable",
1439                            err.to_string(),
1440                        )?]);
1441                    }
1442                    Err(_) => {
1443                        return Ok(vec![control_error_frame(
1444                            &frame,
1445                            "module_timeout",
1446                            format!(
1447                                "module_id '{module_id}' did not answer health.check within {:?}",
1448                                self.health_probe_timeout
1449                            ),
1450                        )?]);
1451                    }
1452                }
1453
1454                match timeout_at(deadline, receiver).await {
1455                    Ok(Ok(ModuleControlRpcOutcome::RawResponse(_))) => {
1456                        Ok(vec![control_error_frame(
1457                            &frame,
1458                            "invalid_control_body",
1459                            "health.check returned an unexpected config response",
1460                        )?])
1461                    }
1462                    Ok(Ok(ModuleControlRpcOutcome::Response(response))) => {
1463                        guard.disarm();
1464                        let Some(report) = response.health_report() else {
1465                            return Ok(vec![control_error_frame(
1466                                &frame,
1467                                "invalid_control_body",
1468                                "health.check RPC returned a non-health response",
1469                            )?]);
1470                        };
1471                        // Metrics go out whole here. The supervisor's cached snapshot
1472                        // caps this blob (see truncate_health_metrics), and this path
1473                        // exists precisely to answer without that cap -- so applying it
1474                        // here would leave no way to see what the cached view drops.
1475                        let HealthReport {
1476                            status,
1477                            detail,
1478                            metrics,
1479                        } = report;
1480                        let capability_detail = self
1481                            .capability_evaluator
1482                            .required_problem_detail(&module_id);
1483                        let response = ClientControlResponse::SupervisorHealthProbe {
1484                            module_id,
1485                            status,
1486                            detail: append_capability_problem_detail(detail, capability_detail),
1487                            metrics,
1488                        };
1489                        Ok(vec![control_response_body_frame(
1490                            &frame,
1491                            &response,
1492                            "ClientControlResponse::SupervisorHealthProbe",
1493                        )?])
1494                    }
1495                    Ok(Ok(ModuleControlRpcOutcome::Rejected(body))) => {
1496                        guard.disarm();
1497                        // The module refused the health probe with its own body, so
1498                        // the refusal is relayed without the daemon-origin flag
1499                        // (bit 6): a client must not read it as the daemon's own
1500                        // refusal, which it may treat as never forwarded.
1501                        Ok(vec![control_relayed_error_body_frame(&frame, body)?])
1502                    }
1503                    Ok(Ok(ModuleControlRpcOutcome::ModuleGone(message))) => {
1504                        guard.disarm();
1505                        Ok(vec![control_error_frame(
1506                            &frame,
1507                            "target_unavailable",
1508                            message,
1509                        )?])
1510                    }
1511                    Ok(Ok(ModuleControlRpcOutcome::MalformedResponse(message))) => {
1512                        guard.disarm();
1513                        Ok(vec![control_error_frame(
1514                            &frame,
1515                            "invalid_control_body",
1516                            message,
1517                        )?])
1518                    }
1519                    Ok(Ok(ModuleControlRpcOutcome::UnexpectedOp { expected, actual })) => {
1520                        guard.disarm();
1521                        Ok(vec![control_error_frame(
1522                            &frame,
1523                            "invalid_control_body",
1524                            format!("expected module-control op '{expected}', got '{actual}'"),
1525                        )?])
1526                    }
1527                    Ok(Ok(ModuleControlRpcOutcome::DeadlineElapsed)) => {
1528                        guard.disarm();
1529                        Ok(vec![control_error_frame(
1530                            &frame,
1531                            "module_timeout",
1532                            format!(
1533                                "module_id '{module_id}' answered health.check after {:?}",
1534                                self.health_probe_timeout
1535                            ),
1536                        )?])
1537                    }
1538                    Ok(Err(_)) => Ok(vec![control_error_frame(
1539                        &frame,
1540                        "target_unavailable",
1541                        "health.check waiter was canceled before the module responded",
1542                    )?]),
1543                    Err(_) => Ok(vec![control_error_frame(
1544                        &frame,
1545                        "module_timeout",
1546                        format!(
1547                            "module_id '{module_id}' did not answer health.check within {:?}",
1548                            self.health_probe_timeout
1549                        ),
1550                    )?]),
1551                }
1552            },
1553        )
1554        .await
1555    }
1556
1557    pub(super) fn supervisor_status(
1558        &self,
1559        module_id: &str,
1560        corr: u64,
1561    ) -> Result<Option<(crate::supervise::ModuleStatus, bool)>, RouterError> {
1562        self.supervisor
1563            .get(module_id)
1564            .map(|module| {
1565                let warming = module.is_warming_for_control("status").map_err(|err| {
1566                    RouterError::backend(
1567                        0,
1568                        corr,
1569                        format!(
1570                            "failed to read supervisor warming state for module_id '{module_id}': {err}"
1571                        ),
1572                    )
1573                })?;
1574                module.status_for_control("status").map_err(|err| {
1575                    RouterError::backend(
1576                        0,
1577                        corr,
1578                        format!(
1579                            "failed to read supervisor status for module_id '{module_id}': {err}"
1580                        ),
1581                    )
1582                }).map(|status| (status, warming))
1583            })
1584            .transpose()
1585    }
1586}