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