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