Skip to main content

subc_daemon/
supervise_swap.rs

1//! Blue/green swap of one supervised module.
2//!
3//! A swap starts a CANDIDATE process beside the running INCUMBENT, routes
4//! nothing to it while it warms, and once it has declared itself ready moves new
5//! routes onto it and drains the incumbent. The sequence, and why each step is
6//! shaped the way it is, is `docs/designs/module-readiness-and-swap.md`
7//! ("Rung 3").
8//!
9//! Two rules run through everything here:
10//!
11//! * Until cutover the incumbent is the module. Nothing on a failure path may
12//!   drain it, touch its snapshot, move its nonce, or spend a unit of its
13//!   crash-restart budget. A candidate that fails is killed, its slot is freed,
14//!   and the swap reports which arm failed; the module is exactly as it was.
15//! * The candidate is reached only by connection or by endpoint, never by
16//!   module id, because every by-id lookup resolves the incumbent.
17//!
18//! The whole swap runs inside the module's supervise loop, like a restart, and
19//! the incumbent is not health-probed while it runs. But the candidate's warm-up
20//! can take the whole readiness budget, so it keeps serving the module's
21//! commands meanwhile (see [`serve_command_while_warming`]): an operator stop,
22//! disable or retire aborts the swap and is then carried out on the incumbent,
23//! instead of queueing for up to the budget. The operator's reply is sent at
24//! cutover or failure, before the incumbent's drain, so a caller whose own
25//! requests ride the incumbent is not left waiting on a drain that is waiting
26//! on it.
27
28use super::*;
29use crate::registry::RegistrationSlot;
30
31#[path = "supervise/swap_terminal.rs"]
32mod swap_terminal;
33
34// Gate publication can spend several seconds in disk-bound work under fsync load.
35// Allow that work the same 30 s as a live config ACK, but do not retain a warmed
36// candidate indefinitely if cutover still cannot acquire the gate.
37const SWAP_CUTOVER_DEADLINE: Duration = Duration::from_secs(30);
38
39/// The cgroup directory name for one process of `module_id`.
40///
41/// A swap overlaps two processes of one module and they must not share a
42/// cgroup (it would make them one kill domain), so each module has two names
43/// and a swap's candidate takes whichever the incumbent is not using, keeping
44/// it after cutover. The alternate name is the primary one plus `_swap`.
45///
46/// The encoding is injective, so no module id can name another module's
47/// cgroup, swap or not. Bytes outside `[A-Za-z0-9.-]`, the underscore
48/// included, are written as `_` and two lowercase hex digits; so every `_`
49/// the encoding produces is followed by two hex digits, and `_swap` (with `s`
50/// not a hex digit) can only be the suffix. Placement then escapes `_` again:
51/// this label is not yet the filesystem component.
52#[cfg(any(target_os = "linux", test))]
53pub(crate) fn cgroup_name(module_id: &str, alternate: bool) -> String {
54    let mut name = String::with_capacity(module_id.len() + 5);
55    for byte in module_id.bytes() {
56        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.') {
57            name.push(char::from(byte));
58        } else {
59            name.push_str(&format!("_{byte:02x}"));
60        }
61    }
62    if alternate {
63        name.push_str("_swap");
64    }
65    name
66}
67
68/// How a candidate's warm-up ended.
69enum Warm {
70    /// Registered and ready (or registered while the incumbent was gone), on
71    /// this connection.
72    Ready(ConnectionId),
73    Failed(CandidateFailure),
74    /// A newer approved configuration requires a launch the candidate missed.
75    Superseded {
76        generation: u64,
77    },
78    /// An operator command that must win over the swap arrived while the
79    /// candidate warmed. `connection` is the candidate's, if it registered.
80    Interrupted {
81        command: Option<SupervisorCommand>,
82        connection: Option<ConnectionId>,
83    },
84}
85
86/// What a swap hands back to the supervise loop when it ends.
87#[derive(Default)]
88pub(super) struct SwapEnd {
89    /// Commands for the loop to run next. An interrupting stop, disable or hold
90    /// takes priority over retained configuration commands so a queued restart
91    /// cannot run before the stop is applied. Otherwise arrival order is kept.
92    pub(super) requeue: Vec<SupervisorCommand>,
93}
94
95struct CandidateFailure {
96    arm: SwapFailureArm,
97    detail: String,
98    /// Set when the candidate exited on its own; it is then already reaped.
99    exit: Option<ExitReport>,
100    /// The candidate's connection, when it registered.
101    connection: Option<ConnectionId>,
102}
103
104impl CandidateFailure {
105    fn into_error(self, module_id: &str, exit: ExitReport) -> SuperviseError {
106        SuperviseError::SwapFailed {
107            module_id: module_id.to_string(),
108            arm: self.arm,
109            detail: self.detail,
110            candidate_exit: Some(exit),
111        }
112    }
113}
114
115/// Run one swap through cutover or failure. Successful cutover starts
116/// incumbent retirement in the background and replies on `reply` immediately.
117#[allow(clippy::too_many_arguments)]
118pub(super) async fn run_swap(
119    spec: &ModuleSpec,
120    runtime: &SupervisorRuntimeConfig,
121    registry: &Arc<Registry>,
122    process_liveness: &SupervisorProcessLiveness,
123    snapshot: &SharedSnapshot,
124    child: &mut Option<SupervisedChild>,
125    commands: &mut mpsc::Receiver<SupervisorCommand>,
126    ready_timeout: Duration,
127    reply: oneshot::Sender<Result<SwapOutcome, SuperviseError>>,
128) -> SwapEnd {
129    let mut end = SwapEnd::default();
130    run_swap_inner(
131        spec,
132        runtime,
133        registry,
134        process_liveness,
135        snapshot,
136        child,
137        commands,
138        ready_timeout,
139        reply,
140        &mut end,
141    )
142    .await;
143    end
144}
145
146#[allow(clippy::too_many_arguments)]
147async fn run_swap_inner(
148    spec: &ModuleSpec,
149    runtime: &SupervisorRuntimeConfig,
150    registry: &Arc<Registry>,
151    process_liveness: &SupervisorProcessLiveness,
152    snapshot: &SharedSnapshot,
153    child: &mut Option<SupervisedChild>,
154    commands: &mut mpsc::Receiver<SupervisorCommand>,
155    ready_timeout: Duration,
156    reply: oneshot::Sender<Result<SwapOutcome, SuperviseError>>,
157    end: &mut SwapEnd,
158) {
159    let module_id = spec.module_id.as_str();
160    let (forwarding, handle, incumbent_connection) =
161        match admit_swap(spec, runtime, registry, snapshot, child) {
162            Ok(admitted) => admitted,
163            Err(err) => {
164                info!(module_id, error = %err, "swap refused before spawning a candidate");
165                let _ = reply.send(Err(err));
166                return;
167            }
168        };
169
170    // The candidate takes whichever cgroup the incumbent is not using.
171    let candidate_alternate = !lock_snapshot(snapshot)
172        .map(|state| state.in_alternate_slot)
173        .unwrap_or(false);
174    let mut candidate = loop {
175        match spawn_child_in_slot_async(
176            spec,
177            runtime,
178            SpawnRole::SwapCandidate,
179            candidate_alternate,
180        )
181        .await
182        {
183            Ok(candidate) => break candidate,
184            Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
185                if wait_for_config_gate(runtime, module_id, commands, end, None).await {
186                    continue;
187                }
188                handle.close_swap(module_id);
189                let _ = reply.send(Err(SuperviseError::SwapFailed {
190                    module_id: module_id.to_owned(),
191                    arm: SwapFailureArm::Interrupted,
192                    detail: "swap interrupted while configuration publication was pending".into(),
193                    candidate_exit: None,
194                }));
195                return;
196            }
197            Err(err) => {
198                handle.close_swap(module_id);
199                warn!(module_id, error = %err, "swap candidate failed to spawn; incumbent untouched");
200                let _ = reply.send(Err(SuperviseError::SwapFailed {
201                    module_id: module_id.to_string(),
202                    arm: SwapFailureArm::SpawnFailed,
203                    detail: err.to_string(),
204                    candidate_exit: None,
205                }));
206                return;
207            }
208        }
209    };
210    #[cfg(target_os = "macos")]
211    candidate.confirm_privacy_exec().await;
212    #[cfg(target_os = "linux")]
213    let candidate_cgroup = candidate
214        .cgroup_placement
215        .as_ref()
216        .map(|_| candidate.module_id.as_str());
217    #[cfg(not(target_os = "linux"))]
218    let candidate_cgroup: Option<&str> = None;
219    info!(
220        module_id,
221        candidate_pid = candidate.pid,
222        cgroup = ?candidate_cgroup,
223        incumbent_connection_id = incumbent_connection.get(),
224        ready_timeout_ms = ready_timeout.as_millis() as u64,
225        "swap candidate spawned; routing stays on the incumbent until it is ready"
226    );
227
228    let config_deadline = config_candidate_deadline(runtime, &candidate);
229    let warm = warm_candidate(
230        module_id,
231        registry,
232        &mut candidate,
233        incumbent_connection,
234        ready_timeout,
235        config_deadline,
236        runtime.config_delivery.as_ref(),
237        commands,
238        end,
239    )
240    .await;
241    let candidate_connection = match warm {
242        Warm::Superseded { generation } => {
243            abandon_candidate(module_id, registry, &forwarding, runtime, candidate, None).await;
244            update_snapshot(snapshot, Some(module_id), |state| {
245                state.swap_outcome = Some(SwapOutcome::SupersededByConfigRestart)
246            })
247            .ok();
248            end.requeue.push(SupervisorCommand::ConfigApplyRestart {
249                generation,
250                supersedes_swap: true,
251            });
252            let _ = reply.send(Ok(SwapOutcome::SupersededByConfigRestart));
253            return;
254        }
255        Warm::Ready(connection) => connection,
256        Warm::Interrupted {
257            command,
258            connection,
259        } => {
260            let failure = CandidateFailure {
261                arm: SwapFailureArm::Interrupted,
262                detail: "an operator stop, disable or retire arrived while the candidate warmed"
263                    .to_string(),
264                exit: None,
265                connection,
266            };
267            let exit = abandon_candidate(
268                module_id,
269                registry,
270                &forwarding,
271                runtime,
272                candidate,
273                Some(&failure),
274            )
275            .await;
276            let _ = reply.send(Err(failure.into_error(module_id, exit)));
277            // Stop/disable/hold must take effect before retained restart
278            // commands; the actor then discards restarts for the stopped child.
279            if let Some(command) = command {
280                end.requeue.insert(0, command);
281            }
282            return;
283        }
284        Warm::Failed(failure) => {
285            let exit = abandon_candidate(
286                module_id,
287                registry,
288                &forwarding,
289                runtime,
290                candidate,
291                Some(&failure),
292            )
293            .await;
294            let _ = reply.send(Err(failure.into_error(module_id, exit)));
295            return;
296        }
297    };
298
299    if let Err(failure) = probe_candidate(
300        module_id,
301        runtime,
302        registry,
303        &forwarding,
304        config_deadline,
305        candidate_connection,
306    )
307    .await
308    {
309        let exit = abandon_candidate(
310            module_id,
311            registry,
312            &forwarding,
313            runtime,
314            candidate,
315            Some(&failure),
316        )
317        .await;
318        let _ = reply.send(Err(failure.into_error(module_id, exit)));
319        return;
320    }
321
322    let config_owner = runtime
323        .config_delivery
324        .as_ref()
325        .map(|delivery| delivery.0.clone());
326    let config_gate = match &config_owner {
327        Some(owner) => match owner.module_gate(module_id) {
328            Ok(gate) => Some(gate),
329            Err(error) => {
330                let failure = CandidateFailure {
331                    arm: SwapFailureArm::CandidateUnhealthy,
332                    detail: format!("config_gated: {error}"),
333                    exit: None,
334                    connection: Some(candidate_connection),
335                };
336                let exit = abandon_candidate(
337                    module_id,
338                    registry,
339                    &forwarding,
340                    runtime,
341                    candidate,
342                    Some(&failure),
343                )
344                .await;
345                let _ = reply.send(Err(failure.into_error(module_id, exit)));
346                return;
347            }
348        },
349        None => None,
350    };
351    let config_opted_in = registry
352        .registration(RegistrationSlot::Connection(candidate_connection))
353        .ok()
354        .flatten()
355        .is_some_and(|registration| {
356            registration
357                .control_ops
358                .iter()
359                .any(|op| op == "config.review")
360        });
361    let mut cutover_deadline = None;
362    let mut candidate_exit = None;
363    let (forwarding_cutover, promoted) = loop {
364        let attempt = if cutover_deadline.is_some_and(|deadline| Instant::now() >= deadline) {
365            Err(CutoverDeferred::DeadlineExceeded)
366        } else {
367            try_config_cutover(
368                module_id,
369                config_owner.as_ref(),
370                config_gate.as_ref(),
371                config_opted_in,
372                candidate.config_delivery.as_ref(),
373                candidate_connection,
374                registry,
375                &forwarding,
376            )
377        };
378        match attempt {
379            Ok(cutover) => break cutover,
380            Err(CutoverDeferred::Busy) => {
381                let deadline =
382                    *cutover_deadline.get_or_insert_with(|| Instant::now() + SWAP_CUTOVER_DEADLINE);
383                let retry = tokio::select! {
384                    ready=wait_for_config_gate(runtime,module_id,commands,end,Some(deadline))=>ready,
385                    status=candidate.wait()=>{
386                        candidate_exit = Some(swap_terminal::observed_exit(module_id, status));
387                        false
388                    },
389                    _=async {match child.as_mut() {Some(incumbent)=>{let _=incumbent.wait().await;},None=>std::future::pending::<()>().await}}=>false,
390                };
391                if retry || Instant::now() >= deadline {
392                    continue;
393                }
394                let failure = CandidateFailure {
395                    arm: SwapFailureArm::Interrupted,
396                    detail: "swap interrupted before configuration cutover".into(),
397                    exit: candidate_exit.take(),
398                    connection: Some(candidate_connection),
399                };
400                let exit = abandon_candidate(
401                    module_id,
402                    registry,
403                    &forwarding,
404                    runtime,
405                    candidate,
406                    Some(&failure),
407                )
408                .await;
409                let _ = reply.send(Err(failure.into_error(module_id, exit)));
410                return;
411            }
412            Err(CutoverDeferred::NewGeneration(generation)) => {
413                abandon_candidate(module_id, registry, &forwarding, runtime, candidate, None).await;
414                update_snapshot(snapshot, Some(module_id), |state| {
415                    state.swap_outcome = Some(SwapOutcome::SupersededByConfigRestart)
416                })
417                .ok();
418                end.requeue.push(SupervisorCommand::ConfigApplyRestart {
419                    generation,
420                    supersedes_swap: true,
421                });
422                let _ = reply.send(Ok(SwapOutcome::SupersededByConfigRestart));
423                return;
424            }
425            Err(failed) => {
426                let restart = matches!(failed, CutoverDeferred::RegistryLost);
427                let failure = CandidateFailure {
428                    arm: if matches!(failed, CutoverDeferred::Refused(_)) {
429                        SwapFailureArm::CandidateUnhealthy
430                    } else {
431                        SwapFailureArm::CutoverLost
432                    },
433                    detail: match failed {
434                        CutoverDeferred::DeadlineExceeded => {
435                            "configuration cutover deadline expired while the gate was busy".into()
436                        }
437                        CutoverDeferred::Refused(error) => format!("config_gated: {error}"),
438                        CutoverDeferred::RegistryLost => {
439                            "the candidate registration closed during cutover; restarting plainly"
440                                .into()
441                        }
442                        _ => "the candidate connection closed just before cutover".into(),
443                    },
444                    exit: candidate_exit.take(),
445                    connection: Some(candidate_connection),
446                };
447                let exit = abandon_candidate(
448                    module_id,
449                    registry,
450                    &forwarding,
451                    runtime,
452                    candidate,
453                    Some(&failure),
454                )
455                .await;
456                let _ = reply.send(Err(failure.into_error(module_id, exit)));
457                if restart {
458                    if let Err(error) = restart_child(
459                        spec,
460                        runtime,
461                        registry,
462                        process_liveness,
463                        snapshot,
464                        child,
465                        runtime.drain_timeout,
466                    )
467                    .await
468                    {
469                        warn!(module_id,%error,"plain restart after a lost swap cutover failed");
470                        fail_snapshot(snapshot, Some(module_id), None, &FailureContext::operator());
471                    }
472                }
473                return;
474            }
475        }
476    };
477
478    // The candidate is the module now: its nonce is the module's nonce, the
479    // control plane's capability state is recomputed from its manifest (its
480    // HELLO skipped that, not being routable then), and the snapshot describes
481    // its process.
482    handle.promote_swap_nonce(module_id, spec.reserved);
483    handle.notify_swap_promoted(&promoted);
484    let incumbent_generation = lock_snapshot(snapshot)
485        .map(|state| state.spawn_generation)
486        .unwrap_or(0);
487    let activity_spawn = runtime.begin_activity_spawn(module_id);
488    if let Err(err) = set_running(snapshot, &candidate, module_id, &runtime.spawn_events) {
489        error!(module_id, error = %err, "failed to record the promoted swap candidate");
490    }
491    let _ = update_snapshot(snapshot, Some(module_id), |state| {
492        state.in_alternate_slot = candidate_alternate;
493    });
494    if let Some(spawn) = activity_spawn {
495        spawn.complete(snapshot);
496    }
497    handle.record_activity_registration(module_id);
498    process_liveness.track(module_id.to_string(), Arc::clone(snapshot));
499    runtime.record_activity_transition(
500        "subc.module_swapped",
501        module_id,
502        runtime.start_requester.clone(),
503    );
504    let incumbent = child.replace(candidate);
505    info!(
506        module_id,
507        promoted_connection_id = candidate_connection.get(),
508        superseded_connection_id = incumbent_connection.get(),
509        "swap cut over; new routes land on the promoted candidate, draining the incumbent"
510    );
511    update_snapshot(snapshot, Some(module_id), |state| {
512        state.swap_outcome = Some(SwapOutcome::Cutover)
513    })
514    .ok();
515    let _ = reply.send(Ok(SwapOutcome::Cutover));
516
517    dispatch_retirement(
518        spec,
519        runtime,
520        registry,
521        &forwarding,
522        snapshot,
523        incumbent,
524        forwarding_cutover.incumbent,
525        incumbent_connection,
526        incumbent_generation,
527    )
528    .await;
529}
530
531#[allow(clippy::too_many_arguments)]
532async fn dispatch_retirement(
533    spec: &ModuleSpec,
534    runtime: &SupervisorRuntimeConfig,
535    registry: &Arc<Registry>,
536    forwarding: &Arc<ForwardingTable>,
537    snapshot: &SharedSnapshot,
538    incumbent: Option<SupervisedChild>,
539    incumbent_endpoint: Option<crate::ModuleEndpointId>,
540    incumbent_connection: ConnectionId,
541    incumbent_generation: u64,
542) {
543    let spec = spec.clone();
544    let runtime = runtime.clone();
545    let registry = Arc::clone(registry);
546    let forwarding = Arc::clone(forwarding);
547    let snapshot = Arc::clone(snapshot);
548    // The promoted process must return to its supervision loop at cutover.
549    // Keep the swap open until the old process is reaped so another swap
550    // cannot reuse its slot or discard its consumer attestation nonce.
551    tokio::spawn(async move {
552        retire_incumbent(
553            &spec,
554            &runtime,
555            &registry,
556            &forwarding,
557            &snapshot,
558            incumbent,
559            incumbent_endpoint,
560            incumbent_connection,
561            incumbent_generation,
562        )
563        .await;
564        if let Some(handle) = &runtime.supervisor_handle {
565            handle.close_swap(&spec.module_id);
566        }
567    });
568}
569
570enum CutoverDeferred {
571    Busy,
572    DeadlineExceeded,
573    NewGeneration(u64),
574    Refused(crate::config_gate::GateError),
575    ForwardingLost,
576    RegistryLost,
577}
578
579/// Publish forwarding first, registry second and the config ACK target last.
580/// Both configuration guards are acquired without waiting, and only verified
581/// in-memory bytes are read until both guards have been released.
582#[allow(clippy::too_many_arguments)]
583fn try_config_cutover(
584    module: &str,
585    owner: Option<&Arc<crate::config_gate::runtime::RuntimeOwner>>,
586    gate: Option<&Arc<tokio::sync::Mutex<()>>>,
587    opted_in: bool,
588    spawn: Option<&crate::config_gate::runtime::DeliverySpawn>,
589    connection: ConnectionId,
590    registry: &Registry,
591    forwarding: &ForwardingTable,
592) -> Result<
593    (
594        crate::forwarding::ForwardingCutover,
595        crate::registry::ModuleRegistration,
596    ),
597    CutoverDeferred,
598> {
599    let _gate = gate
600        .map(|gate| {
601            gate.clone()
602                .try_lock_owned()
603                .map_err(|_| CutoverDeferred::Busy)
604        })
605        .transpose()?;
606    if let Some(owner) = owner {
607        owner.check_module_hold(module).map_err(|error| {
608            if error.code == "config_delivery_deferred" {
609                CutoverDeferred::Busy
610            } else {
611                CutoverDeferred::Refused(error)
612            }
613        })?;
614    }
615    let mut configuration = if let Some(owner) = owner.filter(|_| opted_in) {
616        #[cfg(test)]
617        owner
618            .swap_preflight_attempts
619            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
620        Some(
621            owner
622                .try_swap_configuration()
623                .map_err(|_| CutoverDeferred::Busy)?,
624        )
625    } else {
626        None
627    };
628    if let Some(configuration) = &mut configuration {
629        if let Some(generation) = configuration
630            .before_cutover(module, connection, spawn)
631            .map_err(CutoverDeferred::Refused)?
632        {
633            return Err(CutoverDeferred::NewGeneration(generation));
634        }
635    }
636    let forwarded = forwarding
637        .cutover_candidate(module)
638        .ok()
639        .flatten()
640        .ok_or(CutoverDeferred::ForwardingLost)?;
641    #[cfg(feature = "test-support")]
642    if let Some(owner) = owner {
643        if let Err(error) = owner.pause_swap_before_promotion() {
644            warn!(module,%error,"swap promotion test pause failed");
645        }
646    }
647    let promoted = registry
648        .promote_candidate(module)
649        .ok()
650        .flatten()
651        .ok_or(CutoverDeferred::RegistryLost)?
652        .promoted;
653    if let Some(configuration) = &mut configuration {
654        if let Err(error) = configuration.promoted(module, connection, Instant::now()) {
655            warn!(module,%error,"promoted configuration target is gated");
656        }
657    }
658    drop(configuration);
659    if let Some(owner) = owner {
660        owner.notify_delivery_changed();
661    }
662    Ok((forwarded, promoted))
663}
664
665async fn wait_for_config_gate(
666    runtime: &SupervisorRuntimeConfig,
667    module: &str,
668    commands: &mut mpsc::Receiver<SupervisorCommand>,
669    end: &mut SwapEnd,
670    deadline: Option<Instant>,
671) -> bool {
672    let expired = async {
673        match deadline {
674            Some(deadline) => tokio::time::sleep_until(deadline).await,
675            None => std::future::pending::<()>().await,
676        }
677    };
678    tokio::pin!(expired);
679    let backoff = tokio::time::sleep(CONFIG_ADMISSION_RETRY_DELAY);
680    tokio::pin!(backoff);
681    loop {
682        tokio::select! {
683            _=&mut expired=>return false,
684            _=&mut backoff=>break,
685            command=commands.recv()=>{
686                let Some(command)=command else {return false;};
687                if let Some(interrupt)=serve_command_while_warming(module,command,end,runtime.config_delivery.as_ref().is_some_and(|delivery|delivery.0.module_is_gated(module))) {end.requeue.push(interrupt);return false;}
688            }
689        }
690    }
691    let Some(delivery) = &runtime.config_delivery else {
692        return true;
693    };
694    let Ok(gate) = delivery.0.module_gate(module) else {
695        return false;
696    };
697    loop {
698        tokio::select! {
699            _=&mut expired=>return false,
700            guard = gate.lock() => { drop(guard); return true; }
701            command = commands.recv() => {
702                let Some(command) = command else { return false; };
703                if let Some(interrupt) = serve_command_while_warming(module, command, end,runtime.config_delivery.as_ref().is_some_and(|delivery|delivery.0.module_is_gated(module))) {
704                    end.requeue.push(interrupt);
705                    return false;
706                }
707            }
708        }
709    }
710}
711
712/// Answer non-interrupting commands while a swap waits, or return a stop,
713/// disable, retire, configuration restart or configuration hold command for
714/// the module loop to apply.
715/// Live file updates cannot replace the configuration saved by operator approval.
716fn serve_command_while_warming(
717    module_id: &str,
718    command: SupervisorCommand,
719    end: &mut SwapEnd,
720    gated: bool,
721) -> Option<SupervisorCommand> {
722    let in_progress = || SuperviseError::SwapInProgress {
723        module_id: module_id.to_string(),
724    };
725    match command {
726        SupervisorCommand::ConfigPolicyProbe { .. } => {
727            end.requeue.push(command);
728            None
729        }
730        SupervisorCommand::ConfigApplyRestart { .. } => Some(command),
731        SupervisorCommand::Drain { .. }
732        | SupervisorCommand::ApprovedConfiguration { .. }
733        | SupervisorCommand::ConfigExitHold { .. }
734        | SupervisorCommand::ConfigDeliveryFailed { .. }
735        | SupervisorCommand::Retire { .. }
736        | SupervisorCommand::SetEnabled { enabled: false, .. } => Some(command),
737        SupervisorCommand::SetEnabled {
738            enabled: true,
739            reply,
740            ..
741        } => {
742            let _ = reply.send(Ok(false));
743            None
744        }
745        SupervisorCommand::Restart { reply, .. } | SupervisorCommand::Reload { reply, .. } => {
746            let _ = reply.send(Err(in_progress()));
747            None
748        }
749        SupervisorCommand::Swap { reply, .. } => {
750            let _ = reply.send(Err(SuperviseError::SwapRefused {
751                module_id: module_id.to_string(),
752                reason: SwapRefusal::AlreadySwapping,
753            }));
754            None
755        }
756        SupervisorCommand::UpdateConfiguration { reply, .. } if gated => {
757            let _ = reply.send(Err(SuperviseError::ConfigHeld {
758                module_id: module_id.into(),
759                code: "config_gated".into(),
760                detail: "live file reconfiguration cannot replace stamped authority".into(),
761            }));
762            None
763        }
764        SupervisorCommand::UpdateConfiguration {
765            spec,
766            health,
767            drain_timeout_ms,
768            reply,
769        } => {
770            let _ = reply.send(Ok(()));
771            // The caller has its answer; the replayed command's reply channel
772            // has no receiver and is only there to fit the command's shape.
773            let (unanswered, _) = oneshot::channel();
774            end.requeue.push(SupervisorCommand::UpdateConfiguration {
775                spec,
776                health,
777                drain_timeout_ms,
778                reply: unanswered,
779            });
780            None
781        }
782    }
783}
784
785/// Every check a swap makes before spawning anything. Returns the forwarding
786/// table, the shared handle, and the incumbent's connection.
787fn admit_swap(
788    spec: &ModuleSpec,
789    runtime: &SupervisorRuntimeConfig,
790    registry: &Registry,
791    snapshot: &SharedSnapshot,
792    child: &Option<SupervisedChild>,
793) -> Result<(Arc<ForwardingTable>, SupervisorHandle, ConnectionId), SuperviseError> {
794    let module_id = spec.module_id.as_str();
795    let refuse = |reason| SuperviseError::SwapRefused {
796        module_id: module_id.to_string(),
797        reason,
798    };
799    // First, and unconditionally: a module that has not declared it tolerates
800    // a second process of itself is never given one.
801    if spec.overlap != ModuleOverlap::Safe {
802        return Err(refuse(SwapRefusal::OverlapExclusive));
803    }
804    if !lock_snapshot(snapshot)?.enabled {
805        return Err(SuperviseError::Disabled {
806            module_id: module_id.to_string(),
807        });
808    }
809    if spec.protocol == ModuleProtocol::None {
810        return Err(refuse(SwapRefusal::ProtocolNone));
811    }
812    let (Some(forwarding), Some(handle)) = (
813        runtime.forwarding.clone(),
814        runtime.supervisor_handle.clone(),
815    ) else {
816        return Err(refuse(SwapRefusal::NotConfigured));
817    };
818    if handle.swap_open(module_id) {
819        return Err(refuse(SwapRefusal::AlreadySwapping));
820    }
821    let registration = registry
822        .get_module(module_id)
823        .map_err(SuperviseError::Registry)?;
824    let (Some(registration), true) = (registration, child.is_some()) else {
825        return Err(refuse(SwapRefusal::NotRegistered));
826    };
827    Ok((forwarding, handle, registration.connection_id))
828}
829
830/// Wait for the candidate to register and declare itself ready, or to fail.
831///
832/// Readiness is read from the candidate's own registration, which its
833/// `catalog.update(ready: true)` updates through its connection (the registry
834/// searches every slot by connection for exactly this). Nothing here goes
835/// through a by-id lookup, all of which resolve the incumbent.
836///
837/// The module's commands are served meanwhile; see
838/// [`serve_command_while_warming`].
839#[allow(clippy::too_many_arguments)]
840async fn warm_candidate(
841    module_id: &str,
842    registry: &Registry,
843    candidate: &mut SupervisedChild,
844    incumbent_connection: ConnectionId,
845    ready_timeout: Duration,
846    config_deadline: Option<Instant>,
847    config_delivery: Option<&super::config_delivery::ConfigDelivery>,
848    commands: &mut mpsc::Receiver<SupervisorCommand>,
849    end: &mut SwapEnd,
850) -> Warm {
851    let requeue_start = end.requeue.len();
852    let outcome = warm_candidate_until_outcome(
853        module_id,
854        registry,
855        candidate,
856        incumbent_connection,
857        ready_timeout,
858        config_deadline,
859        config_delivery,
860        commands,
861        end,
862    )
863    .await;
864    if matches!(outcome, Warm::Superseded { .. }) {
865        // The superseded branch queues its freshly checked generation instead.
866        // Downstream revalidation would discard a stale duplicate anyway, so
867        // filtering prevents a redundant command rather than a second launch.
868        let deferred = end.requeue.split_off(requeue_start);
869        end.requeue.extend(
870            deferred
871                .into_iter()
872                .filter(|command| !matches!(command, SupervisorCommand::ConfigApplyRestart { .. })),
873        );
874    }
875    outcome
876}
877
878/// The warm-up loop proper. Every return path leaves any configuration
879/// restart it consumed in `end.requeue`; [`warm_candidate`] drops those again
880/// when the outcome is `Superseded`, whose caller queues a fresher generation.
881#[allow(clippy::too_many_arguments)]
882async fn warm_candidate_until_outcome(
883    module_id: &str,
884    registry: &Registry,
885    candidate: &mut SupervisedChild,
886    incumbent_connection: ConnectionId,
887    ready_timeout: Duration,
888    config_deadline: Option<Instant>,
889    config_delivery: Option<&super::config_delivery::ConfigDelivery>,
890    commands: &mut mpsc::Receiver<SupervisorCommand>,
891    end: &mut SwapEnd,
892) -> Warm {
893    let mut deadline = Instant::now() + ready_timeout;
894    let mut registered: Option<ConnectionId> = None;
895    let mut config_restart_pending = false;
896    let mut next_config_check = Instant::now();
897    loop {
898        if config_restart_pending && Instant::now() >= next_config_check {
899            if let Some(delivery) = config_delivery {
900                match delivery
901                    .0
902                    .try_requires_fresher_spawn(module_id, candidate.config_delivery.as_ref())
903                {
904                    Ok(Some(generation)) => return Warm::Superseded { generation },
905                    Ok(None) => config_restart_pending = false,
906                    Err(_) => {
907                        #[cfg(test)]
908                        if let Some(reached) = delivery.0.warm_restart_busy.lock().unwrap().take() {
909                            let _ = reached.send(());
910                        }
911                        next_config_check = Instant::now() + CONFIG_ADMISSION_RETRY_DELAY;
912                    }
913                }
914            } else {
915                config_restart_pending = false;
916            }
917        }
918        // Before the candidate registers, the candidate slot is the only
919        // place to look for it; once it has, its connection names it exactly.
920        let slot = match registered {
921            Some(connection) => RegistrationSlot::Connection(connection),
922            None => RegistrationSlot::Candidate(module_id),
923        };
924        // Only a published candidate counts as registered. A candidate's HELLO
925        // reserves its registry entry before installing its forwarding
926        // endpoint and publishes it after; a ready candidate seen in between
927        // would be promoted while the forwarding cutover still finds no
928        // candidate endpoint, and the swap would fail as if the candidate's
929        // connection had closed.
930        match registry.published_registration(slot) {
931            Ok(Some(registration)) => {
932                registered = Some(registration.connection_id);
933                if registration
934                    .control_ops
935                    .iter()
936                    .any(|op| op == "config.review")
937                {
938                    if let Some(cap) = config_deadline {
939                        deadline = deadline.min(cap);
940                        if Instant::now() >= cap {
941                            return Warm::Failed(CandidateFailure {
942                                arm:SwapFailureArm::NeverReady,
943                                detail:"config_gated: candidate configuration warm-up deadline expired before readiness".into(),
944                                exit:None, connection:registered,
945                            });
946                        }
947                    }
948                }
949                if registration.ready {
950                    return Warm::Ready(registration.connection_id);
951                }
952                // The incumbent died while the candidate warmed. The candidate
953                // is now the only process, so waiting for it to finish warming
954                // serves nobody: promote it, and callers get `module_warming`
955                // until it declares itself ready, as on a plain restart.
956                if matches!(
957                    registry.registration(RegistrationSlot::Connection(incumbent_connection)),
958                    Ok(None)
959                ) {
960                    warn!(
961                        module_id,
962                        "incumbent went away while the swap candidate warmed; promoting the candidate before it is ready"
963                    );
964                    return Warm::Ready(registration.connection_id);
965                }
966            }
967            Ok(None) if registered.is_some() => {
968                // It registered and then its registration went away: its
969                // connection closed. Its exit is reaped below or next poll.
970            }
971            Ok(None) => {}
972            Err(err) => {
973                return Warm::Failed(CandidateFailure {
974                    arm: if registered.is_some() {
975                        SwapFailureArm::NeverReady
976                    } else {
977                        SwapFailureArm::NeverRegistered
978                    },
979                    detail: format!("could not read the candidate's registration: {err}"),
980                    exit: None,
981                    connection: registered,
982                });
983            }
984        }
985
986        let now = Instant::now();
987        if now >= deadline {
988            let (arm, detail) = match registered {
989                Some(_) => (
990                    SwapFailureArm::NeverReady,
991                    format!("the candidate registered but did not declare itself ready within {ready_timeout:?}"),
992                ),
993                None => (
994                    SwapFailureArm::NeverRegistered,
995                    format!("the candidate did not register within {ready_timeout:?}"),
996                ),
997            };
998            return Warm::Failed(CandidateFailure {
999                arm,
1000                detail,
1001                exit: None,
1002                connection: registered,
1003            });
1004        }
1005        let poll = deadline
1006            .saturating_duration_since(now)
1007            .min(REGISTRY_RELEASE_POLL);
1008        tokio::select! {
1009            status = candidate.wait() => {
1010                // Classified on its own: the module snapshot's severance marker
1011                // belongs to the incumbent and must not be consumed here.
1012                let exit = swap_terminal::observed_exit(module_id, status);
1013                return Warm::Failed(CandidateFailure {
1014                    arm: SwapFailureArm::CandidateExited,
1015                    detail: candidate.spawn_failure.clone().unwrap_or_else(|| format!(
1016                        "the candidate exited before it was ready (code {:?}, signal {:?})",
1017                        exit.code, exit.signal
1018                    )),
1019                    exit: Some(exit),
1020                    connection: registered,
1021                });
1022            }
1023            command = commands.recv() => {
1024                // A closed channel means the module handle is gone; the loop
1025                // will see the same and stop, so abandon the candidate first.
1026                let Some(command) = command else {
1027                    return Warm::Interrupted { command: None, connection: registered };
1028                };
1029                if matches!(command, SupervisorCommand::ConfigApplyRestart { .. }) {
1030                    // The coordinator sends each generation only once. Keep
1031                    // the command even if readiness, exit or timeout wins the
1032                    // race with the nonblocking freshness recheck. The actor
1033                    // revalidates it against the current spawn before acting.
1034                    end.requeue.push(command);
1035                    #[cfg(test)]
1036                    if let Some(delivery) = config_delivery {
1037                        let pause = delivery.0.warm_restart_pause.lock().unwrap().take();
1038                        if let Some(pause) = pause {
1039                            let _ = pause.reached.send(());
1040                            let _ = pause.resume.await;
1041                        }
1042                    }
1043                    config_restart_pending = true;
1044                    next_config_check = Instant::now();
1045                    continue;
1046                }
1047                if let Some(command) = serve_command_while_warming(module_id, command, end,config_delivery.is_some_and(|delivery|delivery.0.module_is_gated(module_id))) {
1048                    return Warm::Interrupted { command: Some(command), connection: registered };
1049                }
1050            }
1051            _ = sleep(poll) => {}
1052        }
1053    }
1054}
1055
1056fn config_candidate_deadline(
1057    runtime: &SupervisorRuntimeConfig,
1058    candidate: &SupervisedChild,
1059) -> Option<Instant> {
1060    runtime.config_delivery.as_ref().map(|_| {
1061        candidate.spawned_at
1062            + runtime.register_timeout
1063            + runtime.health.deadline
1064            + crate::config_gate::runtime::delivery::CONFIG_WARMUP_SLACK
1065    })
1066}
1067
1068/// Probe a ready candidate once, by endpoint, before promoting it.
1069///
1070/// The same `health.check` the supervisor probes every module with, sent only
1071/// when the candidate advertises it. A `failing` answer or no usable answer
1072/// fails the swap. A configuration-delivery candidate must answer healthy;
1073/// otherwise the existing non-config swap policy also accepts degraded service.
1074/// Like every other swap failure it spends no crash-restart budget: the
1075/// budget is the incumbent's, and the incumbent did nothing.
1076async fn probe_candidate(
1077    module_id: &str,
1078    runtime: &SupervisorRuntimeConfig,
1079    registry: &Registry,
1080    forwarding: &ForwardingTable,
1081    config_deadline: Option<Instant>,
1082    candidate_connection: ConnectionId,
1083) -> Result<(), CandidateFailure> {
1084    let unhealthy = |detail: String| CandidateFailure {
1085        arm: SwapFailureArm::CandidateUnhealthy,
1086        detail,
1087        exit: None,
1088        connection: Some(candidate_connection),
1089    };
1090    let registration = registry
1091        .registration(RegistrationSlot::Connection(candidate_connection))
1092        .ok()
1093        .flatten();
1094    let config_owned = runtime.config_delivery.is_some()
1095        && registration.as_ref().is_some_and(|registration| {
1096            registration
1097                .control_ops
1098                .iter()
1099                .any(|op| op == "config.review")
1100        });
1101    let advertises_health = registration.as_ref().is_some_and(|registration| {
1102        registration
1103            .control_ops
1104            .iter()
1105            .any(|op| op == MODULE_CONTROL_OP_HEALTH_CHECK)
1106    });
1107    if !advertises_health {
1108        if config_owned {
1109            return Err(unhealthy(
1110                "config_gated: configuration readiness requires the first healthy probe".into(),
1111            ));
1112        }
1113        return Ok(());
1114    }
1115    let Some(endpoint) = forwarding
1116        .module_endpoint_for_connection(candidate_connection)
1117        .ok()
1118        .flatten()
1119    else {
1120        return Err(unhealthy(
1121            "the candidate's connection closed before its health probe".to_string(),
1122        ));
1123    };
1124    let deadline_cap = config_owned.then_some(config_deadline).flatten();
1125    match probe_endpoint_health(endpoint, runtime, deadline_cap).await {
1126        Ok(_) if deadline_cap.is_some_and(|cap| Instant::now() >= cap) => Err(unhealthy(
1127            "config_gated: candidate configuration warm-up deadline expired before its first healthy probe finished".into())),
1128        Ok(report) if config_owned && report.status != HealthStatus::Ok => Err(unhealthy(
1129            "config_gated: configuration readiness requires a healthy, not degraded or failing, probe".into())),
1130        Ok(report) if report.status == HealthStatus::Failing => Err(unhealthy(format!(
1131            "the candidate answered its health probe with status failing{}",
1132            report
1133                .detail
1134                .map(|detail| format!(": {detail}"))
1135                .unwrap_or_default()
1136        ))),
1137        Ok(_) => Ok(()),
1138        Err(err) => {
1139            debug!(module_id, error = %err, "swap candidate health probe failed");
1140            Err(unhealthy(format!(
1141                "the candidate's health probe failed: {err}"
1142            )))
1143        }
1144    }
1145}
1146
1147/// Kill a failed candidate and free exactly its slot.
1148///
1149/// This is the candidate's own reap path. The ordinary one classifies an exit
1150/// into the module's snapshot and then asks the crash budget for a respawn;
1151/// either would be wrong here, because the snapshot and the budget are the
1152/// incumbent's and the incumbent is still serving. So this kills and reaps
1153/// only the candidate, waits only for the candidate's registration (by its
1154/// connection, or by the candidate slot if it never registered) to go, and
1155/// closes the swap, which releases only the candidate's nonce.
1156async fn abandon_candidate(
1157    module_id: &str,
1158    registry: &Registry,
1159    forwarding: &ForwardingTable,
1160    runtime: &SupervisorRuntimeConfig,
1161    mut candidate: SupervisedChild,
1162    failure: Option<&CandidateFailure>,
1163) -> ExitReport {
1164    candidate.retire_registration();
1165    if let Some(failure) = failure {
1166        warn!(module_id, arm=failure.arm.as_str(), detail=%failure.detail, candidate_pid=candidate.pid,
1167            "swap failed; killing the candidate and leaving the incumbent serving");
1168    } else {
1169        info!(
1170            module_id,
1171            candidate_pid = candidate.pid,
1172            outcome = SwapOutcome::SupersededByConfigRestart.as_str(),
1173            "swap superseded by approved configuration restart; leaving the incumbent serving"
1174        );
1175    }
1176    let exit = swap_terminal::abandoned_exit(module_id, &mut candidate, failure).await;
1177    candidate.drain_stderr(module_id).await;
1178    swap_terminal::record_abandonment(module_id, runtime, &exit, failure);
1179    if let Err(error) = candidate.finish_exit(false).await {
1180        warn!(module_id, %error, "could not finalize the abandoned swap candidate");
1181    }
1182
1183    let slot = match failure.and_then(|failure| failure.connection) {
1184        Some(connection) => RegistrationSlot::Connection(connection),
1185        None => RegistrationSlot::Candidate(module_id),
1186    };
1187    if let Err(err) =
1188        wait_for_slot_registration_release(registry, slot, REGISTRY_RELEASE_TIMEOUT).await
1189    {
1190        // The process is dead, so its connection is on its way down; if the
1191        // registration outlived the wait, close the connection outright so the
1192        // candidate slot is free for the next swap.
1193        warn!(module_id, error = %err, "abandoned swap candidate is still registered; closing its connection");
1194        if let Some(connection) = failure.and_then(|failure| failure.connection).or_else(|| {
1195            registry
1196                .get_candidate(module_id)
1197                .ok()
1198                .flatten()
1199                .map(|registration| registration.connection_id)
1200        }) {
1201            forwarding.request_connection_close(
1202                connection,
1203                CloseReason::new(
1204                    "swap_candidate_abandoned",
1205                    format!("swap of module '{module_id}' ended; closing its candidate"),
1206                ),
1207            );
1208        }
1209    }
1210    if let Some(handle) = &runtime.supervisor_handle {
1211        handle.close_swap(module_id);
1212    }
1213    exit
1214}
1215
1216/// Drain and reap the incumbent a swap has just replaced.
1217///
1218/// The drain is the plain restart's drain (route.closing, quiescence,
1219/// route.closed, per-route GOODBYE, module GOODBYE) with reason `Restart`, so
1220/// deployed SDKs keep treating it as may-reopen, but addressed to the
1221/// incumbent's endpoint rather than the module id, which now resolves to the
1222/// promoted candidate. The incumbent's release is awaited by its connection,
1223/// since the id's active registration is the candidate's and never goes away.
1224/// The module's state is not touched: it describes the promoted candidate.
1225#[allow(clippy::too_many_arguments)]
1226pub(super) async fn retire_incumbent(
1227    spec: &ModuleSpec,
1228    runtime: &SupervisorRuntimeConfig,
1229    registry: &Registry,
1230    forwarding: &ForwardingTable,
1231    snapshot: &SharedSnapshot,
1232    incumbent: Option<SupervisedChild>,
1233    incumbent_endpoint: Option<crate::ModuleEndpointId>,
1234    incumbent_connection: ConnectionId,
1235    incumbent_generation: u64,
1236) {
1237    let module_id = spec.module_id.as_str();
1238    let mut incumbent = incumbent;
1239    let mut observed_exit = None;
1240    let stop_notice = if let Some(endpoint) = incumbent_endpoint {
1241        let drain = begin_forwarding_drain_with(
1242            forwarding,
1243            ForwardingDrainContext {
1244                spec,
1245                runtime,
1246                registry,
1247                scope: DrainScope::Endpoint(endpoint),
1248            },
1249            snapshot,
1250            None,
1251            RouteCloseReason::Restart,
1252            runtime.drain_timeout,
1253        );
1254        let result = if let Some(child) = incumbent.as_mut() {
1255            tokio::select! {
1256                status = child.wait() => {
1257                    observed_exit = Some(status);
1258                    Ok(StopNotice::NotSent)
1259                }
1260                result = drain => result,
1261            }
1262        } else {
1263            drain.await
1264        };
1265        result.unwrap_or_else(|err| {
1266            warn!(module_id, error = %err, "draining the swapped-out incumbent failed; stopping it anyway");
1267            StopNotice::NotSent
1268        })
1269    } else {
1270        StopNotice::NoConnection
1271    };
1272
1273    let Some(mut incumbent) = incumbent else {
1274        return;
1275    };
1276    // Cutover already revoked authority. Keep the transport for in-flight
1277    // replies and drain notices until its bounded GOODBYE flush completes.
1278    incumbent.retire_registration();
1279    if observed_exit.is_none() && stop_notice != StopNotice::SentOverConnection {
1280        request_graceful_stop(module_id, &incumbent);
1281    }
1282    // The module GOODBYE above asks the incumbent to exit; give it the same
1283    // budget a plain restart gives the child it drains, then kill it.
1284    let status = match observed_exit {
1285        Some(status) => status,
1286        None => match timeout(
1287            incumbent.group_drain_budget(runtime.drain_timeout, stop_notice),
1288            incumbent.wait(),
1289        )
1290        .await
1291        {
1292            Ok(status) => status,
1293            Err(_) => {
1294                warn!(
1295                    module_id,
1296                    pid = incumbent.pid,
1297                    budget_ms =
1298                        u64::try_from(runtime.drain_timeout.as_millis()).unwrap_or(u64::MAX),
1299                    reason = "swapped-out incumbent",
1300                    "drain budget expired before the module exited; killing it"
1301                );
1302                if let Err(err) = incumbent.start_kill() {
1303                    debug!(module_id, error = %err, "swapped-out incumbent kill failed; it may already have exited");
1304                }
1305                incumbent.wait().await
1306            }
1307        },
1308    };
1309    let exit_report = match status {
1310        Ok(status) => classify_exit(&status),
1311        Err(err) => {
1312            warn!(module_id, error = %err, "could not reap the swapped-out incumbent");
1313            wait_error_exit_report()
1314        }
1315    };
1316    incumbent.drain_stderr(module_id).await;
1317    runtime.spawn_events.emit_superseded_exited(
1318        module_id,
1319        incumbent_generation,
1320        incumbent.pid,
1321        exit_report.code,
1322        exit_report.signal,
1323    );
1324    {
1325        let record = TerminalRecord {
1326            exit_code: exit_report.code,
1327            exit_signal: exit_report.signal,
1328            at_ms: exit_report.at_ms,
1329            disposition: TerminalDisposition::Restarting,
1330            exit_kind: exit_report.kind.into(),
1331            disposition_detail: incumbent
1332                .exit_cleanup_detail(Some("replaced by a blue/green swap".into())),
1333        };
1334        // Recorded as `daemon_shutdown` instead if the daemon has begun
1335        // shutting down (see `TerminalRing::record_exit`).
1336        runtime
1337            .terminal_ring
1338            .lock()
1339            .unwrap_or_else(|poisoned| poisoned.into_inner())
1340            .record_exit(module_id, record);
1341    }
1342    // Shutdown waits for the roster to empty before flushing the journal.
1343    // Enqueue the record before releasing this roster entry.
1344    if let Err(error) = incumbent.finish_exit(false).await {
1345        warn!(module_id, %error, "could not finalize the swapped-out incumbent");
1346    }
1347    if let Err(err) = wait_for_slot_registration_release(
1348        registry,
1349        RegistrationSlot::Connection(incumbent_connection),
1350        REGISTRY_RELEASE_TIMEOUT,
1351    )
1352    .await
1353    {
1354        warn!(module_id, error = %err, "swapped-out incumbent's registration outlived its process");
1355    }
1356    info!(
1357        module_id,
1358        exit_code = ?exit_report.code,
1359        exit_signal = ?exit_report.signal,
1360        "swapped-out incumbent drained and exited; swap complete"
1361    );
1362}
1363
1364#[cfg(test)]
1365mod tests {
1366    use super::*;
1367
1368    #[cfg(unix)]
1369    #[tokio::test]
1370    async fn config_admission_swap_cannot_ack_or_queue_an_unapproved_configuration_update() {
1371        let (_rig, _owner, _supervisor, _handler, spec) =
1372            crate::config_gate::runtime::RuntimeOwner::unactivated_supervisor_fixture_for_test();
1373        let (reply, answer) = oneshot::channel();
1374        let mut end = SwapEnd::default();
1375        assert!(serve_command_while_warming(
1376            &spec.module_id.clone(),
1377            SupervisorCommand::UpdateConfiguration {
1378                spec,
1379                health: HealthConfig::default(),
1380                drain_timeout_ms: None,
1381                reply
1382            },
1383            &mut end,
1384            true
1385        )
1386        .is_none());
1387        assert!(matches!(
1388            answer.await.unwrap(),
1389            Err(SuperviseError::ConfigHeld { .. })
1390        ));
1391        assert!(end.requeue.is_empty());
1392    }
1393
1394    #[cfg(unix)]
1395    struct ConfigTimingFixture {
1396        dir: cortexkit_test_support::ScratchDir,
1397        runtime: SupervisorRuntimeConfig,
1398        registry: Arc<Registry>,
1399        forwarding: Arc<ForwardingTable>,
1400        child: SupervisedChild,
1401        receiver: mpsc::Receiver<crate::router::OutboundFrame>,
1402    }
1403
1404    #[cfg(unix)]
1405    fn config_timing_fixture() -> ConfigTimingFixture {
1406        let dir = cortexkit_test_support::ScratchDir::new("config-swap-deadline");
1407        let owner = Arc::new(crate::config_gate::runtime::RuntimeOwner::new(
1408            "swap-deadline".into(),
1409            crate::config_store::ConfigStore::open_digest_only_for_tests(
1410                crate::config_store::StoreRoot::from_service_definition(dir.join("store")).unwrap(),
1411            ),
1412            crate::config_gate::capture::ConfigCapturer {
1413                daemon_path: dir.join("subc.jsonc"),
1414                config_home: dir.to_path_buf(),
1415                projects: Arc::new(crate::config_gate::capture::OfflineProjectRegistry),
1416            },
1417        ));
1418        let registry = Arc::new(Registry::default());
1419        let forwarding = Arc::new(ForwardingTable::default());
1420        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
1421            .with_config_runtime(owner)
1422            .with_live_children_record(dir.join("children.json"))
1423            .with_forwarding(forwarding.clone());
1424        let mut runtime = supervisor.runtime_config();
1425        runtime.register_timeout = Duration::from_secs(5);
1426        runtime.health.deadline = Duration::from_secs(2);
1427        let spec = ModuleSpec {
1428            script: None,
1429            module_id: "timed".into(),
1430            program: PathBuf::from("/bin/sleep"),
1431            args: vec!["600".into()],
1432            env: vec![],
1433            reserved: false,
1434            reserved_prefixes: vec![],
1435            protocol: ModuleProtocol::None,
1436            overlap: ModuleOverlap::Safe,
1437            carry_containment: false,
1438        };
1439        let candidate = spawn_child(
1440            &spec,
1441            None,
1442            runtime.supervisor_handle.as_ref(),
1443            &runtime.stderr_ring,
1444            None,
1445            &runtime.child_roster,
1446            runtime.spawn_delivery(),
1447            #[cfg(target_os = "linux")]
1448            None,
1449            runtime.register_timeout,
1450        )
1451        .unwrap();
1452        let mut manifest =
1453            subc_protocol::manifest::ModuleManifest::builder("timed", "1.0.0").build();
1454        manifest.ready = Some(true);
1455        registry
1456            .register_candidate_with_control_ops(
1457                manifest,
1458                subc_protocol::PROTOCOL_VERSION,
1459                ConnectionId::new(2),
1460                vec![
1461                    "config.review".into(),
1462                    MODULE_CONTROL_OP_HEALTH_CHECK.into(),
1463                ],
1464            )
1465            .unwrap();
1466        let (sender, receiver) = mpsc::channel(8);
1467        forwarding
1468            .register_candidate_module_connection(
1469                ConnectionId::new(2),
1470                "timed".into(),
1471                subc_protocol::PROTOCOL_VERSION,
1472                subc_protocol::manifest::Concurrency::ModuleManaged,
1473                FrameSink::new(sender),
1474            )
1475            .unwrap();
1476        ConfigTimingFixture {
1477            dir,
1478            runtime,
1479            registry,
1480            forwarding,
1481            child: candidate,
1482            receiver,
1483        }
1484    }
1485
1486    #[cfg(unix)]
1487    #[tokio::test(start_paused = true)]
1488    async fn config_admission_swap_retry_has_a_bounded_backoff_even_when_gate_is_free() {
1489        let fixture = config_timing_fixture();
1490        let (_tx, mut commands) = mpsc::channel(8);
1491        let mut end = SwapEnd::default();
1492        let mut wait = Box::pin(wait_for_config_gate(
1493            &fixture.runtime,
1494            "timed",
1495            &mut commands,
1496            &mut end,
1497            None,
1498        ));
1499        for advance in [Duration::ZERO, Duration::from_millis(99)] {
1500            tokio::time::advance(advance).await;
1501            std::future::poll_fn(|cx| {
1502                assert!(
1503                    std::future::Future::poll(wait.as_mut(), cx).is_pending(),
1504                    "a free gate must not spin configuration-deferred candidate launches"
1505                );
1506                std::task::Poll::Ready(())
1507            })
1508            .await;
1509        }
1510        tokio::time::advance(Duration::from_millis(1)).await;
1511        assert!(wait.await);
1512        finish_timing_child(fixture.child).await;
1513    }
1514
1515    #[cfg(unix)]
1516    #[tokio::test(start_paused = true)]
1517    async fn config_admission_swap_busy_gate_wait_uses_absolute_deadline() {
1518        let fixture = config_timing_fixture();
1519        let gate = fixture
1520            .runtime
1521            .config_delivery
1522            .as_ref()
1523            .unwrap()
1524            .0
1525            .module_gate("timed")
1526            .unwrap();
1527        let _guard = gate.lock().await;
1528        let (_sender, mut commands) = mpsc::channel(8);
1529        let mut end = SwapEnd::default();
1530        let deadline = Instant::now() + SWAP_CUTOVER_DEADLINE;
1531        let mut wait = Box::pin(wait_for_config_gate(
1532            &fixture.runtime,
1533            "timed",
1534            &mut commands,
1535            &mut end,
1536            Some(deadline),
1537        ));
1538        std::future::poll_fn(|cx| {
1539            assert!(std::future::Future::poll(wait.as_mut(), cx).is_pending());
1540            std::task::Poll::Ready(())
1541        })
1542        .await;
1543        tokio::time::advance(SWAP_CUTOVER_DEADLINE - Duration::from_nanos(1)).await;
1544        std::future::poll_fn(|cx| {
1545            assert!(std::future::Future::poll(wait.as_mut(), cx).is_pending());
1546            std::task::Poll::Ready(())
1547        })
1548        .await;
1549        tokio::time::advance(Duration::from_nanos(1)).await;
1550        let expired = std::future::poll_fn(|cx| {
1551            std::task::Poll::Ready(matches!(
1552                std::future::Future::poll(wait.as_mut(), cx),
1553                std::task::Poll::Ready(false)
1554            ))
1555        })
1556        .await;
1557        drop(wait);
1558        finish_timing_child(fixture.child).await;
1559        assert!(expired, "the config gate lock await must end at the cutover deadline, even while the mutex stays held");
1560    }
1561
1562    #[cfg(unix)]
1563    async fn busy_cutover_failure(
1564        hold_module_gate: bool,
1565    ) -> (
1566        Vec<subc_config::Generation>,
1567        SupervisorSnapshot,
1568        SupervisorSnapshot,
1569    ) {
1570        let mut fixture = config_timing_fixture();
1571        approve_timing_restart(&fixture);
1572        let owner = fixture.runtime.config_delivery.as_ref().unwrap().0.clone();
1573        fixture.runtime.supervisor_handle = Some(SupervisorHandle::new());
1574        let mut manifest = fixture
1575            .registry
1576            .get_candidate("timed")
1577            .unwrap()
1578            .unwrap()
1579            .manifest;
1580        fixture
1581            .registry
1582            .deregister_connection(ConnectionId::new(2))
1583            .unwrap();
1584        fixture
1585            .registry
1586            .register_with_control_ops(
1587                manifest.clone(),
1588                subc_protocol::PROTOCOL_VERSION,
1589                ConnectionId::new(1),
1590                vec![],
1591            )
1592            .unwrap();
1593        manifest.ready = Some(true);
1594        fixture
1595            .registry
1596            .register_candidate_with_control_ops(
1597                manifest,
1598                subc_protocol::PROTOCOL_VERSION,
1599                ConnectionId::new(2),
1600                vec![
1601                    "config.review".into(),
1602                    MODULE_CONTROL_OP_HEALTH_CHECK.into(),
1603                ],
1604            )
1605            .unwrap();
1606        let (incumbent_sender, _incumbent_receiver) = mpsc::channel(8);
1607        fixture
1608            .forwarding
1609            .register_module_connection(
1610                ConnectionId::new(1),
1611                "timed".into(),
1612                subc_protocol::PROTOCOL_VERSION,
1613                subc_protocol::manifest::Concurrency::ModuleManaged,
1614                FrameSink::new(incumbent_sender),
1615            )
1616            .unwrap();
1617        let spec = ModuleSpec {
1618            script: None,
1619            module_id: "timed".into(),
1620            program: PathBuf::from("/bin/sleep"),
1621            args: vec!["600".into()],
1622            env: vec![],
1623            reserved: false,
1624            reserved_prefixes: vec![],
1625            protocol: ModuleProtocol::Subc,
1626            overlap: ModuleOverlap::Safe,
1627            carry_containment: false,
1628        };
1629        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
1630        set_running(
1631            &snapshot,
1632            &fixture.child,
1633            "timed",
1634            &fixture.runtime.spawn_events,
1635        )
1636        .unwrap();
1637        snapshot
1638            .lock()
1639            .unwrap()
1640            .record_crash_restart(&RestartPolicy::default(), Instant::now());
1641        let before = snapshot.lock().unwrap().clone();
1642        let mut child = Some(fixture.child);
1643        let incumbent_pid = child.as_ref().unwrap().pid;
1644        let (_sender, mut commands) = mpsc::channel(8);
1645        let (reply, mut answer) = oneshot::channel();
1646        let liveness = SupervisorProcessLiveness::default();
1647        let mut swap = Box::pin(run_swap(
1648            &spec,
1649            &fixture.runtime,
1650            &fixture.registry,
1651            &liveness,
1652            &snapshot,
1653            &mut child,
1654            &mut commands,
1655            Duration::from_secs(5),
1656            reply,
1657        ));
1658        let probe = tokio::select! {
1659            frame = fixture.receiver.recv() => frame.unwrap(),
1660            _ = &mut swap => panic!("swap ended before probing the candidate"),
1661        };
1662        assert_eq!(fixture.runtime.child_roster.live_count_for_test(), 2);
1663        let candidate_pid = crate::live_children::read_record(&fixture.dir.join("children.json"))
1664            .unwrap()
1665            .into_iter()
1666            .find(|entry| entry.pid != incumbent_pid)
1667            .unwrap()
1668            .pid;
1669        let gate = owner.module_gate("timed").unwrap();
1670        let _gate_guard = if hold_module_gate {
1671            Some(gate.lock().await)
1672        } else {
1673            None
1674        };
1675        let owner_guard = if hold_module_gate {
1676            None
1677        } else {
1678            Some(owner.try_swap_configuration().unwrap())
1679        };
1680        fixture
1681            .forwarding
1682            .complete_module_control_rpc(
1683                ConnectionId::new(2),
1684                probe.header.corr,
1685                Some(MODULE_CONTROL_OP_HEALTH_CHECK),
1686                ModuleControlRpcOutcome::Response(
1687                    subc_protocol::session::ModuleControlResponse::HealthCheck {
1688                        status: HealthStatus::Ok,
1689                        detail: None,
1690                        metrics: None,
1691                    },
1692                ),
1693            )
1694            .unwrap();
1695        std::future::poll_fn(|cx| {
1696            assert!(std::future::Future::poll(swap.as_mut(), cx).is_pending());
1697            std::task::Poll::Ready(())
1698        })
1699        .await;
1700        // Exercise multiple retries when only the owner's state is busy, as well
1701        // as the single parked lock await when the module gate is held.
1702        for advance in [
1703            SWAP_CUTOVER_DEADLINE / 2,
1704            SWAP_CUTOVER_DEADLINE / 2 - Duration::from_nanos(1),
1705        ] {
1706            tokio::time::advance(advance).await;
1707            std::future::poll_fn(|cx| {
1708                assert!(std::future::Future::poll(swap.as_mut(), cx).is_pending());
1709                std::task::Poll::Ready(())
1710            })
1711            .await;
1712            assert!(
1713                matches!(answer.try_recv(), Err(oneshot::error::TryRecvError::Empty)),
1714                "a busy cutover must retain its candidate until the deadline"
1715            );
1716        }
1717        tokio::time::advance(Duration::from_nanos(1)).await;
1718        // The fake registration has no socket to observe EOF and deregister it.
1719        fixture
1720            .registry
1721            .deregister_connection(ConnectionId::new(2))
1722            .unwrap();
1723        tokio::time::resume();
1724        let end = timeout(Duration::from_secs(2), &mut swap)
1725            .await
1726            .expect("cutover expiry must clean up while the config lock remains held");
1727        drop(swap);
1728        assert!(matches!(
1729            answer.try_recv().unwrap(),
1730            Err(SuperviseError::SwapFailed {
1731                arm: SwapFailureArm::CutoverLost,
1732                ..
1733            })
1734        ));
1735        assert!(end.requeue.is_empty());
1736        assert_eq!(
1737            fixture.runtime.child_roster.live_count_for_test(),
1738            1,
1739            "candidate must be reaped and released from the roster"
1740        );
1741        assert_eq!(
1742            subc_os::child_exit::observe(candidate_pid)
1743                .unwrap_err()
1744                .raw_os_error(),
1745            Some(rustix::io::Errno::CHILD.raw_os_error()),
1746            "candidate must be killed and reaped, not just removed from the roster"
1747        );
1748        assert_eq!(child.as_ref().unwrap().pid, incumbent_pid);
1749        assert!(
1750            child.as_mut().unwrap().child.try_wait().unwrap().is_none(),
1751            "incumbent process must keep serving"
1752        );
1753        assert_eq!(
1754            fixture
1755                .registry
1756                .get_module("timed")
1757                .unwrap()
1758                .unwrap()
1759                .connection_id,
1760            ConnectionId::new(1)
1761        );
1762        let (client_sender, _client_receiver) = mpsc::channel(8);
1763        let route = fixture
1764            .forwarding
1765            .begin_route_bind_relay_for_test(
1766                ConnectionId::new(3),
1767                FrameSink::new(client_sender),
1768                1,
1769                "timed",
1770            )
1771            .unwrap();
1772        assert_eq!(
1773            route.endpoint.connection_id,
1774            ConnectionId::new(1),
1775            "new requests must still reach the incumbent"
1776        );
1777        assert!(!fixture
1778            .runtime
1779            .supervisor_handle
1780            .as_ref()
1781            .unwrap()
1782            .swap_open("timed"));
1783        let after = snapshot.lock().unwrap().clone();
1784        drop(owner_guard);
1785        let generations = owner.history().unwrap().0;
1786        finish_timing_child(child.take().unwrap()).await;
1787        (generations, before, after)
1788    }
1789
1790    #[cfg(unix)]
1791    #[tokio::test(start_paused = true)]
1792    async fn config_admission_swap_busy_cutover_keeps_generation_deliverable() {
1793        let (generations, _, _) = busy_cutover_failure(true).await;
1794        assert_eq!(generations.len(), 2);
1795        assert!(
1796            generations.iter().all(|generation| !generation
1797                .never_redeliver
1798                .iter()
1799                .any(|module| module == "timed")),
1800            "gate contention must not poison any approved generation"
1801        );
1802    }
1803
1804    #[cfg(unix)]
1805    #[tokio::test(start_paused = true)]
1806    async fn config_admission_swap_busy_cutover_preserves_restart_budget() {
1807        let (_, before, after) = busy_cutover_failure(true).await;
1808        assert_eq!(after.crash_restarts, before.crash_restarts);
1809        assert_eq!(after.lifetime_restarts, before.lifetime_restarts);
1810        assert_eq!(after.spawn_generation, before.spawn_generation);
1811    }
1812
1813    #[cfg(unix)]
1814    #[tokio::test(start_paused = true)]
1815    async fn config_admission_swap_busy_cutover_retries_share_one_deadline() {
1816        busy_cutover_failure(false).await;
1817    }
1818
1819    #[cfg(unix)]
1820    async fn finish_timing_child(mut candidate: SupervisedChild) {
1821        candidate.start_kill().unwrap();
1822        candidate.wait().await.unwrap();
1823        candidate.finish_exit(false).await.unwrap();
1824    }
1825
1826    #[cfg(unix)]
1827    fn approve_timing_restart(fixture: &ConfigTimingFixture) {
1828        use crate::config_gate::{ApprovalFacts, ApprovalReply, PlanKind, PresenceDecision};
1829        use serde_json::json;
1830        let owner = &fixture.runtime.config_delivery.as_ref().unwrap().0;
1831        std::fs::create_dir_all(fixture.dir.join("cortexkit")).unwrap();
1832        std::fs::write(
1833            fixture.dir.join("subc.jsonc"),
1834            serde_json::to_vec(
1835                &json!({"version":1,"modules":{"timed":{"program":"/bin/sleep","args":["600"],"registration_channel":true}}}),
1836            )
1837            .unwrap(),
1838        )
1839        .unwrap();
1840        let path = fixture.dir.join("cortexkit/timed.jsonc");
1841        std::fs::write(&path, br#"{"limit":1}"#).unwrap();
1842        owner.declare(
1843            ConnectionId::new(1),
1844            "timed",
1845            subc_protocol::config::ConfigDeclareRequest::new(
1846                json!({"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","unevaluatedProperties":false,"x-ck-layers":["user"],"x-ck-apply":"live","properties":{"limit":{"type":"integer","description":"Limit","default":1,"x-ck-apply":"module_restart"}}}),
1847                path.to_string_lossy(), vec![],
1848            ),
1849            true,
1850        ).unwrap();
1851        let facts = ApprovalFacts {
1852            connection: 7,
1853            owner_uid: true,
1854            desktop_app: true,
1855            attested_operator_app: true,
1856            os_prompt_available: true,
1857            phone: None,
1858            caller: crate::caller_identity::CallerIdentity::default(),
1859        };
1860        for (kind, generation) in [(PlanKind::Stamp, 1), (PlanKind::Change, 2)] {
1861            std::fs::write(
1862                &path,
1863                serde_json::to_vec(&json!({"limit":generation})).unwrap(),
1864            )
1865            .unwrap();
1866            let plan = owner
1867                .finish_plan(
1868                    owner.prepare(kind).unwrap(),
1869                    crate::config_gate::runtime::daemon_review,
1870                )
1871                .unwrap();
1872            owner
1873                .desktop_view_delivered(ConnectionId::new(7), &plan)
1874                .unwrap();
1875            let challenge = owner.begin_approval(&plan.digest, &facts).unwrap();
1876            owner
1877                .finish_approval(
1878                    challenge.attempt(),
1879                    &facts,
1880                    ApprovalReply::Presence(PresenceDecision::InteractiveApproval),
1881                    generation,
1882                )
1883                .unwrap();
1884        }
1885        assert_eq!(
1886            owner
1887                .try_requires_fresher_spawn("timed", fixture.child.config_delivery.as_ref())
1888                .unwrap(),
1889            Some(2)
1890        );
1891    }
1892
1893    #[cfg(unix)]
1894    async fn retained_restart_after_warm_exit(exit: &str) {
1895        let mut fixture = config_timing_fixture();
1896        fixture
1897            .registry
1898            .deregister_connection(ConnectionId::new(2))
1899            .unwrap();
1900        let mut manifest =
1901            subc_protocol::manifest::ModuleManifest::builder("timed", "1.0.0").build();
1902        fixture
1903            .registry
1904            .register_with_control_ops(
1905                manifest.clone(),
1906                subc_protocol::PROTOCOL_VERSION,
1907                ConnectionId::new(1),
1908                vec![],
1909            )
1910            .unwrap();
1911        manifest.ready = Some(false);
1912        fixture
1913            .registry
1914            .register_candidate_with_control_ops(
1915                manifest.clone(),
1916                subc_protocol::PROTOCOL_VERSION,
1917                ConnectionId::new(2),
1918                vec![],
1919            )
1920            .unwrap();
1921        let (sender, mut commands) = mpsc::channel(8);
1922        let owner = fixture.runtime.config_delivery.as_ref().unwrap().0.clone();
1923        let (busy_tx, mut busy_rx) = oneshot::channel();
1924        let owner_guard = if exit == "superseded" {
1925            approve_timing_restart(&fixture);
1926            *owner.warm_restart_busy.lock().unwrap() = Some(busy_tx);
1927            Some(owner.try_swap_configuration().unwrap())
1928        } else {
1929            None
1930        };
1931        sender
1932            .send(SupervisorCommand::ConfigApplyRestart {
1933                generation: 23,
1934                supersedes_swap: false,
1935            })
1936            .await
1937            .unwrap();
1938        let mut end = SwapEnd::default();
1939        let mut warm = Box::pin(warm_candidate(
1940            "timed",
1941            &fixture.registry,
1942            &mut fixture.child,
1943            ConnectionId::new(1),
1944            Duration::from_secs(5),
1945            None,
1946            (exit == "superseded").then_some(fixture.runtime.config_delivery.as_ref().unwrap()),
1947            &mut commands,
1948            &mut end,
1949        ));
1950        std::future::poll_fn(|cx| {
1951            assert!(std::future::Future::poll(warm.as_mut(), cx).is_pending());
1952            std::task::Poll::Ready(())
1953        })
1954        .await;
1955        match exit {
1956            "superseded" => {
1957                assert!(
1958                    busy_rx.try_recv().is_ok(),
1959                    "warm-up must observe the busy owner"
1960                );
1961                drop(owner_guard);
1962                tokio::time::advance(CONFIG_ADMISSION_RETRY_DELAY).await;
1963            }
1964            "ready" => {
1965                fixture
1966                    .registry
1967                    .deregister_connection(ConnectionId::new(2))
1968                    .unwrap();
1969                manifest.ready = Some(true);
1970                fixture
1971                    .registry
1972                    .register_candidate_with_control_ops(
1973                        manifest,
1974                        subc_protocol::PROTOCOL_VERSION,
1975                        ConnectionId::new(2),
1976                        vec![],
1977                    )
1978                    .unwrap();
1979            }
1980            "timeout" => tokio::time::advance(Duration::from_secs(5)).await,
1981            _ => unreachable!(),
1982        }
1983        let outcome = warm.await;
1984        let correct_outcome = match exit {
1985            "ready" => matches!(outcome, Warm::Ready(_)),
1986            "superseded" => matches!(outcome, Warm::Superseded { generation: 2 }),
1987            _ => matches!(outcome, Warm::Failed(_)),
1988        };
1989        let retained = end
1990            .requeue
1991            .iter()
1992            .filter(|command| {
1993                matches!(command, SupervisorCommand::ConfigApplyRestart {
1994                    generation,
1995                    supersedes_swap
1996                } if exit == "superseded" || (*generation == 23 && !*supersedes_swap))
1997            })
1998            .count();
1999        finish_timing_child(fixture.child).await;
2000        assert!(correct_outcome);
2001        assert_eq!(
2002            retained,
2003            usize::from(exit != "superseded"),
2004            "warm {exit} retained the wrong number of consumed restarts"
2005        );
2006    }
2007
2008    #[cfg(unix)]
2009    #[tokio::test(start_paused = true)]
2010    async fn config_admission_warm_ready_requeues_consumed_restart() {
2011        retained_restart_after_warm_exit("ready").await;
2012    }
2013
2014    #[cfg(unix)]
2015    #[tokio::test(start_paused = true)]
2016    async fn config_admission_warm_timeout_requeues_consumed_restart() {
2017        retained_restart_after_warm_exit("timeout").await;
2018    }
2019
2020    #[cfg(unix)]
2021    #[tokio::test(start_paused = true)]
2022    async fn config_admission_warm_superseded_drops_consumed_restart() {
2023        retained_restart_after_warm_exit("superseded").await;
2024    }
2025
2026    #[cfg(unix)]
2027    #[tokio::test(start_paused = true)]
2028    async fn config_delivery_swap_adapter_ready_uses_spawn_bound_and_rejects_the_exact_edge() {
2029        let ConfigTimingFixture {
2030            dir: _dir,
2031            runtime,
2032            registry,
2033            mut child,
2034            ..
2035        } = config_timing_fixture();
2036        let cap = config_candidate_deadline(&runtime, &child).unwrap();
2037        assert_eq!(
2038            cap.duration_since(child.spawned_at),
2039            Duration::from_secs(17)
2040        );
2041        tokio::time::advance(Duration::from_secs(17) - Duration::from_nanos(1)).await;
2042        let (_sender, mut commands) = mpsc::channel(8);
2043        let mut end = SwapEnd::default();
2044        assert!(matches!(
2045            warm_candidate(
2046                "timed",
2047                &registry,
2048                &mut child,
2049                ConnectionId::new(1),
2050                Duration::from_secs(60),
2051                Some(cap),
2052                None,
2053                &mut commands,
2054                &mut end
2055            )
2056            .await,
2057            Warm::Ready(_)
2058        ));
2059        tokio::time::advance(Duration::from_nanos(1)).await;
2060        let late = warm_candidate(
2061            "timed",
2062            &registry,
2063            &mut child,
2064            ConnectionId::new(1),
2065            Duration::from_secs(60),
2066            Some(cap),
2067            None,
2068            &mut commands,
2069            &mut end,
2070        )
2071        .await;
2072        assert!(
2073            matches!(late, Warm::Failed(failure) if failure.detail.contains("configuration warm-up deadline"))
2074        );
2075        finish_timing_child(child).await;
2076    }
2077
2078    #[cfg(unix)]
2079    #[tokio::test(start_paused = true)]
2080    async fn config_delivery_swap_adapter_healthy_probe_cannot_extend_the_spawn_budget() {
2081        let ConfigTimingFixture {
2082            dir: _dir,
2083            runtime,
2084            registry,
2085            forwarding,
2086            child,
2087            mut receiver,
2088        } = config_timing_fixture();
2089        let cap = config_candidate_deadline(&runtime, &child).unwrap();
2090        tokio::time::advance(Duration::from_secs(15)).await;
2091        for late in [false, true] {
2092            let (runtime, registry, table) =
2093                (runtime.clone(), registry.clone(), forwarding.clone());
2094            let probe = tokio::spawn(async move {
2095                probe_candidate(
2096                    "timed",
2097                    &runtime,
2098                    &registry,
2099                    &table,
2100                    Some(cap),
2101                    ConnectionId::new(2),
2102                )
2103                .await
2104            });
2105            let frame = receiver.recv().await.unwrap();
2106            tokio::time::advance(if late {
2107                Duration::from_nanos(1)
2108            } else {
2109                Duration::from_secs(2) - Duration::from_nanos(1)
2110            })
2111            .await;
2112            forwarding
2113                .complete_module_control_rpc(
2114                    ConnectionId::new(2),
2115                    frame.header.corr,
2116                    Some(MODULE_CONTROL_OP_HEALTH_CHECK),
2117                    ModuleControlRpcOutcome::Response(
2118                        subc_protocol::session::ModuleControlResponse::HealthCheck {
2119                            status: HealthStatus::Ok,
2120                            detail: None,
2121                            metrics: None,
2122                        },
2123                    ),
2124                )
2125                .unwrap();
2126            assert_eq!(
2127                probe.await.unwrap().is_err(),
2128                late,
2129                "only the healthy response strictly before the warm-up edge qualifies"
2130            );
2131        }
2132        finish_timing_child(child).await;
2133    }
2134
2135    #[cfg(unix)]
2136    #[tokio::test]
2137    async fn retirement_returns_promptly_and_shutdown_waits_for_its_journal() {
2138        let dir = cortexkit_test_support::ScratchDir::new("background-retirement");
2139        let journal = dir.join("terminals.jsonl");
2140        let supervisor =
2141            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
2142                .with_handle(SupervisorHandle::new())
2143                .with_terminal_journal(journal.clone(), "retirement-test".into());
2144        let runtime = supervisor.runtime_config();
2145        let spec = ModuleSpec {
2146            script: None,
2147            carry_containment: false,
2148            module_id: "retiring".into(),
2149            program: PathBuf::from("/bin/sleep"),
2150            args: vec!["60".into()],
2151            env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
2152                .into_iter()
2153                .map(|key| (key.into(), dir.to_string_lossy().into_owned()))
2154                .collect(),
2155            reserved: false,
2156            reserved_prefixes: vec![],
2157            protocol: ModuleProtocol::None,
2158            overlap: ModuleOverlap::Safe,
2159        };
2160        let incumbent = spawn_child(
2161            &spec,
2162            None,
2163            runtime.supervisor_handle.as_ref(),
2164            &runtime.stderr_ring,
2165            None,
2166            &runtime.child_roster,
2167            runtime.spawn_delivery(),
2168            #[cfg(target_os = "linux")]
2169            None,
2170            runtime.register_timeout,
2171        )
2172        .unwrap();
2173        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
2174        let mut active_exit = wait_error_exit_report();
2175        active_exit.code = Some(42);
2176        snapshot.lock().unwrap().last_exit = Some(active_exit);
2177        let forwarding = Arc::new(ForwardingTable::default());
2178        timeout(
2179            Duration::from_millis(100),
2180            dispatch_retirement(
2181                &spec,
2182                &runtime,
2183                &supervisor.registry,
2184                &forwarding,
2185                &snapshot,
2186                Some(incumbent),
2187                None,
2188                ConnectionId::new(999),
2189                1,
2190            ),
2191        )
2192        .await
2193        .expect("incumbent retirement must not block the promoted process's supervision");
2194        supervisor.begin_daemon_shutdown();
2195        supervisor
2196            .end_children_for_daemon_shutdown(false, std::future::pending())
2197            .await;
2198        let records = std::fs::read_to_string(&journal).unwrap();
2199        assert!(
2200            records.contains("retiring"),
2201            "shutdown must wait for the incumbent's terminal record: {records}"
2202        );
2203        assert!(records.contains("daemon_shutdown"));
2204        assert_eq!(
2205            snapshot.lock().unwrap().last_exit.as_ref().unwrap().code,
2206            Some(42),
2207            "retirement must not replace the active lifecycle's exit"
2208        );
2209    }
2210
2211    /// During a swap two processes of the module are alive, and consumers
2212    /// started by either one attest before cutover. Promotion ends the
2213    /// incumbent's authority even while its process is still draining.
2214    #[test]
2215    fn consumer_attestation_revokes_incumbent_nonce_at_promotion() {
2216        let handle = SupervisorHandle::new();
2217        handle.set_spawn_nonce("aft", "incumbent".to_string());
2218        assert!(!handle.spawned_consumer_authorized("aft", "candidate"));
2219
2220        handle.open_swap("aft", "candidate".to_string());
2221        assert!(handle.spawned_consumer_authorized("aft", "incumbent"));
2222        assert!(handle.spawned_consumer_authorized("aft", "candidate"));
2223        assert!(!handle.spawned_consumer_authorized("aft", "forged"));
2224
2225        handle.promote_swap_nonce("aft", false);
2226        assert!(
2227            !handle.spawned_consumer_authorized("aft", "incumbent"),
2228            "promotion retires the incumbent's nonce before its drain ends"
2229        );
2230        assert!(handle.spawned_consumer_authorized("aft", "candidate"));
2231
2232        handle.close_swap("aft");
2233        assert!(handle.spawned_consumer_authorized("aft", "candidate"));
2234        assert!(!handle.spawned_consumer_authorized("aft", "incumbent"));
2235    }
2236
2237    /// A module has two cgroup names, and no module id, however it is
2238    /// spelled, can produce another module's name of either kind. The ids
2239    /// here are the ones the cgroup library's own encoding merges: an `@`, its
2240    /// escape spelled out literally, and an id ending in the swap suffix.
2241    #[test]
2242    fn cgroup_names_are_injective_across_ids_and_slots() {
2243        assert_eq!(cgroup_name("aft", false), "aft");
2244        assert_eq!(cgroup_name("aft", true), "aft_swap");
2245        let ids = [
2246            "aft",
2247            "aft@swap",
2248            "aft_40swap",
2249            "aft_swap",
2250            "aft_",
2251            "mcp:x",
2252            "mcp_3ax",
2253        ];
2254        let mut names = std::collections::HashSet::new();
2255        for id in ids {
2256            for alternate in [false, true] {
2257                assert!(
2258                    names.insert(cgroup_name(id, alternate)),
2259                    "{id:?} (alternate: {alternate}) names a directory another id or slot already has: {}",
2260                    cgroup_name(id, alternate)
2261                );
2262            }
2263        }
2264    }
2265}
2266
2267/// How long a swap waits for its candidate to register and declare itself
2268/// ready when the operator does not say. A module warming as a swap candidate
2269/// may take up to 90 s (aft's ceiling, the largest in the fleet), so the
2270/// daemon allows that plus time to start the process and send HELLO.
2271pub const DEFAULT_SWAP_READY_TIMEOUT: Duration = Duration::from_secs(100);
2272
2273/// Told when a swap has promoted its candidate to be the module's active
2274/// registration.
2275///
2276/// An ordinary HELLO runs the control plane's registration side effects (the
2277/// capability cache, the deny census, the requirement recompute) as it
2278/// registers. A swap candidate's HELLO does not, because it is not routable;
2279/// promotion is when those must run instead, and promotion happens in the
2280/// supervisor, which has no other way into the control handler.
2281pub(crate) trait SwapPromotionObserver: Send + Sync {
2282    fn swap_promoted(&self, registration: &crate::registry::ModuleRegistration);
2283}
2284
2285/// The installed [`SwapPromotionObserver`], held weakly: the observer (the
2286/// control handler) owns this handle, so a strong reference back would be a
2287/// cycle that keeps both alive.
2288#[derive(Clone, Default)]
2289pub(super) struct PromotionObserverSlot(
2290    pub(super) Arc<Mutex<Option<std::sync::Weak<dyn SwapPromotionObserver>>>>,
2291);
2292
2293impl fmt::Debug for PromotionObserverSlot {
2294    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2295        f.write_str("PromotionObserverSlot")
2296    }
2297}
2298
2299/// The nonces of one open swap.
2300#[derive(Debug, Clone)]
2301pub(super) struct OpenSwap {
2302    /// Legacy candidate token. A gated candidate has an empty lifecycle
2303    /// placeholder instead; only its own channel admits its HELLO.
2304    pub(super) candidate_nonce: String,
2305    /// Incumbent token accepted before cutover, then cleared by promotion even
2306    /// while the incumbent's process is still draining.
2307    pub(super) incumbent_nonce: Option<String>,
2308    /// Set once a HELLO has been admitted with the swap token, so the token
2309    /// admits one registration and cannot be replayed after cutover empties
2310    /// the candidate slot.
2311    candidate_admitted: bool,
2312}
2313
2314/// What the swap gate says about a HELLO. See
2315/// [`SupervisorHandle::swap_hello_admission`].
2316#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2317pub(crate) enum SwapHelloAdmission {
2318    /// No swap is open for the id (or the HELLO carries the incumbent's own
2319    /// nonce); the ordinary gates decide.
2320    NotSwapping,
2321    /// The HELLO carries the swap token: register it into the candidate slot.
2322    Candidate,
2323    /// A swap is open and the HELLO carries a nonce the supervisor did not
2324    /// mint for this id, no nonce, or a token already used.
2325    Refused,
2326    /// The id belongs to a supervised `protocol: none` module. Such a module
2327    /// never registers, so no HELLO may claim its id, with or without a nonce.
2328    ProtocolNone,
2329    /// The id is gated. Its supervised child registers only over the
2330    /// registration channel it inherited at launch, never by HELLO alone.
2331    ChannelRequired,
2332}
2333
2334impl SupervisorHandle {
2335    /// Whether `presented` is either nonce of an open swap for `module_id`.
2336    pub(super) fn swap_nonce_matches(&self, module_id: &str, presented: &str) -> bool {
2337        if self.module_is_gated(module_id) || self.protocol_none(module_id) || presented.is_empty()
2338        {
2339            return false;
2340        }
2341        let swaps = self
2342            .swaps
2343            .lock()
2344            .unwrap_or_else(|poisoned| poisoned.into_inner());
2345        swaps.get(module_id).is_some_and(|swap| {
2346            constant_time_eq(swap.candidate_nonce.as_bytes(), presented.as_bytes())
2347                || swap.incumbent_nonce.as_deref().is_some_and(|incumbent| {
2348                    constant_time_eq(incumbent.as_bytes(), presented.as_bytes())
2349                })
2350        })
2351    }
2352
2353    /// Open a swap for `module_id` with the candidate's freshly minted nonce.
2354    /// Called before the candidate process exists.
2355    pub(crate) fn open_swap(&self, module_id: &str, candidate_nonce: String) {
2356        let incumbent_nonce = self
2357            .spawn_nonces
2358            .lock()
2359            .unwrap_or_else(|poisoned| poisoned.into_inner())
2360            .get(module_id)
2361            .cloned();
2362        self.swaps
2363            .lock()
2364            .unwrap_or_else(|poisoned| poisoned.into_inner())
2365            .insert(
2366                module_id.to_string(),
2367                OpenSwap {
2368                    candidate_nonce,
2369                    incumbent_nonce,
2370                    candidate_admitted: false,
2371                },
2372            );
2373        self.refresh_program_binding_nonces(module_id);
2374    }
2375
2376    /// Close the swap for `module_id`, releasing whichever nonce is no longer
2377    /// the module's recorded one.
2378    pub(crate) fn close_swap(&self, module_id: &str) {
2379        self.swaps
2380            .lock()
2381            .unwrap_or_else(|poisoned| poisoned.into_inner())
2382            .remove(module_id);
2383        self.refresh_program_binding_nonces(module_id);
2384    }
2385
2386    /// Install the observer told about swap promotions, replacing any earlier
2387    /// one.
2388    pub(crate) fn set_swap_promotion_observer(
2389        &self,
2390        observer: std::sync::Weak<dyn SwapPromotionObserver>,
2391    ) {
2392        *self
2393            .promotion_observer
2394            .0
2395            .lock()
2396            .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(observer);
2397    }
2398
2399    /// Tell the installed observer, if it is still alive, that a swap promoted
2400    /// `registration`.
2401    fn notify_swap_promoted(&self, registration: &crate::registry::ModuleRegistration) {
2402        let observer = self
2403            .promotion_observer
2404            .0
2405            .lock()
2406            .unwrap_or_else(|poisoned| poisoned.into_inner())
2407            .as_ref()
2408            .and_then(std::sync::Weak::upgrade);
2409        if let Some(observer) = observer {
2410            observer.swap_promoted(registration);
2411        }
2412    }
2413
2414    /// Whether a swap is open for `module_id`.
2415    pub(crate) fn swap_open(&self, module_id: &str) -> bool {
2416        self.swaps
2417            .lock()
2418            .unwrap_or_else(|poisoned| poisoned.into_inner())
2419            .contains_key(module_id)
2420    }
2421
2422    /// Make the candidate's nonce the module's recorded spawn nonce, as a plain
2423    /// respawn would, once cutover has made the candidate the module's process.
2424    /// Promotion revokes the incumbent's tokens; the swap record stays open
2425    /// only for lifecycle cleanup while the old process drains.
2426    pub(super) fn promote_swap_nonce(&self, module_id: &str, reserved: bool) {
2427        let candidate_nonce = self
2428            .swaps
2429            .lock()
2430            .unwrap_or_else(|poisoned| poisoned.into_inner())
2431            .get_mut(module_id)
2432            .map(|swap| {
2433                swap.incumbent_nonce = None;
2434                swap.candidate_nonce.clone()
2435            });
2436        self.spawn_nonces
2437            .lock()
2438            .unwrap_or_else(|p| p.into_inner())
2439            .remove(module_id);
2440        {
2441            let mut nonces = self
2442                .reserved_nonces
2443                .lock()
2444                .unwrap_or_else(|p| p.into_inner());
2445            if reserved || nonces.contains_key(module_id) {
2446                nonces.insert(module_id.into(), None);
2447            }
2448        }
2449        if self.module_is_gated(module_id) {
2450            return;
2451        }
2452        let Some(nonce) = candidate_nonce.filter(|nonce| !nonce.is_empty()) else {
2453            return;
2454        };
2455        self.set_spawn_nonce(module_id, nonce.clone());
2456        if reserved {
2457            self.set_reserved_nonce(module_id, nonce);
2458        }
2459    }
2460
2461    /// The swap gate for a HELLO claiming `module_id`.
2462    ///
2463    /// This runs BEFORE the reserved-module gate. A reserved module's candidate
2464    /// presents the candidate nonce, which the reserved gate (holding the
2465    /// incumbent's nonce) would refuse as `reserved_module` before swap
2466    /// admission was ever reached. And it applies to unreserved ids too: for an
2467    /// unreserved id the only thing that ever stopped a second process claiming
2468    /// a live id was the `duplicate_module_id` refusal, which is exactly the
2469    /// refusal a swap lifts for its candidate.
2470    ///
2471    /// The incumbent's own nonce falls through to the ordinary gates, which
2472    /// treat it as they always have (a live incumbent is refused as a
2473    /// duplicate). Anything else while a swap is open is refused, including an
2474    /// absent nonce.
2475    pub(crate) fn swap_hello_admission(
2476        &self,
2477        module_id: &str,
2478        presented: Option<&str>,
2479    ) -> SwapHelloAdmission {
2480        if self.protocol_none(module_id) {
2481            return SwapHelloAdmission::ProtocolNone;
2482        }
2483        if self.module_is_gated(module_id) {
2484            return SwapHelloAdmission::ChannelRequired;
2485        }
2486        let swaps = self
2487            .swaps
2488            .lock()
2489            .unwrap_or_else(|poisoned| poisoned.into_inner());
2490        let Some(swap) = swaps.get(module_id) else {
2491            return SwapHelloAdmission::NotSwapping;
2492        };
2493        let Some(presented) = presented.filter(|nonce| !nonce.is_empty()) else {
2494            return SwapHelloAdmission::Refused;
2495        };
2496        if constant_time_eq(swap.candidate_nonce.as_bytes(), presented.as_bytes()) {
2497            return if swap.candidate_admitted {
2498                SwapHelloAdmission::Refused
2499            } else {
2500                SwapHelloAdmission::Candidate
2501            };
2502        }
2503        if swap
2504            .incumbent_nonce
2505            .as_deref()
2506            .is_some_and(|incumbent| constant_time_eq(incumbent.as_bytes(), presented.as_bytes()))
2507        {
2508            return SwapHelloAdmission::NotSwapping;
2509        }
2510        SwapHelloAdmission::Refused
2511    }
2512}
2513
2514impl SupervisorHandle {
2515    /// Exclude swap closure through the short, synchronous candidate publication.
2516    pub(crate) fn with_swap_candidate_admission<T>(
2517        &self,
2518        module_id: &str,
2519        publish: impl FnOnce() -> (T, bool),
2520    ) -> Option<T> {
2521        let mut swaps = self.swaps.lock().unwrap_or_else(|p| p.into_inner());
2522        let swap = swaps
2523            .get_mut(module_id)
2524            .filter(|swap| !swap.candidate_admitted)?;
2525        let (result, admitted) = publish();
2526        swap.candidate_admitted = admitted;
2527        Some(result)
2528    }
2529}
2530
2531impl SupervisedModule {
2532    /// Blue/green restart: see `SupervisorCommand::Swap` and the
2533    /// `supervisor_swap` module. Returns once the swap has cut over (the old
2534    /// process then drains in the background of the supervise loop), has been
2535    /// superseded by an approved configuration restart, or has failed. Both
2536    /// supersession and failure leave the old process serving until replacement.
2537    pub async fn swap(
2538        &self,
2539        ready_timeout: Option<Duration>,
2540    ) -> Result<SwapOutcome, SuperviseError> {
2541        self.swap_requested(ready_timeout, None).await
2542    }
2543
2544    pub(crate) async fn swap_requested(
2545        &self,
2546        ready_timeout: Option<Duration>,
2547        requester: Option<Principal>,
2548    ) -> Result<SwapOutcome, SuperviseError> {
2549        let (reply_tx, reply_rx) = oneshot::channel();
2550        self.inner
2551            .commands
2552            .send(SupervisorCommand::Swap {
2553                requester,
2554                ready_timeout,
2555                reply: reply_tx,
2556            })
2557            .await
2558            .map_err(|_| SuperviseError::CommandClosed {
2559                module_id: self.inner.module_id.clone(),
2560            })?;
2561        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
2562            module_id: self.inner.module_id.clone(),
2563        })?
2564    }
2565}