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