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