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