Skip to main content

subc_daemon/control/
supervisor_operations.rs

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