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    command.stdout(Stdio::piped());
2196    command.stderr(Stdio::piped());
2197    command.kill_on_drop(!carrying);
2198    // EACH MODULE LEADS ITS OWN PROCESS GROUP (the child calls setpgid(0, 0)
2199    // before exec). In the daemon's group, a service manager that kills the
2200    // job's process group when the daemon exits (launchd's default) killed
2201    // every module at the same moment its control connection closed, so no
2202    // module ever ran its EOF teardown on a daemon stop. Outside that group a
2203    // module is reached only by the daemon: the EOF it sees when its
2204    // connection closes, and the bounded stop in `child_roster` for anything
2205    // still running after that. On Linux this composes with the cgroup
2206    // placement above: that is a pre_exec write to cgroup.procs, std performs
2207    // setpgid in the child before running pre_exec callbacks, and the two
2208    // change independent process attributes.
2209    //
2210    // stdin is /dev/null because a process outside the terminal's foreground
2211    // group is stopped (SIGTTIN) if it reads the terminal, which a daemon run
2212    // by hand would otherwise hand down. Under a service manager stdin is
2213    // already /dev/null.
2214    #[cfg(unix)]
2215    command.process_group(
2216        carried
2217            .as_ref()
2218            .map(|container| container.verified_join_group())
2219            .transpose()
2220            .map_err(|source| SuperviseError::Spawn {
2221                program: spec.program.clone(),
2222                source,
2223                cgroup_path: cgroup_path.clone(),
2224            })?
2225            .flatten()
2226            .unwrap_or(0) as i32,
2227    );
2228    command.stdin(Stdio::null());
2229    #[cfg(unix)]
2230    if let Some(gate) = &mut admission_gate {
2231        gate.install_placement(&mut command);
2232    }
2233    // Fill all reserved slots in one allocation-free step, after placement has
2234    // stopped using descriptors that the fixed slots may replace.
2235    #[cfg(unix)]
2236    {
2237        if let Some(handoff) = nonce_handoff {
2238            slots.nonce(handoff);
2239        }
2240        #[cfg(target_os = "macos")]
2241        slots
2242            .acknowledgement(exec_ack.into_descriptor())
2243            .map_err(|source| SuperviseError::Spawn {
2244                program: spec.program.clone(),
2245                source,
2246                cgroup_path: cgroup_path.clone(),
2247            })?;
2248        slots.install(command.as_std_mut());
2249    }
2250    #[cfg(not(any(unix, windows)))]
2251    let _ = nonce_handoff;
2252
2253    // Containment, step 1 of 3 (issue #109): create the child suspended so it
2254    // cannot run a single instruction -- and therefore cannot spawn a
2255    // grandchild -- before it is in the job. See `contain_spawned_child` for the
2256    // other two steps and why the window matters.
2257    #[cfg(windows)]
2258    {
2259        subc_jobobject::ensure_root_job().map_err(|source| SuperviseError::Spawn {
2260            program: spec.program.clone(),
2261            source,
2262            cgroup_path: None,
2263        })?;
2264        subc_jobobject::suspend_on_create_async(&mut command);
2265    }
2266    // Timestamp before the spawn call: on Unix the child can serve before that
2267    // call even returns. This conservative bound never labels an older child
2268    // as a replacement for a request received during process creation.
2269    let spawned_at = Instant::now();
2270    let delivery_context = config_delivery;
2271    let config_delivery = config_delivery
2272        .map(|delivery| {
2273            delivery.spawned(
2274                spec,
2275                spawn_admission
2276                    .as_ref()
2277                    .expect("delivery prepares spawn admission"),
2278                spawned_at,
2279                role,
2280                registration_spawn
2281                    .as_ref()
2282                    .map(|spawn| spawn.authority.clone()),
2283            )
2284        })
2285        .transpose()?
2286        .flatten();
2287    let mut delivery_registration =
2288        delivery_context.map(|context| context.registration_guard(config_delivery.as_ref(), role));
2289    if let Some(registration) = &mut delivery_registration {
2290        registration.defer_cleanup();
2291    }
2292    if asynchronous {
2293        #[cfg(test)]
2294        if let Some(context) = delivery_context {
2295            context.pause_preflight_for_test();
2296        }
2297    }
2298    validate_spawn_program(spec, spawn_admission.as_ref(), delivery_context)?;
2299    Ok(PreparedChild {
2300        script_delivery,
2301        registration_spawn,
2302        registration_handle: handle.cloned(),
2303        #[cfg(any(unix, windows))]
2304        registration_channel,
2305        config_context: delivery_context.map(|delivery| delivery.runtime()),
2306        binding_publication,
2307        launch_spec,
2308        spawn_admission,
2309        command,
2310        carrying,
2311        carried: carried.clone(),
2312        #[cfg(unix)]
2313        launch_identity,
2314        #[cfg(unix)]
2315        group_target,
2316        #[cfg(target_os = "linux")]
2317        cgroup_placement: cgroup_placement.cloned(),
2318        #[cfg(target_os = "linux")]
2319        cgroup_cleanup,
2320        #[cfg(target_os = "linux")]
2321        cgroup_name,
2322        cgroup_path,
2323        #[cfg(unix)]
2324        admission_gate,
2325        output_sink,
2326        #[cfg(target_os = "macos")]
2327        privacy_exec,
2328        #[cfg(windows)]
2329        image_capture,
2330        #[cfg(windows)]
2331        nonce_handoff,
2332        #[cfg(windows)]
2333        role,
2334        spawned_at,
2335        config_delivery,
2336        delivery_registration,
2337        program_binding,
2338    })
2339}
2340
2341pub(super) fn launch_child_in_slot(
2342    _spec: &ModuleSpec,
2343    ring: &Arc<Mutex<StderrRing>>,
2344    roster: &ChildRoster,
2345    prepared: PreparedChild,
2346    register_timeout: Duration,
2347) -> Result<SupervisedChild, SuperviseError> {
2348    let launch_spec = prepared.launch_spec.clone();
2349    let registration_declaration = prepared
2350        .spawn_admission
2351        .as_ref()
2352        .and_then(|admission| admission.registration_declaration(&launch_spec.module_id));
2353    let admission_base = prepared
2354        .spawn_admission
2355        .as_ref()
2356        .and_then(|admission| admission.approved_base())
2357        .cloned();
2358    let spec = &launch_spec;
2359    let expected_image = prepared
2360        .spawn_admission
2361        .as_ref()
2362        .and_then(|admission| admission.launch.as_ref())
2363        .map(|launch| launch.image);
2364    let program_launch = prepared
2365        .spawn_admission
2366        .and_then(|admission| admission.launch);
2367    let config_owner = prepared
2368        .config_context
2369        .as_ref()
2370        .map(|context| context.0.clone());
2371    let binding_publication = prepared.binding_publication;
2372    #[cfg(test)]
2373    if let Some(context) = &prepared.config_context {
2374        context.0.before_spawn_exec_for_test();
2375    }
2376    #[cfg(feature = "test-support")]
2377    if let Some(context) = &prepared.config_context {
2378        context
2379            .0
2380            .pause_spawn_before_exec()
2381            .map_err(|error| config_delivery::gate_hold_error(spec, error, Some(context)))?;
2382    }
2383    let mut command = prepared.command;
2384    let carrying = prepared.carrying;
2385    let carried = prepared.carried;
2386    #[cfg(unix)]
2387    let launch_identity = prepared.launch_identity;
2388    #[cfg(unix)]
2389    let group_target = prepared.group_target;
2390    #[cfg(target_os = "linux")]
2391    let cgroup_placement = prepared.cgroup_placement.as_ref();
2392    #[cfg(target_os = "linux")]
2393    let cgroup_name = prepared.cgroup_name;
2394    #[cfg(target_os = "linux")]
2395    let mut cgroup_cleanup = prepared.cgroup_cleanup;
2396    #[cfg(target_os = "linux")]
2397    let _ = cgroup_cleanup.0.take();
2398    let cgroup_path = prepared.cgroup_path;
2399    #[cfg(unix)]
2400    let admission_gate = prepared.admission_gate;
2401    let output_sink = prepared.output_sink;
2402    #[cfg(target_os = "macos")]
2403    let mut privacy_exec = prepared.privacy_exec;
2404    #[cfg(target_os = "macos")]
2405    if let Some(pending) = &mut privacy_exec {
2406        pending.admission_binding = binding_publication.clone();
2407        if expected_image.is_some() {
2408            pending.expected = expected_image;
2409        }
2410    }
2411    #[cfg(any(unix, windows))]
2412    let registration_channel = prepared.registration_channel;
2413    let registration_spawn = prepared.registration_spawn;
2414    let registration_handle = prepared.registration_handle;
2415    #[cfg(windows)]
2416    let image_capture = prepared.image_capture;
2417    #[cfg(windows)]
2418    let nonce_handoff = prepared.nonce_handoff;
2419    #[cfg(windows)]
2420    let role = prepared.role;
2421    let spawned_at = prepared.spawned_at;
2422    let config_delivery = prepared.config_delivery;
2423    let delivery_registration = prepared.delivery_registration;
2424    let _program_binding = prepared.program_binding;
2425    #[cfg(all(test, unix))]
2426    containment_tests::record_spawn_attempt(spec, &mut command);
2427    #[cfg(unix)]
2428    let spawned = match admission_gate {
2429        Some(gate) => gate
2430            .spawn(
2431                command,
2432                spec,
2433                roster,
2434                launch_identity,
2435                #[cfg(target_os = "linux")]
2436                cgroup_placement
2437                    .zip(cgroup_path.as_ref())
2438                    .map(|(placement, path)| {
2439                        (placement.clone(), cgroup_name.clone(), path.clone())
2440                    }),
2441            )
2442            .map(|(child, admitted)| (child, Some(admitted))),
2443        None => {
2444            let spawned =
2445                subc_os::child_spawn::tokio_spawn(&mut command).map(|child| (child, None));
2446            // The callback owns all child-only sources. Closing them here is
2447            // necessary for channel EOF and macOS exec acknowledgement EOF.
2448            drop(command);
2449            spawned
2450        }
2451    };
2452    #[cfg(not(unix))]
2453    let spawned = subc_os::child_spawn::tokio_spawn(&mut command);
2454    let spawned = match spawned {
2455        Ok(child) => child,
2456        Err(source) => {
2457            if carried
2458                .as_ref()
2459                .and_then(|container| container.group())
2460                .is_some()
2461            {
2462                containment::note_end_reason(&roster.containment, ContainerEndReason::SpawnFailed);
2463                containment::terminate_blocking(&roster.containment);
2464            }
2465            #[cfg(target_os = "linux")]
2466            if let Some(placement) = cgroup_placement.filter(|_| carried.is_none()) {
2467                remove_module_cgroup(placement, &cgroup_name);
2468            }
2469            return Err(SuperviseError::Spawn {
2470                program: spec.program.clone(),
2471                source,
2472                cgroup_path,
2473            });
2474        }
2475    };
2476    #[cfg(unix)]
2477    let (mut child, mut admitted) = spawned;
2478    #[cfg(unix)]
2479    let group_target = admitted
2480        .as_ref()
2481        .map(|attempt| attempt.group_target())
2482        .unwrap_or(group_target);
2483    #[cfg(not(unix))]
2484    let mut child = spawned;
2485    if let Some(delivery) = prepared.script_delivery {
2486        delivery.start(child.id().expect("spawned child has a pid"));
2487    }
2488    #[cfg(test)]
2489    spawn_record_tests::after_create(&child, spec);
2490
2491    // Bind while the child is still suspended, before job assignment resumes it.
2492    // Keeping the executable handle open across CreateProcessW denies rename
2493    // and deletion, so the file cannot be exchanged during spawn. Bind that
2494    // file ID to the process handle returned by spawn, never a reopened PID.
2495    #[cfg(windows)]
2496    let windows_image = match image_capture.bind_tokio(&child) {
2497        Ok(image) => Arc::new(image),
2498        Err(source) => {
2499            kill_and_reap_rejected_child(&mut child);
2500            return Err(SuperviseError::Spawn {
2501                program: spec.program.clone(),
2502                source,
2503                cgroup_path: None,
2504            });
2505        }
2506    };
2507    // Assign the suspended child to its module job; resume only after its
2508    // process identity has been durably recorded for orphan recovery.
2509    #[cfg(windows)]
2510    let job = contain_spawned_child(&mut child, spec, carried.as_ref())?;
2511    let spawned_at_ms = unix_ms_now();
2512    #[cfg(not(windows))]
2513    let spawned_from = spec.program.clone();
2514    #[cfg(windows)]
2515    let spawned_from = windows_image.path().to_path_buf();
2516    #[cfg(not(windows))]
2517    let spawned_file_identity = spawned_file_identity(&spawned_from);
2518    #[cfg(windows)]
2519    let spawned_file_identity = Some(SpawnedFileIdentity {
2520        device: 0,
2521        inode: 0,
2522        windows_image: Some(Arc::clone(&windows_image)),
2523    });
2524    let pid = child.id().ok_or_else(|| SuperviseError::Spawn {
2525        program: spec.program.clone(),
2526        source: io::Error::other("spawned child exposed no live pid"),
2527        cgroup_path: cgroup_path.clone(),
2528    })?;
2529    #[cfg(unix)]
2530    let plain_group = (!carrying
2531        && cgroup_path.is_none()
2532        && matches!(group_target, containment::GroupTarget::OwnLeader))
2533    .then(|| plain_group::PlainGroup::from_spawn(pid).map(Arc::new))
2534    .flatten();
2535    #[cfg(not(windows))]
2536    let process_start_time = admitted
2537        .as_ref()
2538        .map(|admitted| admitted.birth)
2539        .or_else(|| crate::provenance::process_start_time(pid));
2540    #[cfg(windows)]
2541    let process_start_time = Some(windows_image.start_time());
2542    let process_identity = process_start_time.map(|start_time| ProcessIdentity { pid, start_time });
2543    #[cfg(all(test, target_os = "macos"))]
2544    privacy_exec_boundary_tests::before_image_sample(spec, pid);
2545    #[cfg(all(test, target_os = "linux"))]
2546    assert!(roster.admission_event_for_test(&spec.module_id, "before_image_binding", Some(pid)));
2547    // Record the committed kernel image, not the configured pathname: PATH
2548    // lookup and shebang interpretation can select a different executable.
2549    // Linux's posix_spawn can return before that image is installed, so the
2550    // observer also waits for the kernel's first-exec flag to clear.
2551    #[cfg(not(windows))]
2552    let recorded_image = observe_spawned_image(pid);
2553    #[cfg(all(test, target_os = "linux"))]
2554    let recorded_image = if roster.admission_event_for_test(
2555        &spec.module_id,
2556        "after_spawn_image_sample",
2557        Some(pid),
2558    ) {
2559        recorded_image
2560    } else {
2561        None
2562    };
2563    #[cfg(target_os = "linux")]
2564    // An exited child cannot receive HELLO service and has no readable /proc/exe.
2565    // Keep its real exit for the supervisor instead of turning a crash into a hold.
2566    let exited_before_binding = expected_image.is_some()
2567        && recorded_image.and_then(|image| image.executable) != expected_image
2568        && subc_os::child_exit::observe(pid).ok().flatten().is_some();
2569    #[cfg(target_os = "linux")]
2570    let unavailable_initial_image = expected_image.is_some()
2571        && recorded_image.and_then(|image| image.executable).is_none()
2572        && !exited_before_binding;
2573    #[cfg(not(target_os = "linux"))]
2574    let unavailable_initial_image = false;
2575    #[cfg(target_os = "linux")]
2576    if expected_image
2577        .is_some_and(|expected| recorded_image.and_then(|image| image.executable) != Some(expected))
2578        && !exited_before_binding
2579        && !unavailable_initial_image
2580    {
2581        kill_module_cgroup(cgroup_placement, &cgroup_name);
2582        kill_and_reap_rejected_child(&mut child, group_target.clone());
2583        return Err(SuperviseError::ConfigHeld {
2584            module_id: spec.module_id.clone(),
2585            code: "program_refused".into(),
2586            detail: format!(
2587                "spawned executable {:?} does not match hashed program {:?}",
2588                recorded_image.and_then(|image| image.executable),
2589                expected_image
2590            ),
2591        });
2592    }
2593    #[cfg(not(target_os = "linux"))]
2594    let _ = expected_image;
2595    #[cfg(target_os = "macos")]
2596    let binding_ready = privacy_exec.is_none();
2597    #[cfg(target_os = "linux")]
2598    let binding_ready = !exited_before_binding;
2599    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
2600    let binding_ready = cfg!(windows);
2601    // spawn() confirms only the first exec, into the trampoline. Never persist
2602    // the trampoline image; the asynchronous acknowledgement publishes the
2603    // module image once the trampoline has replaced itself with the module.
2604    #[cfg(target_os = "macos")]
2605    let recorded_image = if privacy_exec.is_some() {
2606        None
2607    } else {
2608        recorded_image
2609    };
2610    #[cfg(target_os = "linux")]
2611    let recorded_cgroup_name = cgroup_path.as_ref().map(|_| cgroup_name.clone());
2612    #[cfg(not(target_os = "linux"))]
2613    let recorded_cgroup_name = None;
2614    #[cfg(unix)]
2615    let preadmitted = admitted
2616        .as_mut()
2617        .and_then(|admitted| admitted.leader.take());
2618    #[cfg(not(unix))]
2619    let preadmitted: Option<crate::child_roster::RosterGuard> = None;
2620    #[cfg(all(test, windows))]
2621    spawn_record_tests::before_roster_admit(spec);
2622    let roster_guard = if let Some(guard) = preadmitted {
2623        Ok(guard)
2624    } else {
2625        roster.admit(
2626            spec.module_id.clone(),
2627            pid,
2628            spec.protocol,
2629            process_start_time,
2630            crate::child_roster::RecordedIdentity {
2631                #[cfg(target_os = "linux")]
2632                container: cgroup_path
2633                    .clone()
2634                    .filter(|_| !carrying)
2635                    .map(ordinary_cgroup::recorded_identity),
2636                #[cfg(not(target_os = "linux"))]
2637                container: None,
2638                #[cfg(unix)]
2639                carried: None,
2640                #[cfg(unix)]
2641                plain_group: plain_group.as_ref().map(Arc::downgrade),
2642                #[cfg(not(windows))]
2643                start_time: recorded_image.map(|image| image.start_time),
2644                #[cfg(windows)]
2645                start_time: process_start_time,
2646                #[cfg(not(windows))]
2647                executable: recorded_image
2648                    .and_then(|image| image.executable)
2649                    .map(crate::live_children::ExecutableIdentity::from),
2650                #[cfg(windows)]
2651                executable: Some(crate::live_children::ExecutableIdentity::from(
2652                    windows_image.identity(),
2653                )),
2654                cgroup_name: recorded_cgroup_name,
2655                #[cfg(target_os = "linux")]
2656                cgroup_placement: cgroup_placement.cloned(),
2657            },
2658        )
2659    };
2660    let roster_guard = match roster_guard {
2661        Ok(guard) => guard,
2662        Err(failure) => {
2663            return failure.with_cleanup(|source| {
2664                #[cfg(windows)]
2665                if let Some(job) = &job {
2666                    let _ = job.lock().unwrap_or_else(|p| p.into_inner()).terminate();
2667                }
2668                #[cfg(target_os = "linux")]
2669                kill_module_cgroup(cgroup_placement, &cgroup_name);
2670                #[cfg(unix)]
2671                let rejected_group = group_target.clone();
2672                kill_and_reap_rejected_child(
2673                    &mut child,
2674                    #[cfg(unix)]
2675                    rejected_group,
2676                );
2677                #[cfg(target_os = "linux")]
2678                if let Some(placement) = cgroup_placement.filter(|_| carried.is_none()) {
2679                    remove_module_cgroup(placement, &cgroup_name);
2680                }
2681                Err(SuperviseError::Spawn {
2682                    program: spec.program.clone(),
2683                    source: io::Error::other(format!(
2684                        "could not durably record module child: {source}"
2685                    )),
2686                    cgroup_path,
2687                })
2688            });
2689        }
2690    };
2691    #[cfg(unix)]
2692    if admitted.is_some() {
2693        if let Some(image) = recorded_image {
2694            if let Err(source) = roster_guard.confirm_executable(image) {
2695                kill_and_reap_rejected_child(&mut child, group_target.clone());
2696                return Err(SuperviseError::Spawn {
2697                    program: spec.program.clone(),
2698                    source,
2699                    cgroup_path,
2700                });
2701            }
2702        }
2703    }
2704    // The pre-spawn check can pass just before shutdown begins. Ownership is
2705    // published at the start of admission, even while a record write is queued.
2706    // If shutdown already saw an empty roster before that publication, this
2707    // check sees the roster closed and ends the child before starting a module.
2708    if roster.is_closed() {
2709        if carrying {
2710            #[cfg(unix)]
2711            let rejected_group = admitted
2712                .as_ref()
2713                .map(|admitted| admitted.rejection_target())
2714                .unwrap_or_else(|| group_target.clone());
2715            #[cfg(windows)]
2716            if let Some(job) = &job {
2717                let _ = job.lock().unwrap_or_else(|p| p.into_inner()).terminate();
2718            }
2719            kill_and_reap_rejected_child(
2720                &mut child,
2721                #[cfg(unix)]
2722                rejected_group,
2723            );
2724            #[cfg(all(test, unix))]
2725            let _ =
2726                roster.admission_event_for_test(&spec.module_id, "after_rejected_child", Some(pid));
2727            drop(roster_guard);
2728            return Err(SuperviseError::Spawn {
2729                program: spec.program.clone(),
2730                source: io::Error::other(
2731                    "the daemon began shutting down during carried admission; ended the container",
2732                ),
2733                cgroup_path,
2734            });
2735        }
2736        // This child was never admitted, so there is no module protocol shutdown to wait for.
2737        #[cfg(target_os = "linux")]
2738        kill_module_cgroup(cgroup_placement, &cgroup_name);
2739        if let Err(error) = child.start_kill() {
2740            debug!(module_id = %spec.module_id, pid, %error, "kill of a process spawned during daemon shutdown failed; it may already have exited");
2741        }
2742        #[cfg(target_os = "linux")]
2743        if let Some(placement) = cgroup_placement.filter(|_| carried.is_none()) {
2744            // This spawn was never admitted, so shutdown has no roster entry
2745            // to await. Do not detach its cleanup: the runtime could exit
2746            // before that task reaps the rejected child and removes its group.
2747            while matches!(child.try_wait(), Ok(None)) {
2748                std::thread::yield_now();
2749            }
2750            if matches!(
2751                subc_cgroup::kill_module(Some(placement), &cgroup_name),
2752                subc_cgroup::KillOutcome::Killed
2753            ) {
2754                if let Ok(path) = placement.module_path(&cgroup_name) {
2755                    while std::fs::read_to_string(path.join("cgroup.events"))
2756                        .ok()
2757                        .is_some_and(|events| events.lines().any(|line| line == "populated 1"))
2758                    {
2759                        std::thread::yield_now();
2760                    }
2761                }
2762            }
2763            remove_module_cgroup(placement, &cgroup_name);
2764        }
2765        drop(roster_guard);
2766        return Err(SuperviseError::Spawn {
2767            program: spec.program.clone(),
2768            source: io::Error::other(
2769                "the daemon began shutting down while this process was starting; ended it",
2770            ),
2771            cgroup_path,
2772        });
2773    }
2774
2775    let pumps = crate::child_output::start(
2776        &mut child,
2777        output_sink,
2778        ring,
2779        &spec.module_id,
2780        #[cfg(unix)]
2781        plain_group.is_some(),
2782    );
2783
2784    let exec = Arc::new(crate::activity::ExecOutcome::new());
2785    #[cfg(target_os = "macos")]
2786    let pending_exec = privacy_exec.is_some();
2787    #[cfg(not(target_os = "macos"))]
2788    let pending_exec = false;
2789    if !pending_exec {
2790        exec.finish(crate::activity::ExecState::CommittedExec);
2791    }
2792    #[cfg(windows)]
2793    let subtree_target = job
2794        .as_ref()
2795        .map(|job| crate::subtree_resources::Target::Job(Arc::downgrade(job)))
2796        .unwrap_or(crate::subtree_resources::Target::Unavailable("no_job"));
2797    #[cfg(target_os = "linux")]
2798    let subtree_target = cgroup_path
2799        .map(crate::subtree_resources::Target::Cgroup)
2800        .unwrap_or(crate::subtree_resources::Target::Unavailable("no_cgroup"));
2801    #[cfg(not(any(target_os = "linux", windows)))]
2802    let subtree_target = crate::subtree_resources::Target::Unavailable("unsupported_platform");
2803    let mut supervised = SupervisedChild {
2804        registration_spawn,
2805        #[cfg(any(unix, windows))]
2806        registration_channel,
2807        live_program_binding: None,
2808        registered_config_connection: None,
2809        admission_base,
2810        registration_declaration,
2811        _program_binding: binding_publication,
2812        subtree_target,
2813        child: containment::ProcessChild::plain(child, pid),
2814        exec: crate::activity::ExecOwner(exec),
2815        #[cfg(windows)]
2816        nonce_delivery: None,
2817        protocol: spec.protocol,
2818        #[cfg(target_os = "linux")]
2819        module_id: cgroup_name,
2820        #[cfg(target_os = "linux")]
2821        cgroup_placement: cgroup_placement.cloned(),
2822        #[cfg(target_os = "linux")]
2823        unresolved_cgroup: None,
2824        #[cfg(windows)]
2825        job,
2826        stdout_pump: pumps.stdout,
2827        stderr_pump: pumps.stderr,
2828        #[cfg(unix)]
2829        capture_stop: pumps.stop,
2830        #[cfg(unix)]
2831        late_output_lost: false,
2832        stderr_ring: Arc::clone(ring),
2833        spawned_at,
2834        config_delivery,
2835        registration_deadline: None,
2836        registration_watch: None,
2837        spawned_at_ms,
2838        spawned_from,
2839        launch_spec_digest: LaunchSpecDigest::from_spec(spec),
2840        spawned_file_identity,
2841        process_start_time,
2842        process_identity,
2843        pid,
2844        roster_guard: Some(roster_guard),
2845        #[cfg(target_os = "macos")]
2846        privacy_exec,
2847        #[cfg(target_os = "macos")]
2848        report_ready: Arc::new(OnceLock::new()),
2849        spawn_failure: None,
2850        admission_kill_sent: false,
2851    };
2852    #[cfg(unix)]
2853    {
2854        supervised.child.plain_group = plain_group;
2855    }
2856    if let Err(error) = containment::adopt(&mut supervised, spec, roster) {
2857        supervised.child.reject(
2858            #[cfg(unix)]
2859            group_target,
2860        );
2861        #[cfg(all(test, unix))]
2862        let _ = roster.admission_event_for_test(&spec.module_id, "after_rejected_child", Some(pid));
2863        return Err(error);
2864    }
2865    if let (Some(launch), Some(owner), Some(base)) = (
2866        program_launch,
2867        config_owner,
2868        supervised.admission_base.clone(),
2869    ) {
2870        supervised.live_program_binding =
2871            content_binding::LiveProgramBinding::new(launch, &supervised, owner, base);
2872        if let (Some(publication), Some(live)) = (
2873            &supervised._program_binding,
2874            &supervised.live_program_binding,
2875        ) {
2876            publication.attach(live);
2877        }
2878    }
2879    #[cfg(unix)]
2880    if let Some(admitted) = admitted.take() {
2881        admitted.disarm();
2882    }
2883    #[cfg(windows)]
2884    {
2885        if let Some(handoff) = nonce_handoff {
2886            // The pipe name was reserved before CreateProcessW, but service
2887            // has a bounded lifetime. Do not spend any of that window on the
2888            // durable admission work while the client cannot run.
2889            match handoff.serve(pid, REGISTRY_RELEASE_TIMEOUT) {
2890                Ok(delivery) => supervised.nonce_delivery = Some(delivery),
2891                Err(source) => {
2892                    supervised.child.reject();
2893                    update_nonce_pipe_refusal(
2894                        registration_handle.as_ref(),
2895                        spec,
2896                        role,
2897                        Some("launch_nonce_pipe_serve_failed"),
2898                    );
2899                    return Err(windows_nonce_pipe_error(spec, "start serving", source));
2900                }
2901            }
2902        }
2903        if let Err(error) = resume_suspended_child(pid, spec) {
2904            containment::note_end_reason(&roster.containment, ContainerEndReason::SpawnFailed);
2905            containment::terminate_blocking(&roster.containment);
2906            let _ = supervised.child.start_kill();
2907            return Err(error);
2908        }
2909    }
2910    if binding_ready {
2911        // An unreadable initial image is not a definite mismatch. Keep the
2912        // owned child and delivery registration until its reaped status decides
2913        // whether it crashed on its own or was stopped by admission's kill.
2914        let checked = if unavailable_initial_image {
2915            Err(crate::config_gate::GateError::new(
2916                "config_delivery_deferred",
2917                "initial process image is unavailable",
2918            ))
2919        } else {
2920            match (
2921                &supervised._program_binding,
2922                &supervised.live_program_binding,
2923            ) {
2924                (Some(binding), _) => binding.verify(),
2925                (None, Some(live)) => live.check(),
2926                _ if supervised.admission_base.is_some() => {
2927                    Err(crate::config_gate::GateError::new(
2928                        "config_delivery_deferred",
2929                        "live program witness is unavailable",
2930                    ))
2931                }
2932                _ => Ok(()),
2933            }
2934        };
2935        #[cfg(all(test, target_os = "linux"))]
2936        let checked = if roster.admission_event_for_test(
2937            &spec.module_id,
2938            "after_content_witness_check",
2939            Some(pid),
2940        ) {
2941            checked
2942        } else {
2943            Err(crate::config_gate::GateError::new(
2944                "config_delivery_deferred",
2945                "current process image is unavailable",
2946            ))
2947        };
2948        if let Err(error) = checked {
2949            if let Some(binding) = &mut supervised._program_binding {
2950                binding.reject();
2951            }
2952            // Reap through the normal child-reaping path, retaining the real exit record and
2953            // its roster ownership. A refusal must also end any helpers.
2954            if error.code == "program_refused" || supervised.try_wait().ok().flatten().is_none() {
2955                supervised.spawn_failure = Some(format!("{}: {}", error.code, error.detail));
2956                #[cfg(all(test, target_os = "linux"))]
2957                assert!(roster.admission_event_for_test(
2958                    &spec.module_id,
2959                    if unavailable_initial_image {
2960                        "before_initial_image_kill"
2961                    } else {
2962                        "before_content_witness_kill"
2963                    },
2964                    Some(pid),
2965                ));
2966                let _ = supervised.start_admission_kill();
2967                #[cfg(all(test, target_os = "linux"))]
2968                if supervised.admission_kill_sent {
2969                    assert!(roster.admission_event_for_test(
2970                        &spec.module_id,
2971                        "after_admission_kill_sent",
2972                        Some(pid),
2973                    ));
2974                }
2975            }
2976        }
2977    }
2978    if let Some(registration) = delivery_registration {
2979        registration.commit();
2980    }
2981    if let Some(spawn) = &supervised.registration_spawn {
2982        if let Some(record) = supervised
2983            .roster_guard
2984            .as_ref()
2985            .and_then(crate::child_roster::RosterGuard::resume_token_record)
2986        {
2987            let _ = spawn.resume_token_record.set(record);
2988        }
2989        if let Some(identity) = supervised.process_identity {
2990            let _ = spawn.identity.set(identity);
2991        }
2992        if supervised.spawn_failure.is_some() {
2993            spawn.refuse();
2994        } else if binding_ready {
2995            spawn.ready();
2996        }
2997        #[cfg(any(unix, windows))]
2998        if let (Some(handle), Some(channel)) =
2999            (registration_handle, supervised.registration_channel.take())
3000        {
3001            handle.serve_registration(channel, spawn.clone(), pid, spawned_at + register_timeout);
3002        }
3003    }
3004    Ok(supervised)
3005}
3006
3007#[cfg(target_os = "linux")]
3008pub(crate) fn kill_module_cgroup(placement: Option<&subc_cgroup::Placement>, module_id: &str) {
3009    use subc_cgroup::KillOutcome;
3010    match subc_cgroup::kill_module(placement, module_id) {
3011        KillOutcome::Killed => {}
3012        KillOutcome::NotPlaced | KillOutcome::Unsupported => {
3013            debug!(
3014                module_id,
3015                "cgroup tree kill unavailable; using direct-child kill"
3016            );
3017        }
3018        KillOutcome::IoError { path, error } => {
3019            warn!(module_id, path = %path.display(), %error, "cgroup tree kill failed; using direct-child kill");
3020        }
3021    }
3022}
3023
3024/// Assign a freshly spawned Windows child without ever resuming on failure.
3025///
3026/// Steps 2 and 3 of the suspended-create contract: the job is created and the
3027/// child assigned **while it is still suspended** (step 1 is
3028/// `suspend_on_create_async` at the spawn site). The caller resumes only after
3029/// the child's roster admission is durable. Failed containment kills and reaps
3030/// the suspended child instead of running an unprotected module.
3031#[cfg(windows)]
3032fn contain_spawned_child(
3033    child: &mut Child,
3034    spec: &ModuleSpec,
3035    carried: Option<&Arc<containment::CarriedContainment>>,
3036) -> Result<Option<Arc<Mutex<subc_jobobject::JobObject>>>, SuperviseError> {
3037    let assignment = || {
3038        let job = match carried {
3039            Some(container) => container.job(),
3040            None => Arc::new(Mutex::new(subc_jobobject::JobObject::new()?)),
3041        };
3042        #[cfg(test)]
3043        spawn_record_tests::assignment_failpoint(spec)?;
3044        job.lock()
3045            .unwrap_or_else(|p| p.into_inner())
3046            .assign(child)?;
3047        Ok::<_, io::Error>(job)
3048    };
3049    match assignment() {
3050        Ok(job) => Ok(Some(job)),
3051        Err(source) => {
3052            kill_and_reap_rejected_child(child);
3053            Err(SuperviseError::Spawn {
3054                program: spec.program.clone(),
3055                source: io::Error::other(format!(
3056                    "Windows module job containment failed: {source}"
3057                )),
3058                cgroup_path: None,
3059            })
3060        }
3061    }
3062}
3063
3064/// Rejection is synchronous: do not return a spawn error while the child can
3065/// still run, or rely on kill-on-drop to reap it at some later runtime turn.
3066pub(super) fn kill_and_reap_rejected_child(
3067    child: &mut Child,
3068    #[cfg(unix)] group: containment::GroupTarget,
3069) {
3070    #[cfg(unix)]
3071    group.signal_rejected(child);
3072    let _ = child.start_kill();
3073    while matches!(child.try_wait(), Ok(None)) {
3074        std::thread::yield_now();
3075    }
3076}
3077
3078/// Resume a suspended child, killing it if it cannot be started.
3079///
3080/// A suspended process holds a pid and does nothing, so there is no useful
3081/// state to return: the caller gets an error and the spawn fails.
3082#[cfg(windows)]
3083fn resume_suspended_child(pid: u32, spec: &ModuleSpec) -> Result<(), SuperviseError> {
3084    if let Err(source) = subc_jobobject::resume_main_thread(pid) {
3085        // Kill it here rather than leaving a suspended process for the caller
3086        // to notice; `kill_on_drop` would eventually do this, but the module
3087        // would have been reported as running in between.
3088        let _ = subc_os::child_spawn::status(
3089            std::process::Command::new("taskkill.exe")
3090                .args(["/PID", &pid.to_string(), "/T", "/F"])
3091                .stdin(Stdio::null())
3092                .stdout(Stdio::null())
3093                .stderr(Stdio::null()),
3094        );
3095        return Err(SuperviseError::Spawn {
3096            program: spec.program.clone(),
3097            source,
3098            cgroup_path: None,
3099        });
3100    }
3101    Ok(())
3102}
3103
3104#[cfg(target_os = "linux")]
3105pub(super) fn remove_module_cgroup(placement: &subc_cgroup::Placement, module_id: &str) {
3106    match placement.remove_module(module_id) {
3107        Ok(()) => debug!(module_id, "removed module cgroup after process exit"),
3108        Err(error) => warn!(
3109            module_id,
3110            error = %error,
3111            "could not remove module cgroup after process exit; continuing teardown"
3112        ),
3113    }
3114}
3115
3116#[cfg(target_os = "linux")]
3117pub(super) fn apply_cgroup_placement(
3118    command: &mut Command,
3119    spec: &ModuleSpec,
3120    path: &std::path::Path,
3121) -> Result<(), SuperviseError> {
3122    subc_cgroup::apply(command, path).map_err(|source| SuperviseError::Cgroup {
3123        module_id: spec.module_id.clone(),
3124        source,
3125    })
3126}
3127
3128fn capture_retention(spec: &ModuleSpec) -> Retention {
3129    let defaults = Retention::default();
3130    let value = |name: &str| {
3131        spec.env
3132            .iter()
3133            .rev()
3134            .find_map(|(key, value)| (key == name).then_some(value.as_str()))
3135    };
3136    Retention {
3137        max_file_mb: value(CAPTURE_MAX_FILE_MB_ENV)
3138            .and_then(|value| value.parse().ok())
3139            .unwrap_or(defaults.max_file_mb),
3140        keep: value(CAPTURE_KEEP_ENV)
3141            .and_then(|value| value.parse().ok())
3142            .unwrap_or(defaults.keep),
3143        max_age_days: value(CAPTURE_MAX_AGE_DAYS_ENV)
3144            .and_then(|value| value.parse().ok())
3145            .unwrap_or(defaults.max_age_days),
3146    }
3147}
3148
3149pub(super) fn capture_sink(
3150    spec: &ModuleSpec,
3151    logs_dir: Option<&std::path::Path>,
3152) -> ChildOutputSink {
3153    let Some(logs_dir) = logs_dir else {
3154        return ChildOutputSink::Stderr;
3155    };
3156    let path = logs_dir.join(format!("{}.stderr.log", spec.module_id));
3157    match ChildOutputSink::open(&path, capture_retention(spec)) {
3158        Ok(sink) => sink,
3159        Err(error) => {
3160            warn!(module_id = %spec.module_id, path = %path.display(), %error,
3161                "could not open child output capture file; forwarding to stderr");
3162            ChildOutputSink::Stderr
3163        }
3164    }
3165}
3166
3167/// A fresh 256-bit CSPRNG launch nonce, lowercase hex. Used to bind a reserved
3168/// module's registration to the exact process the supervisor spawned.
3169fn generate_launch_nonce() -> Result<String, SuperviseError> {
3170    let mut bytes = [0u8; 32];
3171    getrandom::getrandom(&mut bytes).map_err(|source| SuperviseError::LaunchNonce {
3172        reason: source.to_string(),
3173    })?;
3174    let mut hex = String::with_capacity(64);
3175    for b in bytes {
3176        use std::fmt::Write;
3177        let _ = write!(hex, "{b:02x}");
3178    }
3179    Ok(hex)
3180}
3181
3182/// The kernel's image after an acknowledged exec, shared by ordinary launches
3183/// and privacy trampolines. PATH and shebang interpretation are kernel facts,
3184/// not identities inferred from a configured pathname.
3185#[cfg(not(windows))]
3186pub(super) fn observe_spawned_image(pid: u32) -> Option<subc_os::Observation> {
3187    let process = subc_os::Process::open(pid).ok().flatten()?;
3188    #[cfg(target_os = "linux")]
3189    return sample_after_linux_exec(
3190        || {
3191            let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
3192            let committed = linux_exec_committed(&stat);
3193            #[cfg(test)]
3194            spawn_image_tests::report_exec_state(committed);
3195            committed
3196        },
3197        || process.observe(),
3198    );
3199    #[cfg(not(target_os = "linux"))]
3200    process.observe()
3201}
3202
3203/// glibc's posix_spawn parent can wake in exec_mmap before the child's new mm
3204/// is installed. PF_FORKNOEXEC is cleared later in begin_new_exec, after that
3205/// installation. Until it clears, /proc/pid/exe can still name the daemon.
3206#[cfg(target_os = "linux")]
3207pub(super) fn linux_exec_committed(stat: &str) -> Option<bool> {
3208    const PF_FORKNOEXEC: u64 = 0x40;
3209    let flags = stat.rsplit_once(')')?.1.split_whitespace().nth(6)?;
3210    Some(flags.parse::<u64>().ok()? & PF_FORKNOEXEC == 0)
3211}
3212
3213#[cfg(target_os = "linux")]
3214pub(super) fn sample_after_linux_exec(
3215    mut exec_committed: impl FnMut() -> Option<bool>,
3216    observe: impl FnOnce() -> Option<subc_os::Observation>,
3217) -> Option<subc_os::Observation> {
3218    let deadline = std::time::Instant::now() + Duration::from_secs(1);
3219    while !exec_committed()? {
3220        // A failed or indefinitely stalled exec must not publish the inherited
3221        // image as authority to signal a future orphan. Missing identity keeps
3222        // the existing conservative orphan-sweep behavior.
3223        if std::time::Instant::now() >= deadline {
3224            return None;
3225        }
3226        std::thread::sleep(Duration::from_micros(50));
3227    }
3228    observe()
3229}
3230
3231/// Resolve once and spawn that exact path, so PATH lookup cannot choose a
3232/// different executable after the no-delete capture was taken.
3233#[cfg(windows)]
3234pub(crate) fn windows_spawn_capture(spec: &ModuleSpec) -> io::Result<subc_os::ExecutableCapture> {
3235    if let Err(error) = require_program_search_path(spec) {
3236        return Err(match error {
3237            SuperviseError::Spawn { source, .. } => source,
3238            error => io::Error::other(error),
3239        });
3240    }
3241    let mut program = spec.program.clone();
3242    if program.is_absolute() || program.components().count() > 1 {
3243        // An explicit path can name a PE image with no extension. Try that
3244        // exact file first, as Command does, before falling back to .exe.
3245        match subc_os::ExecutableCapture::open(&program) {
3246            Ok(capture) => return Ok(capture),
3247            Err(error)
3248                if error.kind() == io::ErrorKind::NotFound && program.extension().is_none() => {}
3249            Err(error) => return Err(error),
3250        }
3251        program.set_extension("exe");
3252        return subc_os::ExecutableCapture::open(&program);
3253    }
3254    if program.extension().is_none() {
3255        program.set_extension("exe");
3256    }
3257    let custom_path = spec
3258        .env
3259        .iter()
3260        .rev()
3261        .find(|(key, _)| key.eq_ignore_ascii_case("PATH"));
3262    let mut directories = Vec::new();
3263    // These are Windows' default executable search locations. A configured
3264    // PATH still overrides the inherited PATH, not the system directories.
3265    if let Some(parent) = std::env::current_exe()?.parent() {
3266        directories.push(parent.to_path_buf());
3267    }
3268    directories.push(std::env::current_dir()?);
3269    if let Some(windows) = std::env::var_os("SystemRoot") {
3270        let windows = PathBuf::from(windows);
3271        directories.push(windows.join("System32"));
3272        directories.push(windows.clone());
3273    }
3274    let path = custom_path
3275        .map(|(_, value)| std::ffi::OsString::from(value))
3276        .or_else(|| std::env::var_os("PATH"));
3277    if let Some(path) = path {
3278        directories.extend(std::env::split_paths(&path));
3279    }
3280    for directory in directories {
3281        match subc_os::ExecutableCapture::open(&directory.join(&program)) {
3282            Ok(capture) => return Ok(capture),
3283            Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
3284            Err(error) => return Err(error),
3285        }
3286    }
3287    Err(io::Error::new(
3288        io::ErrorKind::NotFound,
3289        "resolved executable not found",
3290    ))
3291}
3292
3293#[cfg(test)]
3294pub(super) fn spawn_and_mark_running(
3295    spec: &ModuleSpec,
3296    runtime: &SupervisorRuntimeConfig,
3297    snapshot: &SharedSnapshot,
3298) -> Result<SupervisedChild, SuperviseError> {
3299    let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
3300    let registration_watch = watch_registration(&runtime.registry, spec);
3301    #[cfg(unix)]
3302    let joining_group = containment::current(&runtime.child_roster.containment)
3303        .is_some_and(|container| container.group().is_some());
3304    let spawn = || {
3305        spawn_child(
3306            spec,
3307            runtime.connection_file_path.as_deref(),
3308            runtime.supervisor_handle.as_ref(),
3309            &runtime.stderr_ring,
3310            runtime.capture_logs_dir.as_deref(),
3311            &runtime.child_roster,
3312            runtime.spawn_delivery(),
3313            #[cfg(target_os = "linux")]
3314            runtime.cgroup_placement.as_ref(),
3315            runtime.register_timeout,
3316        )
3317    };
3318    let result = spawn();
3319    #[cfg(unix)]
3320    let result = match result {
3321        Err(error)
3322            if joining_group
3323                && !is_launch_deferral(&error)
3324                && !runtime.child_roster.is_closed()
3325                && lock_snapshot(snapshot).is_ok_and(|state| state.enabled)
3326                && runtime
3327                    .child_roster
3328                    .previous_instance(&spec.module_id)
3329                    .is_none() =>
3330        {
3331            // The failed join already destroyed and verified the old container.
3332            // Try one fresh group as part of this same restart, without spending
3333            // another crash-budget entry. Cgroups and Windows jobs do not retry.
3334            warn!(module_id = %spec.module_id, %error, "carried process-group spawn failed; trying one fresh container");
3335            spawn()
3336        }
3337        other => other,
3338    };
3339    let child = result?;
3340    let mut child = child;
3341    arm_registration_deadline(&mut child, runtime.register_timeout, registration_watch);
3342    if let Err(error) = set_running(snapshot, &child, &spec.module_id, &runtime.spawn_events) {
3343        containment::terminate_blocking(&runtime.child_roster.containment);
3344        return Err(error);
3345    }
3346    if let Some(spawn) = activity_spawn {
3347        spawn.complete(snapshot);
3348    }
3349    Ok(child)
3350}
3351
3352pub(super) fn set_running(
3353    snapshot: &SharedSnapshot,
3354    child: &SupervisedChild,
3355    module_id: &str,
3356    spawn_events: &SpawnEventFeed,
3357) -> Result<(), SuperviseError> {
3358    let mut state = snapshot.lock().map_err(|_| SuperviseError::StatePoisoned {
3359        module_id: Some(module_id.to_string()),
3360    })?;
3361    state.spawn_generation = spawn_events.emit_spawned(
3362        module_id,
3363        child
3364            .registration_spawn
3365            .as_ref()
3366            .map(|spawn| spawn.authority.spawn_number()),
3367        child.pid,
3368        child.spawned_at_ms,
3369    );
3370    if std::mem::take(&mut state.coalesced_restart_pending) {
3371        let generation = state.spawn_generation;
3372        info!(module_id, "restart already satisfied by generation {generation}; coalesced pending request completed");
3373    }
3374    state.drain_disposition_detail = None;
3375    state.spawn_failure = None;
3376    state.admission_refused = None;
3377    #[cfg(windows)]
3378    {
3379        state.nonce_pipe_refusal = None;
3380    }
3381    state.config_hold_parked = false;
3382    state.config_hold_daemon_initiated = false;
3383    state.config_hold_approval = None;
3384    state.legacy_registration_spawn =
3385        child.registration_spawn.is_some() && child.admission_base.is_none();
3386    state.registration_declaration = child.registration_declaration.clone();
3387    state.stop_reason = None;
3388    state.config_exit_failed_approval = None;
3389    state.waiting_for_previous_pid = None;
3390    state.waiting_for_previous_detail = None;
3391    // Every caller of this is a plain spawn, which always uses the primary key;
3392    // a promoted swap candidate sets the flag itself after this returns.
3393    state.in_alternate_slot = false;
3394    state.configuration_updated_since_spawn = false;
3395    state.spawned_protocol = Some(child.protocol);
3396    state.state = ModuleState::Running;
3397    state.approved_start_failure = None;
3398    state.enabled = true;
3399    state.process_alive = true;
3400    state.pid = child.id();
3401    state.subtree_target = child.subtree_target.clone();
3402    // Probe samples belong to one process. Keep module-level escalation and
3403    // late-answer history, but never charge a new child for its predecessor's misses.
3404    state.health.status = SupervisorHealthStatus::Unknown;
3405    state.last_probe_evidence = None;
3406    state.health.consecutive_failures = 0;
3407    state.health.detail = None;
3408    state.health.metrics = None;
3409    state.health.last_probe_ms = None;
3410    state.failed_retry.healthy_since = None;
3411    state.failed_retry.failed_at = None;
3412    state.failed_retry.running_since = Some(child.spawned_at);
3413    #[cfg(windows)]
3414    {
3415        state.pipe_consumed = child
3416            .nonce_delivery
3417            .as_ref()
3418            .map(|delivery| delivery.consumed());
3419    }
3420    #[cfg(target_os = "macos")]
3421    {
3422        state.report_ready = Some(Arc::clone(&child.report_ready));
3423    }
3424    state.spawned_at_ms = Some(child.spawned_at_ms);
3425    state.exec_outcome = Some(Arc::clone(&child.exec.0));
3426    state.spawned_from = Some(child.spawned_from.clone());
3427    state.launch_spec_digest = Some(child.launch_spec_digest.clone());
3428    state.spawned_file_identity = child.spawned_file_identity.clone();
3429    state.process_start_time = child.process_start_time;
3430    Ok(())
3431}