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