Skip to main content

subc_daemon/control/
supervisor_operations.rs

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