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