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        #[cfg(any(target_os = "linux", target_os = "macos"))]
727        SupervisorCommand::Upgrade { request, .. } => {
728            request.refuse_running_swap(module_id);
729            None
730        }
731        #[cfg(any(target_os = "linux", target_os = "macos"))]
732        SupervisorCommand::HeldAdoptionResolved { .. } => {
733            end.requeue.push(command);
734            None
735        }
736        SupervisorCommand::ConfigPolicyProbe { .. }
737        | SupervisorCommand::ConfigUnstampedRestart(_) => {
738            end.requeue.push(command);
739            None
740        }
741        SupervisorCommand::ConfigApplyRestart { .. } => Some(command),
742        SupervisorCommand::Drain { .. }
743        | SupervisorCommand::ApprovedConfiguration { .. }
744        | SupervisorCommand::ConfigExitHold { .. }
745        | SupervisorCommand::ConfigDeliveryFailed { .. }
746        | SupervisorCommand::Retire { .. }
747        | SupervisorCommand::SetEnabled { enabled: false, .. } => Some(command),
748        SupervisorCommand::SetEnabled {
749            enabled: true,
750            reply,
751            ..
752        } => {
753            let _ = reply.send(Ok(false));
754            None
755        }
756        SupervisorCommand::Restart { reply, .. } | SupervisorCommand::Reload { reply, .. } => {
757            let _ = reply.send(Err(in_progress()));
758            None
759        }
760        SupervisorCommand::Swap { reply, .. } => {
761            let _ = reply.send(Err(SuperviseError::SwapRefused {
762                module_id: module_id.to_string(),
763                reason: SwapRefusal::AlreadySwapping,
764            }));
765            None
766        }
767        SupervisorCommand::UpdateConfiguration { reply, .. } if gated => {
768            let _ = reply.send(Err(SuperviseError::ConfigHeld {
769                module_id: module_id.into(),
770                code: "config_gated".into(),
771                detail: "live file reconfiguration cannot replace stamped authority".into(),
772            }));
773            None
774        }
775        SupervisorCommand::UpdateConfiguration {
776            spec,
777            health,
778            drain_timeout_ms,
779            reply,
780        } => {
781            let _ = reply.send(Ok(()));
782            // A swap keeps the drain budget it started with, even if it hasn't
783            // begun draining the incumbent yet. Replay the update after the swap
784            // so subsequent drains use it. The caller already has its answer.
785            let (unanswered, _) = oneshot::channel();
786            end.requeue.push(SupervisorCommand::UpdateConfiguration {
787                spec,
788                health,
789                drain_timeout_ms,
790                reply: unanswered,
791            });
792            None
793        }
794    }
795}
796
797/// Every check a swap makes before spawning anything. Returns the forwarding
798/// table, the shared handle, and the incumbent's connection.
799fn admit_swap(
800    spec: &ModuleSpec,
801    runtime: &SupervisorRuntimeConfig,
802    registry: &Registry,
803    snapshot: &SharedSnapshot,
804    child: &Option<SupervisedChild>,
805) -> Result<(Arc<ForwardingTable>, SupervisorHandle, ConnectionId), SuperviseError> {
806    let module_id = spec.module_id.as_str();
807    let refuse = |reason| SuperviseError::SwapRefused {
808        module_id: module_id.to_string(),
809        reason,
810    };
811    // First, and unconditionally: a module that has not declared it tolerates
812    // a second process of itself is never given one.
813    if spec.overlap != ModuleOverlap::Safe {
814        return Err(refuse(SwapRefusal::OverlapExclusive));
815    }
816    if !lock_snapshot(snapshot)?.enabled {
817        return Err(SuperviseError::Disabled {
818            module_id: module_id.to_string(),
819        });
820    }
821    if spec.protocol == ModuleProtocol::None {
822        return Err(refuse(SwapRefusal::ProtocolNone));
823    }
824    let (Some(forwarding), Some(handle)) = (
825        runtime.forwarding.clone(),
826        runtime.supervisor_handle.clone(),
827    ) else {
828        return Err(refuse(SwapRefusal::NotConfigured));
829    };
830    if handle.swap_open(module_id) {
831        return Err(refuse(SwapRefusal::AlreadySwapping));
832    }
833    let registration = registry
834        .get_module(module_id)
835        .map_err(SuperviseError::Registry)?;
836    let (Some(registration), true) = (registration, child.is_some()) else {
837        return Err(refuse(SwapRefusal::NotRegistered));
838    };
839    Ok((forwarding, handle, registration.connection_id))
840}
841
842/// Wait for the candidate to register and declare itself ready, or to fail.
843///
844/// Readiness is read from the candidate's own registration, which its
845/// `catalog.update(ready: true)` updates through its connection (the registry
846/// searches every slot by connection for exactly this). Nothing here goes
847/// through a by-id lookup, all of which resolve the incumbent.
848///
849/// The module's commands are served meanwhile; see
850/// [`serve_command_while_warming`].
851#[allow(clippy::too_many_arguments)]
852async fn warm_candidate(
853    module_id: &str,
854    registry: &Registry,
855    candidate: &mut SupervisedChild,
856    incumbent_connection: ConnectionId,
857    ready_timeout: Duration,
858    config_deadline: Option<Instant>,
859    config_delivery: Option<&super::config_delivery::ConfigDelivery>,
860    commands: &mut mpsc::Receiver<SupervisorCommand>,
861    end: &mut SwapEnd,
862) -> Warm {
863    let requeue_start = end.requeue.len();
864    let outcome = warm_candidate_until_outcome(
865        module_id,
866        registry,
867        candidate,
868        incumbent_connection,
869        ready_timeout,
870        config_deadline,
871        config_delivery,
872        commands,
873        end,
874    )
875    .await;
876    if matches!(outcome, Warm::Superseded { .. }) {
877        // The superseded branch queues its freshly checked generation instead.
878        // Downstream revalidation would discard a stale duplicate anyway, so
879        // filtering prevents a redundant command rather than a second launch.
880        let deferred = end.requeue.split_off(requeue_start);
881        end.requeue.extend(
882            deferred
883                .into_iter()
884                .filter(|command| !matches!(command, SupervisorCommand::ConfigApplyRestart { .. })),
885        );
886    }
887    outcome
888}
889
890/// The warm-up loop proper. Every return path leaves any configuration
891/// restart it consumed in `end.requeue`; [`warm_candidate`] drops those again
892/// when the outcome is `Superseded`, whose caller queues a fresher generation.
893#[allow(clippy::too_many_arguments)]
894async fn warm_candidate_until_outcome(
895    module_id: &str,
896    registry: &Registry,
897    candidate: &mut SupervisedChild,
898    incumbent_connection: ConnectionId,
899    ready_timeout: Duration,
900    config_deadline: Option<Instant>,
901    config_delivery: Option<&super::config_delivery::ConfigDelivery>,
902    commands: &mut mpsc::Receiver<SupervisorCommand>,
903    end: &mut SwapEnd,
904) -> Warm {
905    let mut deadline = Instant::now() + ready_timeout;
906    let mut registered: Option<ConnectionId> = None;
907    let mut config_restart_pending = false;
908    let mut next_config_check = Instant::now();
909    loop {
910        if config_restart_pending && Instant::now() >= next_config_check {
911            if let Some(delivery) = config_delivery {
912                match delivery
913                    .0
914                    .try_requires_fresher_spawn(module_id, candidate.config_delivery.as_ref())
915                {
916                    Ok(Some(generation)) => return Warm::Superseded { generation },
917                    Ok(None) => config_restart_pending = false,
918                    Err(_) => {
919                        #[cfg(test)]
920                        if let Some(reached) = delivery.0.warm_restart_busy.lock().unwrap().take() {
921                            let _ = reached.send(());
922                        }
923                        next_config_check = Instant::now() + CONFIG_ADMISSION_RETRY_DELAY;
924                    }
925                }
926            } else {
927                config_restart_pending = false;
928            }
929        }
930        // Before the candidate registers, the candidate slot is the only
931        // place to look for it; once it has, its connection names it exactly.
932        let slot = match registered {
933            Some(connection) => RegistrationSlot::Connection(connection),
934            None => RegistrationSlot::Candidate(module_id),
935        };
936        // Only a published candidate counts as registered. A candidate's HELLO
937        // reserves its registry entry before installing its forwarding
938        // endpoint and publishes it after; a ready candidate seen in between
939        // would be promoted while the forwarding cutover still finds no
940        // candidate endpoint, and the swap would fail as if the candidate's
941        // connection had closed.
942        match registry.published_registration(slot) {
943            Ok(Some(registration)) => {
944                registered = Some(registration.connection_id);
945                if registration
946                    .control_ops
947                    .iter()
948                    .any(|op| op == "config.review")
949                {
950                    if let Some(cap) = config_deadline {
951                        deadline = deadline.min(cap);
952                        if Instant::now() >= cap {
953                            return Warm::Failed(CandidateFailure {
954                                arm:SwapFailureArm::NeverReady,
955                                detail:"config_gated: candidate configuration warm-up deadline expired before readiness".into(),
956                                exit:None, connection:registered,
957                            });
958                        }
959                    }
960                }
961                if registration.ready {
962                    return Warm::Ready(registration.connection_id);
963                }
964                // The incumbent died while the candidate warmed. The candidate
965                // is now the only process, so waiting for it to finish warming
966                // serves nobody: promote it, and callers get `module_warming`
967                // until it declares itself ready, as on a plain restart.
968                if matches!(
969                    registry.registration(RegistrationSlot::Connection(incumbent_connection)),
970                    Ok(None)
971                ) {
972                    warn!(
973                        module_id,
974                        "incumbent went away while the swap candidate warmed; promoting the candidate before it is ready"
975                    );
976                    return Warm::Ready(registration.connection_id);
977                }
978            }
979            Ok(None) if registered.is_some() => {
980                // It registered and then its registration went away: its
981                // connection closed. Its exit is reaped below or next poll.
982            }
983            Ok(None) => {}
984            Err(err) => {
985                return Warm::Failed(CandidateFailure {
986                    arm: if registered.is_some() {
987                        SwapFailureArm::NeverReady
988                    } else {
989                        SwapFailureArm::NeverRegistered
990                    },
991                    detail: format!("could not read the candidate's registration: {err}"),
992                    exit: None,
993                    connection: registered,
994                });
995            }
996        }
997
998        let now = Instant::now();
999        if now >= deadline {
1000            let (arm, detail) = match registered {
1001                Some(_) => (
1002                    SwapFailureArm::NeverReady,
1003                    format!("the candidate registered but did not declare itself ready within {ready_timeout:?}"),
1004                ),
1005                None => (
1006                    SwapFailureArm::NeverRegistered,
1007                    format!("the candidate did not register within {ready_timeout:?}"),
1008                ),
1009            };
1010            return Warm::Failed(CandidateFailure {
1011                arm,
1012                detail,
1013                exit: None,
1014                connection: registered,
1015            });
1016        }
1017        let poll = deadline
1018            .saturating_duration_since(now)
1019            .min(REGISTRY_RELEASE_POLL);
1020        tokio::select! {
1021            status = candidate.wait() => {
1022                // Classified on its own: the module snapshot's severance marker
1023                // belongs to the incumbent and must not be consumed here.
1024                let exit = swap_terminal::observed_exit(module_id, status);
1025                return Warm::Failed(CandidateFailure {
1026                    arm: SwapFailureArm::CandidateExited,
1027                    detail: candidate.spawn_failure.clone().unwrap_or_else(|| format!(
1028                        "the candidate exited before it was ready (code {:?}, signal {:?})",
1029                        exit.code, exit.signal
1030                    )),
1031                    exit: Some(exit),
1032                    connection: registered,
1033                });
1034            }
1035            command = commands.recv() => {
1036                // A closed channel means the module handle is gone; the loop
1037                // will see the same and stop, so abandon the candidate first.
1038                let Some(command) = command else {
1039                    return Warm::Interrupted { command: None, connection: registered };
1040                };
1041                if matches!(command, SupervisorCommand::ConfigApplyRestart { .. }) {
1042                    // The coordinator sends each generation only once. Keep
1043                    // the command even if readiness, exit or timeout wins the
1044                    // race with the nonblocking freshness recheck. The actor
1045                    // revalidates it against the current spawn before acting.
1046                    end.requeue.push(command);
1047                    #[cfg(test)]
1048                    if let Some(delivery) = config_delivery {
1049                        let pause = delivery.0.warm_restart_pause.lock().unwrap().take();
1050                        if let Some(pause) = pause {
1051                            let _ = pause.reached.send(());
1052                            let _ = pause.resume.await;
1053                        }
1054                    }
1055                    config_restart_pending = true;
1056                    next_config_check = Instant::now();
1057                    continue;
1058                }
1059                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))) {
1060                    return Warm::Interrupted { command: Some(command), connection: registered };
1061                }
1062            }
1063            _ = sleep(poll) => {}
1064        }
1065    }
1066}
1067
1068fn config_candidate_deadline(
1069    runtime: &SupervisorRuntimeConfig,
1070    candidate: &SupervisedChild,
1071) -> Option<Instant> {
1072    runtime.config_delivery.as_ref().map(|_| {
1073        candidate.spawned_at
1074            + runtime.register_timeout
1075            + runtime.health.deadline
1076            + crate::config_gate::runtime::delivery::CONFIG_WARMUP_SLACK
1077    })
1078}
1079
1080/// Probe a ready candidate once, by endpoint, before promoting it.
1081///
1082/// The same `health.check` the supervisor probes every module with, sent only
1083/// when the candidate advertises it. A `failing` answer or no usable answer
1084/// fails the swap. A configuration-delivery candidate must answer healthy;
1085/// otherwise the existing non-config swap policy also accepts degraded service.
1086/// Like every other swap failure it spends no crash-restart budget: the
1087/// budget is the incumbent's, and the incumbent did nothing.
1088async fn probe_candidate(
1089    module_id: &str,
1090    runtime: &SupervisorRuntimeConfig,
1091    registry: &Registry,
1092    forwarding: &ForwardingTable,
1093    config_deadline: Option<Instant>,
1094    candidate_connection: ConnectionId,
1095) -> Result<(), CandidateFailure> {
1096    let unhealthy = |detail: String| CandidateFailure {
1097        arm: SwapFailureArm::CandidateUnhealthy,
1098        detail,
1099        exit: None,
1100        connection: Some(candidate_connection),
1101    };
1102    let registration = registry
1103        .registration(RegistrationSlot::Connection(candidate_connection))
1104        .ok()
1105        .flatten();
1106    let config_owned = runtime.config_delivery.is_some()
1107        && registration.as_ref().is_some_and(|registration| {
1108            registration
1109                .control_ops
1110                .iter()
1111                .any(|op| op == "config.review")
1112        });
1113    let advertises_health = registration.as_ref().is_some_and(|registration| {
1114        registration
1115            .control_ops
1116            .iter()
1117            .any(|op| op == MODULE_CONTROL_OP_HEALTH_CHECK)
1118    });
1119    if !advertises_health {
1120        if config_owned {
1121            return Err(unhealthy(
1122                "config_gated: configuration readiness requires the first healthy probe".into(),
1123            ));
1124        }
1125        return Ok(());
1126    }
1127    let Some(endpoint) = forwarding
1128        .module_endpoint_for_connection(candidate_connection)
1129        .ok()
1130        .flatten()
1131    else {
1132        return Err(unhealthy(
1133            "the candidate's connection closed before its health probe".to_string(),
1134        ));
1135    };
1136    let deadline_cap = config_owned.then_some(config_deadline).flatten();
1137    match probe_endpoint_health(endpoint, runtime, deadline_cap).await {
1138        Ok(_) if deadline_cap.is_some_and(|cap| Instant::now() >= cap) => Err(unhealthy(
1139            "config_gated: candidate configuration warm-up deadline expired before its first healthy probe finished".into())),
1140        Ok(report) if config_owned && report.status != HealthStatus::Ok => Err(unhealthy(
1141            "config_gated: configuration readiness requires a healthy, not degraded or failing, probe".into())),
1142        Ok(report) if report.status == HealthStatus::Failing => Err(unhealthy(format!(
1143            "the candidate answered its health probe with status failing{}",
1144            report
1145                .detail
1146                .map(|detail| format!(": {detail}"))
1147                .unwrap_or_default()
1148        ))),
1149        Ok(_) => Ok(()),
1150        Err(err) => {
1151            debug!(module_id, error = %err, "swap candidate health probe failed");
1152            Err(unhealthy(format!(
1153                "the candidate's health probe failed: {err}"
1154            )))
1155        }
1156    }
1157}
1158
1159/// Kill a failed candidate and free exactly its slot.
1160///
1161/// This is the candidate's own reap path. The ordinary one classifies an exit
1162/// into the module's snapshot and then asks the crash budget for a respawn;
1163/// either would be wrong here, because the snapshot and the budget are the
1164/// incumbent's and the incumbent is still serving. So this kills and reaps
1165/// only the candidate, waits only for the candidate's registration (by its
1166/// connection, or by the candidate slot if it never registered) to go, and
1167/// closes the swap, which releases only the candidate's nonce.
1168async fn abandon_candidate(
1169    module_id: &str,
1170    registry: &Registry,
1171    forwarding: &ForwardingTable,
1172    runtime: &SupervisorRuntimeConfig,
1173    mut candidate: SupervisedChild,
1174    failure: Option<&CandidateFailure>,
1175) -> ExitReport {
1176    candidate.retire_registration();
1177    if let Some(failure) = failure {
1178        warn!(module_id, arm=failure.arm.as_str(), detail=%failure.detail, candidate_pid=candidate.pid,
1179            "swap failed; killing the candidate and leaving the incumbent serving");
1180    } else {
1181        info!(
1182            module_id,
1183            candidate_pid = candidate.pid,
1184            outcome = SwapOutcome::SupersededByConfigRestart.as_str(),
1185            "swap superseded by approved configuration restart; leaving the incumbent serving"
1186        );
1187    }
1188    let exit = swap_terminal::abandoned_exit(module_id, &mut candidate, failure).await;
1189    candidate.drain_stderr(module_id).await;
1190    swap_terminal::record_abandonment(module_id, runtime, &exit, failure);
1191    if let Err(error) = candidate.finish_exit(false).await {
1192        warn!(module_id, %error, "could not finalize the abandoned swap candidate");
1193    }
1194
1195    let slot = match failure.and_then(|failure| failure.connection) {
1196        Some(connection) => RegistrationSlot::Connection(connection),
1197        None => RegistrationSlot::Candidate(module_id),
1198    };
1199    if let Err(err) =
1200        wait_for_slot_registration_release(registry, slot, REGISTRY_RELEASE_TIMEOUT).await
1201    {
1202        // The process is dead, so its connection is on its way down; if the
1203        // registration outlived the wait, close the connection outright so the
1204        // candidate slot is free for the next swap.
1205        warn!(module_id, error = %err, "abandoned swap candidate is still registered; closing its connection");
1206        if let Some(connection) = failure.and_then(|failure| failure.connection).or_else(|| {
1207            registry
1208                .get_candidate(module_id)
1209                .ok()
1210                .flatten()
1211                .map(|registration| registration.connection_id)
1212        }) {
1213            forwarding.request_connection_close(
1214                connection,
1215                CloseReason::new(
1216                    "swap_candidate_abandoned",
1217                    format!("swap of module '{module_id}' ended; closing its candidate"),
1218                ),
1219            );
1220        }
1221    }
1222    if let Some(handle) = &runtime.supervisor_handle {
1223        handle.close_swap(module_id);
1224    }
1225    exit
1226}
1227
1228/// Drain and reap the incumbent a swap has just replaced.
1229///
1230/// The drain is the plain restart's drain (route.closing, quiescence,
1231/// route.closed, per-route GOODBYE, module GOODBYE) with reason `Restart`, so
1232/// deployed SDKs keep treating it as may-reopen, but addressed to the
1233/// incumbent's endpoint rather than the module id, which now resolves to the
1234/// promoted candidate. The incumbent's release is awaited by its connection,
1235/// since the id's active registration is the candidate's and never goes away.
1236/// The module's state is not touched: it describes the promoted candidate.
1237#[allow(clippy::too_many_arguments)]
1238pub(super) async fn retire_incumbent(
1239    spec: &ModuleSpec,
1240    runtime: &SupervisorRuntimeConfig,
1241    registry: &Registry,
1242    forwarding: &ForwardingTable,
1243    snapshot: &SharedSnapshot,
1244    incumbent: Option<SupervisedChild>,
1245    incumbent_endpoint: Option<crate::ModuleEndpointId>,
1246    incumbent_connection: ConnectionId,
1247    incumbent_generation: u64,
1248) {
1249    let module_id = spec.module_id.as_str();
1250    let mut incumbent = incumbent;
1251    let mut observed_exit = None;
1252    let stop_notice = if let Some(endpoint) = incumbent_endpoint {
1253        let drain = begin_forwarding_drain_with(
1254            forwarding,
1255            ForwardingDrainContext {
1256                spec,
1257                runtime,
1258                registry,
1259                scope: DrainScope::Endpoint(endpoint),
1260            },
1261            snapshot,
1262            None,
1263            RouteCloseReason::Restart,
1264            runtime.drain_timeout,
1265        );
1266        let result = if let Some(child) = incumbent.as_mut() {
1267            tokio::select! {
1268                status = child.wait() => {
1269                    observed_exit = Some(status);
1270                    Ok(StopNotice::NotSent)
1271                }
1272                result = drain => result,
1273            }
1274        } else {
1275            drain.await
1276        };
1277        result.unwrap_or_else(|err| {
1278            warn!(module_id, error = %err, "draining the swapped-out incumbent failed; stopping it anyway");
1279            StopNotice::NotSent
1280        })
1281    } else {
1282        StopNotice::NoConnection
1283    };
1284
1285    let Some(mut incumbent) = incumbent else {
1286        return;
1287    };
1288    // Cutover already revoked authority. Keep the transport for in-flight
1289    // replies and drain notices until its bounded GOODBYE flush completes.
1290    incumbent.retire_registration();
1291    if observed_exit.is_none() && stop_notice != StopNotice::SentOverConnection {
1292        request_graceful_stop(module_id, &incumbent);
1293    }
1294    // The module GOODBYE above asks the incumbent to exit; give it the same
1295    // budget a plain restart gives the child it drains, then kill it.
1296    let status = match observed_exit {
1297        Some(status) => status,
1298        None => match timeout(
1299            incumbent.group_drain_budget(runtime.drain_timeout, stop_notice),
1300            incumbent.wait(),
1301        )
1302        .await
1303        {
1304            Ok(status) => status,
1305            Err(_) => {
1306                warn!(
1307                    module_id,
1308                    pid = incumbent.pid,
1309                    budget_ms =
1310                        u64::try_from(runtime.drain_timeout.as_millis()).unwrap_or(u64::MAX),
1311                    reason = "swapped-out incumbent",
1312                    "drain budget expired before the module exited; killing it"
1313                );
1314                if let Err(err) = incumbent.start_kill() {
1315                    debug!(module_id, error = %err, "swapped-out incumbent kill failed; it may already have exited");
1316                }
1317                incumbent.wait().await
1318            }
1319        },
1320    };
1321    let exit_report = match status {
1322        Ok(status) => classify_exit(&status),
1323        Err(err) => {
1324            warn!(module_id, error = %err, "could not reap the swapped-out incumbent");
1325            wait_error_exit_report()
1326        }
1327    };
1328    incumbent.drain_stderr(module_id).await;
1329    runtime.spawn_events.emit_superseded_exited(
1330        module_id,
1331        incumbent_generation,
1332        incumbent.pid,
1333        exit_report.code,
1334        exit_report.signal,
1335    );
1336    {
1337        let record = TerminalRecord {
1338            exit_code: exit_report.code,
1339            exit_signal: exit_report.signal,
1340            at_ms: exit_report.at_ms,
1341            disposition: TerminalDisposition::Restarting,
1342            exit_kind: exit_report.kind.into(),
1343            disposition_detail: incumbent
1344                .exit_cleanup_detail(Some("replaced by a blue/green swap".into())),
1345        };
1346        // Recorded as `daemon_shutdown` instead if the daemon has begun
1347        // shutting down (see `TerminalRing::record_exit`).
1348        runtime
1349            .terminal_ring
1350            .lock()
1351            .unwrap_or_else(|poisoned| poisoned.into_inner())
1352            .record_exit(module_id, record);
1353    }
1354    // Shutdown waits for the roster to empty before flushing the journal.
1355    // Enqueue the record before releasing this roster entry.
1356    if let Err(error) = incumbent.finish_exit(false).await {
1357        warn!(module_id, %error, "could not finalize the swapped-out incumbent");
1358    }
1359    if let Err(err) = wait_for_slot_registration_release(
1360        registry,
1361        RegistrationSlot::Connection(incumbent_connection),
1362        REGISTRY_RELEASE_TIMEOUT,
1363    )
1364    .await
1365    {
1366        warn!(module_id, error = %err, "swapped-out incumbent's registration outlived its process");
1367    }
1368    info!(
1369        module_id,
1370        exit_code = ?exit_report.code,
1371        exit_signal = ?exit_report.signal,
1372        "swapped-out incumbent drained and exited; swap complete"
1373    );
1374}
1375
1376#[cfg(test)]
1377mod tests {
1378    use super::*;
1379
1380    #[cfg(any(target_os = "linux", target_os = "macos"))]
1381    #[tokio::test]
1382    async fn running_swap_refuses_upgrade_without_interrupting_candidate() {
1383        let (reply, response) = oneshot::channel();
1384        let mut end = SwapEnd::default();
1385        let request = SupervisorCommand::Upgrade {
1386            key: Arc::new(()),
1387            request: crate::supervise::live_upgrade::ActorRequest::Select(reply),
1388        };
1389        assert!(serve_command_while_warming("candidate", request, &mut end, false).is_none());
1390        let refusal = response.await.unwrap().unwrap_err();
1391        assert_eq!(refusal.kind(), std::io::ErrorKind::WouldBlock);
1392        assert!(refusal
1393            .to_string()
1394            .contains("module 'candidate' is swapping"));
1395        assert!(end.requeue.is_empty());
1396    }
1397
1398    #[cfg(unix)]
1399    #[tokio::test]
1400    async fn config_admission_swap_cannot_ack_or_queue_an_unapproved_configuration_update() {
1401        let (_rig, _owner, _supervisor, _handler, spec) =
1402            crate::config_gate::runtime::RuntimeOwner::unactivated_supervisor_fixture_for_test();
1403        let (reply, answer) = oneshot::channel();
1404        let mut end = SwapEnd::default();
1405        assert!(serve_command_while_warming(
1406            &spec.module_id.clone(),
1407            SupervisorCommand::UpdateConfiguration {
1408                spec,
1409                health: HealthConfig::default(),
1410                drain_timeout_ms: None,
1411                reply
1412            },
1413            &mut end,
1414            true
1415        )
1416        .is_none());
1417        assert!(matches!(
1418            answer.await.unwrap(),
1419            Err(SuperviseError::ConfigHeld { .. })
1420        ));
1421        assert!(end.requeue.is_empty());
1422    }
1423
1424    #[cfg(unix)]
1425    struct ConfigTimingFixture {
1426        dir: cortexkit_test_support::ScratchDir,
1427        runtime: SupervisorRuntimeConfig,
1428        registry: Arc<Registry>,
1429        forwarding: Arc<ForwardingTable>,
1430        child: SupervisedChild,
1431        receiver: mpsc::Receiver<crate::router::OutboundFrame>,
1432    }
1433
1434    #[cfg(unix)]
1435    fn config_timing_fixture() -> ConfigTimingFixture {
1436        let dir = cortexkit_test_support::ScratchDir::new("config-swap-deadline");
1437        let owner = Arc::new(crate::config_gate::runtime::RuntimeOwner::new(
1438            "swap-deadline".into(),
1439            crate::config_store::ConfigStore::open_digest_only_for_tests(
1440                crate::config_store::StoreRoot::from_service_definition(dir.join("store")).unwrap(),
1441            ),
1442            crate::config_gate::capture::ConfigCapturer {
1443                daemon_path: dir.join("subc.jsonc"),
1444                config_home: dir.to_path_buf(),
1445                projects: Arc::new(crate::config_gate::capture::OfflineProjectRegistry),
1446            },
1447        ));
1448        let registry = Arc::new(Registry::default());
1449        let forwarding = Arc::new(ForwardingTable::default());
1450        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
1451            .with_config_runtime(owner)
1452            .with_live_children_record(dir.join("children.json"))
1453            .with_forwarding(forwarding.clone());
1454        let mut runtime = supervisor.runtime_config();
1455        runtime.register_timeout = Duration::from_secs(5);
1456        runtime.health.deadline = Duration::from_secs(2);
1457        let spec = ModuleSpec {
1458            script: None,
1459            module_id: "timed".into(),
1460            program: PathBuf::from("/bin/sleep"),
1461            args: vec!["600".into()],
1462            env: vec![],
1463            reserved: false,
1464            reserved_prefixes: vec![],
1465            protocol: ModuleProtocol::None,
1466            overlap: ModuleOverlap::Safe,
1467            carry_containment: false,
1468        };
1469        let candidate = spawn_child(
1470            &spec,
1471            None,
1472            runtime.supervisor_handle.as_ref(),
1473            &runtime.stderr_ring,
1474            None,
1475            &runtime.child_roster,
1476            runtime.spawn_delivery(),
1477            #[cfg(target_os = "linux")]
1478            None,
1479            runtime.register_timeout,
1480        )
1481        .unwrap();
1482        let mut manifest =
1483            subc_protocol::manifest::ModuleManifest::builder("timed", "1.0.0").build();
1484        manifest.ready = Some(true);
1485        registry
1486            .register_candidate_with_control_ops(
1487                manifest,
1488                subc_protocol::PROTOCOL_VERSION,
1489                ConnectionId::new(2),
1490                vec![
1491                    "config.review".into(),
1492                    MODULE_CONTROL_OP_HEALTH_CHECK.into(),
1493                ],
1494            )
1495            .unwrap();
1496        let (sender, receiver) = mpsc::channel(8);
1497        forwarding
1498            .register_candidate_module_connection(
1499                ConnectionId::new(2),
1500                "timed".into(),
1501                subc_protocol::PROTOCOL_VERSION,
1502                subc_protocol::manifest::Concurrency::ModuleManaged,
1503                FrameSink::new(sender),
1504            )
1505            .unwrap();
1506        ConfigTimingFixture {
1507            dir,
1508            runtime,
1509            registry,
1510            forwarding,
1511            child: candidate,
1512            receiver,
1513        }
1514    }
1515
1516    #[cfg(unix)]
1517    #[tokio::test(start_paused = true)]
1518    async fn config_admission_swap_retry_has_a_bounded_backoff_even_when_gate_is_free() {
1519        let fixture = config_timing_fixture();
1520        let (_tx, mut commands) = mpsc::channel(8);
1521        let mut end = SwapEnd::default();
1522        let mut wait = Box::pin(wait_for_config_gate(
1523            &fixture.runtime,
1524            "timed",
1525            &mut commands,
1526            &mut end,
1527            None,
1528        ));
1529        for advance in [Duration::ZERO, Duration::from_millis(99)] {
1530            tokio::time::advance(advance).await;
1531            std::future::poll_fn(|cx| {
1532                assert!(
1533                    std::future::Future::poll(wait.as_mut(), cx).is_pending(),
1534                    "a free gate must not spin configuration-deferred candidate launches"
1535                );
1536                std::task::Poll::Ready(())
1537            })
1538            .await;
1539        }
1540        tokio::time::advance(Duration::from_millis(1)).await;
1541        assert!(wait.await);
1542        finish_timing_child(fixture.child).await;
1543    }
1544
1545    #[cfg(unix)]
1546    #[tokio::test(start_paused = true)]
1547    async fn config_admission_swap_busy_gate_wait_uses_absolute_deadline() {
1548        let fixture = config_timing_fixture();
1549        let gate = fixture
1550            .runtime
1551            .config_delivery
1552            .as_ref()
1553            .unwrap()
1554            .0
1555            .module_gate("timed")
1556            .unwrap();
1557        let _guard = gate.lock().await;
1558        let (_sender, mut commands) = mpsc::channel(8);
1559        let mut end = SwapEnd::default();
1560        let deadline = Instant::now() + SWAP_CUTOVER_DEADLINE;
1561        let mut wait = Box::pin(wait_for_config_gate(
1562            &fixture.runtime,
1563            "timed",
1564            &mut commands,
1565            &mut end,
1566            Some(deadline),
1567        ));
1568        std::future::poll_fn(|cx| {
1569            assert!(std::future::Future::poll(wait.as_mut(), cx).is_pending());
1570            std::task::Poll::Ready(())
1571        })
1572        .await;
1573        tokio::time::advance(SWAP_CUTOVER_DEADLINE - Duration::from_nanos(1)).await;
1574        std::future::poll_fn(|cx| {
1575            assert!(std::future::Future::poll(wait.as_mut(), cx).is_pending());
1576            std::task::Poll::Ready(())
1577        })
1578        .await;
1579        tokio::time::advance(Duration::from_nanos(1)).await;
1580        let expired = std::future::poll_fn(|cx| {
1581            std::task::Poll::Ready(matches!(
1582                std::future::Future::poll(wait.as_mut(), cx),
1583                std::task::Poll::Ready(false)
1584            ))
1585        })
1586        .await;
1587        drop(wait);
1588        finish_timing_child(fixture.child).await;
1589        assert!(expired, "the config gate lock await must end at the cutover deadline, even while the mutex stays held");
1590    }
1591
1592    #[cfg(unix)]
1593    async fn busy_cutover_failure(
1594        hold_module_gate: bool,
1595    ) -> (
1596        Vec<subc_config::Generation>,
1597        SupervisorSnapshot,
1598        SupervisorSnapshot,
1599    ) {
1600        let mut fixture = config_timing_fixture();
1601        approve_timing_restart(&fixture);
1602        let owner = fixture.runtime.config_delivery.as_ref().unwrap().0.clone();
1603        fixture.runtime.supervisor_handle = Some(SupervisorHandle::new());
1604        let mut manifest = fixture
1605            .registry
1606            .get_candidate("timed")
1607            .unwrap()
1608            .unwrap()
1609            .manifest;
1610        fixture
1611            .registry
1612            .deregister_connection(ConnectionId::new(2))
1613            .unwrap();
1614        fixture
1615            .registry
1616            .register_with_control_ops(
1617                manifest.clone(),
1618                subc_protocol::PROTOCOL_VERSION,
1619                ConnectionId::new(1),
1620                vec![],
1621            )
1622            .unwrap();
1623        manifest.ready = Some(true);
1624        fixture
1625            .registry
1626            .register_candidate_with_control_ops(
1627                manifest,
1628                subc_protocol::PROTOCOL_VERSION,
1629                ConnectionId::new(2),
1630                vec![
1631                    "config.review".into(),
1632                    MODULE_CONTROL_OP_HEALTH_CHECK.into(),
1633                ],
1634            )
1635            .unwrap();
1636        let (incumbent_sender, _incumbent_receiver) = mpsc::channel(8);
1637        fixture
1638            .forwarding
1639            .register_module_connection(
1640                ConnectionId::new(1),
1641                "timed".into(),
1642                subc_protocol::PROTOCOL_VERSION,
1643                subc_protocol::manifest::Concurrency::ModuleManaged,
1644                FrameSink::new(incumbent_sender),
1645            )
1646            .unwrap();
1647        let spec = ModuleSpec {
1648            script: None,
1649            module_id: "timed".into(),
1650            program: PathBuf::from("/bin/sleep"),
1651            args: vec!["600".into()],
1652            env: vec![],
1653            reserved: false,
1654            reserved_prefixes: vec![],
1655            protocol: ModuleProtocol::Subc,
1656            overlap: ModuleOverlap::Safe,
1657            carry_containment: false,
1658        };
1659        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
1660        set_running(
1661            &snapshot,
1662            &fixture.child,
1663            "timed",
1664            &fixture.runtime.spawn_events,
1665        )
1666        .unwrap();
1667        snapshot
1668            .lock()
1669            .unwrap()
1670            .record_crash_restart(&RestartPolicy::default(), Instant::now());
1671        let before = snapshot.lock().unwrap().clone();
1672        let mut child = Some(fixture.child);
1673        let incumbent_pid = child.as_ref().unwrap().pid;
1674        let (_sender, mut commands) = mpsc::channel(8);
1675        let (reply, mut answer) = oneshot::channel();
1676        let liveness = SupervisorProcessLiveness::default();
1677        let mut swap = Box::pin(run_swap(
1678            &spec,
1679            &fixture.runtime,
1680            &fixture.registry,
1681            &liveness,
1682            &snapshot,
1683            &mut child,
1684            &mut commands,
1685            Duration::from_secs(5),
1686            reply,
1687        ));
1688        let probe = tokio::select! {
1689            frame = fixture.receiver.recv() => frame.unwrap(),
1690            _ = &mut swap => panic!("swap ended before probing the candidate"),
1691        };
1692        assert_eq!(fixture.runtime.child_roster.live_count_for_test(), 2);
1693        let candidate_pid = crate::live_children::read_record(&fixture.dir.join("children.json"))
1694            .unwrap()
1695            .into_iter()
1696            .find(|entry| entry.pid != incumbent_pid)
1697            .unwrap()
1698            .pid;
1699        let gate = owner.module_gate("timed").unwrap();
1700        let _gate_guard = if hold_module_gate {
1701            Some(gate.lock().await)
1702        } else {
1703            None
1704        };
1705        let owner_guard = if hold_module_gate {
1706            None
1707        } else {
1708            Some(owner.try_swap_configuration().unwrap())
1709        };
1710        fixture
1711            .forwarding
1712            .complete_module_control_rpc(
1713                ConnectionId::new(2),
1714                probe.header.corr,
1715                Some(MODULE_CONTROL_OP_HEALTH_CHECK),
1716                ModuleControlRpcOutcome::Response(
1717                    subc_protocol::session::ModuleControlResponse::HealthCheck {
1718                        status: HealthStatus::Ok,
1719                        detail: None,
1720                        metrics: None,
1721                        summary: None,
1722                    },
1723                ),
1724            )
1725            .unwrap();
1726        std::future::poll_fn(|cx| {
1727            assert!(std::future::Future::poll(swap.as_mut(), cx).is_pending());
1728            std::task::Poll::Ready(())
1729        })
1730        .await;
1731        // Exercise multiple retries when only the owner's state is busy, as well
1732        // as the single parked lock await when the module gate is held.
1733        for advance in [
1734            SWAP_CUTOVER_DEADLINE / 2,
1735            SWAP_CUTOVER_DEADLINE / 2 - Duration::from_nanos(1),
1736        ] {
1737            tokio::time::advance(advance).await;
1738            std::future::poll_fn(|cx| {
1739                assert!(std::future::Future::poll(swap.as_mut(), cx).is_pending());
1740                std::task::Poll::Ready(())
1741            })
1742            .await;
1743            assert!(
1744                matches!(answer.try_recv(), Err(oneshot::error::TryRecvError::Empty)),
1745                "a busy cutover must retain its candidate until the deadline"
1746            );
1747        }
1748        tokio::time::advance(Duration::from_nanos(1)).await;
1749        // The fake registration has no socket to observe EOF and deregister it.
1750        fixture
1751            .registry
1752            .deregister_connection(ConnectionId::new(2))
1753            .unwrap();
1754        tokio::time::resume();
1755        let end = timeout(Duration::from_secs(2), &mut swap)
1756            .await
1757            .expect("cutover expiry must clean up while the config lock remains held");
1758        drop(swap);
1759        assert!(matches!(
1760            answer.try_recv().unwrap(),
1761            Err(SuperviseError::SwapFailed {
1762                arm: SwapFailureArm::CutoverLost,
1763                ..
1764            })
1765        ));
1766        assert!(end.requeue.is_empty());
1767        assert_eq!(
1768            fixture.runtime.child_roster.live_count_for_test(),
1769            1,
1770            "candidate must be reaped and released from the roster"
1771        );
1772        assert_eq!(
1773            subc_os::child_exit::observe(candidate_pid)
1774                .unwrap_err()
1775                .raw_os_error(),
1776            Some(rustix::io::Errno::CHILD.raw_os_error()),
1777            "candidate must be killed and reaped, not just removed from the roster"
1778        );
1779        assert_eq!(child.as_ref().unwrap().pid, incumbent_pid);
1780        assert!(
1781            child.as_mut().unwrap().child.try_wait().unwrap().is_none(),
1782            "incumbent process must keep serving"
1783        );
1784        assert_eq!(
1785            fixture
1786                .registry
1787                .get_module("timed")
1788                .unwrap()
1789                .unwrap()
1790                .connection_id,
1791            ConnectionId::new(1)
1792        );
1793        let (client_sender, _client_receiver) = mpsc::channel(8);
1794        let route = fixture
1795            .forwarding
1796            .begin_route_bind_relay_for_test(
1797                ConnectionId::new(3),
1798                FrameSink::new(client_sender),
1799                1,
1800                "timed",
1801            )
1802            .unwrap();
1803        assert_eq!(
1804            route.endpoint.connection_id,
1805            ConnectionId::new(1),
1806            "new requests must still reach the incumbent"
1807        );
1808        assert!(!fixture
1809            .runtime
1810            .supervisor_handle
1811            .as_ref()
1812            .unwrap()
1813            .swap_open("timed"));
1814        let after = snapshot.lock().unwrap().clone();
1815        drop(owner_guard);
1816        let generations = owner.history().unwrap().0;
1817        finish_timing_child(child.take().unwrap()).await;
1818        (generations, before, after)
1819    }
1820
1821    #[cfg(unix)]
1822    #[tokio::test(start_paused = true)]
1823    async fn config_admission_swap_busy_cutover_keeps_generation_deliverable() {
1824        let (generations, _, _) = busy_cutover_failure(true).await;
1825        assert_eq!(generations.len(), 2);
1826        assert!(
1827            generations.iter().all(|generation| !generation
1828                .never_redeliver
1829                .iter()
1830                .any(|module| module == "timed")),
1831            "gate contention must not poison any approved generation"
1832        );
1833    }
1834
1835    #[cfg(unix)]
1836    #[tokio::test(start_paused = true)]
1837    async fn config_admission_swap_busy_cutover_preserves_restart_budget() {
1838        let (_, before, after) = busy_cutover_failure(true).await;
1839        assert_eq!(after.crash_restarts, before.crash_restarts);
1840        assert_eq!(after.lifetime_restarts, before.lifetime_restarts);
1841        assert_eq!(after.spawn_generation, before.spawn_generation);
1842    }
1843
1844    #[cfg(unix)]
1845    #[tokio::test(start_paused = true)]
1846    async fn config_admission_swap_busy_cutover_retries_share_one_deadline() {
1847        busy_cutover_failure(false).await;
1848    }
1849
1850    #[cfg(unix)]
1851    async fn finish_timing_child(mut candidate: SupervisedChild) {
1852        candidate.start_kill().unwrap();
1853        candidate.wait().await.unwrap();
1854        candidate.finish_exit(false).await.unwrap();
1855    }
1856
1857    #[cfg(unix)]
1858    fn approve_timing_restart(fixture: &ConfigTimingFixture) {
1859        use crate::config_gate::{ApprovalFacts, ApprovalReply, PlanKind, PresenceDecision};
1860        use serde_json::json;
1861        let owner = &fixture.runtime.config_delivery.as_ref().unwrap().0;
1862        std::fs::create_dir_all(fixture.dir.join("cortexkit")).unwrap();
1863        std::fs::write(
1864            fixture.dir.join("subc.jsonc"),
1865            serde_json::to_vec(
1866                &json!({"version":1,"modules":{"timed":{"program":"/bin/sleep","args":["600"],"registration_channel":true}}}),
1867            )
1868            .unwrap(),
1869        )
1870        .unwrap();
1871        let path = fixture.dir.join("cortexkit/timed.jsonc");
1872        std::fs::write(&path, br#"{"limit":1}"#).unwrap();
1873        owner.declare(
1874            ConnectionId::new(1),
1875            "timed",
1876            subc_protocol::config::ConfigDeclareRequest::new(
1877                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"}}}),
1878                path.to_string_lossy(), vec![],
1879            ),
1880            true,
1881        ).unwrap();
1882        let facts = ApprovalFacts {
1883            connection: 7,
1884            owner_uid: true,
1885            desktop_app: true,
1886            attested_operator_app: true,
1887            os_prompt_available: true,
1888            phone: None,
1889            caller: crate::caller_identity::CallerIdentity::default(),
1890        };
1891        for (kind, generation) in [(PlanKind::Stamp, 1), (PlanKind::Change, 2)] {
1892            std::fs::write(
1893                &path,
1894                serde_json::to_vec(&json!({"limit":generation})).unwrap(),
1895            )
1896            .unwrap();
1897            let plan = owner
1898                .finish_plan(
1899                    owner.prepare(kind).unwrap(),
1900                    crate::config_gate::runtime::daemon_review,
1901                )
1902                .unwrap();
1903            owner
1904                .desktop_view_delivered(ConnectionId::new(7), &plan)
1905                .unwrap();
1906            let challenge = owner.begin_approval(&plan.digest, &facts).unwrap();
1907            owner
1908                .finish_approval(
1909                    challenge.attempt(),
1910                    &facts,
1911                    ApprovalReply::Presence(PresenceDecision::InteractiveApproval),
1912                    generation,
1913                )
1914                .unwrap();
1915        }
1916        assert_eq!(
1917            owner
1918                .try_requires_fresher_spawn("timed", fixture.child.config_delivery.as_ref())
1919                .unwrap(),
1920            Some(2)
1921        );
1922    }
1923
1924    #[cfg(unix)]
1925    async fn retained_restart_after_warm_exit(exit: &str) {
1926        let mut fixture = config_timing_fixture();
1927        fixture
1928            .registry
1929            .deregister_connection(ConnectionId::new(2))
1930            .unwrap();
1931        let mut manifest =
1932            subc_protocol::manifest::ModuleManifest::builder("timed", "1.0.0").build();
1933        fixture
1934            .registry
1935            .register_with_control_ops(
1936                manifest.clone(),
1937                subc_protocol::PROTOCOL_VERSION,
1938                ConnectionId::new(1),
1939                vec![],
1940            )
1941            .unwrap();
1942        manifest.ready = Some(false);
1943        fixture
1944            .registry
1945            .register_candidate_with_control_ops(
1946                manifest.clone(),
1947                subc_protocol::PROTOCOL_VERSION,
1948                ConnectionId::new(2),
1949                vec![],
1950            )
1951            .unwrap();
1952        let (sender, mut commands) = mpsc::channel(8);
1953        let owner = fixture.runtime.config_delivery.as_ref().unwrap().0.clone();
1954        let (busy_tx, mut busy_rx) = oneshot::channel();
1955        let owner_guard = if exit == "superseded" {
1956            approve_timing_restart(&fixture);
1957            *owner.warm_restart_busy.lock().unwrap() = Some(busy_tx);
1958            Some(owner.try_swap_configuration().unwrap())
1959        } else {
1960            None
1961        };
1962        sender
1963            .send(SupervisorCommand::ConfigApplyRestart {
1964                generation: 23,
1965                supersedes_swap: false,
1966            })
1967            .await
1968            .unwrap();
1969        let mut end = SwapEnd::default();
1970        let mut warm = Box::pin(warm_candidate(
1971            "timed",
1972            &fixture.registry,
1973            &mut fixture.child,
1974            ConnectionId::new(1),
1975            Duration::from_secs(5),
1976            None,
1977            (exit == "superseded").then_some(fixture.runtime.config_delivery.as_ref().unwrap()),
1978            &mut commands,
1979            &mut end,
1980        ));
1981        std::future::poll_fn(|cx| {
1982            assert!(std::future::Future::poll(warm.as_mut(), cx).is_pending());
1983            std::task::Poll::Ready(())
1984        })
1985        .await;
1986        match exit {
1987            "superseded" => {
1988                assert!(
1989                    busy_rx.try_recv().is_ok(),
1990                    "warm-up must observe the busy owner"
1991                );
1992                drop(owner_guard);
1993                tokio::time::advance(CONFIG_ADMISSION_RETRY_DELAY).await;
1994            }
1995            "ready" => {
1996                fixture
1997                    .registry
1998                    .deregister_connection(ConnectionId::new(2))
1999                    .unwrap();
2000                manifest.ready = Some(true);
2001                fixture
2002                    .registry
2003                    .register_candidate_with_control_ops(
2004                        manifest,
2005                        subc_protocol::PROTOCOL_VERSION,
2006                        ConnectionId::new(2),
2007                        vec![],
2008                    )
2009                    .unwrap();
2010            }
2011            "timeout" => tokio::time::advance(Duration::from_secs(5)).await,
2012            _ => unreachable!(),
2013        }
2014        let outcome = warm.await;
2015        let correct_outcome = match exit {
2016            "ready" => matches!(outcome, Warm::Ready(_)),
2017            "superseded" => matches!(outcome, Warm::Superseded { generation: 2 }),
2018            _ => matches!(outcome, Warm::Failed(_)),
2019        };
2020        let retained = end
2021            .requeue
2022            .iter()
2023            .filter(|command| {
2024                matches!(command, SupervisorCommand::ConfigApplyRestart {
2025                    generation,
2026                    supersedes_swap
2027                } if exit == "superseded" || (*generation == 23 && !*supersedes_swap))
2028            })
2029            .count();
2030        finish_timing_child(fixture.child).await;
2031        assert!(correct_outcome);
2032        assert_eq!(
2033            retained,
2034            usize::from(exit != "superseded"),
2035            "warm {exit} retained the wrong number of consumed restarts"
2036        );
2037    }
2038
2039    #[cfg(unix)]
2040    #[tokio::test(start_paused = true)]
2041    async fn config_admission_warm_ready_requeues_consumed_restart() {
2042        retained_restart_after_warm_exit("ready").await;
2043    }
2044
2045    #[cfg(unix)]
2046    #[tokio::test(start_paused = true)]
2047    async fn config_admission_warm_timeout_requeues_consumed_restart() {
2048        retained_restart_after_warm_exit("timeout").await;
2049    }
2050
2051    #[cfg(unix)]
2052    #[tokio::test(start_paused = true)]
2053    async fn config_admission_warm_superseded_drops_consumed_restart() {
2054        retained_restart_after_warm_exit("superseded").await;
2055    }
2056
2057    #[cfg(unix)]
2058    #[tokio::test(start_paused = true)]
2059    async fn config_delivery_swap_adapter_ready_uses_spawn_bound_and_rejects_the_exact_edge() {
2060        let ConfigTimingFixture {
2061            dir: _dir,
2062            runtime,
2063            registry,
2064            mut child,
2065            ..
2066        } = config_timing_fixture();
2067        let cap = config_candidate_deadline(&runtime, &child).unwrap();
2068        assert_eq!(
2069            cap.duration_since(child.spawned_at),
2070            Duration::from_secs(17)
2071        );
2072        tokio::time::advance(Duration::from_secs(17) - Duration::from_nanos(1)).await;
2073        let (_sender, mut commands) = mpsc::channel(8);
2074        let mut end = SwapEnd::default();
2075        assert!(matches!(
2076            warm_candidate(
2077                "timed",
2078                &registry,
2079                &mut child,
2080                ConnectionId::new(1),
2081                Duration::from_secs(60),
2082                Some(cap),
2083                None,
2084                &mut commands,
2085                &mut end
2086            )
2087            .await,
2088            Warm::Ready(_)
2089        ));
2090        tokio::time::advance(Duration::from_nanos(1)).await;
2091        let late = warm_candidate(
2092            "timed",
2093            &registry,
2094            &mut child,
2095            ConnectionId::new(1),
2096            Duration::from_secs(60),
2097            Some(cap),
2098            None,
2099            &mut commands,
2100            &mut end,
2101        )
2102        .await;
2103        assert!(
2104            matches!(late, Warm::Failed(failure) if failure.detail.contains("configuration warm-up deadline"))
2105        );
2106        finish_timing_child(child).await;
2107    }
2108
2109    #[cfg(unix)]
2110    #[tokio::test(start_paused = true)]
2111    async fn config_delivery_swap_adapter_healthy_probe_cannot_extend_the_spawn_budget() {
2112        let ConfigTimingFixture {
2113            dir: _dir,
2114            runtime,
2115            registry,
2116            forwarding,
2117            child,
2118            mut receiver,
2119        } = config_timing_fixture();
2120        let cap = config_candidate_deadline(&runtime, &child).unwrap();
2121        tokio::time::advance(Duration::from_secs(15)).await;
2122        for late in [false, true] {
2123            let (runtime, registry, table) =
2124                (runtime.clone(), registry.clone(), forwarding.clone());
2125            let probe = tokio::spawn(async move {
2126                probe_candidate(
2127                    "timed",
2128                    &runtime,
2129                    &registry,
2130                    &table,
2131                    Some(cap),
2132                    ConnectionId::new(2),
2133                )
2134                .await
2135            });
2136            let frame = receiver.recv().await.unwrap();
2137            tokio::time::advance(if late {
2138                Duration::from_nanos(1)
2139            } else {
2140                Duration::from_secs(2) - Duration::from_nanos(1)
2141            })
2142            .await;
2143            forwarding
2144                .complete_module_control_rpc(
2145                    ConnectionId::new(2),
2146                    frame.header.corr,
2147                    Some(MODULE_CONTROL_OP_HEALTH_CHECK),
2148                    ModuleControlRpcOutcome::Response(
2149                        subc_protocol::session::ModuleControlResponse::HealthCheck {
2150                            status: HealthStatus::Ok,
2151                            detail: None,
2152                            metrics: None,
2153                            summary: None,
2154                        },
2155                    ),
2156                )
2157                .unwrap();
2158            assert_eq!(
2159                probe.await.unwrap().is_err(),
2160                late,
2161                "only the healthy response strictly before the warm-up edge qualifies"
2162            );
2163        }
2164        finish_timing_child(child).await;
2165    }
2166
2167    #[cfg(unix)]
2168    #[tokio::test]
2169    async fn retirement_returns_promptly_and_shutdown_waits_for_its_journal() {
2170        let dir = cortexkit_test_support::ScratchDir::new("background-retirement");
2171        let journal = dir.join("terminals.jsonl");
2172        let supervisor =
2173            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
2174                .with_handle(SupervisorHandle::new())
2175                .with_terminal_journal(journal.clone(), "retirement-test".into());
2176        let runtime = supervisor.runtime_config();
2177        let spec = ModuleSpec {
2178            script: None,
2179            carry_containment: false,
2180            module_id: "retiring".into(),
2181            program: PathBuf::from("/bin/sleep"),
2182            args: vec!["60".into()],
2183            env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
2184                .into_iter()
2185                .map(|key| (key.into(), dir.to_string_lossy().into_owned()))
2186                .collect(),
2187            reserved: false,
2188            reserved_prefixes: vec![],
2189            protocol: ModuleProtocol::None,
2190            overlap: ModuleOverlap::Safe,
2191        };
2192        let incumbent = spawn_child(
2193            &spec,
2194            None,
2195            runtime.supervisor_handle.as_ref(),
2196            &runtime.stderr_ring,
2197            None,
2198            &runtime.child_roster,
2199            runtime.spawn_delivery(),
2200            #[cfg(target_os = "linux")]
2201            None,
2202            runtime.register_timeout,
2203        )
2204        .unwrap();
2205        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
2206        let mut active_exit = wait_error_exit_report();
2207        active_exit.code = Some(42);
2208        snapshot.lock().unwrap().last_exit = Some(active_exit);
2209        let forwarding = Arc::new(ForwardingTable::default());
2210        timeout(
2211            Duration::from_millis(100),
2212            dispatch_retirement(
2213                &spec,
2214                &runtime,
2215                &supervisor.registry,
2216                &forwarding,
2217                &snapshot,
2218                Some(incumbent),
2219                None,
2220                ConnectionId::new(999),
2221                1,
2222            ),
2223        )
2224        .await
2225        .expect("incumbent retirement must not block the promoted process's supervision");
2226        supervisor.begin_daemon_shutdown();
2227        supervisor
2228            .end_children_for_daemon_shutdown(false, std::future::pending())
2229            .await;
2230        let records = std::fs::read_to_string(&journal).unwrap();
2231        assert!(
2232            records.contains("retiring"),
2233            "shutdown must wait for the incumbent's terminal record: {records}"
2234        );
2235        assert!(records.contains("daemon_shutdown"));
2236        assert_eq!(
2237            snapshot.lock().unwrap().last_exit.as_ref().unwrap().code,
2238            Some(42),
2239            "retirement must not replace the active lifecycle's exit"
2240        );
2241    }
2242
2243    /// During a swap two processes of the module are alive, and consumers
2244    /// started by either one attest before cutover. Promotion ends the
2245    /// incumbent's authority even while its process is still draining.
2246    #[test]
2247    fn consumer_attestation_revokes_incumbent_nonce_at_promotion() {
2248        let handle = SupervisorHandle::new();
2249        handle.set_spawn_nonce("aft", "incumbent".to_string());
2250        assert!(!handle.spawned_consumer_authorized("aft", "candidate"));
2251
2252        handle.open_swap("aft", "candidate".to_string());
2253        assert!(handle.spawned_consumer_authorized("aft", "incumbent"));
2254        assert!(handle.spawned_consumer_authorized("aft", "candidate"));
2255        assert!(!handle.spawned_consumer_authorized("aft", "forged"));
2256
2257        handle.promote_swap_nonce("aft", false);
2258        assert!(
2259            !handle.spawned_consumer_authorized("aft", "incumbent"),
2260            "promotion retires the incumbent's nonce before its drain ends"
2261        );
2262        assert!(handle.spawned_consumer_authorized("aft", "candidate"));
2263
2264        handle.close_swap("aft");
2265        assert!(handle.spawned_consumer_authorized("aft", "candidate"));
2266        assert!(!handle.spawned_consumer_authorized("aft", "incumbent"));
2267    }
2268
2269    /// A module has two cgroup names, and no module id, however it is
2270    /// spelled, can produce another module's name of either kind. The ids
2271    /// here are the ones the cgroup library's own encoding merges: an `@`, its
2272    /// escape spelled out literally, and an id ending in the swap suffix.
2273    #[test]
2274    fn cgroup_names_are_injective_across_ids_and_slots() {
2275        assert_eq!(cgroup_name("aft", false), "aft");
2276        assert_eq!(cgroup_name("aft", true), "aft_swap");
2277        let ids = [
2278            "aft",
2279            "aft@swap",
2280            "aft_40swap",
2281            "aft_swap",
2282            "aft_",
2283            "mcp:x",
2284            "mcp_3ax",
2285        ];
2286        let mut names = std::collections::HashSet::new();
2287        for id in ids {
2288            for alternate in [false, true] {
2289                assert!(
2290                    names.insert(cgroup_name(id, alternate)),
2291                    "{id:?} (alternate: {alternate}) names a directory another id or slot already has: {}",
2292                    cgroup_name(id, alternate)
2293                );
2294            }
2295        }
2296    }
2297}
2298
2299/// How long a swap waits for its candidate to register and declare itself
2300/// ready when the operator does not say. A module warming as a swap candidate
2301/// may take up to 90 s (aft's ceiling, the largest in the fleet), so the
2302/// daemon allows that plus time to start the process and send HELLO.
2303pub const DEFAULT_SWAP_READY_TIMEOUT: Duration = Duration::from_secs(100);
2304
2305/// Told when a swap has promoted its candidate to be the module's active
2306/// registration.
2307///
2308/// An ordinary HELLO runs the control plane's registration side effects (the
2309/// capability cache, the deny census, the requirement recompute) as it
2310/// registers. A swap candidate's HELLO does not, because it is not routable;
2311/// promotion is when those must run instead, and promotion happens in the
2312/// supervisor, which has no other way into the control handler.
2313pub(crate) trait SwapPromotionObserver: Send + Sync {
2314    fn swap_promoted(&self, registration: &crate::registry::ModuleRegistration);
2315}
2316
2317/// The installed [`SwapPromotionObserver`], held weakly: the observer (the
2318/// control handler) owns this handle, so a strong reference back would be a
2319/// cycle that keeps both alive.
2320#[derive(Clone, Default)]
2321pub(super) struct PromotionObserverSlot(
2322    pub(super) Arc<Mutex<Option<std::sync::Weak<dyn SwapPromotionObserver>>>>,
2323);
2324
2325impl fmt::Debug for PromotionObserverSlot {
2326    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2327        f.write_str("PromotionObserverSlot")
2328    }
2329}
2330
2331/// The nonces of one open swap.
2332#[derive(Debug, Clone)]
2333pub(super) struct OpenSwap {
2334    /// Legacy candidate token. A gated candidate has an empty lifecycle
2335    /// placeholder instead; only its own channel admits its HELLO.
2336    pub(super) candidate_nonce: String,
2337    /// Incumbent token accepted before cutover, then cleared by promotion even
2338    /// while the incumbent's process is still draining.
2339    pub(super) incumbent_nonce: Option<String>,
2340    /// Set once a HELLO has been admitted with the swap token, so the token
2341    /// admits one registration and cannot be replayed after cutover empties
2342    /// the candidate slot.
2343    candidate_admitted: bool,
2344}
2345
2346/// What the swap gate says about a HELLO. See
2347/// [`SupervisorHandle::swap_hello_admission`].
2348#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2349pub(crate) enum SwapHelloAdmission {
2350    /// No swap is open for the id (or the HELLO carries the incumbent's own
2351    /// nonce); the ordinary gates decide.
2352    NotSwapping,
2353    /// The HELLO carries the swap token: register it into the candidate slot.
2354    Candidate,
2355    /// A swap is open and the HELLO carries a nonce the supervisor did not
2356    /// mint for this id, no nonce, or a token already used.
2357    Refused,
2358    /// The id belongs to a supervised `protocol: none` module. Such a module
2359    /// never registers, so no HELLO may claim its id, with or without a nonce.
2360    ProtocolNone,
2361    /// The id is gated. Its supervised child registers only over the
2362    /// registration channel it inherited at launch, never by HELLO alone.
2363    ChannelRequired,
2364}
2365
2366impl SupervisorHandle {
2367    /// Whether `presented` is either nonce of an open swap for `module_id`.
2368    pub(super) fn swap_nonce_matches(&self, module_id: &str, presented: &str) -> bool {
2369        if self.module_is_gated(module_id) || self.protocol_none(module_id) || presented.is_empty()
2370        {
2371            return false;
2372        }
2373        let swaps = self
2374            .swaps
2375            .lock()
2376            .unwrap_or_else(|poisoned| poisoned.into_inner());
2377        swaps.get(module_id).is_some_and(|swap| {
2378            constant_time_eq(swap.candidate_nonce.as_bytes(), presented.as_bytes())
2379                || swap.incumbent_nonce.as_deref().is_some_and(|incumbent| {
2380                    constant_time_eq(incumbent.as_bytes(), presented.as_bytes())
2381                })
2382        })
2383    }
2384
2385    /// Open a swap for `module_id` with the candidate's freshly minted nonce.
2386    /// Called before the candidate process exists.
2387    pub(crate) fn open_swap(&self, module_id: &str, candidate_nonce: String) {
2388        let incumbent_nonce = self
2389            .spawn_nonces
2390            .lock()
2391            .unwrap_or_else(|poisoned| poisoned.into_inner())
2392            .get(module_id)
2393            .cloned();
2394        self.swaps
2395            .lock()
2396            .unwrap_or_else(|poisoned| poisoned.into_inner())
2397            .insert(
2398                module_id.to_string(),
2399                OpenSwap {
2400                    candidate_nonce,
2401                    incumbent_nonce,
2402                    candidate_admitted: false,
2403                },
2404            );
2405        self.refresh_program_binding_nonces(module_id);
2406    }
2407
2408    /// Close the swap for `module_id`, releasing whichever nonce is no longer
2409    /// the module's recorded one.
2410    pub(crate) fn close_swap(&self, module_id: &str) {
2411        self.swaps
2412            .lock()
2413            .unwrap_or_else(|poisoned| poisoned.into_inner())
2414            .remove(module_id);
2415        self.refresh_program_binding_nonces(module_id);
2416    }
2417
2418    /// Install the observer told about swap promotions, replacing any earlier
2419    /// one.
2420    pub(crate) fn set_swap_promotion_observer(
2421        &self,
2422        observer: std::sync::Weak<dyn SwapPromotionObserver>,
2423    ) {
2424        *self
2425            .promotion_observer
2426            .0
2427            .lock()
2428            .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(observer);
2429    }
2430
2431    /// Tell the installed observer, if it is still alive, that a swap promoted
2432    /// `registration`.
2433    fn notify_swap_promoted(&self, registration: &crate::registry::ModuleRegistration) {
2434        let observer = self
2435            .promotion_observer
2436            .0
2437            .lock()
2438            .unwrap_or_else(|poisoned| poisoned.into_inner())
2439            .as_ref()
2440            .and_then(std::sync::Weak::upgrade);
2441        if let Some(observer) = observer {
2442            observer.swap_promoted(registration);
2443        }
2444    }
2445
2446    /// Whether a swap is open for `module_id`.
2447    pub(crate) fn swap_open(&self, module_id: &str) -> bool {
2448        self.swaps
2449            .lock()
2450            .unwrap_or_else(|poisoned| poisoned.into_inner())
2451            .contains_key(module_id)
2452    }
2453
2454    /// Make the candidate's nonce the module's recorded spawn nonce, as a plain
2455    /// respawn would, once cutover has made the candidate the module's process.
2456    /// Promotion revokes the incumbent's tokens; the swap record stays open
2457    /// only for lifecycle cleanup while the old process drains.
2458    pub(super) fn promote_swap_nonce(&self, module_id: &str, reserved: bool) {
2459        let candidate_nonce = self
2460            .swaps
2461            .lock()
2462            .unwrap_or_else(|poisoned| poisoned.into_inner())
2463            .get_mut(module_id)
2464            .map(|swap| {
2465                swap.incumbent_nonce = None;
2466                swap.candidate_nonce.clone()
2467            });
2468        self.spawn_nonces
2469            .lock()
2470            .unwrap_or_else(|p| p.into_inner())
2471            .remove(module_id);
2472        {
2473            let mut nonces = self
2474                .reserved_nonces
2475                .lock()
2476                .unwrap_or_else(|p| p.into_inner());
2477            if reserved || nonces.contains_key(module_id) {
2478                nonces.insert(module_id.into(), None);
2479            }
2480        }
2481        if self.module_is_gated(module_id) {
2482            return;
2483        }
2484        let Some(nonce) = candidate_nonce.filter(|nonce| !nonce.is_empty()) else {
2485            return;
2486        };
2487        self.set_spawn_nonce(module_id, nonce.clone());
2488        if reserved {
2489            self.set_reserved_nonce(module_id, nonce);
2490        }
2491    }
2492
2493    /// The swap gate for a HELLO claiming `module_id`.
2494    ///
2495    /// This runs BEFORE the reserved-module gate. A reserved module's candidate
2496    /// presents the candidate nonce, which the reserved gate (holding the
2497    /// incumbent's nonce) would refuse as `reserved_module` before swap
2498    /// admission was ever reached. And it applies to unreserved ids too: for an
2499    /// unreserved id the only thing that ever stopped a second process claiming
2500    /// a live id was the `duplicate_module_id` refusal, which is exactly the
2501    /// refusal a swap lifts for its candidate.
2502    ///
2503    /// The incumbent's own nonce falls through to the ordinary gates, which
2504    /// treat it as they always have (a live incumbent is refused as a
2505    /// duplicate). Anything else while a swap is open is refused, including an
2506    /// absent nonce.
2507    pub(crate) fn swap_hello_admission(
2508        &self,
2509        module_id: &str,
2510        presented: Option<&str>,
2511    ) -> SwapHelloAdmission {
2512        if self.protocol_none(module_id) {
2513            return SwapHelloAdmission::ProtocolNone;
2514        }
2515        if self.module_is_gated(module_id) {
2516            return SwapHelloAdmission::ChannelRequired;
2517        }
2518        let swaps = self
2519            .swaps
2520            .lock()
2521            .unwrap_or_else(|poisoned| poisoned.into_inner());
2522        let Some(swap) = swaps.get(module_id) else {
2523            return SwapHelloAdmission::NotSwapping;
2524        };
2525        let Some(presented) = presented.filter(|nonce| !nonce.is_empty()) else {
2526            return SwapHelloAdmission::Refused;
2527        };
2528        if constant_time_eq(swap.candidate_nonce.as_bytes(), presented.as_bytes()) {
2529            return if swap.candidate_admitted {
2530                SwapHelloAdmission::Refused
2531            } else {
2532                SwapHelloAdmission::Candidate
2533            };
2534        }
2535        if swap
2536            .incumbent_nonce
2537            .as_deref()
2538            .is_some_and(|incumbent| constant_time_eq(incumbent.as_bytes(), presented.as_bytes()))
2539        {
2540            return SwapHelloAdmission::NotSwapping;
2541        }
2542        SwapHelloAdmission::Refused
2543    }
2544}
2545
2546impl SupervisorHandle {
2547    /// Exclude swap closure through the short, synchronous candidate publication.
2548    pub(crate) fn with_swap_candidate_admission<T>(
2549        &self,
2550        module_id: &str,
2551        publish: impl FnOnce() -> (T, bool),
2552    ) -> Option<T> {
2553        let mut swaps = self.swaps.lock().unwrap_or_else(|p| p.into_inner());
2554        let swap = swaps
2555            .get_mut(module_id)
2556            .filter(|swap| !swap.candidate_admitted)?;
2557        let (result, admitted) = publish();
2558        swap.candidate_admitted = admitted;
2559        Some(result)
2560    }
2561}
2562
2563impl SupervisedModule {
2564    /// Blue/green restart: see `SupervisorCommand::Swap` and the
2565    /// `supervisor_swap` module. Returns once the swap has cut over (the old
2566    /// process then drains in the background of the supervise loop), has been
2567    /// superseded by an approved configuration restart, or has failed. Both
2568    /// supersession and failure leave the old process serving until replacement.
2569    pub async fn swap(
2570        &self,
2571        ready_timeout: Option<Duration>,
2572    ) -> Result<SwapOutcome, SuperviseError> {
2573        self.swap_requested(ready_timeout, None).await
2574    }
2575
2576    pub(crate) async fn swap_requested(
2577        &self,
2578        ready_timeout: Option<Duration>,
2579        requester: Option<Principal>,
2580    ) -> Result<SwapOutcome, SuperviseError> {
2581        let (reply_tx, reply_rx) = oneshot::channel();
2582        self.inner
2583            .commands
2584            .send(SupervisorCommand::Swap {
2585                requester,
2586                ready_timeout,
2587                reply: reply_tx,
2588            })
2589            .await
2590            .map_err(|_| SuperviseError::CommandClosed {
2591                module_id: self.inner.module_id.clone(),
2592            })?;
2593        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
2594            module_id: self.inner.module_id.clone(),
2595        })?
2596    }
2597}