Skip to main content

subc_daemon/control/
rescan_checked.rs

1//! `supervisor.rescan_checked`: previewing caller-supplied configuration text
2//! without writing or applying it, and applying the config file only while the
3//! file and the staged configuration still match that preview.
4//!
5//! Both halves run through [`ControlHandler::handle_supervisor_rescan`], the
6//! code `supervisor.rescan` uses, so a preview and an apply cannot drift from
7//! what a plain rescan does. This file holds only what differs: where the
8//! configuration text comes from, the apply's precondition, and the extra
9//! detail a candidate preview reports.
10
11use std::{
12    collections::{BTreeMap, BTreeSet},
13    path::{Path, PathBuf},
14    sync::atomic::Ordering,
15    time::Duration,
16};
17
18use sha2::{Digest, Sha256};
19use subc_control::{
20    ops, BusyGaugeReading, LaunchSpecAgreement, RescanExpect, RescanModuleAction,
21    RescanModuleActionKind, StagedGeneration, SupervisorRescanResult, CONFIG_CHANGED_SINCE_PREVIEW,
22    RESCAN_CANDIDATE_MAX_BYTES, RESCAN_CANDIDATE_PREVIEW_CAPABILITY, RESCAN_CANDIDATE_TOO_LARGE,
23};
24
25use super::*;
26use crate::{
27    daemon_config::{ActivityConfig, ConfiguredModule, DaemonConfig},
28    router::{RouteCtx, RouterError},
29    supervise::{ModuleSpec, SupervisedModule},
30    Frame, HealthConfig,
31};
32
33#[cfg(test)]
34mod tests;
35
36/// Where a rescan's configuration comes from, and whether it is applied.
37#[derive(Clone)]
38pub(super) enum RescanMode {
39    /// `supervisor.rescan`: read the config file and apply it.
40    Execute,
41    /// `supervisor.rescan { preview: true }`: read the config file and apply
42    /// nothing.
43    Preview,
44    /// A `supervisor.rescan_checked` preview: parse this text and apply
45    /// nothing.
46    Candidate(String),
47    /// A `supervisor.rescan_checked` apply: read the config file and apply it,
48    /// but only if the file and the staged configuration still match.
49    Checked(RescanExpect),
50}
51
52const CONFIG_READ_DEADLINE: Duration = Duration::from_secs(5);
53// A timed-out filesystem read cannot be cancelled. Its slot stays charged
54// until it finishes, so repeated rescans cannot create unbounded threads.
55static CONFIG_READ_SLOTS: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(4);
56
57pub(super) struct RescanInput {
58    pub(super) config: Option<(DaemonConfig, ActivityConfig)>,
59    pub(super) approved_preview: Option<DaemonConfig>,
60    pub(super) guard: tokio::sync::OwnedMutexGuard<()>,
61}
62
63pub(super) enum RescanInputError {
64    Lifecycle(crate::supervise::live_upgrade::LifecycleRefusal),
65    Config(&'static str, String),
66    Gate(crate::config_gate::GateError),
67}
68
69impl RescanInputError {
70    pub(super) fn into_frame(self, request: &Frame) -> Result<Frame, RouterError> {
71        match self {
72            Self::Config(code, message) => control_error_frame(request, code, message),
73            Self::Gate(error) => config_gate::config_error_frame(request, error),
74            Self::Lifecycle(refusal) => super::control_error_body_frame(request, refusal.body()),
75        }
76    }
77}
78
79impl RescanMode {
80    pub(super) fn previews(&self) -> bool {
81        matches!(self, Self::Preview | Self::Candidate(_))
82    }
83}
84
85/// One supervised module as a rescan finds it: the module, its staged launch
86/// spec and health policy, and whether it is enabled.
87pub(super) type CurrentModule = (SupervisedModule, ModuleSpec, HealthConfig, bool);
88
89#[derive(Debug, Default)]
90pub(super) struct ModuleEntries {
91    registration_channels: BTreeMap<String, bool>,
92    configured: BTreeMap<String, ConfiguredModule>,
93}
94
95impl ModuleEntries {
96    pub(super) fn reserved(&self, module_id: &str) -> bool {
97        self.configured
98            .get(module_id)
99            .is_some_and(|entry| entry.reserved)
100    }
101    pub(super) fn seed(&mut self, modules: &[ConfiguredModule]) {
102        self.configured = modules
103            .iter()
104            .cloned()
105            .map(|m| (m.module_id.clone(), m))
106            .collect();
107        self.registration_channels = modules
108            .iter()
109            .map(|m| (m.module_id.clone(), m.registration_channel))
110            .collect();
111    }
112
113    pub(super) fn record(
114        &mut self,
115        configured: &BTreeMap<String, ConfiguredModule>,
116        added: &[String],
117        removed: &[String],
118    ) {
119        for id in removed {
120            self.registration_channels.remove(id);
121        }
122        for id in added {
123            self.registration_channels
124                .insert(id.clone(), configured[id].registration_channel);
125        }
126        self.configured = configured.clone();
127    }
128}
129
130pub(super) fn entry_pending_fields(
131    current: &ConfiguredModule,
132    next: &ConfiguredModule,
133    applies_configuration: bool,
134) -> Vec<subc_control::SupervisorPendingField> {
135    use subc_control::{PendingModuleApply as Apply, SupervisorPendingField};
136    let mut fields = Vec::new();
137    let mut add = |field: &str, applies, value| {
138        fields.push(SupervisorPendingField {
139            field: field.to_owned(),
140            applies,
141            value: Some(value),
142        })
143    };
144    if current.register_timeout != next.register_timeout {
145        add(
146            "register_timeout_s",
147            Apply::NextSupervision,
148            serde_json::json!(next.register_timeout.as_secs()),
149        );
150    }
151    if current.restart != next.restart {
152        add(
153            "restart",
154            Apply::NextSupervision,
155            serde_json::json!({
156                "max_restarts": next.restart.max_restarts,
157                "window_secs": next.restart.window.as_secs(),
158                "backoff_ms": next.restart.backoff.as_millis() as u64,
159                "max_backoff_ms": next.restart.max_backoff.as_millis() as u64,
160            }),
161        );
162    }
163    let drain = |module: &ConfiguredModule| {
164        module
165            .drain_timeout_ms
166            .map(Duration::from_millis)
167            .unwrap_or(crate::supervise::DEFAULT_DRAIN_TIMEOUT)
168    };
169    if !applies_configuration && drain(current) != drain(next) {
170        add(
171            "drain_timeout_ms",
172            Apply::WithNextLaunchOrHealthChange,
173            serde_json::json!(drain(next).as_millis() as u64),
174        );
175    }
176    let relay = |module: &ConfiguredModule| {
177        module
178            .route_bind_relay_timeout_ms
179            .map(Duration::from_millis)
180            .unwrap_or(crate::DEFAULT_ROUTE_BIND_RELAY_TIMEOUT)
181    };
182    if relay(current) != relay(next) {
183        add(
184            "route_bind_relay_timeout_ms",
185            Apply::DaemonRestart,
186            serde_json::json!(relay(next).as_millis() as u64),
187        );
188    }
189    if current.registration_channel != next.registration_channel {
190        add(
191            "registration_channel",
192            Apply::ConfigGate,
193            serde_json::json!(next.registration_channel),
194        );
195    }
196    fields
197}
198
199impl ControlHandler {
200    pub(super) fn registration_channel_in_force(
201        declaration: Option<&str>,
202        configured: Option<bool>,
203    ) -> Option<bool> {
204        match declaration {
205            Some("declared") => Some(true),
206            Some("undeclared") => Some(false),
207            // Entries with `protocol: none` speak no control protocol and have
208            // no registration channel; use their approved metadata instead.
209            _ => configured,
210        }
211    }
212
213    pub(super) fn pending_module_fields(
214        &self,
215        module: &SupervisedModule,
216        proposed: Option<&ConfiguredModule>,
217        applies_configuration: bool,
218        approved_registration_channel: Option<bool>,
219        publication: Option<&crate::config_gate::runtime::Published>,
220    ) -> Result<Vec<subc_control::SupervisorPendingField>, String> {
221        let id = module.module_id();
222        let (recorded, registration_channel) = self
223            .rescan
224            .as_ref()
225            .map(|context| {
226                let entries = context
227                    .module_entries
228                    .lock()
229                    .unwrap_or_else(|e| e.into_inner());
230                (
231                    entries.configured.get(id).cloned(),
232                    entries
233                        .registration_channels
234                        .get(id)
235                        .copied()
236                        .unwrap_or(false),
237                )
238            })
239            .unwrap_or_default();
240        let Some(next) = proposed.cloned().or(recorded) else {
241            return Ok(Vec::new());
242        };
243        let status = module.status().map_err(|e| e.to_string())?;
244        let mut current = next.clone();
245        current.register_timeout = module
246            .configured_register_timeout()
247            .map_err(|e| e.to_string())?;
248        current.restart = crate::supervise::RestartPolicy {
249            max_restarts: status.max_restarts,
250            window: status.restart_window,
251            backoff: status.restart_backoff,
252            max_backoff: status.restart_max_backoff,
253        };
254        current.drain_timeout_ms = Some(status.drain_timeout.as_millis() as u64);
255        current.route_bind_relay_timeout_ms =
256            Some(self.route_bind_relay_timeout_for(id).as_millis() as u64);
257        current.registration_channel =
258            approved_registration_channel.unwrap_or(registration_channel);
259        let mut fields = entry_pending_fields(&current, &next, applies_configuration);
260        // The caller passes the publication it already read for the whole
261        // list, so a status of many modules reads it once. With no settings
262        // owner, or one reporting an unstamped install, nothing is pending.
263        // An unreadable publication keeps the field, as the safer report.
264        let unstamped = match &self.config_runtime {
265            None => true,
266            Some(_) => publication.is_some_and(|view| {
267                matches!(
268                    view.approved_daemon,
269                    crate::config_gate::runtime::ApprovedDaemonView::NotStamped
270                )
271            }),
272        };
273        if unstamped {
274            fields.retain(|field| field.field != "registration_channel");
275        }
276        Ok(fields)
277    }
278}
279
280/// The comparison a rescan makes between the configured modules and the
281/// supervised ones, before anything is applied.
282pub(super) struct RescanPlan {
283    pub(super) current: BTreeMap<String, CurrentModule>,
284    pub(super) configured: BTreeMap<String, ConfiguredModule>,
285    pub(super) added: Vec<String>,
286    pub(super) removed: Vec<String>,
287    /// Modules whose launch spec changes. Their running process keeps the old
288    /// one until it restarts.
289    pub(super) changed_pending_reload: Vec<String>,
290    pub(super) changed_pending: Vec<subc_control::SupervisorPendingModule>,
291    /// Modules whose launch spec or health policy changes.
292    pub(super) configuration_changes: BTreeSet<String>,
293    pub(super) enabled_changes: BTreeSet<String>,
294    pub(super) unchanged: u32,
295}
296
297impl RescanPlan {
298    pub(super) fn preview_result(&self) -> SupervisorRescanResult {
299        SupervisorRescanResult {
300            added: self.added.clone(),
301            removed: self.removed.clone(),
302            changed_pending_reload: self.changed_pending_reload.clone(),
303            changed_pending: self.changed_pending.clone(),
304            enabled_changes: self.enabled_changes.iter().cloned().collect(),
305            unchanged: self.unchanged,
306            preview: true,
307            // Filled by the caller on both paths, so the preview reports
308            // restart-required sections identically to an executed rescan --
309            // the preview is where an operator is most likely to be looking.
310            restart_required: Vec::new(),
311            capability_warnings: Vec::new(),
312            module_actions: Vec::new(),
313            earlier_pending: Vec::new(),
314            expect: None,
315        }
316    }
317}
318
319/// The configuration path `server.describe` reports: the path the daemon
320/// reads, unchanged, or nothing when that path is relative. A relative path
321/// resolves against the daemon's working directory, so a client reading it
322/// would find a different file. A path that is not valid UTF-8 is left out
323/// too, because the reply carries it as a JSON string.
324pub(super) fn reported_config_path(path: &Path) -> Option<PathBuf> {
325    (path.is_absolute() && path.to_str().is_some()).then(|| path.to_path_buf())
326}
327
328fn sha256_hex(bytes: &[u8]) -> String {
329    Sha256::digest(bytes)
330        .iter()
331        .map(|byte| format!("{byte:02x}"))
332        .collect()
333}
334
335fn duration_ms(duration: Duration) -> u64 {
336    u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
337}
338
339/// The parts of a module's entry that differ between its staged state and the
340/// configured entry, named as `RescanModuleAction::changed` documents.
341fn changed_parts(
342    current_spec: &ModuleSpec,
343    current_health: &HealthConfig,
344    configured: &ConfiguredModule,
345) -> Vec<String> {
346    let next = configured.module_spec();
347    [
348        ("program", current_spec.program != next.program),
349        ("arguments", current_spec.args != next.args),
350        ("environment", current_spec.env != next.env),
351        ("protocol", current_spec.protocol != next.protocol),
352        ("reserved", current_spec.reserved != next.reserved),
353        (
354            "reserved_prefixes",
355            current_spec.reserved_prefixes != next.reserved_prefixes,
356        ),
357        ("overlap", current_spec.overlap != next.overlap),
358        (
359            "carry_containment",
360            current_spec.carry_containment != next.carry_containment,
361        ),
362        ("health", *current_health != configured.health),
363    ]
364    .into_iter()
365    .filter(|(_, changed)| *changed)
366    .map(|(part, _)| part.to_string())
367    .collect()
368}
369
370impl ControlHandler {
371    /// The capabilities `server.describe` lists. `supervisor.rescan_checked`
372    /// is announced only by a daemon that has a config file to rescan; any
373    /// other daemon refuses the op as `rescan_unavailable`.
374    pub(super) fn describe_capabilities(&self) -> Vec<String> {
375        let mut capabilities = self.capabilities_with_settings();
376        if self.rescan.is_some() {
377            capabilities.push(RESCAN_CANDIDATE_PREVIEW_CAPABILITY.to_string());
378        }
379        capabilities
380    }
381
382    fn staged_generation(&self, context: &SupervisorRescanContext) -> StagedGeneration {
383        StagedGeneration {
384            incarnation: self.supervisor.spawn_snapshot().cursor.daemon_incarnation,
385            counter: context.generation.load(Ordering::SeqCst),
386        }
387    }
388
389    pub(super) async fn handle_supervisor_rescan_checked(
390        &self,
391        ctx: &RouteCtx,
392        frame: Frame,
393        preview: bool,
394        candidate: Option<String>,
395        expect: Option<RescanExpect>,
396    ) -> Result<Vec<Frame>, RouterError> {
397        let corr = frame.header.corr;
398        let mode = match (preview, candidate, expect) {
399            (true, Some(candidate), None) => {
400                if candidate.len() > RESCAN_CANDIDATE_MAX_BYTES {
401                    return Ok(vec![control_error_frame(
402                        &frame,
403                        RESCAN_CANDIDATE_TOO_LARGE,
404                        format!(
405                            "the candidate config is {} bytes; a preview accepts at most {RESCAN_CANDIDATE_MAX_BYTES}",
406                            candidate.len()
407                        ),
408                    )?]);
409                }
410                RescanMode::Candidate(candidate)
411            }
412            (false, None, Some(expect)) => {
413                self.log_supervisor_request_received(
414                    ctx,
415                    corr,
416                    ops::SUPERVISOR_RESCAN_CHECKED,
417                    None,
418                    None,
419                )?;
420                RescanMode::Checked(expect)
421            }
422            _ => {
423                return Ok(vec![control_error_frame(
424                    &frame,
425                    "invalid_control_body",
426                    "supervisor.rescan_checked takes either preview: true with a candidate and \
427                     no expect, or preview: false with an expect and no candidate",
428                )?]);
429            }
430        };
431        let requester = self.supervisor_requester(ctx, corr)?;
432        self.handle_supervisor_rescan(frame, mode, requester).await
433    }
434
435    // The caller holds the rescan lock through both read and apply. Take the
436    // supervisor operation lock only after the read so other operations can
437    // proceed during file I/O. Check the staged generation for changes made
438    // outside the rescan lock, then build the plan from current module state.
439    pub(super) async fn rescan_input(
440        &self,
441        mode: &RescanMode,
442        context: &SupervisorRescanContext,
443    ) -> Result<RescanInput, RescanInputError> {
444        use tokio::time::{timeout_at, Instant};
445        use RescanInputError::Config;
446
447        if let Some(refusal) = self.supervisor.lifecycle_refusal(None) {
448            return Err(RescanInputError::Lifecycle(refusal));
449        }
450
451        let staged = self.staged_generation(context);
452        let (config, approved_preview) = if matches!(mode, RescanMode::Candidate(_)) {
453            (Self::read_rescan_config(mode, &context.config_path)?, None)
454        } else {
455            let deadline = Instant::now() + CONFIG_READ_DEADLINE;
456            let timed_out = || {
457                Config(
458                    "rescan_config_read_timeout",
459                    format!(
460                        "supervisor rescan timed out reading daemon config at {}; nothing was applied",
461                        context.config_path.display()
462                    ),
463                )
464            };
465            let permit = timeout_at(deadline, CONFIG_READ_SLOTS.acquire())
466                .await
467                .map_err(|_| timed_out())?
468                .expect("rescan read slots never close");
469            if Instant::now() >= deadline {
470                return Err(timed_out());
471            }
472            let path = context.config_path.clone();
473            let owner = if matches!(mode, RescanMode::Preview) {
474                self.config_runtime.clone()
475            } else {
476                None
477            };
478            let mode = mode.clone();
479            let (send, recv) = tokio::sync::oneshot::channel();
480            std::thread::Builder::new()
481                .name("rescan-config-read".into())
482                .spawn(move || {
483                    let _permit = permit;
484                    let result = (|| {
485                        let config = Self::read_rescan_config(&mode, &path)?;
486                        // Preview can record a file proposal, but only the caller
487                        // (after the deadline and generation checks) can apply a
488                        // rescan. The worker has no supervisor handle.
489                        let approved = if let Some(owner) = owner.filter(|_| !send.is_closed()) {
490                            owner
491                                .observe_file_proposal()
492                                .map_err(RescanInputError::Gate)?;
493                            owner
494                                .approved_daemon_configuration()
495                                .map_err(RescanInputError::Gate)?
496                        } else {
497                            None
498                        };
499                        Ok((config, approved))
500                    })();
501                    let _ = send.send(result);
502                })
503                .map_err(|error| {
504                    Config(
505                        "rescan_failed",
506                        format!("could not start supervisor rescan config read: {error}"),
507                    )
508                })?;
509            let result = timeout_at(deadline, recv).await.map_err(|_| timed_out())?;
510            // Tokio polls the result before the timer when both are ready.
511            // Never apply a read after its deadline, even in that race.
512            if Instant::now() >= deadline {
513                return Err(timed_out());
514            }
515            result.map_err(|error| {
516                Config(
517                    "rescan_failed",
518                    format!("supervisor rescan config reader stopped: {error}"),
519                )
520            })??
521        };
522
523        let guard = self
524            .supervisor
525            .lifecycle_operation(None)
526            .await
527            .map_err(RescanInputError::Lifecycle)?;
528        let current = self.staged_generation(context);
529        let changed = match mode {
530            RescanMode::Candidate(_) => None,
531            RescanMode::Checked(expect) if current != expect.staged_generation => Some((
532                CONFIG_CHANGED_SINCE_PREVIEW,
533                &expect.staged_generation,
534                "after the preview",
535            )),
536            _ if current != staged => {
537                Some(("rescan_failed", &staged, "while reading daemon config"))
538            }
539            _ => None,
540        };
541        if let Some((code, before, reason)) = changed {
542            return Err(Config(code, format!(
543                "the daemon's staged configuration changed {reason} (was {}:{}, now {}:{}); nothing was applied",
544                before.incarnation, before.counter, current.incarnation, current.counter,
545            )));
546        }
547        Ok(RescanInput {
548            config,
549            approved_preview,
550            guard,
551        })
552    }
553
554    fn read_rescan_config(
555        mode: &RescanMode,
556        path: &Path,
557    ) -> Result<Option<(DaemonConfig, ActivityConfig)>, RescanInputError> {
558        let rejected = |err: crate::daemon_config::DaemonConfigError| {
559            RescanInputError::Config(
560                "invalid_daemon_config",
561                format!("supervisor rescan rejected daemon config: {err}"),
562            )
563        };
564        match mode {
565            RescanMode::Execute | RescanMode::Preview => {
566                crate::daemon_config::load_with_activity(path).map_err(rejected)
567            }
568            RescanMode::Candidate(candidate) => {
569                crate::daemon_config::parse_with_activity(candidate, path)
570                    .map(Some)
571                    .map_err(rejected)
572            }
573            RescanMode::Checked(expect) => {
574                let doc = Self::checked_config_doc(path, expect)?;
575                crate::daemon_config::parse_with_activity(&doc, path)
576                    .map(Some)
577                    .map_err(rejected)
578            }
579        }
580    }
581
582    /// Read and hash the bytes that will be parsed, so a write landing after
583    /// the hash check cannot be what gets applied.
584    fn checked_config_doc(path: &Path, expect: &RescanExpect) -> Result<String, RescanInputError> {
585        use RescanInputError::Config;
586        let bytes = match std::fs::read(path) {
587            Ok(bytes) => bytes,
588            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
589                return Err(Config(
590                    CONFIG_CHANGED_SINCE_PREVIEW,
591                    format!(
592                        "daemon config not found at {}; nothing was applied",
593                        path.display()
594                    ),
595                ));
596            }
597            Err(err) => {
598                return Err(Config(
599                    "invalid_daemon_config",
600                    format!(
601                        "supervisor rescan could not read daemon config at {}: {err}",
602                        path.display()
603                    ),
604                ));
605            }
606        };
607        if !sha256_hex(&bytes).eq_ignore_ascii_case(&expect.config_sha256) {
608            return Err(Config(
609                CONFIG_CHANGED_SINCE_PREVIEW,
610                format!(
611                    "daemon config at {} is not the text that was previewed; nothing was applied",
612                    path.display(),
613                ),
614            ));
615        }
616        // The hash matched text that arrived as a JSON string, so this only
617        // fails on a hash collision; refuse rather than assume.
618        String::from_utf8(bytes).map_err(|err| {
619            Config(
620                "invalid_daemon_config",
621                format!("daemon config at {} is not UTF-8: {err}", path.display()),
622            )
623        })
624    }
625
626    /// The preview of `candidate` (already parsed into `modules`): the plain
627    /// rescan preview plus what applying it would do to each module, the
628    /// modules still waiting for a restart from an earlier rescan, and the
629    /// `expect` an apply must send. Applies nothing.
630    pub(super) fn preview_candidate(
631        &self,
632        context: &SupervisorRescanContext,
633        modules: Vec<ConfiguredModule>,
634        candidate: &str,
635    ) -> Result<SupervisorRescanResult, String> {
636        let plan = self.plan_rescan(modules)?;
637        let mut result = plan.preview_result();
638        let default_drain_ms = duration_ms(context.supervisor.default_drain_timeout());
639        let module_ids = plan
640            .current
641            .keys()
642            .chain(plan.configured.keys())
643            .collect::<BTreeSet<_>>();
644        let mut drained = BTreeSet::new();
645        for module_id in module_ids {
646            let current = plan.current.get(module_id);
647            let configured = plan.configured.get(module_id);
648            let (action, changed) = match (current, configured) {
649                (None, Some(configured)) if configured.enabled => {
650                    (RescanModuleActionKind::Start, Vec::new())
651                }
652                (Some((_, _, _, true)), None) => (RescanModuleActionKind::Stop, Vec::new()),
653                (Some((_, _, _, enabled)), Some(configured)) if *enabled != configured.enabled => {
654                    if configured.enabled {
655                        (RescanModuleActionKind::Start, Vec::new())
656                    } else {
657                        (RescanModuleActionKind::Stop, Vec::new())
658                    }
659                }
660                (Some((_, spec, health, enabled)), Some(configured))
661                    if plan.configuration_changes.contains(module_id) =>
662                {
663                    let changed = changed_parts(spec, health, configured);
664                    // A rescan stores new launch inputs without touching the
665                    // running process, so only a module that is enabled needs
666                    // a restart to use them. A disabled one starts with them
667                    // whenever it is enabled.
668                    if *enabled && plan.changed_pending_reload.contains(module_id) {
669                        (RescanModuleActionKind::Restart, changed)
670                    } else {
671                        (RescanModuleActionKind::Reload, changed)
672                    }
673                }
674                _ => continue,
675            };
676            let mut entry = RescanModuleAction {
677                module_id: module_id.clone(),
678                action,
679                changed,
680                drain_timeout_ms: None,
681                busy_gauges: Vec::new(),
682            };
683            if matches!(
684                entry.action,
685                RescanModuleActionKind::Restart | RescanModuleActionKind::Stop
686            ) {
687                if let Some((module, ..)) = current {
688                    let status = module.status().map_err(|err| {
689                        format!("failed to read status for module_id '{module_id}': {err}")
690                    })?;
691                    // A rescan that changes the entry also installs its drain
692                    // budget before anything drains; otherwise the module
693                    // keeps the budget it runs with now.
694                    entry.drain_timeout_ms = Some(match configured {
695                        Some(configured) if plan.configuration_changes.contains(module_id) => {
696                            configured.drain_timeout_ms.unwrap_or(default_drain_ms)
697                        }
698                        _ => duration_ms(status.drain_timeout),
699                    });
700                    let metrics = status
701                        .health
702                        .metrics
703                        .as_ref()
704                        .and_then(serde_json::Value::as_object);
705                    entry.busy_gauges =
706                        crate::supervise::declared_busy_gauges(&self.registry, module_id)
707                            .map_err(|err| {
708                                format!(
709                                    "failed to read busy gauges for module_id '{module_id}': {err}"
710                                )
711                            })?
712                            .into_iter()
713                            .map(|gauge| BusyGaugeReading {
714                                value: metrics.and_then(|metrics| metrics.get(&gauge)).cloned(),
715                                gauge,
716                            })
717                            .collect();
718                }
719                drained.insert(module_id.clone());
720            }
721            result.module_actions.push(entry);
722        }
723        for (module_id, (module, spec, _, _)) in &plan.current {
724            if drained.contains(module_id) {
725                continue;
726            }
727            let status = module.status().map_err(|err| {
728                format!("failed to read status for module_id '{module_id}': {err}")
729            })?;
730            if launch_spec_agreement(
731                spec,
732                status.process_alive,
733                status.launch_spec_digest.as_ref(),
734            ) == LaunchSpecAgreement::Mismatch
735            {
736                result.earlier_pending.push(module_id.clone());
737            }
738        }
739        result.expect = Some(RescanExpect {
740            config_sha256: sha256_hex(candidate.as_bytes()),
741            staged_generation: self.staged_generation(context),
742        });
743        Ok(result)
744    }
745}
746
747#[cfg(all(test, unix))]
748#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
749async fn stalled_config_read_times_out_without_holding_operation_lock() {
750    use crate::{Registry, RestartPolicy, Supervisor, SupervisorHandle};
751    use cortexkit_test_support::ScratchDir;
752    use std::io::Write;
753    use std::sync::{mpsc, Arc};
754    use subc_protocol::{FrameType, Principal};
755
756    let dir = ScratchDir::new("rescan-stalled-file");
757    let path = dir.join("subc.jsonc");
758    assert!(std::process::Command::new("mkfifo")
759        .arg(&path)
760        .status()
761        .unwrap()
762        .success());
763    let registry = Arc::new(Registry::default());
764    let handle = SupervisorHandle::new();
765    let supervisor =
766        Supervisor::new(registry.clone(), RestartPolicy::default()).with_handle(handle.clone());
767    let handler = Arc::new(
768        ControlHandler::new(registry)
769            .with_supervisor(handle.clone())
770            .with_supervisor_rescan(supervisor, &path, None),
771    );
772    let (opened, is_open) = tokio::sync::oneshot::channel();
773    let (release, released) = mpsc::channel();
774    let feeder = std::thread::spawn(move || {
775        let mut fifo = std::fs::OpenOptions::new().write(true).open(path).unwrap();
776        opened.send(()).unwrap();
777        released.recv_timeout(Duration::from_secs(10)).unwrap();
778        let _ = fifo.write_all(br#"{"version":1,"modules":{"never-applied":{"program":"/bin/true","protocol":"none","enabled":false}}}"#);
779    });
780    let request = tokio::spawn({
781        let handler = Arc::clone(&handler);
782        async move {
783            let frame = Frame::build(
784                FrameType::Request,
785                super::control_flags(),
786                0,
787                0,
788                1,
789                Vec::new(),
790            )
791            .unwrap();
792            handler
793                .handle_supervisor_rescan(frame, RescanMode::Execute, Principal::Direct)
794                .await
795                .unwrap()
796                .remove(0)
797        }
798    });
799    tokio::time::timeout(Duration::from_secs(2), is_open)
800        .await
801        .unwrap()
802        .unwrap();
803
804    // Restart takes the operation lock even for an unknown module. Receive
805    // that ordinary refusal while the reader is still waiting for file data.
806    let frame = Frame::build(
807        FrameType::Request,
808        super::control_flags(),
809        0,
810        0,
811        2,
812        Vec::new(),
813    )
814    .unwrap();
815    let restart = tokio::time::timeout(
816        Duration::from_secs(1),
817        handler.handle_supervisor_restart(frame, "missing".into(), None, Principal::Direct),
818    )
819    .await;
820    let mut request = request;
821    let reply = tokio::time::timeout(Duration::from_secs(6), &mut request).await;
822    release.send(()).unwrap();
823    feeder.join().unwrap();
824    let restart = restart
825        .expect("the rescan held the supervisor operation lock during its config read")
826        .unwrap()
827        .remove(0);
828    let body: serde_json::Value = serde_json::from_slice(&restart.body).unwrap();
829    assert_eq!(body["code"], "unknown_module");
830    let reply = reply
831        .expect("rescan did not answer before the config reader was released")
832        .unwrap();
833    assert_eq!(reply.header.ty, FrameType::Error);
834    let body: serde_json::Value = serde_json::from_slice(&reply.body).unwrap();
835    assert_eq!(body["code"], "rescan_config_read_timeout");
836    assert!(body["message"].as_str().unwrap().contains("subc.jsonc"));
837    assert!(handle.list().is_empty());
838    assert_eq!(
839        handler
840            .rescan
841            .as_ref()
842            .unwrap()
843            .generation
844            .load(Ordering::SeqCst),
845        0
846    );
847}
848
849#[derive(Debug, Clone)]
850pub(super) struct SupervisorRescanContext {
851    pub(super) supervisor: Supervisor,
852    pub(super) config_path: PathBuf,
853    pub(super) configured_port: Option<u16>,
854    pub(super) storage_config: Option<crate::daemon_config::StorageConfig>,
855    pub(super) admission_facts_carrier_module_id: Option<String>,
856    pub(super) admission_facts_targets: Option<Vec<String>>,
857    pub(super) scope_authority_owners: Vec<String>,
858    pub(super) flow_scope_authority_owners: Vec<String>,
859    federated_scope_owner: String,
860    pub(super) privileged_operator_prompt: PrivilegedOperatorPrompt,
861    /// Counts executed rescans that set out to change the supervised modules'
862    /// staged or applied configuration, counted before the first change so a
863    /// rescan that fails partway still counts. With the daemon incarnation it
864    /// names the state a `supervisor.rescan_checked` preview was computed
865    /// against.
866    generation: Arc<std::sync::atomic::AtomicU64>,
867    rescan_lock: Arc<tokio::sync::Mutex<()>>,
868    pub(super) module_entries: Arc<Mutex<rescan_checked::ModuleEntries>>,
869}
870
871impl ControlHandler {
872    pub fn with_supervisor_rescan(
873        mut self,
874        supervisor: Supervisor,
875        config_path: impl Into<PathBuf>,
876        configured_port: Option<u16>,
877    ) -> Self {
878        self.rescan = Some(SupervisorRescanContext {
879            supervisor,
880            config_path: config_path.into(),
881            configured_port,
882            storage_config: self.storage_config.clone(),
883            admission_facts_carrier_module_id: self.admission_facts_carrier_module_id.clone(),
884            admission_facts_targets: self.admission_facts_targets.clone(),
885            scope_authority_owners: self.scope_authority_owners.clone(),
886            flow_scope_authority_owners: self.flow_scope_authority_owners.clone(),
887            federated_scope_owner: self.federated_scope_owner.clone(),
888            privileged_operator_prompt: self.privileged_operator_prompt,
889            generation: Arc::default(),
890            rescan_lock: Arc::default(),
891            module_entries: Arc::default(),
892        });
893        self
894    }
895
896    pub(crate) fn with_supervisor_rescan_entries(
897        self,
898        modules: &[crate::daemon_config::ConfiguredModule],
899    ) -> Self {
900        if let Some(context) = &self.rescan {
901            let mut entries = context
902                .module_entries
903                .lock()
904                .unwrap_or_else(|e| e.into_inner());
905            entries.seed(modules);
906        }
907        self
908    }
909}
910
911impl ControlHandler {
912    /// `supervisor.rescan` and `supervisor.rescan_checked`. `mode` says where
913    /// the configuration comes from and whether to apply it; every mode then
914    /// runs the same comparison, so a preview describes the apply it previews.
915    pub(super) async fn handle_supervisor_rescan(
916        &self,
917        frame: Frame,
918        mode: RescanMode,
919        requester: Principal,
920    ) -> Result<Vec<Frame>, RouterError> {
921        let preview = mode.previews();
922        let Some(context) = self.rescan.clone() else {
923            return Ok(vec![control_error_frame(
924                &frame,
925                "rescan_unavailable",
926                "the daemon was not started with a reloadable config path".to_string(),
927            )?]);
928        };
929
930        let _rescan_guard = context.rescan_lock.lock().await;
931        let rescan_checked::RescanInput {
932            config: loaded,
933            approved_preview,
934            guard: _operation_guard,
935        } = match self.rescan_input(&mode, &context).await {
936            Ok(input) => input,
937            Err(error) => return Ok(vec![error.into_frame(&frame)?]),
938        };
939        // `load` reports a missing file as Ok(None), which is correct at boot
940        // (no config, nothing to supervise) and catastrophic here: rescan treats
941        // "not in the config" as "remove it", so an absent file would read as an
942        // empty module list and retire the entire running fleet. An editor
943        // writing via write-new-then-rename, or a half-finished edit, is enough
944        // to open that window. Refuse instead: a config that cannot be read
945        // carries no instruction to remove anything.
946        let Some((config, activity_config)) = loaded else {
947            return Ok(vec![control_error_frame(
948                &frame,
949                "invalid_daemon_config",
950                format!(
951                    "daemon config not found at {}; refusing to rescan (an absent config would \
952                     retire every supervised module)",
953                    context.config_path.display()
954                ),
955            )?]);
956        };
957        let (
958            configured_port,
959            storage_config,
960            admission_facts_carrier_module_id,
961            admission_facts_targets,
962            scope_authority_owners,
963            flow_scope_authority_owners,
964            federated_scope_owner,
965            privileged_operator_prompt,
966            modules,
967            reserved_capabilities,
968        ) = (
969            config.port,
970            config.storage,
971            config.admission_facts_carrier_module_id,
972            config.admission_facts_targets,
973            config.scope_authority_owners,
974            config.flow_scope_authority_owners,
975            config.federated_scope_owner,
976            config.privileged_operator_prompt,
977            config.modules,
978            config.reserved_capabilities,
979        );
980
981        // Collect the sections rescan cannot apply, so the REPLY carries them.
982        //
983        // The warning below has always been correct and has always gone only to
984        // the journal -- addressed to whoever reads logs, while the person who
985        // just edited the config is looking at the CLI. Naming each section
986        // individually rather than setting a flag: "something outside modules
987        // changed" sends the operator back to diffing their own file, which is
988        // the work this is meant to save.
989        let mut restart_required = Vec::new();
990        for section in RestartRequiredSection::ALL {
991            let changed = match section {
992                RestartRequiredSection::Port => configured_port != context.configured_port,
993                RestartRequiredSection::Storage => storage_config != context.storage_config,
994                RestartRequiredSection::AdmissionFactsCarrierModuleId => {
995                    admission_facts_carrier_module_id != context.admission_facts_carrier_module_id
996                }
997                RestartRequiredSection::AdmissionFactsTargets => {
998                    admission_facts_targets != context.admission_facts_targets
999                }
1000                RestartRequiredSection::ScopeAuthorityOwners => {
1001                    scope_authority_owners != context.scope_authority_owners
1002                }
1003                RestartRequiredSection::FlowScopeAuthorityOwners => {
1004                    flow_scope_authority_owners != context.flow_scope_authority_owners
1005                }
1006                RestartRequiredSection::FederatedScopeOwner => {
1007                    federated_scope_owner != context.federated_scope_owner
1008                }
1009                RestartRequiredSection::PrivilegedOperatorPrompt => {
1010                    privileged_operator_prompt != context.privileged_operator_prompt
1011                }
1012            };
1013            if changed {
1014                restart_required.push(section.label().to_string());
1015            }
1016        }
1017        if !restart_required.is_empty() {
1018            warn!(
1019                config_path = %context.config_path.display(),
1020                sections = %restart_required.join(", "),
1021                "daemon config changed outside the modules section; restart the daemon to apply those changes"
1022            );
1023        }
1024
1025        for configured in &modules {
1026            if let Err(err) = validate_spec(&configured.module_spec()) {
1027                return Ok(vec![control_error_frame(
1028                    &frame,
1029                    "invalid_daemon_config",
1030                    format!("supervisor rescan rejected daemon config: {err}"),
1031                )?]);
1032            }
1033        }
1034
1035        let configured_capabilities = modules
1036            .iter()
1037            .map(|module| (module.module_id.clone(), module.enabled))
1038            .collect::<Vec<_>>();
1039        let preview_capability_warnings = if preview {
1040            let (_, registrations) = self.runtime_capability_snapshot()?;
1041            let current_modules = self
1042                .supervisor
1043                .list()
1044                .into_iter()
1045                .map(|module| module.module_id().to_string())
1046                .collect::<BTreeSet<_>>();
1047            let resulting_modules = configured_capabilities.clone();
1048            let removed = current_modules
1049                .into_iter()
1050                .filter(|module_id| {
1051                    !resulting_modules
1052                        .iter()
1053                        .any(|(configured_id, _)| configured_id == module_id)
1054                })
1055                .collect::<Vec<_>>();
1056            // A candidate preview also names providers the candidate disables.
1057            // `supervisor.rescan`'s own preview keeps its removal-only warnings.
1058            let disabled = match &mode {
1059                RescanMode::Candidate(_) => resulting_modules
1060                    .iter()
1061                    .filter(|(_, enabled)| !enabled)
1062                    .map(|(module_id, _)| module_id.clone())
1063                    .collect::<Vec<_>>(),
1064                _ => Vec::new(),
1065            };
1066            self.capability_evaluator.preview_warnings(
1067                resulting_modules,
1068                &removed,
1069                &disabled,
1070                &registrations,
1071            )
1072        } else {
1073            Vec::new()
1074        };
1075        let reconciled = match (&mode, approved_preview.as_ref()) {
1076            (RescanMode::Preview, Some(approved)) => Ok((
1077                config_gate::preview_approved_daemon(approved, &modules),
1078                Vec::new(),
1079            )),
1080            (RescanMode::Candidate(candidate), _) => self
1081                .preview_candidate(&context, modules, candidate)
1082                .map(|result| (result, Vec::new())),
1083            _ => {
1084                self.reconcile_supervised_modules(
1085                    &context.supervisor,
1086                    modules,
1087                    preview,
1088                    requester.clone(),
1089                )
1090                .await
1091            }
1092        };
1093        let (result, changed) = match reconciled {
1094            Ok(result) => result,
1095            Err(message) => {
1096                return Ok(vec![control_error_frame(&frame, "rescan_failed", message)?])
1097            }
1098        };
1099        if !preview {
1100            self.rescan_policy_root(config.agent_policy_root).await;
1101            if let Some(ledger) = &self.activity {
1102                ledger.module_rescanned(&result.added, &result.removed, requester.clone());
1103                ledger.config_changed(&result.added, &result.removed, &changed, requester);
1104            }
1105            if let Err(code) = self.configure_activity(activity_config).await {
1106                warn!(
1107                    code,
1108                    "activity retention could not be applied during rescan"
1109                );
1110            }
1111            self.capability_evaluator
1112                .configure(configured_capabilities, reserved_capabilities);
1113            self.capability_evaluator.wake_deadline_loop();
1114            self.refresh_capability_requirements();
1115        }
1116        let mut result = result;
1117        result.restart_required = restart_required;
1118        result.capability_warnings = preview_capability_warnings;
1119        let response = ClientControlResponse::SupervisorRescan { result };
1120        Ok(vec![control_response_body_frame(
1121            &frame,
1122            &response,
1123            "ClientControlResponse::SupervisorRescan",
1124        )?])
1125    }
1126}
1127
1128impl ControlHandler {
1129    /// Compare the configured module set with the supervised one, changing
1130    /// nothing. The staged spec each supervised module holds is what the
1131    /// configured entry is compared with.
1132    fn plan_rescan(
1133        &self,
1134        configured_modules: Vec<crate::daemon_config::ConfiguredModule>,
1135    ) -> Result<RescanPlan, String> {
1136        let mut current = BTreeMap::new();
1137        for module in self.supervisor.list() {
1138            let (spec, health) = module.configuration().map_err(|err| {
1139                format!(
1140                    "failed to read configuration for module_id '{}': {err}",
1141                    module.module_id()
1142                )
1143            })?;
1144            let enabled = module
1145                .status()
1146                .map_err(|err| {
1147                    format!(
1148                        "failed to read status for module_id '{}': {err}",
1149                        module.module_id()
1150                    )
1151                })?
1152                .enabled;
1153            current.insert(
1154                module.module_id().to_string(),
1155                (module, spec, health, enabled),
1156            );
1157        }
1158        let configured = configured_modules
1159            .into_iter()
1160            .map(|module| (module.module_id.clone(), module))
1161            .collect::<BTreeMap<_, _>>();
1162
1163        let added = configured
1164            .keys()
1165            .filter(|module_id| !current.contains_key(*module_id))
1166            .cloned()
1167            .collect::<Vec<_>>();
1168        let removed = current
1169            .keys()
1170            .filter(|module_id| !configured.contains_key(*module_id))
1171            .cloned()
1172            .collect::<Vec<_>>();
1173        let mut changed_pending_reload = Vec::new();
1174        let mut changed_pending = Vec::new();
1175        let mut configuration_changes = BTreeSet::new();
1176        let mut enabled_changes = BTreeSet::new();
1177        let mut unchanged = 0_u32;
1178        let publication = self
1179            .config_runtime
1180            .as_ref()
1181            .and_then(|owner| owner.polled_snapshot().ok());
1182
1183        for (module_id, configured_module) in &configured {
1184            let Some((module, current_spec, current_health, current_enabled)) =
1185                current.get(module_id)
1186            else {
1187                continue;
1188            };
1189            // Compare the whole launch spec so a future launch field cannot
1190            // accidentally become a live-only policy change. Health is stored
1191            // separately and applies live without replacing the process.
1192            let launch_changed = *current_spec != configured_module.module_spec();
1193            let configuration_changed =
1194                launch_changed || *current_health != configured_module.health;
1195            let pending = self.pending_module_fields(
1196                module,
1197                Some(configured_module),
1198                configuration_changed,
1199                Self::registration_channel_in_force(
1200                    publication
1201                        .as_ref()
1202                        .and_then(|view| view.registration_declaration(module_id))
1203                        .as_deref(),
1204                    publication
1205                        .as_ref()
1206                        .and_then(|view| match &view.approved_daemon {
1207                            crate::config_gate::runtime::ApprovedDaemonView::Approved {
1208                                config,
1209                                ..
1210                            } => config
1211                                .modules
1212                                .iter()
1213                                .find(|entry| entry.module_id == *module_id)
1214                                .map(|entry| entry.registration_channel),
1215                            _ => None,
1216                        }),
1217                ),
1218                publication.as_deref(),
1219            )?;
1220            let has_pending = !pending.is_empty();
1221            if has_pending {
1222                changed_pending.push(subc_control::SupervisorPendingModule {
1223                    module_id: module_id.clone(),
1224                    fields: pending
1225                        .into_iter()
1226                        .map(|mut field| {
1227                            field.value = None;
1228                            field
1229                        })
1230                        .collect(),
1231                });
1232            }
1233            // Applying a rescan also replaces the recorded config value, even
1234            // when an operator already put the runtime in the requested state.
1235            let enabled_changed = *current_enabled != configured_module.enabled
1236                || self
1237                    .capability_evaluator
1238                    .configured_enabled(module_id)
1239                    .is_some_and(|enabled| enabled != configured_module.enabled);
1240            if configuration_changed {
1241                configuration_changes.insert(module_id.clone());
1242            }
1243            if launch_changed {
1244                changed_pending_reload.push(module_id.clone());
1245            }
1246            if enabled_changed {
1247                enabled_changes.insert(module_id.clone());
1248            }
1249            if !configuration_changed && !enabled_changed && !has_pending {
1250                unchanged = unchanged.saturating_add(1);
1251            }
1252        }
1253        Ok(RescanPlan {
1254            current,
1255            configured,
1256            added,
1257            removed,
1258            changed_pending_reload,
1259            changed_pending,
1260            configuration_changes,
1261            enabled_changes,
1262            unchanged,
1263        })
1264    }
1265
1266    /// Reconcile the running module set against the configured one.
1267    ///
1268    /// With `preview` set, the diff is computed and returned WITHOUT applying any
1269    /// of it: nothing is retired, reconfigured, enabled or spawned. The preview
1270    /// deliberately shares this function with the executing path rather than
1271    /// computing the same diff somewhere else -- two implementations of one
1272    /// decision agree until they do not, and the whole value of a preview is that
1273    /// it describes the operation that will actually run.
1274    pub(super) async fn reconcile_supervised_modules(
1275        &self,
1276        supervisor: &Supervisor,
1277        configured_modules: Vec<crate::daemon_config::ConfiguredModule>,
1278        preview: bool,
1279        requester: Principal,
1280    ) -> Result<(SupervisorRescanResult, Vec<String>), String> {
1281        let plan = self.plan_rescan(configured_modules)?;
1282
1283        // Everything above this point is pure computation over two snapshots.
1284        // Everything below MUTATES. The preview returns here so the boundary is a
1285        // single early return rather than a condition repeated at each mutation
1286        // site, where one missed guard would apply part of a change the caller was
1287        // told would not happen.
1288        if preview {
1289            return Ok((plan.preview_result(), Vec::new()));
1290        }
1291        let changed = plan
1292            .configuration_changes
1293            .union(&plan.enabled_changes)
1294            .cloned()
1295            .collect::<Vec<_>>();
1296        let RescanPlan {
1297            current,
1298            configured,
1299            added,
1300            removed,
1301            changed_pending_reload,
1302            changed_pending,
1303            configuration_changes,
1304            enabled_changes,
1305            unchanged,
1306        } = plan;
1307        // The staged generation moves before the first change rather than
1308        // after the last, so a rescan that fails partway still invalidates
1309        // every earlier `supervisor.rescan_checked` preview: part of its diff
1310        // may have run.
1311        if !(added.is_empty()
1312            && removed.is_empty()
1313            && configuration_changes.is_empty()
1314            && changed_pending.is_empty()
1315            && enabled_changes.is_empty())
1316        {
1317            if let Some(context) = &self.rescan {
1318                context
1319                    .generation
1320                    .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1321            }
1322        }
1323
1324        for module_id in &removed {
1325            let module = &current
1326                .get(module_id)
1327                .expect("removed module came from current supervisor state")
1328                .0;
1329            module
1330                .retire_requested(Some(requester.clone()))
1331                .await
1332                .map_err(|err| {
1333                    format!("failed to retire module_id '{module_id}' during rescan: {err}")
1334                })?;
1335            // TOMBSTONE BEFORE RETIRE, and the order is the whole fix.
1336            //
1337            // `handle_route_open` resolves an absent module in three steps:
1338            // registry, then supervisor status, then tombstone. Retiring first
1339            // opens a window where ALL THREE ARE ABSENT -- the registry entry
1340            // went with the teardown above, the supervisor entry went with
1341            // `retire`, and the tombstone does not exist yet -- so a route.open
1342            // landing in it gets `unknown_module` (RETRYABLE, "never heard of
1343            // it") for a module that was deliberately removed and whose caller
1344            // should get `module_removed` (TERMINAL, carrying a removal age).
1345            //
1346            // Writing the tombstone first closes it: during the window the
1347            // supervisor entry still answers, so the caller gets
1348            // `target_unavailable` -- retryable, and TRUE, because the module
1349            // is mid-teardown. After both statements it is `module_removed`.
1350            // No instant remains where a removed module reads as one that
1351            // never existed.
1352            //
1353            // NOT DETERMINISTICALLY TESTABLE FROM HERE, said plainly because
1354            // the absence of a test beside a fix invites deletion: these are
1355            // two sync statements with no await between them, so reaching the
1356            // window needs a second worker thread to land exactly between them
1357            // and there is no hook to force it. MEASURED: the 25 daemon_config
1358            // tests pass identically with the old order and the new one, so
1359            // the existing suite cannot see this and a green run is not
1360            // evidence either way. What the suite does hold is the
1361            // post-condition -- a removed module answers `module_removed` --
1362            // which this preserves.
1363            //
1364            // Found by an Athena panel reading the shipped tree against a
1365            // design note (2026-09-19), as the one concrete instance of that
1366            // note's class that survived contact with source. Direction is
1367            // benign: retryable where terminal was intended, never the reverse.
1368            self.supervisor.record_rescan_removal(module_id);
1369            self.supervisor.retire(module_id);
1370            self.route_outages.forget(module_id);
1371        }
1372
1373        for module_id in configured.keys() {
1374            let Some((module, _, _, current_enabled)) = current.get(module_id) else {
1375                continue;
1376            };
1377            let configured_module = configured
1378                .get(module_id)
1379                .expect("configured module id came from configured map");
1380            if configuration_changes.contains(module_id) {
1381                module
1382                    .update_configuration(
1383                        configured_module.module_spec(),
1384                        configured_module.health.clone(),
1385                        configured_module.drain_timeout_ms,
1386                    )
1387                    .await
1388                    .map_err(|err| {
1389                        format!(
1390                            "failed to update module_id '{module_id}' configuration during rescan: {err}"
1391                        )
1392                    })?;
1393            }
1394            // Config-only drift is applied by the evaluator's config update;
1395            // do not turn it into a runtime start or stop.
1396            if *current_enabled != configured_module.enabled {
1397                // A rescan that starts or stops a module applies an operator's
1398                // edit to the config, so the resulting outage was asked for.
1399                self.route_outages.mark_operator_action(module_id);
1400                module
1401                    .set_enabled_requested(configured_module.enabled, Some(requester.clone()))
1402                    .await
1403                    .map_err(|err| {
1404                        self.route_outages.operator_action_ended_unrefused(module_id);
1405                        format!(
1406                            "failed to apply module_id '{module_id}' enabled={} during rescan: {err}",
1407                            configured_module.enabled
1408                        )
1409                    })?;
1410            }
1411        }
1412
1413        for module_id in &added {
1414            let configured_module = configured
1415                .get(module_id)
1416                .expect("added module id came from configured map");
1417            supervisor
1418                .supervise_configured_requested_async(
1419                    configured_module.module_spec(),
1420                    configured_module.enabled,
1421                    configured_module.health.clone(),
1422                    configured_module.drain_timeout_ms,
1423                    configured_module.restart,
1424                    configured_module.register_timeout,
1425                    Some(requester.clone()),
1426                )
1427                .await
1428                .map_err(|err| {
1429                    format!("failed to add module_id '{module_id}' during rescan: {err}")
1430                })?;
1431        }
1432
1433        if let Some(context) = &self.rescan {
1434            let mut entries = context
1435                .module_entries
1436                .lock()
1437                .unwrap_or_else(|e| e.into_inner());
1438            entries.record(&configured, &added, &removed);
1439        }
1440
1441        Ok((
1442            SupervisorRescanResult {
1443                added,
1444                removed,
1445                changed_pending_reload,
1446                changed_pending,
1447                enabled_changes: enabled_changes.iter().cloned().collect(),
1448                unchanged,
1449                preview: false,
1450                // Filled by the caller, which is the only layer that can see the
1451                // previous config to diff against.
1452                restart_required: Vec::new(),
1453                capability_warnings: Vec::new(),
1454                module_actions: Vec::new(),
1455                earlier_pending: Vec::new(),
1456                expect: None,
1457            },
1458            changed,
1459        ))
1460    }
1461}