Skip to main content

subc_daemon/supervise/
spawn.rs

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