Skip to main content

subc_daemon/supervise/
spawn.rs

1use super::*;
2use crate::live_children::ContainerEndReason;
3
4/// Command-line flag used by supervised modules to find subc.
5///
6/// subc launches module-mode children as `<module> --subc <connection-file-path>`.
7/// The path points at the TCP+key connection file; it is not an ambient signal and
8/// is never inherited by standalone children.
9pub const SUBC_ARG: &str = "--subc";
10
11// Child admission durably records identity before exec. Disk pressure can make
12// fsync slow without implying a failed child start, so allow a generous budget.
13#[cfg(any(unix, feature = "test-support"))]
14pub(super) const ADMISSION_TIMEOUT: Duration = Duration::from_secs(30);
15
16/// Daemon-side child-admission budget, for integration-test RPC deadlines.
17#[cfg(feature = "test-support")]
18pub const CHILD_ADMISSION_TIMEOUT: Duration = ADMISSION_TIMEOUT;
19
20#[cfg(unix)]
21pub(super) type SpawnRegistrationChannel = std::os::unix::net::UnixStream;
22#[cfg(windows)]
23pub(super) type SpawnRegistrationChannel = subc_os::registration_channel::RegistrationPipe;
24#[cfg(test)]
25pub(super) type CapturedRegistrationChannels =
26    Arc<Mutex<Option<Vec<(Arc<RegistrationSpawn>, CapturedRegistrationEndpoint)>>>>;
27#[cfg(test)]
28pub(super) struct CapturedRegistrationEndpoint {
29    pub(super) _channel: SpawnRegistrationChannel,
30}
31#[cfg(test)]
32impl fmt::Debug for CapturedRegistrationEndpoint {
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        f.write_str("CapturedRegistrationEndpoint")
35    }
36}
37
38/// The installed companion that evaluates a script module.
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40#[non_exhaustive]
41pub enum ScriptRuntime {
42    Bun,
43    Python,
44}
45
46impl ScriptRuntime {
47    pub const fn as_str(self) -> &'static str {
48        match self {
49            Self::Bun => "bun",
50            Self::Python => "python",
51        }
52    }
53}
54
55/// Script content and the runtime approved to evaluate it.
56#[derive(Debug, Clone, PartialEq, Eq)]
57#[non_exhaustive]
58pub struct ScriptEntry {
59    pub runtime: ScriptRuntime,
60    pub path: PathBuf,
61}
62
63impl ScriptEntry {
64    pub fn new(runtime: ScriptRuntime, path: PathBuf) -> Self {
65        Self { runtime, path }
66    }
67}
68
69/// How to launch one singleton module process.
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct ModuleSpec {
72    pub module_id: String,
73    pub program: PathBuf,
74    /// Bundled script content. The program is always the installed runtime runner.
75    pub script: Option<ScriptEntry>,
76    pub args: Vec<String>,
77    pub env: Vec<(String, String)>,
78    /// When true this is a reserved module: each spawn gets a fresh one-time launch
79    /// nonce that the child must echo in its HELLO, so only the daemon-spawned
80    /// process can register this module_id (a security-boundary module like the
81    /// credential vault must not be impersonable while it is down/restarting).
82    pub reserved: bool,
83    /// Module-id prefixes this supervised module owns for reserved HELLO checks.
84    /// Prefixes come from daemon config and must end in `:` before they reach the
85    /// supervisor; the owner module's current spawn nonce authorizes claims under
86    /// each prefix.
87    pub reserved_prefixes: Vec<String>,
88    /// The wire protocol this module speaks, as DECLARED in daemon config.
89    ///
90    /// [`ModuleProtocol::None`] changes five things and nothing else: wire health
91    /// probing is suppressed (an optional HTTP probe can replace it), teardown sends SIGTERM before waiting,
92    /// `route.open` is refused, the spawn passes NO `--subc <path>` argument
93    /// and NO launch nonce, and a clean exit the daemon did not request is
94    /// restarted as a crash rather than recorded as a stop (see `on_child_exit`:
95    /// a stock program exits 0 on a stray SIGTERM, and a stop would leave it
96    /// down for good). `SUBC_MODULE_ID` still goes into the environment,
97    /// because a process ignores an environment variable it does not read.
98    ///
99    /// The argument is the part that cannot be "harmless to a process that
100    /// ignores it": a stock binary exits on an unknown flag before it listens
101    /// (`nats-server`: "flag provided but not defined: -subc"), which is how the
102    /// first conformance run against this mode found it. The nonce is withheld
103    /// because a process that will never present it gains nothing from holding
104    /// it, and a secret in the environment of a process that does not need it is
105    /// a leak surface for no benefit.
106    pub protocol: ModuleProtocol,
107    /// Whether two processes of this module may run at once, which is what a
108    /// blue/green swap does for the length of its overlap. Declared in daemon
109    /// config because the daemon must be able to answer it while the module is
110    /// down, and so a module cannot talk itself into it after registering.
111    pub overlap: ModuleOverlap,
112    /// Keep module-started helpers in the same container across replacements.
113    /// This is a daemon-config policy, fixed for the lifetime of a container;
114    /// stopping the module or losing its supervisor still destroys the container.
115    pub carry_containment: bool,
116}
117
118/// Only the configured launch inputs enter this value; spawned connection paths,
119/// nonces and inherited environment never do. Its bytes remain daemon-private.
120#[derive(Clone, PartialEq, Eq)]
121pub(crate) struct LaunchSpecDigest(pub(super) [u8; 32]);
122
123impl fmt::Debug for LaunchSpecDigest {
124    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125        f.write_str("LaunchSpecDigest([redacted])")
126    }
127}
128
129impl LaunchSpecDigest {
130    pub(crate) fn from_spec(spec: &ModuleSpec) -> Self {
131        fn field(hash: &mut Sha256, bytes: &[u8]) {
132            hash.update((bytes.len() as u64).to_le_bytes());
133            hash.update(bytes);
134        }
135        let mut hash = Sha256::new();
136        if let Some(script) = &spec.script {
137            field(
138                &mut hash,
139                match script.runtime {
140                    ScriptRuntime::Bun => b"bun-script",
141                    ScriptRuntime::Python => b"python-script",
142                },
143            );
144            field(&mut hash, script.path.as_os_str().as_encoded_bytes());
145        }
146        if let Some(program) = spec.program.to_str() {
147            field(&mut hash, b"utf8-program");
148            field(&mut hash, program.as_bytes());
149        } else {
150            // The daemon config is UTF-8, but in-process callers may provide
151            // native paths: lossy conversion would collapse distinct programs.
152            #[cfg(unix)]
153            {
154                use std::os::unix::ffi::OsStrExt;
155                field(&mut hash, b"unix-program");
156                field(&mut hash, spec.program.as_os_str().as_bytes());
157            }
158            #[cfg(windows)]
159            {
160                use std::os::windows::ffi::OsStrExt;
161                field(&mut hash, b"windows-program");
162                let bytes = spec
163                    .program
164                    .as_os_str()
165                    .encode_wide()
166                    .flat_map(u16::to_le_bytes)
167                    .collect::<Vec<_>>();
168                field(&mut hash, &bytes);
169            }
170            #[cfg(not(any(unix, windows)))]
171            field(&mut hash, spec.program.to_string_lossy().as_bytes());
172        }
173        hash.update((spec.args.len() as u64).to_le_bytes());
174        for arg in &spec.args {
175            field(&mut hash, arg.as_bytes());
176        }
177        let mut env = spec.env.iter().collect::<Vec<_>>();
178        env.sort_unstable();
179        hash.update((env.len() as u64).to_le_bytes());
180        for (key, value) in env {
181            field(&mut hash, key.as_bytes());
182            field(&mut hash, value.as_bytes());
183        }
184        field(
185            &mut hash,
186            match spec.protocol {
187                ModuleProtocol::Subc => b"subc",
188                ModuleProtocol::None => b"none",
189            },
190        );
191        Self(hash.finalize().into())
192    }
193}
194
195/// Whether a module tolerates a second process of itself running alongside.
196///
197/// Most modules are single-writer on their store (a WAL, a capture log, a
198/// resident index behind a writer barrier), and two processes on one store
199/// corrupt it. So a swap, which overlaps the old and new process by design,
200/// is refused unless the module's config opts in with `overlap: "safe"`.
201#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
202pub enum ModuleOverlap {
203    /// Never run two processes of this module at once. The default.
204    #[default]
205    Exclusive,
206    /// The module has said a second process of itself is harmless for the
207    /// length of a swap.
208    ///
209    /// Declare it only if a second instance can run for a few seconds without
210    /// touching ANY single-writer store: every database, WAL, index, projector
211    /// and scheduled job the module owns. A lease on part of that state is not
212    /// enough. broca's session lease guards WAL appends while its run index, its
213    /// store projector and its archive fold timer (which unlinks live WAL files)
214    /// stay single-writer, so broca is exclusive despite holding a lease. The
215    /// refusal only fires after this has been decided, so the decision is the
216    /// check.
217    Safe,
218}
219
220impl ModuleOverlap {
221    pub fn as_str(self) -> &'static str {
222        match self {
223            Self::Exclusive => "exclusive",
224            Self::Safe => "safe",
225        }
226    }
227}
228
229/// Environment variable telling a spawned module which case it was started
230/// for, before it sends HELLO. Only a swap candidate carries it, as
231/// [`SPAWN_ROLE_SWAP_CANDIDATE`]; every other spawn has it removed.
232///
233/// It chooses a warm-up budget, nothing else: a swap candidate can warm for
234/// longer because nobody waits on it, while a plain restart must flip ready
235/// quickly because callers see `module_warming` until it does. Absence means
236/// plain restart, the safe reading. The daemon trusts nothing about it; the
237/// candidate is proven by its launch nonce at HELLO.
238pub const SUBC_SPAWN_ROLE_ENV: &str = "SUBC_SPAWN_ROLE";
239/// The one value of [`SUBC_SPAWN_ROLE_ENV`] the daemon sets.
240pub const SPAWN_ROLE_SWAP_CANDIDATE: &str = "swap_candidate";
241
242/// A roster entry whose monitor and first process have not started yet.
243/// Keeping the command receiver here lets discovery serve status immediately
244/// while start/stop requests wait until bootstrap has published the connection file.
245pub(crate) struct RegisteredConfiguredModule {
246    pub(super) spec: ModuleSpec,
247    pub(super) runtime: SupervisorRuntimeConfig,
248    pub(super) module: SupervisedModule,
249    pub(super) commands: mpsc::Receiver<SupervisorCommand>,
250}
251
252/// Test-only hook run on the path that takes on a new module, right after its
253/// first `spawn_child` returns (the process exists and could already be
254/// registering) and before that process is handed to the module's supervise
255/// loop and put on the roster. Lets a test observe what a fast child would see
256/// in that window without racing a real one.
257#[cfg(test)]
258#[derive(Clone, Default)]
259pub(super) struct AfterFirstSpawnHook(pub(super) Option<AfterFirstSpawnFn>);
260
261#[cfg(test)]
262type AfterFirstSpawnFn = Arc<dyn Fn(&str) + Send + Sync>;
263
264#[cfg(test)]
265impl fmt::Debug for AfterFirstSpawnHook {
266    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267        f.write_str("AfterFirstSpawnHook")
268    }
269}
270
271#[cfg(test)]
272impl AfterFirstSpawnHook {
273    fn run(&self, module_id: &str) {
274        if let Some(hook) = &self.0 {
275            hook(module_id);
276        }
277    }
278}
279
280impl Supervisor {
281    #[cfg(all(test, target_os = "linux"))]
282    pub(crate) fn set_admission_hook_for_test(
283        &self,
284        hook: impl Fn(&str, &'static str, Option<u32>) -> bool + Send + Sync + 'static,
285    ) {
286        self.child_roster.set_admission_hook_for_test(hook);
287    }
288
289    #[cfg(test)]
290    pub(crate) fn new_for_test(registry: Arc<Registry>, policy: RestartPolicy) -> Self {
291        let supervisor = Self::new(registry, policy);
292        #[cfg(target_os = "macos")]
293        let supervisor = supervisor.with_privacy_trampoline(test_privacy_trampoline());
294        supervisor
295    }
296}
297
298impl Supervisor {
299    /// Spawn `spec.program` and start monitoring it.
300    ///
301    /// The child is expected to parse `--subc <connection-file-path>`, read the
302    /// TCP+key connection file, authenticate to the already-running listener, and
303    /// register with channel-0 `HELLO` using `spec.module_id` as its manifest id.
304    ///
305    /// This synchronous embedder API blocks on launch admission and store I/O.
306    /// Do not call it on an async runtime thread; use [`Self::spawn_async`].
307    pub fn spawn(&self, spec: ModuleSpec) -> Result<SupervisedModule, SuperviseError> {
308        validate_spec(&spec)?;
309        self.establish_identity(&spec);
310
311        let runtime = self.runtime_config();
312        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
313        let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
314        let registration_watch = watch_registration(&self.registry, &spec);
315        let spawned = spawn_child(
316            &spec,
317            runtime.connection_file_path.as_deref(),
318            self.supervisor_handle.as_ref(),
319            &runtime.stderr_ring,
320            runtime.capture_logs_dir.as_deref(),
321            &runtime.child_roster,
322            runtime.spawn_delivery(),
323            #[cfg(target_os = "linux")]
324            runtime.cgroup_placement.as_ref(),
325            runtime.register_timeout,
326        );
327        #[cfg(test)]
328        self.test_after_first_spawn.run(&spec.module_id);
329        let mut child = match spawned {
330            Ok(child) => child,
331            Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
332                defer_config_spawn(
333                    &spec,
334                    &runtime,
335                    &snapshot,
336                    RespawnKind::Spawn,
337                    &runtime.failure_context(runtime.recovery_is_daemon),
338                )?;
339                return Ok(self.supervised_module(spec, runtime, snapshot, None));
340            }
341            Err(SuperviseError::ConfigHeld { .. }) => {
342                hold_config_spawn(
343                    &spec,
344                    &runtime,
345                    &snapshot,
346                    &runtime.failure_context(runtime.recovery_is_daemon),
347                )?;
348                return Ok(self.supervised_module(spec, runtime, snapshot, None));
349            }
350            Err(err) => {
351                // Unlike the configured paths, a failed `spawn` leaves nothing
352                // on the roster, so the module must not stay marked configured.
353                self.abandon_unrostered(&spec.module_id);
354                return Err(err);
355            }
356        };
357        arm_registration_deadline(&mut child, runtime.register_timeout, registration_watch);
358        self.mark_first_process_running(&spec, &runtime, &snapshot, &mut child)?;
359        if let Some(spawn) = activity_spawn {
360            spawn.complete(&snapshot);
361        }
362
363        Ok(self.supervised_module(spec, runtime, snapshot, Some(child)))
364    }
365
366    /// Spawn without running configuration integrity or keychain checks on the
367    /// runtime thread. Cancellation during preparation cannot create a child.
368    pub async fn spawn_async(&self, spec: ModuleSpec) -> Result<SupervisedModule, SuperviseError> {
369        validate_spec(&spec)?;
370        self.establish_identity(&spec);
371        let mut identity = AsyncInitialIdentity {
372            supervisor: self,
373            module: spec.module_id.clone(),
374            committed: false,
375        };
376        let runtime = self.runtime_config();
377        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
378        let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
379        let registration_watch = watch_registration(&self.registry, &spec);
380        let spawned = spawn_child_async(&spec, &runtime).await;
381        #[cfg(test)]
382        self.test_after_first_spawn.run(&spec.module_id);
383        let mut child = match spawned {
384            Ok(child) => child,
385            Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
386                defer_config_spawn(
387                    &spec,
388                    &runtime,
389                    &snapshot,
390                    RespawnKind::Spawn,
391                    &runtime.failure_context(runtime.recovery_is_daemon),
392                )?;
393                identity.committed = true;
394                return Ok(self.supervised_module(spec, runtime, snapshot, None));
395            }
396            Err(SuperviseError::ConfigHeld { .. }) => {
397                hold_config_spawn(
398                    &spec,
399                    &runtime,
400                    &snapshot,
401                    &runtime.failure_context(runtime.recovery_is_daemon),
402                )?;
403                identity.committed = true;
404                return Ok(self.supervised_module(spec, runtime, snapshot, None));
405            }
406            Err(err) => {
407                self.abandon_unrostered(&spec.module_id);
408                return Err(err);
409            }
410        };
411        arm_registration_deadline(&mut child, runtime.register_timeout, registration_watch);
412        self.mark_first_process_running(&spec, &runtime, &snapshot, &mut child)?;
413        if let Some(spawn) = activity_spawn {
414            spawn.complete(&snapshot);
415        }
416        identity.committed = true;
417        Ok(self.supervised_module(spec, runtime, snapshot, Some(child)))
418    }
419
420    /// Make `spec`'s module count as configured, with its identity gates
421    /// (reserved id, reserved prefixes) in place, BEFORE any process of it
422    /// exists.
423    ///
424    /// Every path that takes on a new module calls this before `spawn_child`.
425    /// The order is the point: the child can connect, register, sync its
426    /// scopes and ask about them as soon as it is spawned, and the module is
427    /// only put on the roster after `spawn_child` returns. Were the mark set
428    /// with the roster entry, a fast child would see its own owner reported
429    /// as not configured, and a scoped `route.open` in that window would be
430    /// refused as terminal `scope_not_live` ("will never sync") instead of
431    /// retryable `scope_not_synced`.
432    fn establish_identity(&self, spec: &ModuleSpec) {
433        if let Some(supervisor_handle) = &self.supervisor_handle {
434            supervisor_handle.apply_identity_configuration(spec);
435            supervisor_handle.mark_configured(&spec.module_id);
436        }
437    }
438
439    /// Take back [`Self::establish_identity`]'s configured mark when the
440    /// module will not be put on the roster after all.
441    fn abandon_unrostered(&self, module_id: &str) {
442        if let Some(supervisor_handle) = &self.supervisor_handle {
443            supervisor_handle.unmark_configured_unless_rostered(module_id);
444        }
445    }
446
447    /// Record a freshly spawned first process as running. On failure the
448    /// module never reaches the roster, so its configured mark is taken back.
449    fn mark_first_process_running(
450        &self,
451        spec: &ModuleSpec,
452        runtime: &SupervisorRuntimeConfig,
453        snapshot: &SharedSnapshot,
454        child: &mut SupervisedChild,
455    ) -> Result<(), SuperviseError> {
456        if let Err(err) = set_running(snapshot, child, &spec.module_id, &runtime.spawn_events) {
457            containment::terminate_blocking(&runtime.child_roster.containment);
458            self.abandon_unrostered(&spec.module_id);
459            return Err(err);
460        }
461        self.process_liveness
462            .track(spec.module_id.clone(), Arc::clone(snapshot));
463        Ok(())
464    }
465
466    /// Start supervising a module declared in daemon configuration.
467    ///
468    /// Unlike [`Self::spawn`], this records disabled modules and immediate spawn
469    /// failures in the supervisor handle so operator-facing `supervisor.list`
470    /// reflects every configured module while daemon startup continues.
471    pub fn supervise_configured(
472        &self,
473        spec: ModuleSpec,
474        enabled: bool,
475    ) -> Result<SupervisedModule, SuperviseError> {
476        self.supervise_configured_requested(
477            spec,
478            enabled,
479            self.health.clone(),
480            None,
481            self.restart_policy,
482            DEFAULT_REGISTER_TIMEOUT,
483            None,
484        )
485    }
486
487    /// Supervise a configured module with its own health, drain, and crash
488    /// budget. The restart policy is per-module because the config file is:
489    /// `modules.<id>.restart` resolves to a full policy at parse time, and a
490    /// module that is expensive to restart should not be forced onto the same
491    /// budget as one that is cheap.
492    pub fn supervise_configured_with_health(
493        &self,
494        spec: ModuleSpec,
495        enabled: bool,
496        health: HealthConfig,
497        drain_timeout_ms: Option<u64>,
498        restart_policy: RestartPolicy,
499    ) -> Result<SupervisedModule, SuperviseError> {
500        self.supervise_configured_requested(
501            spec,
502            enabled,
503            health,
504            drain_timeout_ms,
505            restart_policy,
506            DEFAULT_REGISTER_TIMEOUT,
507            None,
508        )
509    }
510
511    #[allow(clippy::too_many_arguments)]
512    pub(crate) fn supervise_configured_requested(
513        &self,
514        spec: ModuleSpec,
515        enabled: bool,
516        health: HealthConfig,
517        drain_timeout_ms: Option<u64>,
518        restart_policy: RestartPolicy,
519        register_timeout: Duration,
520        requester: Option<Principal>,
521    ) -> Result<SupervisedModule, SuperviseError> {
522        let registered = self.register_configured_with_health(
523            spec,
524            enabled,
525            health,
526            drain_timeout_ms,
527            restart_policy,
528            register_timeout,
529        )?;
530        let daemon_initiated = requester.is_none();
531        self.start_registered_configured(registered, requester, daemon_initiated)
532    }
533
534    #[allow(clippy::too_many_arguments)]
535    pub(crate) async fn supervise_configured_requested_async(
536        &self,
537        spec: ModuleSpec,
538        enabled: bool,
539        health: HealthConfig,
540        drain_timeout_ms: Option<u64>,
541        restart_policy: RestartPolicy,
542        register_timeout: Duration,
543        requester: Option<Principal>,
544    ) -> Result<SupervisedModule, SuperviseError> {
545        let registered = self.register_configured_with_health(
546            spec,
547            enabled,
548            health,
549            drain_timeout_ms,
550            restart_policy,
551            register_timeout,
552        )?;
553        let daemon_initiated = requester.is_none();
554        self.start_registered_configured_async(registered, requester, daemon_initiated)
555            .await
556    }
557
558    /// Record a configured module as starting or disabled, without launching a
559    /// process or running its monitor. Bootstrap registers the entire roster
560    /// before publishing discovery, then activates it once children can read
561    /// the connection file passed in their `--subc` argument.
562    pub(crate) fn register_configured_with_health(
563        &self,
564        spec: ModuleSpec,
565        enabled: bool,
566        health: HealthConfig,
567        drain_timeout_ms: Option<u64>,
568        restart_policy: RestartPolicy,
569        register_timeout: Duration,
570    ) -> Result<RegisteredConfiguredModule, SuperviseError> {
571        validate_spec(&spec)?;
572        self.establish_identity(&spec);
573
574        let mut runtime = self.runtime_config();
575        runtime.health = health;
576        runtime.restart_policy = restart_policy;
577        runtime.register_timeout = register_timeout;
578        if let Some(ms) = drain_timeout_ms {
579            runtime.drain_timeout = Duration::from_millis(ms);
580            *runtime
581                .effective_drain_timeout
582                .lock()
583                .unwrap_or_else(|poisoned| poisoned.into_inner()) = runtime.drain_timeout;
584        }
585        let snapshot = if enabled {
586            SupervisorSnapshot::starting()
587        } else {
588            SupervisorSnapshot::disabled()
589        };
590        let snapshot = {
591            let mut snapshot = snapshot;
592            if enabled {
593                if let Some((pid, reason)) = runtime.child_roster.previous_instance(&spec.module_id)
594                {
595                    snapshot.waiting_for_previous_pid = Some(pid);
596                    snapshot.waiting_for_previous_detail = Some(reason.waiting_message(pid));
597                }
598            }
599            snapshot
600        };
601        let (module, commands) =
602            self.register_module(&spec, &runtime, Arc::new(Mutex::new(snapshot)));
603        Ok(RegisteredConfiguredModule {
604            spec,
605            runtime,
606            module,
607            commands,
608        })
609    }
610
611    /// Activate a previously registered module. Queued control requests are
612    /// served by the monitor after the initial configured spawn has settled.
613    pub(crate) fn start_registered_configured(
614        &self,
615        registered: RegisteredConfiguredModule,
616        requester: Option<Principal>,
617        daemon_initiated: bool,
618    ) -> Result<SupervisedModule, SuperviseError> {
619        let RegisteredConfiguredModule {
620            spec,
621            mut runtime,
622            module,
623            commands,
624        } = registered;
625        runtime.start_requester = requester;
626        runtime.recovery_is_daemon = daemon_initiated;
627        let snapshot = &module.inner.snapshot;
628        let should_spawn = {
629            let state = lock_snapshot(snapshot)?;
630            state.enabled && state.waiting_for_previous_pid.is_none()
631        };
632        let child = if should_spawn {
633            let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
634            let registration_watch = watch_registration(&self.registry, &spec);
635            let spawned = spawn_child(
636                &spec,
637                runtime.connection_file_path.as_deref(),
638                self.supervisor_handle.as_ref(),
639                &runtime.stderr_ring,
640                runtime.capture_logs_dir.as_deref(),
641                &runtime.child_roster,
642                runtime.spawn_delivery(),
643                #[cfg(target_os = "linux")]
644                runtime.cgroup_placement.as_ref(),
645                runtime.register_timeout,
646            );
647            #[cfg(test)]
648            self.test_after_first_spawn.run(&spec.module_id);
649            match spawned {
650                Ok(mut child) => {
651                    arm_registration_deadline(
652                        &mut child,
653                        runtime.register_timeout,
654                        registration_watch,
655                    );
656                    self.mark_first_process_running(&spec, &runtime, snapshot, &mut child)?;
657                    if let Some(spawn) = activity_spawn {
658                        spawn.complete(snapshot);
659                    }
660                    Some(child)
661                }
662                Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
663                    defer_config_spawn(
664                        &spec,
665                        &runtime,
666                        snapshot,
667                        RespawnKind::Spawn,
668                        &runtime.failure_context(daemon_initiated),
669                    )?;
670                    None
671                }
672                Err(mut err) => {
673                    if matches!(err, SuperviseError::ConfigHeld { .. }) {
674                        match hold_config_spawn(
675                            &spec,
676                            &runtime,
677                            snapshot,
678                            &runtime.failure_context(daemon_initiated),
679                        ) {
680                            Ok(()) => {
681                                self.start_monitor(spec, runtime, &module, None, commands);
682                                return Ok(module);
683                            }
684                            Err(parking_error) => err = parking_error,
685                        }
686                    }
687                    if runtime.health.critical {
688                        error!(
689                            module_id = %spec.module_id,
690                            program = %spec.program.display(),
691                            error = %err,
692                            "critical configured module failed to spawn; marking failed and alerting"
693                        );
694                    } else {
695                        error!(
696                            module_id = %spec.module_id,
697                            program = %spec.program.display(),
698                            error = %err,
699                            "configured module failed to spawn; marking failed and continuing"
700                        );
701                    }
702                    fail_snapshot(
703                        snapshot,
704                        Some(&spec.module_id),
705                        None,
706                        &runtime.failure_context(daemon_initiated),
707                    );
708                    None
709                }
710            }
711        } else {
712            None
713        };
714        self.start_monitor(spec, runtime, &module, child, commands);
715        Ok(module)
716    }
717
718    pub(crate) async fn start_registered_configured_async(
719        &self,
720        registered: RegisteredConfiguredModule,
721        requester: Option<Principal>,
722        daemon_initiated: bool,
723    ) -> Result<SupervisedModule, SuperviseError> {
724        self.start_registered_with_failure_policy(registered, requester, daemon_initiated, None)
725            .await
726    }
727
728    pub(crate) async fn start_registered_approved_async(
729        &self,
730        registered: RegisteredConfiguredModule,
731        requester: Principal,
732        generation: crate::config_gate::runtime::ApprovalIdentity,
733    ) -> Result<SupervisedModule, SuperviseError> {
734        self.start_registered_with_failure_policy(
735            registered,
736            Some(requester),
737            false,
738            Some(generation),
739        )
740        .await
741    }
742
743    async fn start_registered_with_failure_policy(
744        &self,
745        registered: RegisteredConfiguredModule,
746        requester: Option<Principal>,
747        daemon_initiated: bool,
748        approved_generation: Option<crate::config_gate::runtime::ApprovalIdentity>,
749    ) -> Result<SupervisedModule, SuperviseError> {
750        let RegisteredConfiguredModule {
751            spec,
752            mut runtime,
753            module,
754            commands,
755        } = registered;
756        runtime.start_requester = requester;
757        runtime.recovery_is_daemon = daemon_initiated;
758        let snapshot = &module.inner.snapshot;
759        let mut startup_error = None;
760        let failure = FailureContext {
761            approval: approved_generation.clone(),
762            ..runtime.failure_context(daemon_initiated)
763        };
764        let should_spawn = {
765            let state = lock_snapshot(snapshot)?;
766            state.enabled && state.waiting_for_previous_pid.is_none()
767        };
768        let child = if should_spawn {
769            let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
770            let registration_watch = watch_registration(&self.registry, &spec);
771            let spawned = spawn_child_async(&spec, &runtime).await;
772            #[cfg(any(target_os = "linux", target_os = "macos"))]
773            {
774                runtime.replacement_ticket = None;
775            }
776            #[cfg(test)]
777            self.test_after_first_spawn.run(&spec.module_id);
778            match spawned {
779                Ok(mut child) => {
780                    arm_registration_deadline(
781                        &mut child,
782                        runtime.register_timeout,
783                        registration_watch,
784                    );
785                    self.mark_first_process_running(&spec, &runtime, snapshot, &mut child)?;
786                    if let Some(spawn) = activity_spawn {
787                        spawn.complete(snapshot);
788                    }
789                    Some(child)
790                }
791                Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
792                    defer_config_spawn(&spec, &runtime, snapshot, RespawnKind::Spawn, &failure)?;
793                    None
794                }
795                Err(mut err) => {
796                    if matches!(err, SuperviseError::ConfigHeld { .. }) {
797                        match hold_config_spawn(&spec, &runtime, snapshot, &failure) {
798                            Ok(()) => {
799                                self.start_monitor(spec, runtime, &module, None, commands);
800                                return Ok(module);
801                            }
802                            Err(parking_error) => err = parking_error,
803                        }
804                    }
805                    if runtime.health.critical {
806                        error!(module_id = %spec.module_id, program = %spec.program.display(), error = %err,
807                            "critical configured module failed to spawn; marking failed and alerting");
808                    } else {
809                        error!(module_id = %spec.module_id, program = %spec.program.display(), error = %err,
810                            "configured module failed to spawn; marking failed and continuing");
811                    }
812                    fail_snapshot(snapshot, Some(&spec.module_id), None, &failure);
813                    if let Some(generation) = approved_generation {
814                        let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
815                            state.approved_start_failure = Some((generation, err.to_string()));
816                        });
817                        startup_error = Some(err);
818                    }
819                    None
820                }
821            }
822        } else {
823            None
824        };
825        self.start_monitor(spec, runtime, &module, child, commands);
826        // Applying an operator-approved configuration must report a spawn error
827        // without removing the failed module or its monitor. Bootstrap instead
828        // tolerates failed starts so other configured modules can still run.
829        startup_error.map_or(Ok(module), Err)
830    }
831
832    pub(super) fn runtime_config(&self) -> SupervisorRuntimeConfig {
833        let effective_drain_timeout = Arc::new(Mutex::new(self.drain_timeout));
834        SupervisorRuntimeConfig {
835            registry: self.registry.clone(),
836            config_delivery: self.config_delivery.clone(),
837            recovery_is_daemon: true,
838            start_requester: None,
839            pending_activity_restart: false,
840            provenance_probe: self.provenance_probe.clone(),
841            scheduled_respawn: Arc::default(),
842            deferred_reload_reply: Arc::default(),
843            restart_policy: self.restart_policy,
844            register_timeout: DEFAULT_REGISTER_TIMEOUT,
845            drain_timeout: self.drain_timeout,
846            // Shared with this module's roster copy: daemon shutdown waits on
847            // each child for the module's own drain budget, as resolved now.
848            child_roster: self
849                .child_roster
850                .for_module(Arc::clone(&effective_drain_timeout)),
851            effective_drain_timeout,
852            default_drain_timeout: self.drain_timeout,
853            health: self.health.clone(),
854            host_health: self.host_health.clone(),
855            connection_file_path: self.connection_file_path.clone(),
856            capture_logs_dir: self.capture_logs_dir.clone(),
857            forwarding: self.forwarding.clone(),
858            supervisor_handle: self.supervisor_handle.clone(),
859            #[cfg(any(target_os = "linux", target_os = "macos"))]
860            replacement_ticket: None,
861            stderr_ring: Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default()))),
862            terminal_ring: Arc::new(Mutex::new(
863                TerminalRing::new(
864                    TerminalRingConfig::default(),
865                    self.daemon_start_clock.started_at_ms(),
866                )
867                .with_start_clock(self.daemon_start_clock)
868                .with_journal(self.terminal_journal.clone())
869                .with_daemon_shutdown(self.child_roster.shutdown_flag()),
870            )),
871            spawn_events: self.spawn_events.clone(),
872            #[cfg(target_os = "linux")]
873            cgroup_placement: self.cgroup_placement.clone(),
874            #[cfg(test)]
875            test_seed_stale_facts_before_enable_spawn: false,
876            #[cfg(test)]
877            test_reload_exit_record_gate: None,
878        }
879    }
880
881    pub(super) fn supervised_module(
882        &self,
883        spec: ModuleSpec,
884        runtime: SupervisorRuntimeConfig,
885        snapshot: SharedSnapshot,
886        child: Option<SupervisedChild>,
887    ) -> SupervisedModule {
888        let (module, commands) = self.register_module(&spec, &runtime, snapshot);
889        self.start_monitor(spec, runtime, &module, child, commands);
890        module
891    }
892
893    pub(super) fn register_module(
894        &self,
895        spec: &ModuleSpec,
896        runtime: &SupervisorRuntimeConfig,
897        snapshot: SharedSnapshot,
898    ) -> (SupervisedModule, mpsc::Receiver<SupervisorCommand>) {
899        runtime.host_health.track(spec, &snapshot);
900        let configuration = Arc::new(Mutex::new(SupervisedConfiguration {
901            spec: spec.clone(),
902            enabled: snapshot.lock().unwrap_or_else(|p| p.into_inner()).enabled,
903            health: runtime.health.clone(),
904            register_timeout: runtime.register_timeout,
905            restart_policy: runtime.restart_policy,
906        }));
907        let stderr_ring = Arc::clone(&runtime.stderr_ring);
908        let terminal_ring = Arc::clone(&runtime.terminal_ring);
909        let effective_drain_timeout = Arc::clone(&runtime.effective_drain_timeout);
910        let (tx, rx) = mpsc::channel(4);
911        let module_id = spec.module_id.clone();
912        let module = SupervisedModule {
913            inner: Arc::new(SupervisedModuleInner {
914                module_id: module_id.clone(),
915                registry: Arc::clone(&self.registry),
916                snapshot,
917                configuration,
918                stderr_ring,
919                terminal_ring,
920                commands: tx,
921                monitor: Mutex::new(None),
922                effective_drain_timeout,
923                provenance_probe: self.provenance_probe.clone(),
924                retained: runtime.child_roster.retained_view(),
925            }),
926        };
927        // Identity gates and the configured mark must precede the roster entry,
928        // so a client never sees a module without its admission policy.
929        if let Some(supervisor_handle) = &self.supervisor_handle {
930            supervisor_handle.insert(module.clone());
931        }
932        (module, rx)
933    }
934
935    pub(super) fn start_monitor(
936        &self,
937        spec: ModuleSpec,
938        runtime: SupervisorRuntimeConfig,
939        module: &SupervisedModule,
940        child: Option<SupervisedChild>,
941        commands: mpsc::Receiver<SupervisorCommand>,
942    ) {
943        let monitor = tokio::spawn(supervise_loop(
944            spec,
945            runtime,
946            Arc::clone(&self.registry),
947            Arc::clone(&self.process_liveness),
948            Arc::clone(&module.inner.snapshot),
949            child,
950            commands,
951        ));
952        *module
953            .inner
954            .monitor
955            .lock()
956            .unwrap_or_else(|p| p.into_inner()) = Some(monitor);
957    }
958}
959
960pub(crate) fn validate_spec(spec: &ModuleSpec) -> Result<(), SuperviseError> {
961    if spec.carry_containment && spec.overlap == ModuleOverlap::Safe {
962        return Err(SuperviseError::InvalidSpec {
963            reason: "carry_containment cannot be combined with overlap: safe".to_owned(),
964        });
965    }
966    if spec.module_id.trim().is_empty() {
967        return Err(SuperviseError::InvalidSpec {
968            reason: "module_id must not be empty".to_string(),
969        });
970    }
971
972    Ok(())
973}
974
975/// The child's environment plan: inherit the parent's, drop ambient `CK_LOG`,
976/// then apply the module's configured entries minus daemon-private capture keys.
977///
978/// Separated from `spawn_child` only so it can be asserted without spawning a
979/// process — a duplicate of this logic in a test would pass while the real one
980/// drifted, which is the defect class this function exists to avoid.
981/// The subc-wire half of a spawn: `--subc <connection file>` and the launch
982/// nonce. A `protocol: "none"` module gets neither, because it cannot use
983/// either and the argument would stop a stock binary from starting at all.
984/// `SUBC_MODULE_ID` is set on every path since an unread variable is inert.
985///
986/// The plain-spawn form, kept for the tests that assert its plan; spawns go
987/// through [`apply_wire_spawn_args_for_admission`].
988#[cfg(test)]
989pub(super) fn apply_wire_spawn_args(
990    command: &mut Command,
991    spec: &ModuleSpec,
992    connection_file_path: Option<&std::path::Path>,
993    handle: Option<&SupervisorHandle>,
994) -> Result<Option<NonceHandoff>, SuperviseError> {
995    apply_wire_spawn_args_for_role(
996        command,
997        spec,
998        connection_file_path,
999        handle,
1000        SpawnRole::Plain,
1001    )
1002}
1003
1004/// The read end of a spawn's launch-nonce pipe, prepared by
1005/// [`apply_wire_spawn_args_for_admission`] and installed as the child's descriptor 3
1006/// by the last pre-exec step, just before `spawn()`. Windows prepares a named
1007/// server before spawn and authenticates its client after the child exists.
1008#[cfg(unix)]
1009type NonceHandoff = subc_os::LaunchNonceHandoff;
1010#[cfg(windows)]
1011type NonceHandoff = subc_os::LaunchNoncePipeHandoff;
1012#[cfg(not(any(unix, windows)))]
1013type NonceHandoff = std::convert::Infallible;
1014
1015/// Create the launch nonce that a new module process must present when it
1016/// registers or opens a consumer connection, including a replacement process
1017/// started alongside a still-serving module.
1018///
1019/// A plain spawn replaces the module's recorded nonce. A swap candidate records
1020/// a separate candidate token so the still-serving incumbent and its consumers
1021/// keep their nonce. Both records are installed before the process exists, so
1022/// the child's initial HELLO registration cannot arrive ahead of its nonce.
1023///
1024/// On Unix the nonce is delivered only through a pipe. It is written into
1025/// a pipe whose read end the child gets as descriptor 3, named by
1026/// `SUBC_LAUNCH_NONCE_FD=3:<pipe inode>`: unlike the environment, another
1027/// process of the same user cannot read it with `ps eww`. That handoff is
1028/// returned rather than installed here. The combined descriptor placement runs
1029/// after the cgroup callback and placement barrier, so replacing slots 3-5
1030/// cannot close a descriptor either callback still needs.
1031/// On Windows only the name of the PID-checked pipe goes into the environment.
1032#[cfg(test)]
1033fn apply_wire_spawn_args_for_role(
1034    command: &mut Command,
1035    spec: &ModuleSpec,
1036    connection_file_path: Option<&std::path::Path>,
1037    handle: Option<&SupervisorHandle>,
1038    role: SpawnRole,
1039) -> Result<Option<NonceHandoff>, SuperviseError> {
1040    apply_wire_spawn_args_for_admission(command, spec, connection_file_path, handle, role, None)
1041}
1042
1043pub(super) fn apply_wire_spawn_args_for_admission(
1044    command: &mut Command,
1045    spec: &ModuleSpec,
1046    connection_file_path: Option<&std::path::Path>,
1047    handle: Option<&SupervisorHandle>,
1048    role: SpawnRole,
1049    admission: Option<&crate::config_gate::runtime::SpawnAdmission>,
1050) -> Result<Option<NonceHandoff>, SuperviseError> {
1051    command.env(SUBC_MODULE_ID_ENV, &spec.module_id);
1052    // SUBC_LAUNCH_NONCE_FD is removed for every child, `protocol: "none"`
1053    // included: a daemon started from a module's process tree inherits it,
1054    // and passing it on would point the child at a descriptor it does not
1055    // have.
1056    command.env_remove(subc_os::LAUNCH_NONCE_FD_ENV);
1057    #[cfg(windows)]
1058    {
1059        command.env_remove(subc_os::LAUNCH_NONCE_PIPE_ENV);
1060        command.env_remove(subc_os::LAUNCH_NONCE_PIPE_FALLBACK_ENV);
1061    }
1062    // Remove inherited or configured copies too: withholding must mean absent.
1063    command.env_remove(SUBC_LAUNCH_NONCE_ENV);
1064    command.env_remove(subc_os::registration_channel::REGISTRATION_FD_ENV);
1065    command.env_remove(subc_os::registration_channel::REGISTRATION_PIPE_ENV);
1066    command.env_remove(subc_os::registration_channel::DAEMON_PID_ENV);
1067    if role == SpawnRole::Plain {
1068        if let Some(handle) = handle {
1069            #[cfg(all(test, unix))]
1070            {
1071                let pause = {
1072                    let mut slot = handle.plain_identity_policy_pause.lock().unwrap();
1073                    if slot
1074                        .as_ref()
1075                        .is_some_and(|(module, _)| module == &spec.module_id)
1076                    {
1077                        slot.take().map(|(_, pause)| pause)
1078                    } else {
1079                        None
1080                    }
1081                };
1082                if let Some(pause) = pause {
1083                    pause.reached.send(()).unwrap();
1084                    pause.release.recv().unwrap();
1085                }
1086            }
1087            // A rescan preserves the running child's nonce and reservation.
1088            // Replacement spawn preparation applies the new protocol now,
1089            // before protocol:none can return without minting a nonce.
1090            handle.apply_identity_policy(spec, spec.protocol);
1091        }
1092    }
1093    if spec.protocol == ModuleProtocol::None {
1094        return Ok(None);
1095    }
1096    if let Some(connection_file_path) = connection_file_path {
1097        command.arg(SUBC_ARG).arg(connection_file_path);
1098    }
1099
1100    if admission.is_some_and(|admission| admission.launch.is_some()) {
1101        if let Some(handle) = handle {
1102            match role {
1103                SpawnRole::Plain => {
1104                    handle
1105                        .spawn_nonces
1106                        .lock()
1107                        .unwrap_or_else(|p| p.into_inner())
1108                        .remove(&spec.module_id);
1109                    if spec.reserved {
1110                        handle
1111                            .reserved_nonces
1112                            .lock()
1113                            .unwrap_or_else(|p| p.into_inner())
1114                            .insert(spec.module_id.clone(), None);
1115                    }
1116                }
1117                // Swaps still need their lifecycle record, but the empty value
1118                // is not a bearer token and is never accepted by nonce HELLO.
1119                SpawnRole::SwapCandidate => handle.open_swap(&spec.module_id, String::new()),
1120            }
1121        }
1122        return Ok(None);
1123    }
1124    // Every subc-wire spawn receives a fresh one-time launch nonce for consumer
1125    // route.open attestation. Reserved modules additionally use the same nonce
1126    // for HELLO id-squatting protection. A respawn rotates both records.
1127    let nonce = generate_launch_nonce()?;
1128    if let Some(handle) = handle {
1129        match role {
1130            SpawnRole::Plain => {
1131                handle.set_spawn_nonce(&spec.module_id, nonce.clone());
1132                if spec.reserved {
1133                    handle.set_reserved_nonce(&spec.module_id, nonce.clone());
1134                }
1135            }
1136            SpawnRole::SwapCandidate => handle.open_swap(&spec.module_id, nonce.clone()),
1137        }
1138    }
1139    #[cfg(unix)]
1140    let handoff = {
1141        let handoff =
1142            subc_os::LaunchNonceHandoff::new(&nonce).map_err(|source| SuperviseError::Spawn {
1143                program: spec.program.clone(),
1144                source,
1145                cgroup_path: None,
1146            })?;
1147        command.env(subc_os::LAUNCH_NONCE_FD_ENV, handoff.fd_env_value());
1148        Some(handoff)
1149    };
1150    #[cfg(windows)]
1151    let handoff = Some(prepare_windows_nonce_pipe(
1152        command, spec, &nonce, handle, role,
1153    )?);
1154    #[cfg(not(any(unix, windows)))]
1155    let handoff = None;
1156    #[cfg(not(any(unix, windows)))]
1157    command.env(SUBC_LAUNCH_NONCE_ENV, nonce);
1158    Ok(handoff)
1159}
1160
1161pub(crate) fn apply_child_env(command: &mut Command, spec: &ModuleSpec) {
1162    command.env_remove(CK_LOG_ENV);
1163    // The spawn role is the supervisor's to set, and only on a swap candidate
1164    // (see `apply_spawn_role`). Removing it here, rather than just not setting
1165    // it, is what makes it absent on a plain spawn: the daemon's own
1166    // environment could carry it, and so could a spec built outside daemon
1167    // config (config refuses it as an `env` key). A module reading it on a
1168    // plain restart would pick the long swap budget and leave callers waiting.
1169    command.env_remove(SUBC_SPAWN_ROLE_ENV);
1170    for (key, value) in &spec.env {
1171        // cortexkit-log currently exposes retention only as a Rust struct, not
1172        // environment names. These values are daemon-private sink metadata and
1173        // must never become a public child-process contract by being inherited.
1174        if matches!(
1175            key.as_str(),
1176            CAPTURE_MAX_FILE_MB_ENV | CAPTURE_KEEP_ENV | CAPTURE_MAX_AGE_DAYS_ENV
1177        ) || key == SUBC_SPAWN_ROLE_ENV
1178        {
1179            continue;
1180        }
1181        command.env(key, value);
1182    }
1183}
1184
1185#[cfg(windows)]
1186pub(super) fn prepare_windows_registration_pipe(
1187    command: &mut Command,
1188    spec: &ModuleSpec,
1189) -> Result<Option<SpawnRegistrationChannel>, SuperviseError> {
1190    if spec.protocol == ModuleProtocol::None {
1191        return Ok(None);
1192    }
1193    let pipe = subc_os::registration_channel::RegistrationPipe::new().map_err(|source| {
1194        SuperviseError::Spawn {
1195            program: spec.program.clone(),
1196            source,
1197            cgroup_path: None,
1198        }
1199    })?;
1200    command
1201        .env(
1202            subc_os::registration_channel::REGISTRATION_PIPE_ENV,
1203            pipe.name(),
1204        )
1205        .env(
1206            subc_os::registration_channel::DAEMON_PID_ENV,
1207            std::process::id().to_string(),
1208        );
1209    Ok(Some(pipe))
1210}
1211
1212#[cfg(windows)]
1213fn prepare_windows_nonce_pipe(
1214    command: &mut Command,
1215    spec: &ModuleSpec,
1216    nonce: &str,
1217    handle: Option<&SupervisorHandle>,
1218    role: SpawnRole,
1219) -> Result<NonceHandoff, SuperviseError> {
1220    let handoff = subc_os::LaunchNoncePipeHandoff::new(nonce).map_err(|source| {
1221        update_nonce_pipe_refusal(handle, spec, role, Some("launch_nonce_pipe_prepare_failed"));
1222        windows_nonce_pipe_error(spec, "prepare", source)
1223    })?;
1224    command.env(subc_os::LAUNCH_NONCE_PIPE_ENV, handoff.name());
1225    Ok(handoff)
1226}
1227
1228#[cfg(windows)]
1229fn update_nonce_pipe_refusal(
1230    handle: Option<&SupervisorHandle>,
1231    spec: &ModuleSpec,
1232    role: SpawnRole,
1233    refusal: Option<&'static str>,
1234) {
1235    // A failed candidate belongs to the swap operation, not to the incumbent.
1236    if role == SpawnRole::Plain {
1237        if let Some(module) = handle.and_then(|handle| handle.get(&spec.module_id)) {
1238            if let Err(error) =
1239                update_snapshot(&module.inner.snapshot, Some(&spec.module_id), |state| {
1240                    state.nonce_pipe_refusal = refusal;
1241                })
1242            {
1243                error!(module_id = %spec.module_id, %error, "could not record Windows launch nonce pipe status");
1244            }
1245        }
1246    }
1247}
1248
1249#[cfg(windows)]
1250fn windows_nonce_pipe_error(spec: &ModuleSpec, step: &str, source: io::Error) -> SuperviseError {
1251    SuperviseError::Spawn {
1252        program: spec.program.clone(),
1253        source: io::Error::new(
1254            source.kind(),
1255            format!("could not {step} Windows launch nonce pipe: {source}"),
1256        ),
1257        cgroup_path: None,
1258    }
1259}
1260
1261pub(super) fn observed_launch_nonce_source(snapshot: &SupervisorSnapshot) -> Option<String> {
1262    #[cfg(windows)]
1263    if snapshot.process_alive
1264        && snapshot.spawned_protocol == Some(ModuleProtocol::Subc)
1265        && snapshot
1266            .pipe_consumed
1267            .as_ref()
1268            .is_some_and(|consumed| consumed.get().is_some())
1269    {
1270        return Some("pipe".to_owned());
1271    }
1272    let _ = snapshot;
1273    None
1274}
1275
1276/// Which slot a spawn fills: the module's ordinary one, or the candidate slot
1277/// of a blue/green swap.
1278#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1279pub(crate) enum SpawnRole {
1280    Plain,
1281    SwapCandidate,
1282}
1283
1284/// Set the spawn role for a swap candidate. A plain spawn gets nothing here;
1285/// `apply_child_env` has already removed the variable for every spawn.
1286pub(super) fn apply_spawn_role(command: &mut Command, role: SpawnRole) {
1287    if role == SpawnRole::SwapCandidate {
1288        command.env(SUBC_SPAWN_ROLE_ENV, SPAWN_ROLE_SWAP_CANDIDATE);
1289    }
1290}
1291
1292pub(super) fn previous_instance_error(
1293    spec: &ModuleSpec,
1294    pid: u32,
1295    reason: crate::live_children::RetainedReason,
1296) -> SuperviseError {
1297    SuperviseError::Spawn {
1298        program: spec.program.clone(),
1299        source: io::Error::new(io::ErrorKind::WouldBlock, reason.waiting_message(pid)),
1300        cgroup_path: None,
1301    }
1302}
1303
1304pub(super) fn carries_containment(configured: bool, has_container: bool) -> bool {
1305    configured || has_container
1306}
1307
1308pub(super) fn recovery_block_error(
1309    spec: &ModuleSpec,
1310    roster: &ChildRoster,
1311) -> Option<SuperviseError> {
1312    if !carries_containment(
1313        spec.carry_containment,
1314        containment::current(&roster.containment).is_some(),
1315    ) {
1316        return None;
1317    }
1318    Some(SuperviseError::Spawn {
1319        program: spec.program.clone(),
1320        source: io::Error::new(io::ErrorKind::WouldBlock, roster.recovery_block()?),
1321        cgroup_path: None,
1322    })
1323}
1324
1325#[allow(clippy::too_many_arguments)]
1326pub(super) fn spawn_child(
1327    spec: &ModuleSpec,
1328    connection_file_path: Option<&std::path::Path>,
1329    handle: Option<&SupervisorHandle>,
1330    ring: &Arc<Mutex<StderrRing>>,
1331    capture_logs_dir: Option<&std::path::Path>,
1332    roster: &ChildRoster,
1333    config_delivery: Option<config_delivery::SpawnDelivery<'_>>,
1334    #[cfg(target_os = "linux")] cgroup_placement: Option<&subc_cgroup::Placement>,
1335    register_timeout: Duration,
1336) -> Result<SupervisedChild, SuperviseError> {
1337    #[cfg(all(test, unix))]
1338    if let Some(source) = containment_tests::join_failure(spec, roster) {
1339        containment::note_end_reason(&roster.containment, ContainerEndReason::SpawnFailed);
1340        containment::terminate_blocking(&roster.containment);
1341        return Err(SuperviseError::Spawn {
1342            program: spec.program.clone(),
1343            source,
1344            cgroup_path: None,
1345        });
1346    }
1347    let result = spawn_child_in_slot(
1348        spec,
1349        connection_file_path,
1350        handle,
1351        ring,
1352        capture_logs_dir,
1353        roster,
1354        config_delivery,
1355        #[cfg(target_os = "linux")]
1356        cgroup_placement,
1357        SpawnRole::Plain,
1358        false,
1359        register_timeout,
1360    );
1361    if result
1362        .as_ref()
1363        .is_err_and(|error| !is_launch_deferral(error))
1364    {
1365        containment::note_end_reason(&roster.containment, ContainerEndReason::SpawnFailed);
1366        if roster.admission_pending(&spec.module_id) {
1367            containment::terminate_deferred(&roster.containment);
1368        } else {
1369            containment::terminate_blocking(&roster.containment);
1370        }
1371    }
1372    result
1373}
1374
1375/// A configuration deferral means the launch never started: the module gate
1376/// or the configuration owner was briefly busy, and every caller schedules
1377/// the same launch again shortly. A carried container stays for that retry,
1378/// as it does across a restart backoff; ending it here would kill the
1379/// module's helpers and give up the group the retry is meant to join.
1380pub(super) fn is_launch_deferral(error: &SuperviseError) -> bool {
1381    matches!(error, SuperviseError::ConfigDeliveryDeferred { .. })
1382}
1383
1384/// Spawn one process of `spec` into a slot.
1385///
1386/// `alternate_slot` picks the process's cgroup label on Linux (see `swap::cgroup_name`).
1387/// A swap candidate needs a different cgroup from the process it is replacing,
1388/// which is still alive: in the same cgroup the two would be one kill domain,
1389/// and killing a failed candidate could take the incumbent with it.
1390///
1391/// The stderr capture file is `<module_id>.stderr.log` for every process of
1392/// the module, whichever slot it is in, because that is the one file
1393/// `ck module logs` reads. During a swap's overlap both processes append to it;
1394/// the daemon writes whole lines, so the two interleave by line, which is also
1395/// the merged view an operator wants while a swap runs.
1396#[allow(clippy::too_many_arguments)]
1397pub(super) fn spawn_child_in_slot(
1398    spec: &ModuleSpec,
1399    connection_file_path: Option<&std::path::Path>,
1400    handle: Option<&SupervisorHandle>,
1401    ring: &Arc<Mutex<StderrRing>>,
1402    capture_logs_dir: Option<&std::path::Path>,
1403    roster: &ChildRoster,
1404    config_delivery: Option<config_delivery::SpawnDelivery<'_>>,
1405    #[cfg(target_os = "linux")] cgroup_placement: Option<&subc_cgroup::Placement>,
1406    role: SpawnRole,
1407    alternate_slot: bool,
1408    register_timeout: Duration,
1409) -> Result<SupervisedChild, SuperviseError> {
1410    let prepared = prepare_child_in_slot(
1411        spec,
1412        connection_file_path,
1413        handle,
1414        capture_logs_dir,
1415        roster,
1416        config_delivery,
1417        #[cfg(target_os = "linux")]
1418        cgroup_placement,
1419        role,
1420        alternate_slot,
1421        false,
1422    )?;
1423    let gate = config_delivery
1424        .map(|delivery| delivery.module_gate(spec))
1425        .transpose()?;
1426    let _gate = gate
1427        .as_ref()
1428        .map(|gate| {
1429            gate.try_lock()
1430                .map_err(|_| SuperviseError::ConfigDeliveryDeferred {
1431                    module_id: spec.module_id.clone(),
1432                })
1433        })
1434        .transpose()?;
1435    if let (Some(delivery), Some(admission)) = (config_delivery, &prepared.spawn_admission) {
1436        delivery.check(spec, admission)?;
1437    }
1438    let checked_base = prepared
1439        .spawn_admission
1440        .as_ref()
1441        .and_then(|admission| admission.approved_base())
1442        .cloned();
1443    let mut result = launch_child_in_slot(spec, ring, roster, prepared, register_timeout);
1444    drop(_gate);
1445    if let (Some(delivery), Err(SuperviseError::ConfigHeld { code, detail, .. })) =
1446        (config_delivery, &result)
1447    {
1448        if let Some(base) = checked_base.as_ref().filter(|_| code == "program_refused") {
1449            if !delivery.record_refusal(spec, base, detail)? {
1450                result = Err(spawn_plan_stale(spec));
1451            }
1452        }
1453    }
1454    result
1455}
1456
1457struct AsyncInitialIdentity<'a> {
1458    supervisor: &'a Supervisor,
1459    module: String,
1460    committed: bool,
1461}
1462impl Drop for AsyncInitialIdentity<'_> {
1463    fn drop(&mut self) {
1464        if !self.committed {
1465            self.supervisor.abandon_unrostered(&self.module);
1466        }
1467    }
1468}
1469
1470/// Child-free preparation can be abandoned without orphaning a process. After
1471/// this value returns, the async caller validates its launch witness and creates
1472/// and publishes the child without another await.
1473pub(super) struct PreparedChild {
1474    script_delivery: Option<script::Delivery>,
1475    registration_spawn: Option<Arc<RegistrationSpawn>>,
1476    registration_handle: Option<SupervisorHandle>,
1477    #[cfg(any(unix, windows))]
1478    registration_channel: Option<SpawnRegistrationChannel>,
1479    config_context: Option<config_delivery::ConfigDelivery>,
1480    binding_publication: Option<ProgramBindingPublication>,
1481    launch_spec: ModuleSpec,
1482    spawn_admission: Option<crate::config_gate::runtime::SpawnAdmission>,
1483    pub(super) command: Command,
1484    carrying: bool,
1485    carried: Option<Arc<containment::CarriedContainment>>,
1486    #[cfg(unix)]
1487    launch_identity: Option<containment::LaunchIdentity>,
1488    #[cfg(unix)]
1489    group_target: containment::GroupTarget,
1490    #[cfg(target_os = "linux")]
1491    pub(super) cgroup_placement: Option<subc_cgroup::Placement>,
1492    #[cfg(target_os = "linux")]
1493    pub(super) cgroup_name: String,
1494    #[cfg(target_os = "linux")]
1495    cgroup_cleanup: PreparedCgroup,
1496    pub(super) cgroup_path: Option<PathBuf>,
1497    #[cfg(unix)]
1498    admission_gate: Option<admission::Gate>,
1499    output_sink: ChildOutputSink,
1500    #[cfg(target_os = "macos")]
1501    privacy_exec: Option<PrivacyExec>,
1502    #[cfg(windows)]
1503    image_capture: subc_os::ExecutableCapture,
1504    #[cfg(windows)]
1505    nonce_handoff: Option<NonceHandoff>,
1506    #[cfg(windows)]
1507    role: SpawnRole,
1508    spawned_at: Instant,
1509    config_delivery: Option<crate::config_gate::runtime::DeliverySpawn>,
1510    delivery_registration: Option<config_delivery::RegistrationGuard>,
1511    program_binding: Option<SpawnProgramBinding>,
1512}
1513
1514#[cfg(target_os = "linux")]
1515struct PreparedCgroup(Option<(subc_cgroup::Placement, String)>);
1516#[cfg(target_os = "linux")]
1517impl Drop for PreparedCgroup {
1518    fn drop(&mut self) {
1519        if let Some((placement, name)) = &self.0 {
1520            remove_module_cgroup(placement, name);
1521        }
1522    }
1523}
1524
1525pub(crate) struct SpawnProgramBinding {
1526    pub(crate) path: PathBuf,
1527    // Keep the inode alive if the configured name is replaced while preparation
1528    // is suspended, so replacement cannot pass through inode reuse.
1529    pub(super) _file: std::fs::File,
1530    pub(crate) identity: subc_os::RetainedFileIdentity,
1531}
1532
1533impl SpawnProgramBinding {
1534    pub(crate) fn capture(spec: &ModuleSpec) -> Result<Self, SuperviseError> {
1535        Self::capture_after_resolution(spec, |_| {})
1536    }
1537
1538    pub(super) fn capture_after_resolution(
1539        spec: &ModuleSpec,
1540        before_open: impl FnOnce(&std::path::Path),
1541    ) -> Result<Self, SuperviseError> {
1542        require_program_search_path(spec)?;
1543        #[cfg(windows)]
1544        let windows_capture =
1545            windows_spawn_capture(spec).map_err(|source| SuperviseError::Spawn {
1546                program: spec.program.clone(),
1547                source,
1548                cgroup_path: None,
1549            })?;
1550        #[cfg(windows)]
1551        let path = windows_capture.path().to_path_buf();
1552        #[cfg(not(windows))]
1553        let path = if spec.program.is_absolute() || spec.program.components().count() > 1 {
1554            spec.program.clone()
1555        } else {
1556            let path = spec
1557                .env
1558                .iter()
1559                .rev()
1560                .find(|(key, _)| key == "PATH")
1561                .map(|(_, path)| std::ffi::OsString::from(path))
1562                .or_else(|| std::env::var_os("PATH"))
1563                .unwrap_or_else(|| {
1564                    if cfg!(target_os = "macos") {
1565                        // Match Darwin's spawn search when PATH is absent, not
1566                        // the current-directory search of an explicitly empty PATH.
1567                        "/usr/bin:/bin".into()
1568                    } else {
1569                        Default::default()
1570                    }
1571                });
1572            std::env::split_paths(&path)
1573                .map(|dir| dir.join(&spec.program))
1574                .find(|path| {
1575                    if !path.is_file() {
1576                        return false;
1577                    }
1578                    #[cfg(unix)]
1579                    {
1580                        rustix::fs::accessat(
1581                            rustix::fs::CWD,
1582                            path,
1583                            rustix::fs::Access::EXEC_OK,
1584                            rustix::fs::AtFlags::EACCESS,
1585                        )
1586                        .is_ok()
1587                    }
1588                    #[cfg(not(unix))]
1589                    {
1590                        true
1591                    }
1592                })
1593                .ok_or_else(|| SuperviseError::Spawn {
1594                    program: spec.program.clone(),
1595                    source: io::Error::new(io::ErrorKind::NotFound, "executable not found in PATH"),
1596                    cgroup_path: None,
1597                })?
1598        };
1599        let resolved = std::fs::canonicalize(&path).map_err(|source| SuperviseError::Spawn {
1600            program: spec.program.clone(),
1601            source,
1602            cgroup_path: None,
1603        })?;
1604        before_open(&resolved);
1605        // Resolving links does not open their target. The descriptor open must
1606        // remain nonblocking and no-follow if that resolved name is substituted.
1607        let file =
1608            subc_os::open_regular_nofollow(&resolved).map_err(|source| SuperviseError::Spawn {
1609                program: spec.program.clone(),
1610                source: io::Error::other(source),
1611                cgroup_path: None,
1612            })?;
1613        let identity =
1614            subc_os::retained_file_identity(&file).map_err(|source| SuperviseError::Spawn {
1615                program: spec.program.clone(),
1616                source,
1617                cgroup_path: None,
1618            })?;
1619        Ok(Self {
1620            path,
1621            _file: file,
1622            identity,
1623        })
1624    }
1625    pub(super) fn current(&self) -> bool {
1626        #[cfg(unix)]
1627        {
1628            subc_os::file_identity(&self.path) == Some(self.identity)
1629        }
1630        #[cfg(windows)]
1631        {
1632            std::fs::canonicalize(&self.path)
1633                .ok()
1634                .and_then(|path| subc_os::open_regular_nofollow(&path).ok())
1635                .and_then(|file| subc_os::retained_file_identity(&file).ok())
1636                == Some(self.identity)
1637        }
1638    }
1639}
1640
1641pub(super) fn spawn_plan_stale(spec: &ModuleSpec) -> SuperviseError {
1642    SuperviseError::ConfigDeliveryDeferred {
1643        module_id: spec.module_id.clone(),
1644    }
1645}
1646
1647fn require_program_search_path(spec: &ModuleSpec) -> Result<(), SuperviseError> {
1648    if !cfg!(target_os = "macos")
1649        && !spec.program.is_absolute()
1650        && spec.program.components().count() == 1
1651        && !spec.env.iter().any(|(key, _)| {
1652            if cfg!(windows) {
1653                key.eq_ignore_ascii_case("PATH")
1654            } else {
1655                key == "PATH"
1656            }
1657        })
1658        && std::env::var_os("PATH").is_none()
1659    {
1660        // The OS default search is not a current-directory search. Refusing an
1661        // unspecified search path prevents approving a decoy in the current directory.
1662        return Err(SuperviseError::Spawn {
1663            program: spec.program.clone(),
1664            source: io::Error::new(io::ErrorKind::InvalidInput, "bare program requires PATH"),
1665            cgroup_path: None,
1666        });
1667    }
1668    Ok(())
1669}
1670
1671pub(super) async fn spawn_child_async(
1672    spec: &ModuleSpec,
1673    runtime: &SupervisorRuntimeConfig,
1674) -> Result<SupervisedChild, SuperviseError> {
1675    #[cfg(all(test, unix))]
1676    if let Some(source) = containment_tests::join_failure(spec, &runtime.child_roster) {
1677        containment::note_end_reason(
1678            &runtime.child_roster.containment,
1679            ContainerEndReason::SpawnFailed,
1680        );
1681        containment::terminate_blocking(&runtime.child_roster.containment);
1682        return Err(SuperviseError::Spawn {
1683            program: spec.program.clone(),
1684            source,
1685            cgroup_path: None,
1686        });
1687    }
1688    let result = spawn_child_in_slot_async(spec, runtime, SpawnRole::Plain, false).await;
1689    if result
1690        .as_ref()
1691        .is_err_and(|error| !is_launch_deferral(error))
1692    {
1693        containment::note_end_reason(
1694            &runtime.child_roster.containment,
1695            ContainerEndReason::SpawnFailed,
1696        );
1697        if runtime.child_roster.admission_pending(&spec.module_id) {
1698            containment::terminate_deferred(&runtime.child_roster.containment);
1699        } else {
1700            containment::terminate_blocking(&runtime.child_roster.containment);
1701        }
1702    }
1703    result
1704}
1705
1706pub(super) async fn spawn_child_in_slot_async(
1707    spec: &ModuleSpec,
1708    runtime: &SupervisorRuntimeConfig,
1709    role: SpawnRole,
1710    alternate_slot: bool,
1711) -> Result<SupervisedChild, SuperviseError> {
1712    let gate = runtime
1713        .config_delivery
1714        .as_ref()
1715        .map(|delivery| delivery.0.module_gate(&spec.module_id))
1716        .transpose()
1717        .map_err(|error| SuperviseError::InvalidSpec {
1718            reason: error.to_string(),
1719        })?;
1720    if gate.as_ref().is_some_and(|gate| gate.try_lock().is_err()) {
1721        return Err(SuperviseError::ConfigDeliveryDeferred {
1722            module_id: spec.module_id.clone(),
1723        });
1724    }
1725    let prepared_spec = spec.clone();
1726    let prepared_runtime = runtime.clone();
1727    let prepared = tokio::task::spawn_blocking(move || {
1728        let prepared = prepare_child_in_slot(
1729            &prepared_spec,
1730            prepared_runtime.connection_file_path.as_deref(),
1731            prepared_runtime.supervisor_handle.as_ref(),
1732            prepared_runtime.capture_logs_dir.as_deref(),
1733            &prepared_runtime.child_roster,
1734            prepared_runtime.spawn_delivery(),
1735            #[cfg(target_os = "linux")]
1736            prepared_runtime.cgroup_placement.as_ref(),
1737            role,
1738            alternate_slot,
1739            true,
1740        );
1741        prepared
1742    })
1743    .await
1744    .map_err(|_| SuperviseError::InvalidSpec {
1745        reason: "configuration launch preparation stopped".into(),
1746    })??;
1747    #[cfg(any(target_os = "linux", target_os = "macos"))]
1748    if let (Some(ticket), Some(launch)) =
1749        (&runtime.replacement_ticket, &prepared.registration_spawn)
1750    {
1751        ticket.bind(launch);
1752    }
1753    if let Some(registration) = &prepared.delivery_registration {
1754        if !registration.launch_current()? {
1755            return Err(spawn_plan_stale(spec));
1756        }
1757    }
1758    let _gate = match gate {
1759        Some(gate) => {
1760            Some(
1761                gate.try_lock_owned()
1762                    .map_err(|_| SuperviseError::ConfigDeliveryDeferred {
1763                        module_id: spec.module_id.clone(),
1764                    })?,
1765            )
1766        }
1767        None => None,
1768    };
1769    if let (Some(delivery), Some(admission)) = (runtime.spawn_delivery(), &prepared.spawn_admission)
1770    {
1771        delivery.check(spec, admission)?;
1772    }
1773    if prepared
1774        .spawn_admission
1775        .as_ref()
1776        .is_none_or(|admission| admission.launch.is_none())
1777        && prepared
1778            .program_binding
1779            .as_ref()
1780            .is_some_and(|binding| !binding.current())
1781    {
1782        return Err(spawn_plan_stale(spec));
1783    }
1784    // No await may separate this last identity check from ownership publication.
1785    let checked_base = prepared
1786        .spawn_admission
1787        .as_ref()
1788        .and_then(|admission| admission.approved_base())
1789        .cloned();
1790    let mut result = launch_child_in_slot(
1791        spec,
1792        &runtime.stderr_ring,
1793        &runtime.child_roster,
1794        prepared,
1795        runtime.register_timeout,
1796    );
1797    drop(_gate);
1798    if let (Some(delivery), Err(SuperviseError::ConfigHeld { code, detail, .. })) =
1799        (runtime.config_delivery.as_ref(), &result)
1800    {
1801        if let Some(base) = checked_base.filter(|_| code == "program_refused") {
1802            let module = spec.module_id.clone();
1803            let identity = subc_config::raw_digest(detail.as_bytes());
1804            let recorded = delivery
1805                .0
1806                .on_blocking(move |owner| owner.record_program_refusal(&module, &base, identity))
1807                .await;
1808            match recorded {
1809                Ok(true) => {}
1810                Ok(false) => result = Err(spawn_plan_stale(spec)),
1811                Err(error) => {
1812                    result = Err(config_delivery::gate_hold_error(
1813                        spec,
1814                        error,
1815                        Some(delivery),
1816                    ))
1817                }
1818            }
1819        }
1820    }
1821    result
1822}
1823
1824fn validate_spawn_program(
1825    spec: &ModuleSpec,
1826    admission: Option<&crate::config_gate::runtime::SpawnAdmission>,
1827    delivery: Option<config_delivery::SpawnDelivery<'_>>,
1828) -> Result<(), SuperviseError> {
1829    if let Some(admission) = admission {
1830        if let Some(program) = &admission.launch {
1831            if let Err(error) = program.validate_for_spawn() {
1832                // A captured unsigned image is a definite refusal. Uncertain
1833                // reads are deferred by validate_for_spawn, not attributed to
1834                // the operator as a changed or unapprovable program.
1835                if let (Some(context), Some(base)) = (delivery, admission.approved_base()) {
1836                    if error.code == "program_refused"
1837                        && !context.record_refusal(spec, base, &error.detail)?
1838                    {
1839                        return Err(spawn_plan_stale(spec));
1840                    }
1841                }
1842                return Err(config_delivery::gate_hold_error(
1843                    spec,
1844                    error,
1845                    delivery.map(|context| context.runtime()).as_ref(),
1846                ));
1847            }
1848        }
1849    }
1850    Ok(())
1851}
1852
1853#[allow(clippy::too_many_arguments)]
1854pub(super) fn prepare_child_in_slot(
1855    spec: &ModuleSpec,
1856    connection_file_path: Option<&std::path::Path>,
1857    handle: Option<&SupervisorHandle>,
1858    capture_logs_dir: Option<&std::path::Path>,
1859    roster: &ChildRoster,
1860    config_delivery: Option<config_delivery::SpawnDelivery<'_>>,
1861    #[cfg(target_os = "linux")] cgroup_placement: Option<&subc_cgroup::Placement>,
1862    role: SpawnRole,
1863    alternate_slot: bool,
1864    asynchronous: bool,
1865) -> Result<PreparedChild, SuperviseError> {
1866    #[cfg(windows)]
1867    update_nonce_pipe_refusal(handle, spec, role, None);
1868    require_program_search_path(spec)?;
1869    let spawn_admission = config_delivery
1870        .map(|delivery| delivery.prepare(spec))
1871        .transpose()?;
1872    #[cfg(target_os = "macos")]
1873    let gated = spawn_admission
1874        .as_ref()
1875        .is_some_and(|admission| admission.approved_base().is_some());
1876    let mut launch_spec = spawn_admission
1877        .as_ref()
1878        .and_then(|admission| admission.launch.as_ref())
1879        .map(|launch| launch.spec.clone())
1880        .unwrap_or_else(|| spec.clone());
1881    if let Some(script) = &launch_spec.script {
1882        launch_spec.program =
1883            script::runner_path(script.runtime).map_err(|source| SuperviseError::Spawn {
1884                program: launch_spec.program.clone(),
1885                source,
1886                cgroup_path: None,
1887            })?;
1888    }
1889    let script_content = if let Some(entry) = &launch_spec.script {
1890        Some(
1891            spawn_admission
1892                .as_ref()
1893                .and_then(|admission| admission.launch.as_ref())
1894                .and_then(|launch| launch.script.clone())
1895                .map_or_else(|| script::ScriptBytes::read(&entry.path), Ok)
1896                .map_err(|error| config_delivery::gate_hold_error(&launch_spec, error, None))?,
1897        )
1898    } else {
1899        None
1900    };
1901    let spec = &launch_spec;
1902    if let Some(error) = recovery_block_error(spec, roster) {
1903        return Err(error);
1904    }
1905    if let Some((pid, reason)) = roster.previous_instance(&spec.module_id) {
1906        return Err(previous_instance_error(spec, pid, reason));
1907    }
1908    if roster.is_closed() {
1909        return Err(SuperviseError::Spawn {
1910            program: spec.program.clone(),
1911            source: io::Error::other("the daemon is shutting down; not starting a new process"),
1912            cgroup_path: None,
1913        });
1914    }
1915    let carried = containment::current(&roster.containment);
1916    let carrying = carries_containment(spec.carry_containment, carried.is_some());
1917    if role != SpawnRole::Plain && carrying {
1918        return Err(SuperviseError::InvalidSpec {
1919            reason: "a carried container cannot overlap a swap candidate".to_owned(),
1920        });
1921    }
1922    #[cfg(unix)]
1923    let launch_identity = if carrying && carried.is_none() {
1924        Some(
1925            containment::LaunchIdentity::capture().map_err(|source| SuperviseError::Spawn {
1926                program: spec.program.clone(),
1927                source,
1928                cgroup_path: None,
1929            })?,
1930        )
1931    } else {
1932        None
1933    };
1934    #[cfg(target_os = "linux")]
1935    let cgroup_placement = match &carried {
1936        Some(container) => container.cgroup().map(|(placement, _)| placement),
1937        None => cgroup_placement,
1938    };
1939    #[cfg(unix)]
1940    let group_target = if let Some(container) = carried
1941        .as_ref()
1942        .filter(|container| container.group().is_some())
1943    {
1944        containment::GroupTarget::Pinned(Arc::clone(container))
1945    } else {
1946        #[cfg(target_os = "linux")]
1947        let cgroup_container = carrying && cgroup_placement.is_some();
1948        #[cfg(not(target_os = "linux"))]
1949        let cgroup_container = false;
1950        if cgroup_container {
1951            containment::GroupTarget::NoGroup
1952        } else {
1953            containment::GroupTarget::OwnLeader
1954        }
1955    };
1956    #[cfg(target_os = "linux")]
1957    let cgroup_name = {
1958        // Slot names alone are not kill domains: a retired incumbent may still
1959        // be draining when a later enable/restart spawns into the same slot.
1960        // Decimal entropy keeps the suffix unambiguous; Placement performs
1961        // the module-id escaping and constructs the filesystem path.
1962        if let Some((_, name)) = carried.as_ref().and_then(|container| container.cgroup()) {
1963            name.to_owned()
1964        } else if cgroup_placement.is_none() {
1965            swap::cgroup_name(&spec.module_id, alternate_slot)
1966        } else {
1967            let nonce = generate_launch_nonce()?;
1968            let suffix = u128::from_str_radix(&nonce[..32], 16).expect("hex launch nonce");
1969            cgroup_label::generation_label(&spec.module_id, alternate_slot, suffix)
1970        }
1971    };
1972    #[cfg(not(target_os = "linux"))]
1973    let _ = alternate_slot;
1974    #[cfg(windows)]
1975    let image_capture = windows_spawn_capture(spec).map_err(|source| SuperviseError::Spawn {
1976        program: spec.program.clone(),
1977        source,
1978        cgroup_path: None,
1979    })?;
1980    #[cfg(windows)]
1981    let program_binding = if asynchronous {
1982        let mut resolved = spec.clone();
1983        resolved.program = image_capture.path().to_path_buf();
1984        Some(SpawnProgramBinding::capture(&resolved)?)
1985    } else {
1986        None
1987    };
1988    #[cfg(not(windows))]
1989    let program_binding = (asynchronous || cfg!(target_os = "macos"))
1990        .then(|| SpawnProgramBinding::capture(spec))
1991        .transpose()?;
1992    #[cfg(target_os = "macos")]
1993    validate_spawn_program(spec, spawn_admission.as_ref(), config_delivery)?;
1994    #[cfg(target_os = "macos")]
1995    let (mut command, privacy_exec, exec_ack) = privacy_command(
1996        spec,
1997        program_binding
1998            .as_ref()
1999            .expect("macOS captures every launch"),
2000        roster,
2001        // Ungated launches retain legacy unsuspended exec, including scripts. Suspended
2002        // verification admits approved programs only. prepare() above fails
2003        // closed if the gate cannot decide; an image sample is not authority.
2004        gated,
2005    )?;
2006    #[cfg(windows)]
2007    let mut command = Command::new(image_capture.path());
2008    #[cfg(not(any(target_os = "macos", windows)))]
2009    let mut command = Command::new(
2010        program_binding
2011            .as_ref()
2012            .map_or(spec.program.as_path(), |binding| binding.path.as_path()),
2013    );
2014    command.args(&spec.args);
2015    // AMBIENT `CK_LOG` MUST NOT LEAK INTO AN OTHERWISE UNCONFIGURED MODULE — but
2016    // that is the whole of the intent, so remove that one key rather than the
2017    // environment.
2018    //
2019    // This was `env_clear()` from 0.17.41 until 0.18.3, which achieved the goal
2020    // and took the POSIX environment with it. Modules spawned that way had no
2021    // HOME, XDG_RUNTIME_DIR, TMPDIR or USER, and the consequences ran past
2022    // logging:
2023    //
2024    //   * `connection_file::discover` reads XDG_RUNTIME_DIR and HOME, so with
2025    //     both unset it fell back to the temp dir alone and `ck` could not find
2026    //     a daemon running on the same machine from inside any module's process
2027    //     tree — reporting a path the file has never lived at, which reads as
2028    //     "the daemon did not write its file".
2029    //   * `default_data_home()` with HOME and XDG_DATA_HOME both unset returns
2030    //     the RELATIVE `.local/share`, so a module deriving its own store path
2031    //     resolved it against its own CWD. That is the store-fragmentation
2032    //     defect the daemon already refuses in config (`parse_doc` rejects a
2033    //     relative `storage.data_home`) arriving by derivation instead.
2034    //   * anything a module spawns inherited it: git without ~/.gitconfig,
2035    //     cargo without CARGO_HOME, ssh, python user dirs — all degrading
2036    //     quietly rather than erroring.
2037    //
2038    // Reported by iceteaSA as #104 after deploying 0.18.2, where `ck daemon`
2039    // offered one candidate under /tmp while the file sat in /run/user/1000.
2040    //
2041    // A configured module is unaffected either way: `module_spec()` puts the
2042    // resolved CK_LOG into `spec.env`, which is applied below and therefore
2043    // wins over anything ambient.
2044    apply_child_env(&mut command, spec);
2045    if spec.script.is_some() {
2046        script::remove_runtime_env(&mut command, spec);
2047    }
2048    let origin_witness = crate::program_origin::LaunchWitness::capture_command(spec, &command)
2049        .map_err(|source| SuperviseError::Spawn {
2050            program: spec.program.clone(),
2051            source,
2052            cgroup_path: None,
2053        })?;
2054    command.current_dir(&origin_witness.working_directory);
2055    apply_spawn_role(&mut command, role);
2056    let nonce_handoff = apply_wire_spawn_args_for_admission(
2057        &mut command,
2058        spec,
2059        connection_file_path,
2060        handle,
2061        role,
2062        spawn_admission.as_ref(),
2063    )?;
2064    #[cfg(unix)]
2065    let mut slots = subc_os::registration_channel::ChildDescriptorSlots::default();
2066    command.env_remove(subc_os::script_pipe::SCRIPT_FD_ENV);
2067    let script_delivery = script_content
2068        .map(|content| {
2069            script::Delivery::prepare(
2070                content,
2071                &mut command,
2072                #[cfg(unix)]
2073                &mut slots,
2074            )
2075        })
2076        .transpose()
2077        .map_err(|source| SuperviseError::Spawn {
2078            program: spec.program.clone(),
2079            source,
2080            cgroup_path: None,
2081        })?;
2082    #[cfg(unix)]
2083    let registration_channel = if spec.protocol == ModuleProtocol::Subc {
2084        let (parent, child, metadata) = subc_os::registration_channel::registration_socketpair()
2085            .map_err(|source| SuperviseError::Spawn {
2086                program: spec.program.clone(),
2087                source,
2088                cgroup_path: None,
2089            })?;
2090        slots
2091            .channel(child)
2092            .map_err(|source| SuperviseError::Spawn {
2093                program: spec.program.clone(),
2094                source,
2095                cgroup_path: None,
2096            })?;
2097        command
2098            .env(subc_os::registration_channel::REGISTRATION_FD_ENV, metadata)
2099            .env(
2100                subc_os::registration_channel::DAEMON_PID_ENV,
2101                std::process::id().to_string(),
2102            );
2103        Some(parent)
2104    } else {
2105        None
2106    };
2107    #[cfg(windows)]
2108    let registration_channel = prepare_windows_registration_pipe(&mut command, spec)?;
2109    let binding_publication = if spawn_admission
2110        .as_ref()
2111        .is_some_and(|admission| admission.launch.is_some())
2112    {
2113        handle.and_then(|handle| handle.begin_program_binding(&spec.module_id, role))
2114    } else {
2115        None
2116    };
2117    let registration_spawn = (spec.protocol == ModuleProtocol::Subc)
2118        .then(|| {
2119            handle.map(|handle| {
2120                let spawn = RegistrationSpawn::new_with_binding_requirement(
2121                    handle,
2122                    &spec.module_id,
2123                    role,
2124                    binding_publication.clone(),
2125                    spawn_admission
2126                        .as_ref()
2127                        .is_some_and(|admission| admission.launch.is_some()),
2128                );
2129                if let Some(admission) = &spawn_admission {
2130                    admission.initialize_origin(&spawn.authority, &origin_witness);
2131                }
2132                handle.record_nonce_launch(&spawn);
2133                spawn
2134            })
2135        })
2136        .flatten();
2137
2138    #[cfg(target_os = "linux")]
2139    let cgroup_path = cgroup_placement
2140        .map(|placement| {
2141            if let Some(container) = &carried {
2142                let path = container
2143                    .cgroup_path()
2144                    .ok_or_else(|| io::Error::other("carried container has no cgroup path"))?;
2145                placement.existing_module_path(path)?.ok_or_else(|| {
2146                    io::Error::new(
2147                        io::ErrorKind::NotFound,
2148                        "carried cgroup disappeared before replacement",
2149                    )
2150                })
2151            } else {
2152                if carrying {
2153                    containment::prepare_cgroup_path(placement, &cgroup_name)
2154                } else {
2155                    placement.module_path(&cgroup_name)
2156                }
2157            }
2158        })
2159        .transpose()
2160        .map_err(|source| SuperviseError::Cgroup {
2161            module_id: spec.module_id.clone(),
2162            source,
2163        })?;
2164    #[cfg(not(target_os = "linux"))]
2165    let cgroup_path: Option<PathBuf> = None;
2166    // Own a newly created directory before any fallible admission or command
2167    // preparation. Existing carried containment must never be removed here.
2168    #[cfg(target_os = "linux")]
2169    let cgroup_cleanup = PreparedCgroup(
2170        cgroup_placement
2171            .filter(|_| carried.is_none())
2172            .map(|placement| (placement.clone(), cgroup_name.clone())),
2173    );
2174    #[cfg(unix)]
2175    let mut admission_gate = if carrying {
2176        Some(
2177            admission::Gate::install(&mut command, spec, roster).map_err(|source| {
2178                SuperviseError::Spawn {
2179                    program: spec.program.clone(),
2180                    source,
2181                    cgroup_path: cgroup_path.clone(),
2182                }
2183            })?,
2184        )
2185    } else {
2186        None
2187    };
2188    #[cfg(target_os = "linux")]
2189    if let Some(path) = &cgroup_path {
2190        apply_cgroup_placement(&mut command, spec, path)?;
2191    }
2192
2193    let output_sink = capture_sink(spec, capture_logs_dir);
2194
2195    #[cfg(not(windows))]
2196    {
2197        command.stdout(Stdio::piped());
2198        command.stderr(Stdio::piped());
2199        command.kill_on_drop(!carrying);
2200    }
2201    // EACH MODULE LEADS ITS OWN PROCESS GROUP (the child calls setpgid(0, 0)
2202    // before exec). In the daemon's group, a service manager that kills the
2203    // job's process group when the daemon exits (launchd's default) killed
2204    // every module at the same moment its control connection closed, so no
2205    // module ever ran its EOF teardown on a daemon stop. Outside that group a
2206    // module is reached only by the daemon: the EOF it sees when its
2207    // connection closes, and the bounded stop in `child_roster` for anything
2208    // still running after that. On Linux this composes with the cgroup
2209    // placement above: that is a pre_exec write to cgroup.procs, std performs
2210    // setpgid in the child before running pre_exec callbacks, and the two
2211    // change independent process attributes.
2212    //
2213    // stdin is /dev/null because a process outside the terminal's foreground
2214    // group is stopped (SIGTTIN) if it reads the terminal, which a daemon run
2215    // by hand would otherwise hand down. Under a service manager stdin is
2216    // already /dev/null.
2217    #[cfg(unix)]
2218    command.process_group(
2219        carried
2220            .as_ref()
2221            .map(|container| container.verified_join_group())
2222            .transpose()
2223            .map_err(|source| SuperviseError::Spawn {
2224                program: spec.program.clone(),
2225                source,
2226                cgroup_path: cgroup_path.clone(),
2227            })?
2228            .flatten()
2229            .unwrap_or(0) as i32,
2230    );
2231    #[cfg(not(windows))]
2232    command.stdin(Stdio::null());
2233    #[cfg(unix)]
2234    if let Some(gate) = &mut admission_gate {
2235        gate.install_placement(&mut command);
2236    }
2237    // Fill all reserved slots in one allocation-free step, after placement has
2238    // stopped using descriptors that the fixed slots may replace.
2239    #[cfg(unix)]
2240    {
2241        if let Some(handoff) = nonce_handoff {
2242            slots.nonce(handoff);
2243        }
2244        #[cfg(target_os = "macos")]
2245        slots
2246            .acknowledgement(exec_ack.into_descriptor())
2247            .map_err(|source| SuperviseError::Spawn {
2248                program: spec.program.clone(),
2249                source,
2250                cgroup_path: cgroup_path.clone(),
2251            })?;
2252        slots.install(command.as_std_mut());
2253    }
2254    #[cfg(not(any(unix, windows)))]
2255    let _ = nonce_handoff;
2256
2257    // Install the daemon's root job before any module exists so that even a
2258    // suspended child cannot outlive the daemon before per-module assignment.
2259    #[cfg(windows)]
2260    {
2261        subc_jobobject::ensure_root_job().map_err(|source| SuperviseError::Spawn {
2262            program: spec.program.clone(),
2263            source,
2264            cgroup_path: None,
2265        })?;
2266    }
2267    // Timestamp before the spawn call: on Unix the child can serve before that
2268    // call even returns. This conservative bound never labels an older child
2269    // as a replacement for a request received during process creation.
2270    let spawned_at = Instant::now();
2271    let delivery_context = config_delivery;
2272    let config_delivery = config_delivery
2273        .map(|delivery| {
2274            delivery.spawned(
2275                spec,
2276                spawn_admission
2277                    .as_ref()
2278                    .expect("delivery prepares spawn admission"),
2279                spawned_at,
2280                role,
2281                registration_spawn
2282                    .as_ref()
2283                    .map(|spawn| spawn.authority.clone()),
2284            )
2285        })
2286        .transpose()?
2287        .flatten();
2288    let mut delivery_registration =
2289        delivery_context.map(|context| context.registration_guard(config_delivery.as_ref(), role));
2290    if let Some(registration) = &mut delivery_registration {
2291        registration.defer_cleanup();
2292    }
2293    if asynchronous {
2294        #[cfg(test)]
2295        if let Some(context) = delivery_context {
2296            context.pause_preflight_for_test();
2297        }
2298    }
2299    validate_spawn_program(spec, spawn_admission.as_ref(), delivery_context)?;
2300    Ok(PreparedChild {
2301        script_delivery,
2302        registration_spawn,
2303        registration_handle: handle.cloned(),
2304        #[cfg(any(unix, windows))]
2305        registration_channel,
2306        config_context: delivery_context.map(|delivery| delivery.runtime()),
2307        binding_publication,
2308        launch_spec,
2309        spawn_admission,
2310        command,
2311        carrying,
2312        carried: carried.clone(),
2313        #[cfg(unix)]
2314        launch_identity,
2315        #[cfg(unix)]
2316        group_target,
2317        #[cfg(target_os = "linux")]
2318        cgroup_placement: cgroup_placement.cloned(),
2319        #[cfg(target_os = "linux")]
2320        cgroup_cleanup,
2321        #[cfg(target_os = "linux")]
2322        cgroup_name,
2323        cgroup_path,
2324        #[cfg(unix)]
2325        admission_gate,
2326        output_sink,
2327        #[cfg(target_os = "macos")]
2328        privacy_exec,
2329        #[cfg(windows)]
2330        image_capture,
2331        #[cfg(windows)]
2332        nonce_handoff,
2333        #[cfg(windows)]
2334        role,
2335        spawned_at,
2336        config_delivery,
2337        delivery_registration,
2338        program_binding,
2339    })
2340}
2341
2342pub(super) fn launch_child_in_slot(
2343    _spec: &ModuleSpec,
2344    ring: &Arc<Mutex<StderrRing>>,
2345    roster: &ChildRoster,
2346    prepared: PreparedChild,
2347    register_timeout: Duration,
2348) -> Result<SupervisedChild, SuperviseError> {
2349    let launch_spec = prepared.launch_spec.clone();
2350    let registration_declaration = prepared
2351        .spawn_admission
2352        .as_ref()
2353        .and_then(|admission| admission.registration_declaration(&launch_spec.module_id));
2354    let admission_base = prepared
2355        .spawn_admission
2356        .as_ref()
2357        .and_then(|admission| admission.approved_base())
2358        .cloned();
2359    let spec = &launch_spec;
2360    let expected_image = prepared
2361        .spawn_admission
2362        .as_ref()
2363        .and_then(|admission| admission.launch.as_ref())
2364        .map(|launch| launch.image);
2365    let program_launch = prepared
2366        .spawn_admission
2367        .and_then(|admission| admission.launch);
2368    let config_owner = prepared
2369        .config_context
2370        .as_ref()
2371        .map(|context| context.0.clone());
2372    let binding_publication = prepared.binding_publication;
2373    #[cfg(test)]
2374    if let Some(context) = &prepared.config_context {
2375        context.0.before_spawn_exec_for_test();
2376    }
2377    #[cfg(feature = "test-support")]
2378    if let Some(context) = &prepared.config_context {
2379        context
2380            .0
2381            .pause_spawn_before_exec()
2382            .map_err(|error| config_delivery::gate_hold_error(spec, error, Some(context)))?;
2383    }
2384    #[cfg(not(windows))]
2385    let mut command = prepared.command;
2386    #[cfg(windows)]
2387    let command = prepared.command;
2388    let carrying = prepared.carrying;
2389    let carried = prepared.carried;
2390    #[cfg(unix)]
2391    let launch_identity = prepared.launch_identity;
2392    #[cfg(unix)]
2393    let group_target = prepared.group_target;
2394    #[cfg(target_os = "linux")]
2395    let cgroup_placement = prepared.cgroup_placement.as_ref();
2396    #[cfg(target_os = "linux")]
2397    let cgroup_name = prepared.cgroup_name;
2398    #[cfg(target_os = "linux")]
2399    let mut cgroup_cleanup = prepared.cgroup_cleanup;
2400    #[cfg(target_os = "linux")]
2401    let _ = cgroup_cleanup.0.take();
2402    let cgroup_path = prepared.cgroup_path;
2403    #[cfg(unix)]
2404    let admission_gate = prepared.admission_gate;
2405    let output_sink = prepared.output_sink;
2406    #[cfg(target_os = "macos")]
2407    let mut privacy_exec = prepared.privacy_exec;
2408    #[cfg(target_os = "macos")]
2409    if let Some(pending) = &mut privacy_exec {
2410        pending.admission_binding = binding_publication.clone();
2411        if expected_image.is_some() {
2412            pending.expected = expected_image;
2413        }
2414    }
2415    #[cfg(any(unix, windows))]
2416    let registration_channel = prepared.registration_channel;
2417    let registration_spawn = prepared.registration_spawn;
2418    let registration_handle = prepared.registration_handle;
2419    #[cfg(windows)]
2420    let image_capture = prepared.image_capture;
2421    #[cfg(windows)]
2422    let nonce_handoff = prepared.nonce_handoff;
2423    #[cfg(windows)]
2424    let role = prepared.role;
2425    let spawned_at = prepared.spawned_at;
2426    let config_delivery = prepared.config_delivery;
2427    let delivery_registration = prepared.delivery_registration;
2428    let _program_binding = prepared.program_binding;
2429    #[cfg(all(test, unix))]
2430    containment_tests::record_spawn_attempt(spec, &mut command);
2431    #[cfg(unix)]
2432    let spawned = match admission_gate {
2433        Some(gate) => gate
2434            .spawn(
2435                command,
2436                spec,
2437                roster,
2438                launch_identity,
2439                #[cfg(target_os = "linux")]
2440                cgroup_placement
2441                    .zip(cgroup_path.as_ref())
2442                    .map(|(placement, path)| {
2443                        (placement.clone(), cgroup_name.clone(), path.clone())
2444                    }),
2445            )
2446            .map(|(child, admitted)| (child, Some(admitted))),
2447        None => {
2448            let spawned =
2449                subc_os::child_spawn::tokio_spawn(&mut command).map(|child| (child, None));
2450            // The callback owns all child-only sources. Closing them here is
2451            // necessary for channel EOF and macOS exec acknowledgement EOF.
2452            drop(command);
2453            spawned
2454        }
2455    };
2456    #[cfg(not(any(unix, windows)))]
2457    let spawned = subc_os::child_spawn::tokio_spawn(&mut command);
2458    #[cfg(windows)]
2459    let spawned = {
2460        use subc_os::windows_spawn::{spawn, Environment};
2461        let command = command.as_std();
2462        Environment::from_entries(std::env::vars_os(), command.get_envs()).and_then(|env| {
2463            spawn(
2464                image_capture.path(),
2465                command.get_args(),
2466                &env,
2467                command
2468                    .get_current_dir()
2469                    .expect("module working directory was captured"),
2470            )
2471        })
2472    };
2473    let spawned = match spawned {
2474        Ok(child) => child,
2475        Err(source) => {
2476            if carried
2477                .as_ref()
2478                .and_then(|container| container.group())
2479                .is_some()
2480            {
2481                containment::note_end_reason(&roster.containment, ContainerEndReason::SpawnFailed);
2482                containment::terminate_blocking(&roster.containment);
2483            }
2484            #[cfg(target_os = "linux")]
2485            if let Some(placement) = cgroup_placement.filter(|_| carried.is_none()) {
2486                remove_module_cgroup(placement, &cgroup_name);
2487            }
2488            return Err(SuperviseError::Spawn {
2489                program: spec.program.clone(),
2490                source,
2491                cgroup_path,
2492            });
2493        }
2494    };
2495    #[cfg(unix)]
2496    let (mut child, mut admitted) = spawned;
2497    #[cfg(unix)]
2498    let group_target = admitted
2499        .as_ref()
2500        .map(|attempt| attempt.group_target())
2501        .unwrap_or(group_target);
2502    #[cfg(not(unix))]
2503    let mut child = spawned;
2504    if let Some(delivery) = prepared.script_delivery {
2505        delivery.start(child.id().expect("spawned child has a pid"));
2506    }
2507    #[cfg(test)]
2508    spawn_record_tests::after_create(&child, spec);
2509
2510    // Bind while the child is still suspended, before job assignment resumes it.
2511    // Keeping the executable handle open across CreateProcessW denies rename
2512    // and deletion, so the file cannot be exchanged during spawn. Bind that
2513    // file ID to the process handle returned by spawn, never a reopened PID.
2514    #[cfg(windows)]
2515    let windows_image = match image_capture.bind_protected(&child) {
2516        Ok(image) => Arc::new(image),
2517        Err(source) => {
2518            kill_and_reap_rejected_child(&mut child);
2519            return Err(SuperviseError::Spawn {
2520                program: spec.program.clone(),
2521                source,
2522                cgroup_path: None,
2523            });
2524        }
2525    };
2526    // Assign the suspended child to its module job; resume only after its
2527    // process identity has been durably recorded for orphan recovery.
2528    #[cfg(windows)]
2529    let job = contain_spawned_child(&mut child, spec, carried.as_ref())?;
2530    let spawned_at_ms = unix_ms_now();
2531    #[cfg(not(windows))]
2532    let spawned_from = spec.program.clone();
2533    #[cfg(windows)]
2534    let spawned_from = windows_image.path().to_path_buf();
2535    #[cfg(not(windows))]
2536    let spawned_file_identity = spawned_file_identity(&spawned_from);
2537    #[cfg(windows)]
2538    let spawned_file_identity = Some(SpawnedFileIdentity {
2539        device: 0,
2540        inode: 0,
2541        windows_image: Some(Arc::clone(&windows_image)),
2542    });
2543    let pid = child.id().ok_or_else(|| SuperviseError::Spawn {
2544        program: spec.program.clone(),
2545        source: io::Error::other("spawned child exposed no live pid"),
2546        cgroup_path: cgroup_path.clone(),
2547    })?;
2548    #[cfg(unix)]
2549    let plain_group = (!carrying
2550        && cgroup_path.is_none()
2551        && matches!(group_target, containment::GroupTarget::OwnLeader))
2552    .then(|| plain_group::PlainGroup::from_spawn(pid).map(Arc::new))
2553    .flatten();
2554    #[cfg(not(windows))]
2555    let process_start_time = admitted
2556        .as_ref()
2557        .map(|admitted| admitted.birth)
2558        .or_else(|| crate::provenance::process_start_time(pid));
2559    #[cfg(windows)]
2560    let process_start_time = Some(windows_image.start_time());
2561    let process_identity = process_start_time.map(|start_time| ProcessIdentity { pid, start_time });
2562    #[cfg(all(test, target_os = "macos"))]
2563    privacy_exec_boundary_tests::before_image_sample(spec, pid);
2564    #[cfg(all(test, target_os = "linux"))]
2565    assert!(roster.admission_event_for_test(&spec.module_id, "before_image_binding", Some(pid)));
2566    // Record the committed kernel image, not the configured pathname: PATH
2567    // lookup and shebang interpretation can select a different executable.
2568    // Linux's posix_spawn can return before that image is installed, so the
2569    // observer also waits for the kernel's first-exec flag to clear.
2570    #[cfg(not(windows))]
2571    let recorded_image = observe_spawned_image(pid);
2572    #[cfg(all(test, target_os = "linux"))]
2573    let recorded_image = if roster.admission_event_for_test(
2574        &spec.module_id,
2575        "after_spawn_image_sample",
2576        Some(pid),
2577    ) {
2578        recorded_image
2579    } else {
2580        None
2581    };
2582    #[cfg(target_os = "linux")]
2583    // An exited child cannot receive HELLO service and has no readable /proc/exe.
2584    // Keep its real exit for the supervisor instead of turning a crash into a hold.
2585    let exited_before_binding = expected_image.is_some()
2586        && recorded_image.and_then(|image| image.executable) != expected_image
2587        && subc_os::child_exit::observe(pid).ok().flatten().is_some();
2588    #[cfg(target_os = "linux")]
2589    let unavailable_initial_image = expected_image.is_some()
2590        && recorded_image.and_then(|image| image.executable).is_none()
2591        && !exited_before_binding;
2592    #[cfg(not(target_os = "linux"))]
2593    let unavailable_initial_image = false;
2594    #[cfg(target_os = "linux")]
2595    if expected_image
2596        .is_some_and(|expected| recorded_image.and_then(|image| image.executable) != Some(expected))
2597        && !exited_before_binding
2598        && !unavailable_initial_image
2599    {
2600        kill_module_cgroup(cgroup_placement, &cgroup_name);
2601        kill_and_reap_rejected_child(&mut child, group_target.clone());
2602        return Err(SuperviseError::ConfigHeld {
2603            module_id: spec.module_id.clone(),
2604            code: "program_refused".into(),
2605            detail: format!(
2606                "spawned executable {:?} does not match hashed program {:?}",
2607                recorded_image.and_then(|image| image.executable),
2608                expected_image
2609            ),
2610        });
2611    }
2612    #[cfg(not(target_os = "linux"))]
2613    let _ = expected_image;
2614    #[cfg(target_os = "macos")]
2615    let binding_ready = privacy_exec.is_none();
2616    #[cfg(target_os = "linux")]
2617    let binding_ready = !exited_before_binding;
2618    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
2619    let binding_ready = cfg!(windows);
2620    // spawn() confirms only the first exec, into the trampoline. Never persist
2621    // the trampoline image; the asynchronous acknowledgement publishes the
2622    // module image once the trampoline has replaced itself with the module.
2623    #[cfg(target_os = "macos")]
2624    let recorded_image = if privacy_exec.is_some() {
2625        None
2626    } else {
2627        recorded_image
2628    };
2629    #[cfg(target_os = "linux")]
2630    let recorded_cgroup_name = cgroup_path.as_ref().map(|_| cgroup_name.clone());
2631    #[cfg(not(target_os = "linux"))]
2632    let recorded_cgroup_name = None;
2633    #[cfg(unix)]
2634    let preadmitted = admitted
2635        .as_mut()
2636        .and_then(|admitted| admitted.leader.take());
2637    #[cfg(not(unix))]
2638    let preadmitted: Option<crate::child_roster::RosterGuard> = None;
2639    #[cfg(all(test, windows))]
2640    spawn_record_tests::before_roster_admit(spec);
2641    let roster_guard = if let Some(guard) = preadmitted {
2642        Ok(guard)
2643    } else {
2644        roster.admit(
2645            spec.module_id.clone(),
2646            pid,
2647            spec.protocol,
2648            process_start_time,
2649            crate::child_roster::RecordedIdentity {
2650                #[cfg(target_os = "linux")]
2651                container: cgroup_path
2652                    .clone()
2653                    .filter(|_| !carrying)
2654                    .map(ordinary_cgroup::recorded_identity),
2655                #[cfg(not(target_os = "linux"))]
2656                container: None,
2657                #[cfg(unix)]
2658                carried: None,
2659                #[cfg(unix)]
2660                plain_group: plain_group.as_ref().map(Arc::downgrade),
2661                #[cfg(not(windows))]
2662                start_time: recorded_image.map(|image| image.start_time),
2663                #[cfg(windows)]
2664                start_time: process_start_time,
2665                #[cfg(not(windows))]
2666                executable: recorded_image
2667                    .and_then(|image| image.executable)
2668                    .map(crate::live_children::ExecutableIdentity::from),
2669                #[cfg(windows)]
2670                executable: Some(crate::live_children::ExecutableIdentity::from(
2671                    windows_image.identity(),
2672                )),
2673                cgroup_name: recorded_cgroup_name,
2674                #[cfg(target_os = "linux")]
2675                cgroup_placement: cgroup_placement.cloned(),
2676            },
2677        )
2678    };
2679    let roster_guard = match roster_guard {
2680        Ok(guard) => guard,
2681        Err(failure) => {
2682            return failure.with_cleanup(|source| {
2683                #[cfg(windows)]
2684                if let Some(job) = &job {
2685                    let _ = job.lock().unwrap_or_else(|p| p.into_inner()).terminate();
2686                }
2687                #[cfg(target_os = "linux")]
2688                kill_module_cgroup(cgroup_placement, &cgroup_name);
2689                #[cfg(unix)]
2690                let rejected_group = group_target.clone();
2691                kill_and_reap_rejected_child(
2692                    &mut child,
2693                    #[cfg(unix)]
2694                    rejected_group,
2695                );
2696                #[cfg(target_os = "linux")]
2697                if let Some(placement) = cgroup_placement.filter(|_| carried.is_none()) {
2698                    remove_module_cgroup(placement, &cgroup_name);
2699                }
2700                Err(SuperviseError::Spawn {
2701                    program: spec.program.clone(),
2702                    source: io::Error::other(format!(
2703                        "could not durably record module child: {source}"
2704                    )),
2705                    cgroup_path,
2706                })
2707            });
2708        }
2709    };
2710    #[cfg(unix)]
2711    if admitted.is_some() {
2712        if let Some(image) = recorded_image {
2713            if let Err(source) = roster_guard.confirm_executable(image) {
2714                kill_and_reap_rejected_child(&mut child, group_target.clone());
2715                return Err(SuperviseError::Spawn {
2716                    program: spec.program.clone(),
2717                    source,
2718                    cgroup_path,
2719                });
2720            }
2721        }
2722    }
2723    // The pre-spawn check can pass just before shutdown begins. Ownership is
2724    // published at the start of admission, even while a record write is queued.
2725    // If shutdown already saw an empty roster before that publication, this
2726    // check sees the roster closed and ends the child before starting a module.
2727    if roster.is_closed() {
2728        if carrying {
2729            #[cfg(unix)]
2730            let rejected_group = admitted
2731                .as_ref()
2732                .map(|admitted| admitted.rejection_target())
2733                .unwrap_or_else(|| group_target.clone());
2734            #[cfg(windows)]
2735            if let Some(job) = &job {
2736                let _ = job.lock().unwrap_or_else(|p| p.into_inner()).terminate();
2737            }
2738            kill_and_reap_rejected_child(
2739                &mut child,
2740                #[cfg(unix)]
2741                rejected_group,
2742            );
2743            #[cfg(all(test, unix))]
2744            let _ =
2745                roster.admission_event_for_test(&spec.module_id, "after_rejected_child", Some(pid));
2746            drop(roster_guard);
2747            return Err(SuperviseError::Spawn {
2748                program: spec.program.clone(),
2749                source: io::Error::other(
2750                    "the daemon began shutting down during carried admission; ended the container",
2751                ),
2752                cgroup_path,
2753            });
2754        }
2755        // This child was never admitted, so there is no module protocol shutdown to wait for.
2756        #[cfg(target_os = "linux")]
2757        kill_module_cgroup(cgroup_placement, &cgroup_name);
2758        if let Err(error) = child.start_kill() {
2759            debug!(module_id = %spec.module_id, pid, %error, "kill of a process spawned during daemon shutdown failed; it may already have exited");
2760        }
2761        #[cfg(target_os = "linux")]
2762        if let Some(placement) = cgroup_placement.filter(|_| carried.is_none()) {
2763            // This spawn was never admitted, so shutdown has no roster entry
2764            // to await. Do not detach its cleanup: the runtime could exit
2765            // before that task reaps the rejected child and removes its group.
2766            while matches!(child.try_wait(), Ok(None)) {
2767                std::thread::yield_now();
2768            }
2769            if matches!(
2770                subc_cgroup::kill_module(Some(placement), &cgroup_name),
2771                subc_cgroup::KillOutcome::Killed
2772            ) {
2773                if let Ok(path) = placement.module_path(&cgroup_name) {
2774                    while std::fs::read_to_string(path.join("cgroup.events"))
2775                        .ok()
2776                        .is_some_and(|events| events.lines().any(|line| line == "populated 1"))
2777                    {
2778                        std::thread::yield_now();
2779                    }
2780                }
2781            }
2782            remove_module_cgroup(placement, &cgroup_name);
2783        }
2784        drop(roster_guard);
2785        return Err(SuperviseError::Spawn {
2786            program: spec.program.clone(),
2787            source: io::Error::other(
2788                "the daemon began shutting down while this process was starting; ended it",
2789            ),
2790            cgroup_path,
2791        });
2792    }
2793
2794    let pumps = crate::child_output::start(
2795        &mut child,
2796        output_sink,
2797        ring,
2798        &spec.module_id,
2799        #[cfg(unix)]
2800        plain_group.is_some(),
2801    );
2802
2803    let exec = Arc::new(crate::activity::ExecOutcome::new());
2804    #[cfg(target_os = "macos")]
2805    let pending_exec = privacy_exec.is_some();
2806    #[cfg(not(target_os = "macos"))]
2807    let pending_exec = false;
2808    if !pending_exec {
2809        exec.finish(crate::activity::ExecState::CommittedExec);
2810    }
2811    #[cfg(windows)]
2812    let subtree_target = job
2813        .as_ref()
2814        .map(|job| crate::subtree_resources::Target::Job(Arc::downgrade(job)))
2815        .unwrap_or(crate::subtree_resources::Target::Unavailable("no_job"));
2816    #[cfg(target_os = "linux")]
2817    let subtree_target = cgroup_path
2818        .map(crate::subtree_resources::Target::Cgroup)
2819        .unwrap_or(crate::subtree_resources::Target::Unavailable("no_cgroup"));
2820    #[cfg(not(any(target_os = "linux", windows)))]
2821    let subtree_target = crate::subtree_resources::Target::Unavailable("unsupported_platform");
2822    let mut supervised = SupervisedChild {
2823        registration_spawn,
2824        #[cfg(any(unix, windows))]
2825        registration_channel,
2826        live_program_binding: None,
2827        registered_config_connection: None,
2828        admission_base,
2829        registration_declaration,
2830        _program_binding: binding_publication,
2831        subtree_target,
2832        child: containment::ProcessChild::plain(child, pid),
2833        exec: crate::activity::ExecOwner(exec),
2834        #[cfg(windows)]
2835        nonce_delivery: None,
2836        protocol: spec.protocol,
2837        #[cfg(target_os = "linux")]
2838        module_id: cgroup_name,
2839        #[cfg(target_os = "linux")]
2840        cgroup_placement: cgroup_placement.cloned(),
2841        #[cfg(target_os = "linux")]
2842        unresolved_cgroup: None,
2843        #[cfg(windows)]
2844        job,
2845        stdout_pump: pumps.stdout,
2846        stderr_pump: pumps.stderr,
2847        #[cfg(unix)]
2848        capture_stop: pumps.stop,
2849        #[cfg(unix)]
2850        late_output_lost: false,
2851        stderr_ring: Arc::clone(ring),
2852        spawned_at,
2853        config_delivery,
2854        registration_deadline: None,
2855        registration_watch: None,
2856        spawned_at_ms,
2857        spawned_from,
2858        launch_spec_digest: LaunchSpecDigest::from_spec(spec),
2859        spawned_file_identity,
2860        process_start_time,
2861        process_identity,
2862        pid,
2863        roster_guard: Some(roster_guard),
2864        #[cfg(target_os = "macos")]
2865        privacy_exec,
2866        #[cfg(target_os = "macos")]
2867        report_ready: Arc::new(OnceLock::new()),
2868        spawn_failure: None,
2869        admission_kill_sent: false,
2870    };
2871    #[cfg(unix)]
2872    {
2873        supervised.child.plain_group = plain_group;
2874    }
2875    if let Err(error) = containment::adopt(&mut supervised, spec, roster) {
2876        supervised.child.reject(
2877            #[cfg(unix)]
2878            group_target,
2879        );
2880        #[cfg(all(test, unix))]
2881        let _ = roster.admission_event_for_test(&spec.module_id, "after_rejected_child", Some(pid));
2882        return Err(error);
2883    }
2884    if let (Some(launch), Some(owner), Some(base)) = (
2885        program_launch,
2886        config_owner,
2887        supervised.admission_base.clone(),
2888    ) {
2889        supervised.live_program_binding =
2890            content_binding::LiveProgramBinding::new(launch, &supervised, owner, base);
2891        if let (Some(publication), Some(live)) = (
2892            &supervised._program_binding,
2893            &supervised.live_program_binding,
2894        ) {
2895            publication.attach(live);
2896        }
2897    }
2898    #[cfg(unix)]
2899    if let Some(admitted) = admitted.take() {
2900        admitted.disarm();
2901    }
2902    #[cfg(windows)]
2903    {
2904        if let Some(handoff) = nonce_handoff {
2905            // The pipe name was reserved before CreateProcessW, but service
2906            // has a bounded lifetime. Do not spend any of that window on the
2907            // durable admission work while the client cannot run.
2908            match handoff.serve(pid, REGISTRY_RELEASE_TIMEOUT) {
2909                Ok(delivery) => supervised.nonce_delivery = Some(delivery),
2910                Err(source) => {
2911                    supervised.child.reject();
2912                    update_nonce_pipe_refusal(
2913                        registration_handle.as_ref(),
2914                        spec,
2915                        role,
2916                        Some("launch_nonce_pipe_serve_failed"),
2917                    );
2918                    return Err(windows_nonce_pipe_error(spec, "start serving", source));
2919                }
2920            }
2921        }
2922        if let Err(source) = supervised.child.resume(carrying) {
2923            containment::note_end_reason(&roster.containment, ContainerEndReason::SpawnFailed);
2924            containment::terminate_blocking(&roster.containment);
2925            supervised.child.reject();
2926            return Err(SuperviseError::Spawn {
2927                program: spec.program.clone(),
2928                source,
2929                cgroup_path: None,
2930            });
2931        }
2932    }
2933    if binding_ready {
2934        // An unreadable initial image is not a definite mismatch. Keep the
2935        // owned child and delivery registration until its reaped status decides
2936        // whether it crashed on its own or was stopped by admission's kill.
2937        let checked = if unavailable_initial_image {
2938            Err(crate::config_gate::GateError::new(
2939                "config_delivery_deferred",
2940                "initial process image is unavailable",
2941            ))
2942        } else {
2943            match (
2944                &supervised._program_binding,
2945                &supervised.live_program_binding,
2946            ) {
2947                (Some(binding), _) => binding.verify(),
2948                (None, Some(live)) => live.check(),
2949                _ if supervised.admission_base.is_some() => {
2950                    Err(crate::config_gate::GateError::new(
2951                        "config_delivery_deferred",
2952                        "live program witness is unavailable",
2953                    ))
2954                }
2955                _ => Ok(()),
2956            }
2957        };
2958        #[cfg(all(test, target_os = "linux"))]
2959        let checked = if roster.admission_event_for_test(
2960            &spec.module_id,
2961            "after_content_witness_check",
2962            Some(pid),
2963        ) {
2964            checked
2965        } else {
2966            Err(crate::config_gate::GateError::new(
2967                "config_delivery_deferred",
2968                "current process image is unavailable",
2969            ))
2970        };
2971        if let Err(error) = checked {
2972            if let Some(binding) = &mut supervised._program_binding {
2973                binding.reject();
2974            }
2975            // Reap through the normal child-reaping path, retaining the real exit record and
2976            // its roster ownership. A refusal must also end any helpers.
2977            if error.code == "program_refused" || supervised.try_wait().ok().flatten().is_none() {
2978                supervised.spawn_failure = Some(format!("{}: {}", error.code, error.detail));
2979                #[cfg(all(test, target_os = "linux"))]
2980                assert!(roster.admission_event_for_test(
2981                    &spec.module_id,
2982                    if unavailable_initial_image {
2983                        "before_initial_image_kill"
2984                    } else {
2985                        "before_content_witness_kill"
2986                    },
2987                    Some(pid),
2988                ));
2989                let _ = supervised.start_admission_kill();
2990                #[cfg(all(test, target_os = "linux"))]
2991                if supervised.admission_kill_sent {
2992                    assert!(roster.admission_event_for_test(
2993                        &spec.module_id,
2994                        "after_admission_kill_sent",
2995                        Some(pid),
2996                    ));
2997                }
2998            }
2999        }
3000    }
3001    if let Some(registration) = delivery_registration {
3002        registration.commit();
3003    }
3004    if let Some(spawn) = &supervised.registration_spawn {
3005        if let Some(record) = supervised
3006            .roster_guard
3007            .as_ref()
3008            .and_then(crate::child_roster::RosterGuard::resume_token_record)
3009        {
3010            let _ = spawn.resume_token_record.set(record);
3011        }
3012        if let Some(identity) = supervised.process_identity {
3013            let _ = spawn.identity.set(identity);
3014        }
3015        if supervised.spawn_failure.is_some() {
3016            spawn.refuse();
3017        } else if binding_ready {
3018            spawn.ready();
3019        }
3020        #[cfg(any(unix, windows))]
3021        if let (Some(handle), Some(channel)) =
3022            (registration_handle, supervised.registration_channel.take())
3023        {
3024            handle.serve_registration(channel, spawn.clone(), pid, spawned_at + register_timeout);
3025        }
3026    }
3027    Ok(supervised)
3028}
3029
3030#[cfg(target_os = "linux")]
3031pub(crate) fn kill_module_cgroup(placement: Option<&subc_cgroup::Placement>, module_id: &str) {
3032    use subc_cgroup::KillOutcome;
3033    match subc_cgroup::kill_module(placement, module_id) {
3034        KillOutcome::Killed => {}
3035        KillOutcome::NotPlaced | KillOutcome::Unsupported => {
3036            debug!(
3037                module_id,
3038                "cgroup tree kill unavailable; using direct-child kill"
3039            );
3040        }
3041        KillOutcome::IoError { path, error } => {
3042            warn!(module_id, path = %path.display(), %error, "cgroup tree kill failed; using direct-child kill");
3043        }
3044    }
3045}
3046
3047/// Assign a freshly spawned Windows child without ever resuming on failure.
3048///
3049/// Assign while the child is still suspended so no descendant can escape the
3050/// job. Resume follows the on-disk record of the child's identity, which lets
3051/// a replacement daemon find and clean up any surviving process.
3052/// Failed containment kills and reaps the suspended child rather than running it.
3053#[cfg(windows)]
3054fn contain_spawned_child(
3055    child: &mut Child,
3056    spec: &ModuleSpec,
3057    carried: Option<&Arc<containment::CarriedContainment>>,
3058) -> Result<Option<Arc<Mutex<subc_jobobject::JobObject>>>, SuperviseError> {
3059    let assignment = || {
3060        let job = match carried {
3061            Some(container) => container.job(),
3062            None => Arc::new(Mutex::new(subc_jobobject::JobObject::new()?)),
3063        };
3064        #[cfg(test)]
3065        spawn_record_tests::assignment_failpoint(spec)?;
3066        job.lock()
3067            .unwrap_or_else(|p| p.into_inner())
3068            .assign(child)?;
3069        Ok::<_, io::Error>(job)
3070    };
3071    match assignment() {
3072        Ok(job) => Ok(Some(job)),
3073        Err(source) => {
3074            kill_and_reap_rejected_child(child);
3075            Err(SuperviseError::Spawn {
3076                program: spec.program.clone(),
3077                source: io::Error::other(format!(
3078                    "Windows module job containment failed: {source}"
3079                )),
3080                cgroup_path: None,
3081            })
3082        }
3083    }
3084}
3085
3086/// Rejection is synchronous: do not return a spawn error while the child can
3087/// still run, or rely on kill-on-drop to reap it at some later runtime turn.
3088pub(super) fn kill_and_reap_rejected_child(
3089    child: &mut Child,
3090    #[cfg(unix)] group: containment::GroupTarget,
3091) {
3092    #[cfg(unix)]
3093    group.signal_rejected(child);
3094    let _ = child.start_kill();
3095    while matches!(child.try_wait(), Ok(None)) {
3096        std::thread::yield_now();
3097    }
3098}
3099
3100#[cfg(target_os = "linux")]
3101pub(super) fn remove_module_cgroup(placement: &subc_cgroup::Placement, module_id: &str) {
3102    match placement.remove_module(module_id) {
3103        Ok(()) => debug!(module_id, "removed module cgroup after process exit"),
3104        Err(error) => warn!(
3105            module_id,
3106            error = %error,
3107            "could not remove module cgroup after process exit; continuing teardown"
3108        ),
3109    }
3110}
3111
3112#[cfg(target_os = "linux")]
3113pub(super) fn apply_cgroup_placement(
3114    command: &mut Command,
3115    spec: &ModuleSpec,
3116    path: &std::path::Path,
3117) -> Result<(), SuperviseError> {
3118    subc_cgroup::apply(command, path).map_err(|source| SuperviseError::Cgroup {
3119        module_id: spec.module_id.clone(),
3120        source,
3121    })
3122}
3123
3124fn capture_retention(spec: &ModuleSpec) -> Retention {
3125    let defaults = Retention::default();
3126    let value = |name: &str| {
3127        spec.env
3128            .iter()
3129            .rev()
3130            .find_map(|(key, value)| (key == name).then_some(value.as_str()))
3131    };
3132    Retention {
3133        max_file_mb: value(CAPTURE_MAX_FILE_MB_ENV)
3134            .and_then(|value| value.parse().ok())
3135            .unwrap_or(defaults.max_file_mb),
3136        keep: value(CAPTURE_KEEP_ENV)
3137            .and_then(|value| value.parse().ok())
3138            .unwrap_or(defaults.keep),
3139        max_age_days: value(CAPTURE_MAX_AGE_DAYS_ENV)
3140            .and_then(|value| value.parse().ok())
3141            .unwrap_or(defaults.max_age_days),
3142    }
3143}
3144
3145pub(super) fn capture_sink(
3146    spec: &ModuleSpec,
3147    logs_dir: Option<&std::path::Path>,
3148) -> ChildOutputSink {
3149    let Some(logs_dir) = logs_dir else {
3150        return ChildOutputSink::Stderr;
3151    };
3152    let path = logs_dir.join(format!("{}.stderr.log", spec.module_id));
3153    match ChildOutputSink::open(&path, capture_retention(spec)) {
3154        Ok(sink) => sink,
3155        Err(error) => {
3156            warn!(module_id = %spec.module_id, path = %path.display(), %error,
3157                "could not open child output capture file; forwarding to stderr");
3158            ChildOutputSink::Stderr
3159        }
3160    }
3161}
3162
3163/// A fresh 256-bit CSPRNG launch nonce, lowercase hex. Used to bind a reserved
3164/// module's registration to the exact process the supervisor spawned.
3165fn generate_launch_nonce() -> Result<String, SuperviseError> {
3166    let mut bytes = [0u8; 32];
3167    getrandom::getrandom(&mut bytes).map_err(|source| SuperviseError::LaunchNonce {
3168        reason: source.to_string(),
3169    })?;
3170    let mut hex = String::with_capacity(64);
3171    for b in bytes {
3172        use std::fmt::Write;
3173        let _ = write!(hex, "{b:02x}");
3174    }
3175    Ok(hex)
3176}
3177
3178/// The kernel's image after an acknowledged exec, shared by ordinary launches
3179/// and privacy trampolines. PATH and shebang interpretation are kernel facts,
3180/// not identities inferred from a configured pathname.
3181#[cfg(not(windows))]
3182pub(super) fn observe_spawned_image(pid: u32) -> Option<subc_os::Observation> {
3183    let process = subc_os::Process::open(pid).ok().flatten()?;
3184    #[cfg(target_os = "linux")]
3185    return sample_after_linux_exec(
3186        || {
3187            let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
3188            let committed = linux_exec_committed(&stat);
3189            #[cfg(test)]
3190            spawn_image_tests::report_exec_state(committed);
3191            committed
3192        },
3193        || process.observe(),
3194    );
3195    #[cfg(not(target_os = "linux"))]
3196    process.observe()
3197}
3198
3199/// glibc's posix_spawn parent can wake in exec_mmap before the child's new mm
3200/// is installed. PF_FORKNOEXEC is cleared later in begin_new_exec, after that
3201/// installation. Until it clears, /proc/pid/exe can still name the daemon.
3202#[cfg(target_os = "linux")]
3203pub(super) fn linux_exec_committed(stat: &str) -> Option<bool> {
3204    const PF_FORKNOEXEC: u64 = 0x40;
3205    let flags = stat.rsplit_once(')')?.1.split_whitespace().nth(6)?;
3206    Some(flags.parse::<u64>().ok()? & PF_FORKNOEXEC == 0)
3207}
3208
3209#[cfg(target_os = "linux")]
3210pub(super) fn sample_after_linux_exec(
3211    mut exec_committed: impl FnMut() -> Option<bool>,
3212    observe: impl FnOnce() -> Option<subc_os::Observation>,
3213) -> Option<subc_os::Observation> {
3214    let deadline = std::time::Instant::now() + Duration::from_secs(1);
3215    while !exec_committed()? {
3216        // A failed or indefinitely stalled exec must not publish the inherited
3217        // image as authority to signal a future orphan. Missing identity keeps
3218        // the existing conservative orphan-sweep behavior.
3219        if std::time::Instant::now() >= deadline {
3220            return None;
3221        }
3222        std::thread::sleep(Duration::from_micros(50));
3223    }
3224    observe()
3225}
3226
3227/// Resolve once and spawn that exact path, so PATH lookup cannot choose a
3228/// different executable after the no-delete capture was taken.
3229#[cfg(windows)]
3230pub(crate) fn windows_spawn_capture(spec: &ModuleSpec) -> io::Result<subc_os::ExecutableCapture> {
3231    if let Err(error) = require_program_search_path(spec) {
3232        return Err(match error {
3233            SuperviseError::Spawn { source, .. } => source,
3234            error => io::Error::other(error),
3235        });
3236    }
3237    let mut program = spec.program.clone();
3238    if program.is_absolute() || program.components().count() > 1 {
3239        // An explicit path can name a PE image with no extension. Try that
3240        // exact file first, as Command does, before falling back to .exe.
3241        match subc_os::ExecutableCapture::open(&program) {
3242            Ok(capture) => return Ok(capture),
3243            Err(error)
3244                if error.kind() == io::ErrorKind::NotFound && program.extension().is_none() => {}
3245            Err(error) => return Err(error),
3246        }
3247        program.set_extension("exe");
3248        return subc_os::ExecutableCapture::open(&program);
3249    }
3250    if program.extension().is_none() {
3251        program.set_extension("exe");
3252    }
3253    let custom_path = spec
3254        .env
3255        .iter()
3256        .rev()
3257        .find(|(key, _)| key.eq_ignore_ascii_case("PATH"));
3258    let mut directories = Vec::new();
3259    // These are Windows' default executable search locations. A configured
3260    // PATH still overrides the inherited PATH, not the system directories.
3261    if let Some(parent) = std::env::current_exe()?.parent() {
3262        directories.push(parent.to_path_buf());
3263    }
3264    directories.push(std::env::current_dir()?);
3265    if let Some(windows) = std::env::var_os("SystemRoot") {
3266        let windows = PathBuf::from(windows);
3267        directories.push(windows.join("System32"));
3268        directories.push(windows.clone());
3269    }
3270    let path = custom_path
3271        .map(|(_, value)| std::ffi::OsString::from(value))
3272        .or_else(|| std::env::var_os("PATH"));
3273    if let Some(path) = path {
3274        directories.extend(std::env::split_paths(&path));
3275    }
3276    for directory in directories {
3277        match subc_os::ExecutableCapture::open(&directory.join(&program)) {
3278            Ok(capture) => return Ok(capture),
3279            Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
3280            Err(error) => return Err(error),
3281        }
3282    }
3283    Err(io::Error::new(
3284        io::ErrorKind::NotFound,
3285        "resolved executable not found",
3286    ))
3287}
3288
3289#[cfg(test)]
3290pub(super) fn spawn_and_mark_running(
3291    spec: &ModuleSpec,
3292    runtime: &SupervisorRuntimeConfig,
3293    snapshot: &SharedSnapshot,
3294) -> Result<SupervisedChild, SuperviseError> {
3295    let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
3296    let registration_watch = watch_registration(&runtime.registry, spec);
3297    #[cfg(unix)]
3298    let joining_group = containment::current(&runtime.child_roster.containment)
3299        .is_some_and(|container| container.group().is_some());
3300    let spawn = || {
3301        spawn_child(
3302            spec,
3303            runtime.connection_file_path.as_deref(),
3304            runtime.supervisor_handle.as_ref(),
3305            &runtime.stderr_ring,
3306            runtime.capture_logs_dir.as_deref(),
3307            &runtime.child_roster,
3308            runtime.spawn_delivery(),
3309            #[cfg(target_os = "linux")]
3310            runtime.cgroup_placement.as_ref(),
3311            runtime.register_timeout,
3312        )
3313    };
3314    let result = spawn();
3315    #[cfg(unix)]
3316    let result = match result {
3317        Err(error)
3318            if joining_group
3319                && !is_launch_deferral(&error)
3320                && !runtime.child_roster.is_closed()
3321                && lock_snapshot(snapshot).is_ok_and(|state| state.enabled)
3322                && runtime
3323                    .child_roster
3324                    .previous_instance(&spec.module_id)
3325                    .is_none() =>
3326        {
3327            // The failed join already destroyed and verified the old container.
3328            // Try one fresh group as part of this same restart, without spending
3329            // another crash-budget entry. Cgroups and Windows jobs do not retry.
3330            warn!(module_id = %spec.module_id, %error, "carried process-group spawn failed; trying one fresh container");
3331            spawn()
3332        }
3333        other => other,
3334    };
3335    let child = result?;
3336    let mut child = child;
3337    arm_registration_deadline(&mut child, runtime.register_timeout, registration_watch);
3338    if let Err(error) = set_running(snapshot, &child, &spec.module_id, &runtime.spawn_events) {
3339        containment::terminate_blocking(&runtime.child_roster.containment);
3340        return Err(error);
3341    }
3342    if let Some(spawn) = activity_spawn {
3343        spawn.complete(snapshot);
3344    }
3345    Ok(child)
3346}
3347
3348pub(super) fn set_running(
3349    snapshot: &SharedSnapshot,
3350    child: &SupervisedChild,
3351    module_id: &str,
3352    spawn_events: &SpawnEventFeed,
3353) -> Result<(), SuperviseError> {
3354    let mut state = snapshot.lock().map_err(|_| SuperviseError::StatePoisoned {
3355        module_id: Some(module_id.to_string()),
3356    })?;
3357    state.spawn_generation = spawn_events.emit_spawned(
3358        module_id,
3359        child
3360            .registration_spawn
3361            .as_ref()
3362            .map(|spawn| spawn.authority.spawn_number()),
3363        child.pid,
3364        child.spawned_at_ms,
3365    );
3366    if std::mem::take(&mut state.coalesced_restart_pending) {
3367        let generation = state.spawn_generation;
3368        info!(module_id, "restart already satisfied by generation {generation}; coalesced pending request completed");
3369    }
3370    state.drain_disposition_detail = None;
3371    state.spawn_failure = None;
3372    state.admission_refused = None;
3373    #[cfg(windows)]
3374    {
3375        state.nonce_pipe_refusal = None;
3376    }
3377    state.config_hold_parked = false;
3378    state.config_hold_daemon_initiated = false;
3379    state.config_hold_approval = None;
3380    state.legacy_registration_spawn =
3381        child.registration_spawn.is_some() && child.admission_base.is_none();
3382    state.registration_declaration = child.registration_declaration.clone();
3383    state.stop_reason = None;
3384    state.config_exit_failed_approval = None;
3385    state.waiting_for_previous_pid = None;
3386    state.waiting_for_previous_detail = None;
3387    // Every caller of this is a plain spawn, which always uses the primary key;
3388    // a promoted swap candidate sets the flag itself after this returns.
3389    state.in_alternate_slot = false;
3390    state.configuration_updated_since_spawn = false;
3391    state.spawned_protocol = Some(child.protocol);
3392    state.state = ModuleState::Running;
3393    state.approved_start_failure = None;
3394    state.enabled = true;
3395    state.process_alive = true;
3396    state.pid = child.id();
3397    state.subtree_target = child.subtree_target.clone();
3398    // Probe samples belong to one process. Keep module-level escalation and
3399    // late-answer history, but never charge a new child for its predecessor's misses.
3400    state.health.status = SupervisorHealthStatus::Unknown;
3401    state.last_probe_evidence = None;
3402    state.health.consecutive_failures = 0;
3403    state.health.detail = None;
3404    state.health.metrics = None;
3405    state.health.last_probe_ms = None;
3406    state.failed_retry.healthy_since = None;
3407    state.failed_retry.failed_at = None;
3408    state.failed_retry.running_since = Some(child.spawned_at);
3409    #[cfg(windows)]
3410    {
3411        state.pipe_consumed = child
3412            .nonce_delivery
3413            .as_ref()
3414            .map(|delivery| delivery.consumed());
3415    }
3416    #[cfg(target_os = "macos")]
3417    {
3418        state.report_ready = Some(Arc::clone(&child.report_ready));
3419    }
3420    state.spawned_at_ms = Some(child.spawned_at_ms);
3421    state.exec_outcome = Some(Arc::clone(&child.exec.0));
3422    state.spawned_from = Some(child.spawned_from.clone());
3423    state.launch_spec_digest = Some(child.launch_spec_digest.clone());
3424    state.spawned_file_identity = child.spawned_file_identity.clone();
3425    state.process_start_time = child.process_start_time;
3426    Ok(())
3427}