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