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.polled_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.polled_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_lock = self.supervisor.operation_lock();
985        let _operation_guard = operation_lock.lock().await;
986        let Some(module) = self.supervisor.get(&module_id) else {
987            return Ok(vec![control_error_frame(
988                &frame,
989                "unknown_module",
990                format!("module_id '{module_id}' is not supervised"),
991            )?]);
992        };
993
994        self.route_outages.mark_operator_action(&module_id);
995        if let Err(err) = module
996            .restart_requested(drain_timeout_ms, Some(requester))
997            .await
998        {
999            self.route_outages
1000                .operator_action_ended_unrefused(&module_id);
1001            let (code, message) = match err {
1002                _ if err.is_config_gate_error() => ("config_gated", err.to_string()),
1003                crate::supervise::SuperviseError::Disabled { .. } => {
1004                    ("module_disabled", err.to_string())
1005                }
1006                crate::supervise::SuperviseError::SwapInProgress { .. } => {
1007                    ("swap_in_progress", err.to_string())
1008                }
1009                _ => (
1010                    "target_unavailable",
1011                    format!("failed to restart module_id '{module_id}': {err}"),
1012                ),
1013            };
1014            return Ok(vec![control_error_frame(&frame, code, message)?]);
1015        }
1016
1017        let response = ClientControlResponse::SupervisorAck {
1018            module_id,
1019            applied: true,
1020        };
1021        Ok(vec![control_response_body_frame(
1022            &frame,
1023            &response,
1024            "ClientControlResponse::SupervisorAck",
1025        )?])
1026    }
1027
1028    /// `supervisor.swap`. Answered when the swap has cut over or failed, not
1029    /// when the old process has finished draining: a caller whose own lane
1030    /// rides the old process must get its reply before that drain waits on it.
1031    pub(super) async fn handle_supervisor_swap(
1032        &self,
1033        frame: Frame,
1034        module_id: String,
1035        ready_timeout_ms: Option<u64>,
1036        requester: Principal,
1037    ) -> Result<Vec<Frame>, RouterError> {
1038        // The daemon-wide operation lock is held only to resolve the handle,
1039        // not across the swap. The swap can take its whole readiness budget,
1040        // and `supervisor.set_enabled` (ck module stop) takes the same lock:
1041        // holding it here would park an operator's stop behind the swap it is
1042        // meant to abort. A rescan or stop that reaches the module during the
1043        // swap is served by the swap itself (see `supervise_swap`).
1044        let module = {
1045            let operation_lock = self.supervisor.operation_lock();
1046            let _operation_guard = operation_lock.lock().await;
1047            self.supervisor.get(&module_id)
1048        };
1049        let Some(module) = module else {
1050            return Ok(vec![control_error_frame(
1051                &frame,
1052                "unknown_module",
1053                format!("module_id '{module_id}' is not supervised"),
1054            )?]);
1055        };
1056
1057        self.route_outages.mark_operator_action(&module_id);
1058        if let Err(err) = module
1059            .swap_requested(ready_timeout_ms.map(Duration::from_millis), Some(requester))
1060            .await
1061        {
1062            self.route_outages
1063                .operator_action_ended_unrefused(&module_id);
1064            use crate::supervise::SuperviseError;
1065            let message = err.to_string();
1066            let error = match err {
1067                SuperviseError::ConfigHeld { .. } => ErrorBody::new("config_gated", message),
1068                SuperviseError::Disabled { .. } => ErrorBody::new("module_disabled", message),
1069                SuperviseError::SwapRefused { reason, .. } => ErrorBody {
1070                    code: "swap_refused".to_string(),
1071                    message,
1072                    detail: Some(serde_json::json!({ "reason": reason.as_str() })),
1073                },
1074                SuperviseError::SwapFailed {
1075                    arm,
1076                    candidate_exit,
1077                    ..
1078                } => ErrorBody {
1079                    code: "swap_failed".to_string(),
1080                    message,
1081                    detail: Some(serde_json::json!({
1082                        "arm": arm.as_str(),
1083                        "candidate_exit_code": candidate_exit.as_ref().and_then(|exit| exit.code),
1084                        "candidate_exit_signal": candidate_exit.as_ref().and_then(|exit| exit.signal),
1085                    })),
1086                },
1087                _ => ErrorBody::new(
1088                    "target_unavailable",
1089                    format!("failed to swap module_id '{module_id}': {message}"),
1090                ),
1091            };
1092            return Ok(vec![control_error_body_frame(&frame, error)?]);
1093        }
1094        // A completed swap kept the incumbent serving until cutover, so it
1095        // usually opened no outage; a mark left behind would make the next,
1096        // unrelated outage read as requested.
1097        self.route_outages
1098            .operator_action_ended_unrefused(&module_id);
1099
1100        let response = ClientControlResponse::SupervisorAck {
1101            module_id,
1102            applied: true,
1103        };
1104        Ok(vec![control_response_body_frame(
1105            &frame,
1106            &response,
1107            "ClientControlResponse::SupervisorAck",
1108        )?])
1109    }
1110
1111    pub(super) async fn handle_supervisor_reload(
1112        &self,
1113        frame: Frame,
1114        module_id: String,
1115        requester: Principal,
1116    ) -> Result<Vec<Frame>, RouterError> {
1117        let operation_lock = self.supervisor.operation_lock();
1118        let _operation_guard = operation_lock.lock().await;
1119        let Some(module) = self.supervisor.get(&module_id) else {
1120            return Ok(vec![control_error_frame(
1121                &frame,
1122                "unknown_module",
1123                format!("module_id '{module_id}' is not supervised"),
1124            )?]);
1125        };
1126
1127        self.route_outages.mark_operator_action(&module_id);
1128        if let Err(err) = module.reload_requested(Some(requester)).await {
1129            self.route_outages
1130                .operator_action_ended_unrefused(&module_id);
1131            let (code, message) = match err {
1132                _ if err.is_config_gate_error() => ("config_gated", err.to_string()),
1133                crate::supervise::SuperviseError::Disabled { .. } => {
1134                    ("module_disabled", err.to_string())
1135                }
1136                crate::supervise::SuperviseError::SwapInProgress { .. } => {
1137                    ("swap_in_progress", err.to_string())
1138                }
1139                _ => (
1140                    "reload_failed",
1141                    format!("failed to reload module_id '{module_id}': {err}"),
1142                ),
1143            };
1144            return Ok(vec![control_error_frame(&frame, code, message)?]);
1145        }
1146
1147        let response = ClientControlResponse::SupervisorAck {
1148            module_id,
1149            applied: true,
1150        };
1151        Ok(vec![control_response_body_frame(
1152            &frame,
1153            &response,
1154            "ClientControlResponse::SupervisorAck",
1155        )?])
1156    }
1157}
1158
1159impl ControlHandler {
1160    pub(super) async fn handle_supervisor_release_reserved(
1161        &self,
1162        frame: Frame,
1163        module_id: String,
1164    ) -> Result<Vec<Frame>, RouterError> {
1165        let Some(context) = self.rescan.clone() else {
1166            return Ok(vec![control_error_frame(
1167                &frame,
1168                "release_unavailable",
1169                "reserved-id release requires a daemon started with a reloadable config path",
1170            )?]);
1171        };
1172        let operation_lock = self.supervisor.operation_lock();
1173        let _operation_guard = operation_lock.lock().await;
1174        let approved = if let Some(owner) = &self.config_runtime {
1175            // Observe the file as a proposal, but decide membership solely from
1176            // approved bytes. A proposed re-add must not retain a removed id.
1177            match owner
1178                .on_blocking(|owner| {
1179                    owner.observe_file_proposal()?;
1180                    owner.approved_daemon_configuration()
1181                })
1182                .await
1183            {
1184                Ok(config) => config,
1185                Err(error) => return Ok(vec![config_gate::config_error_frame(&frame, error)?]),
1186            }
1187        } else {
1188            None
1189        };
1190        let loaded = if let Some(approved) = approved {
1191            Ok(Some(approved))
1192        } else {
1193            crate::daemon_config::load(&context.config_path)
1194        };
1195        let loaded = match loaded {
1196            Ok(Some(config)) => config,
1197            Ok(None) => {
1198                return Ok(vec![control_error_frame(
1199                    &frame,
1200                    "invalid_daemon_config",
1201                    format!(
1202                        "daemon config not found at {}; refusing to release reserved module_id '{module_id}'",
1203                        context.config_path.display()
1204                    ),
1205                )?])
1206            }
1207            Err(err) => {
1208                return Ok(vec![control_error_frame(
1209                    &frame,
1210                    "invalid_daemon_config",
1211                    format!("unable to verify reserved-id release against daemon config: {err}"),
1212                )?])
1213            }
1214        };
1215        if loaded
1216            .modules
1217            .iter()
1218            .any(|configured| configured.module_id == module_id)
1219        {
1220            return Ok(vec![control_error_frame(
1221                &frame,
1222                "reserved_module_configured",
1223                format!(
1224                    "module_id '{module_id}' remains configured; remove its config entry and rescan before releasing its reserved id"
1225                ),
1226            )?]);
1227        }
1228        if !self.supervisor.release_retained_reserved_gate(&module_id) {
1229            return Ok(vec![control_error_frame(
1230                &frame,
1231                "reserved_gate_not_retained",
1232                format!(
1233                    "module_id '{module_id}' has no retired reserved-id gate to release; rescan its removed reserved configuration first"
1234                ),
1235            )?]);
1236        }
1237
1238        let response = ClientControlResponse::SupervisorAck {
1239            module_id,
1240            applied: true,
1241        };
1242        Ok(vec![control_response_body_frame(
1243            &frame,
1244            &response,
1245            "ClientControlResponse::SupervisorAck",
1246        )?])
1247    }
1248}
1249
1250impl ControlHandler {
1251    pub(super) async fn handle_supervisor_set_enabled(
1252        &self,
1253        frame: Frame,
1254        module_id: String,
1255        enabled: bool,
1256        requester: Principal,
1257    ) -> Result<Vec<Frame>, RouterError> {
1258        let operation_lock = self.supervisor.operation_lock();
1259        let _operation_guard = operation_lock.lock().await;
1260        let Some(module) = self.supervisor.get(&module_id) else {
1261            return Ok(vec![control_error_frame(
1262                &frame,
1263                "unknown_module",
1264                format!("module_id '{module_id}' is not supervised"),
1265            )?]);
1266        };
1267
1268        // Enabling counts as well as disabling: a module an operator starts
1269        // is refused until it registers, and that wait was asked for.
1270        self.route_outages.mark_operator_action(&module_id);
1271        let applied = match module.set_enabled_requested(enabled, Some(requester)).await {
1272            Ok(applied) => applied,
1273            Err(err) => {
1274                self.route_outages
1275                    .operator_action_ended_unrefused(&module_id);
1276                return Ok(vec![control_error_frame(
1277                    &frame,
1278                    if err.is_config_gate_error() {
1279                        "config_gated"
1280                    } else {
1281                        "target_unavailable"
1282                    },
1283                    format!("failed to set module_id '{module_id}' enabled={enabled}: {err}"),
1284                )?]);
1285            }
1286        };
1287        if !applied {
1288            // Already in the requested state: nothing was made unavailable,
1289            // so the mark must not outlive this request.
1290            self.route_outages
1291                .operator_action_ended_unrefused(&module_id);
1292        }
1293
1294        self.capability_evaluator.wake_deadline_loop();
1295        self.refresh_capability_requirements();
1296        let response = ClientControlResponse::SupervisorAck { module_id, applied };
1297        Ok(vec![control_response_body_frame(
1298            &frame,
1299            &response,
1300            "ClientControlResponse::SupervisorAck",
1301        )?])
1302    }
1303
1304    pub(super) async fn handle_supervisor_health_probe(
1305        &self,
1306        ctx: &RouteCtx,
1307        frame: Frame,
1308        module_id: String,
1309    ) -> Result<Vec<Frame>, RouterError> {
1310        self.refresh_capability_requirements();
1311        let Some(registration) = self
1312            .registry
1313            .get_module(&module_id)
1314            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
1315        else {
1316            return Ok(vec![control_error_frame(
1317                &frame,
1318                "unknown_module",
1319                format!("module_id '{module_id}' is not registered"),
1320            )?]);
1321        };
1322
1323        // This guard's ACCEPT direction is fenced, but only INCIDENTALLY: no test is
1324        // named for it. Making `module_registration_grants_op` return false
1325        // unconditionally reddens five tests, and every one is named for something
1326        // else -- capability relay, probe/bind demultiplexing, supervision-only
1327        // probing. They exercise a successful advertisement check on the way to their
1328        // own subject.
1329        //
1330        // Real protection, fragile in a specific way: narrowing any of those tests to
1331        // focus on its stated subject would silently remove coverage nobody knows
1332        // they are carrying. Recorded here rather than as a sixth test, because the
1333        // useful fact is WHICH tests hold the guard up -- a new test would add
1334        // coverage without telling the next person what the existing ones quietly do.
1335        if !module_registration_grants_op(&registration.control_ops, MODULE_CONTROL_OP_HEALTH_CHECK)
1336        {
1337            return Ok(vec![control_error_frame(
1338                &frame,
1339                "health_not_advertised",
1340                format!("module_id '{module_id}' did not advertise health.check"),
1341            )?]);
1342        }
1343
1344        self.observe_control_wait(
1345            ctx,
1346            Some(&registration.manifest.module_id),
1347            ops::SUPERVISOR_HEALTH_PROBE,
1348            async {
1349                let deadline = Instant::now() + self.health_probe_timeout;
1350                let pending = match self.forwarding.begin_module_control_rpc_for(
1351                    &module_id,
1352                    MODULE_CONTROL_OP_HEALTH_CHECK,
1353                    deadline,
1354                ) {
1355                    Ok(pending) => pending,
1356                    Err(err) => {
1357                        return Ok(vec![control_error_frame(
1358                            &frame,
1359                            forwarding_error_code(&err),
1360                            err.to_string(),
1361                        )?])
1362                    }
1363                };
1364
1365                let PendingModuleControlRpc {
1366                    endpoint,
1367                    module_sink,
1368                    negotiated_ver,
1369                    corr: probe_corr,
1370                    receiver,
1371                } = pending;
1372                let mut guard =
1373                    ModuleControlRpcGuard::new(Arc::clone(&self.forwarding), endpoint, probe_corr);
1374                let probe_body = serde_json::to_vec(&ModuleControlRequest::HealthCheck {})
1375                    .map_err(|err| {
1376                        RouterError::backend(
1377                            0,
1378                            frame.header.corr,
1379                            format!("failed to encode health.check request: {err}"),
1380                        )
1381                    })?;
1382                let probe_frame = Frame::build_with_version(
1383                    negotiated_ver,
1384                    FrameType::Request,
1385                    control_flags(),
1386                    0,
1387                    0,
1388                    probe_corr,
1389                    probe_body,
1390                )
1391                .map_err(RouterError::FrameBuild)?;
1392
1393                // Queue admission and the reply share one deadline, so a module that
1394                // stops reading cannot park the requesting connection's reader forever.
1395                match timeout_at(deadline, module_sink.send(probe_frame)).await {
1396                    Ok(Ok(())) => {}
1397                    Ok(Err(err)) => {
1398                        return Ok(vec![control_error_frame(
1399                            &frame,
1400                            "target_unavailable",
1401                            err.to_string(),
1402                        )?]);
1403                    }
1404                    Err(_) => {
1405                        return Ok(vec![control_error_frame(
1406                            &frame,
1407                            "module_timeout",
1408                            format!(
1409                                "module_id '{module_id}' did not answer health.check within {:?}",
1410                                self.health_probe_timeout
1411                            ),
1412                        )?]);
1413                    }
1414                }
1415
1416                match timeout_at(deadline, receiver).await {
1417                    Ok(Ok(ModuleControlRpcOutcome::RawResponse(_))) => {
1418                        Ok(vec![control_error_frame(
1419                            &frame,
1420                            "invalid_control_body",
1421                            "health.check returned an unexpected config response",
1422                        )?])
1423                    }
1424                    Ok(Ok(ModuleControlRpcOutcome::Response(response))) => {
1425                        guard.disarm();
1426                        let Some(report) = response.health_report() else {
1427                            return Ok(vec![control_error_frame(
1428                                &frame,
1429                                "invalid_control_body",
1430                                "health.check RPC returned a non-health response",
1431                            )?]);
1432                        };
1433                        // Metrics go out whole here. The supervisor's cached snapshot
1434                        // caps this blob (see truncate_health_metrics), and this path
1435                        // exists precisely to answer without that cap -- so applying it
1436                        // here would leave no way to see what the cached view drops.
1437                        let HealthReport {
1438                            status,
1439                            detail,
1440                            metrics,
1441                        } = report;
1442                        let capability_detail = self
1443                            .capability_evaluator
1444                            .required_problem_detail(&module_id);
1445                        let response = ClientControlResponse::SupervisorHealthProbe {
1446                            module_id,
1447                            status,
1448                            detail: append_capability_problem_detail(detail, capability_detail),
1449                            metrics,
1450                        };
1451                        Ok(vec![control_response_body_frame(
1452                            &frame,
1453                            &response,
1454                            "ClientControlResponse::SupervisorHealthProbe",
1455                        )?])
1456                    }
1457                    Ok(Ok(ModuleControlRpcOutcome::Rejected(body))) => {
1458                        guard.disarm();
1459                        // The module refused the health probe with its own body, so
1460                        // the refusal is relayed without the daemon-origin flag
1461                        // (bit 6): a client must not read it as the daemon's own
1462                        // refusal, which it may treat as never forwarded.
1463                        Ok(vec![control_relayed_error_body_frame(&frame, body)?])
1464                    }
1465                    Ok(Ok(ModuleControlRpcOutcome::ModuleGone(message))) => {
1466                        guard.disarm();
1467                        Ok(vec![control_error_frame(
1468                            &frame,
1469                            "target_unavailable",
1470                            message,
1471                        )?])
1472                    }
1473                    Ok(Ok(ModuleControlRpcOutcome::MalformedResponse(message))) => {
1474                        guard.disarm();
1475                        Ok(vec![control_error_frame(
1476                            &frame,
1477                            "invalid_control_body",
1478                            message,
1479                        )?])
1480                    }
1481                    Ok(Ok(ModuleControlRpcOutcome::UnexpectedOp { expected, actual })) => {
1482                        guard.disarm();
1483                        Ok(vec![control_error_frame(
1484                            &frame,
1485                            "invalid_control_body",
1486                            format!("expected module-control op '{expected}', got '{actual}'"),
1487                        )?])
1488                    }
1489                    Ok(Ok(ModuleControlRpcOutcome::DeadlineElapsed)) => {
1490                        guard.disarm();
1491                        Ok(vec![control_error_frame(
1492                            &frame,
1493                            "module_timeout",
1494                            format!(
1495                                "module_id '{module_id}' answered health.check after {:?}",
1496                                self.health_probe_timeout
1497                            ),
1498                        )?])
1499                    }
1500                    Ok(Err(_)) => Ok(vec![control_error_frame(
1501                        &frame,
1502                        "target_unavailable",
1503                        "health.check waiter was canceled before the module responded",
1504                    )?]),
1505                    Err(_) => Ok(vec![control_error_frame(
1506                        &frame,
1507                        "module_timeout",
1508                        format!(
1509                            "module_id '{module_id}' did not answer health.check within {:?}",
1510                            self.health_probe_timeout
1511                        ),
1512                    )?]),
1513                }
1514            },
1515        )
1516        .await
1517    }
1518
1519    pub(super) fn supervisor_status(
1520        &self,
1521        module_id: &str,
1522        corr: u64,
1523    ) -> Result<Option<(crate::supervise::ModuleStatus, bool)>, RouterError> {
1524        self.supervisor
1525            .get(module_id)
1526            .map(|module| {
1527                let warming = module.is_warming_for_control("status").map_err(|err| {
1528                    RouterError::backend(
1529                        0,
1530                        corr,
1531                        format!(
1532                            "failed to read supervisor warming state for module_id '{module_id}': {err}"
1533                        ),
1534                    )
1535                })?;
1536                module.status_for_control("status").map_err(|err| {
1537                    RouterError::backend(
1538                        0,
1539                        corr,
1540                        format!(
1541                            "failed to read supervisor status for module_id '{module_id}': {err}"
1542                        ),
1543                    )
1544                }).map(|status| (status, warming))
1545            })
1546            .transpose()
1547    }
1548}