Skip to main content

subc_daemon/
supervise_swap.rs

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