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(test)]
772            self.test_after_first_spawn.run(&spec.module_id);
773            match spawned {
774                Ok(mut child) => {
775                    arm_registration_deadline(
776                        &mut child,
777                        runtime.register_timeout,
778                        registration_watch,
779                    );
780                    self.mark_first_process_running(&spec, &runtime, snapshot, &mut child)?;
781                    if let Some(spawn) = activity_spawn {
782                        spawn.complete(snapshot);
783                    }
784                    Some(child)
785                }
786                Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
787                    defer_config_spawn(&spec, &runtime, snapshot, RespawnKind::Spawn, &failure)?;
788                    None
789                }
790                Err(mut err) => {
791                    if matches!(err, SuperviseError::ConfigHeld { .. }) {
792                        match hold_config_spawn(&spec, &runtime, snapshot, &failure) {
793                            Ok(()) => {
794                                self.start_monitor(spec, runtime, &module, None, commands);
795                                return Ok(module);
796                            }
797                            Err(parking_error) => err = parking_error,
798                        }
799                    }
800                    if runtime.health.critical {
801                        error!(module_id = %spec.module_id, program = %spec.program.display(), error = %err,
802                            "critical configured module failed to spawn; marking failed and alerting");
803                    } else {
804                        error!(module_id = %spec.module_id, program = %spec.program.display(), error = %err,
805                            "configured module failed to spawn; marking failed and continuing");
806                    }
807                    fail_snapshot(snapshot, Some(&spec.module_id), None, &failure);
808                    if let Some(generation) = approved_generation {
809                        let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
810                            state.approved_start_failure = Some((generation, err.to_string()));
811                        });
812                        startup_error = Some(err);
813                    }
814                    None
815                }
816            }
817        } else {
818            None
819        };
820        self.start_monitor(spec, runtime, &module, child, commands);
821        // Applying an operator-approved configuration must report a spawn error
822        // without removing the failed module or its monitor. Bootstrap instead
823        // tolerates failed starts so other configured modules can still run.
824        startup_error.map_or(Ok(module), Err)
825    }
826
827    pub(super) fn runtime_config(&self) -> SupervisorRuntimeConfig {
828        let effective_drain_timeout = Arc::new(Mutex::new(self.drain_timeout));
829        SupervisorRuntimeConfig {
830            registry: self.registry.clone(),
831            config_delivery: self.config_delivery.clone(),
832            recovery_is_daemon: true,
833            start_requester: None,
834            pending_activity_restart: false,
835            provenance_probe: self.provenance_probe.clone(),
836            scheduled_respawn: Arc::default(),
837            deferred_reload_reply: Arc::default(),
838            restart_policy: self.restart_policy,
839            register_timeout: DEFAULT_REGISTER_TIMEOUT,
840            drain_timeout: self.drain_timeout,
841            // Shared with this module's roster copy: daemon shutdown waits on
842            // each child for the module's own drain budget, as resolved now.
843            child_roster: self
844                .child_roster
845                .for_module(Arc::clone(&effective_drain_timeout)),
846            effective_drain_timeout,
847            default_drain_timeout: self.drain_timeout,
848            health: self.health.clone(),
849            host_health: self.host_health.clone(),
850            connection_file_path: self.connection_file_path.clone(),
851            capture_logs_dir: self.capture_logs_dir.clone(),
852            forwarding: self.forwarding.clone(),
853            supervisor_handle: self.supervisor_handle.clone(),
854            stderr_ring: Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default()))),
855            terminal_ring: Arc::new(Mutex::new(
856                TerminalRing::new(
857                    TerminalRingConfig::default(),
858                    self.daemon_start_clock.started_at_ms(),
859                )
860                .with_start_clock(self.daemon_start_clock)
861                .with_journal(self.terminal_journal.clone())
862                .with_daemon_shutdown(self.child_roster.shutdown_flag()),
863            )),
864            spawn_events: self.spawn_events.clone(),
865            #[cfg(target_os = "linux")]
866            cgroup_placement: self.cgroup_placement.clone(),
867            #[cfg(test)]
868            test_seed_stale_facts_before_enable_spawn: false,
869            #[cfg(test)]
870            test_reload_exit_record_gate: None,
871        }
872    }
873
874    pub(super) fn supervised_module(
875        &self,
876        spec: ModuleSpec,
877        runtime: SupervisorRuntimeConfig,
878        snapshot: SharedSnapshot,
879        child: Option<SupervisedChild>,
880    ) -> SupervisedModule {
881        let (module, commands) = self.register_module(&spec, &runtime, snapshot);
882        self.start_monitor(spec, runtime, &module, child, commands);
883        module
884    }
885
886    pub(super) fn register_module(
887        &self,
888        spec: &ModuleSpec,
889        runtime: &SupervisorRuntimeConfig,
890        snapshot: SharedSnapshot,
891    ) -> (SupervisedModule, mpsc::Receiver<SupervisorCommand>) {
892        runtime.host_health.track(spec, &snapshot);
893        let configuration = Arc::new(Mutex::new(SupervisedConfiguration {
894            spec: spec.clone(),
895            enabled: snapshot.lock().unwrap_or_else(|p| p.into_inner()).enabled,
896            health: runtime.health.clone(),
897            register_timeout: runtime.register_timeout,
898            restart_policy: runtime.restart_policy,
899        }));
900        let stderr_ring = Arc::clone(&runtime.stderr_ring);
901        let terminal_ring = Arc::clone(&runtime.terminal_ring);
902        let effective_drain_timeout = Arc::clone(&runtime.effective_drain_timeout);
903        let (tx, rx) = mpsc::channel(4);
904        let module_id = spec.module_id.clone();
905        let module = SupervisedModule {
906            inner: Arc::new(SupervisedModuleInner {
907                module_id: module_id.clone(),
908                registry: Arc::clone(&self.registry),
909                snapshot,
910                configuration,
911                stderr_ring,
912                terminal_ring,
913                commands: tx,
914                monitor: Mutex::new(None),
915                effective_drain_timeout,
916                provenance_probe: self.provenance_probe.clone(),
917                retained: runtime.child_roster.retained_view(),
918            }),
919        };
920        // Identity gates and the configured mark must precede the roster entry,
921        // so a client never sees a module without its admission policy.
922        if let Some(supervisor_handle) = &self.supervisor_handle {
923            supervisor_handle.insert(module.clone());
924        }
925        (module, rx)
926    }
927
928    pub(super) fn start_monitor(
929        &self,
930        spec: ModuleSpec,
931        runtime: SupervisorRuntimeConfig,
932        module: &SupervisedModule,
933        child: Option<SupervisedChild>,
934        commands: mpsc::Receiver<SupervisorCommand>,
935    ) {
936        let monitor = tokio::spawn(supervise_loop(
937            spec,
938            runtime,
939            Arc::clone(&self.registry),
940            Arc::clone(&self.process_liveness),
941            Arc::clone(&module.inner.snapshot),
942            child,
943            commands,
944        ));
945        *module
946            .inner
947            .monitor
948            .lock()
949            .unwrap_or_else(|p| p.into_inner()) = Some(monitor);
950    }
951}
952
953pub(crate) fn validate_spec(spec: &ModuleSpec) -> Result<(), SuperviseError> {
954    if spec.carry_containment && spec.overlap == ModuleOverlap::Safe {
955        return Err(SuperviseError::InvalidSpec {
956            reason: "carry_containment cannot be combined with overlap: safe".to_owned(),
957        });
958    }
959    if spec.module_id.trim().is_empty() {
960        return Err(SuperviseError::InvalidSpec {
961            reason: "module_id must not be empty".to_string(),
962        });
963    }
964
965    Ok(())
966}
967
968/// The child's environment plan: inherit the parent's, drop ambient `CK_LOG`,
969/// then apply the module's configured entries minus daemon-private capture keys.
970///
971/// Separated from `spawn_child` only so it can be asserted without spawning a
972/// process — a duplicate of this logic in a test would pass while the real one
973/// drifted, which is the defect class this function exists to avoid.
974/// The subc-wire half of a spawn: `--subc <connection file>` and the launch
975/// nonce. A `protocol: "none"` module gets neither, because it cannot use
976/// either and the argument would stop a stock binary from starting at all.
977/// `SUBC_MODULE_ID` is set on every path since an unread variable is inert.
978///
979/// The plain-spawn form, kept for the tests that assert its plan; spawns go
980/// through [`apply_wire_spawn_args_for_admission`].
981#[cfg(test)]
982pub(super) fn apply_wire_spawn_args(
983    command: &mut Command,
984    spec: &ModuleSpec,
985    connection_file_path: Option<&std::path::Path>,
986    handle: Option<&SupervisorHandle>,
987) -> Result<Option<NonceHandoff>, SuperviseError> {
988    apply_wire_spawn_args_for_role(
989        command,
990        spec,
991        connection_file_path,
992        handle,
993        SpawnRole::Plain,
994    )
995}
996
997/// The read end of a spawn's launch-nonce pipe, prepared by
998/// [`apply_wire_spawn_args_for_admission`] and installed as the child's descriptor 3
999/// by the last pre-exec step, just before `spawn()`. Windows prepares a named
1000/// server before spawn and authenticates its client after the child exists.
1001#[cfg(unix)]
1002type NonceHandoff = subc_os::LaunchNonceHandoff;
1003#[cfg(windows)]
1004type NonceHandoff = subc_os::LaunchNoncePipeHandoff;
1005#[cfg(not(any(unix, windows)))]
1006type NonceHandoff = std::convert::Infallible;
1007
1008/// Create the launch nonce that a new module process must present when it
1009/// registers or opens a consumer connection, including a replacement process
1010/// started alongside a still-serving module.
1011///
1012/// A plain spawn replaces the module's recorded nonce. A swap candidate records
1013/// a separate candidate token so the still-serving incumbent and its consumers
1014/// keep their nonce. Both records are installed before the process exists, so
1015/// the child's initial HELLO registration cannot arrive ahead of its nonce.
1016///
1017/// On Unix the nonce is delivered only through a pipe. It is written into
1018/// a pipe whose read end the child gets as descriptor 3, named by
1019/// `SUBC_LAUNCH_NONCE_FD=3:<pipe inode>`: unlike the environment, another
1020/// process of the same user cannot read it with `ps eww`. That handoff is
1021/// returned rather than installed here. The combined descriptor placement runs
1022/// after the cgroup callback and placement barrier, so replacing slots 3-5
1023/// cannot close a descriptor either callback still needs.
1024/// Windows keeps SUBC_LAUNCH_NONCE as well until every module reads the named pipe.
1025#[cfg(test)]
1026fn apply_wire_spawn_args_for_role(
1027    command: &mut Command,
1028    spec: &ModuleSpec,
1029    connection_file_path: Option<&std::path::Path>,
1030    handle: Option<&SupervisorHandle>,
1031    role: SpawnRole,
1032) -> Result<Option<NonceHandoff>, SuperviseError> {
1033    apply_wire_spawn_args_for_admission(command, spec, connection_file_path, handle, role, None)
1034}
1035
1036pub(super) fn apply_wire_spawn_args_for_admission(
1037    command: &mut Command,
1038    spec: &ModuleSpec,
1039    connection_file_path: Option<&std::path::Path>,
1040    handle: Option<&SupervisorHandle>,
1041    role: SpawnRole,
1042    admission: Option<&crate::config_gate::runtime::SpawnAdmission>,
1043) -> Result<Option<NonceHandoff>, SuperviseError> {
1044    command.env(SUBC_MODULE_ID_ENV, &spec.module_id);
1045    // SUBC_LAUNCH_NONCE_FD is removed for every child, `protocol: "none"`
1046    // included: a daemon started from a module's process tree inherits it,
1047    // and passing it on would point the child at a descriptor it does not
1048    // have.
1049    command.env_remove(subc_os::LAUNCH_NONCE_FD_ENV);
1050    #[cfg(windows)]
1051    {
1052        command.env_remove(subc_os::LAUNCH_NONCE_PIPE_ENV);
1053        command.env_remove(subc_os::LAUNCH_NONCE_PIPE_FALLBACK_ENV);
1054    }
1055    // Remove inherited or configured copies too: withholding must mean absent.
1056    command.env_remove(SUBC_LAUNCH_NONCE_ENV);
1057    command.env_remove(subc_os::registration_channel::REGISTRATION_FD_ENV);
1058    command.env_remove(subc_os::registration_channel::REGISTRATION_PIPE_ENV);
1059    command.env_remove(subc_os::registration_channel::DAEMON_PID_ENV);
1060    if role == SpawnRole::Plain {
1061        if let Some(handle) = handle {
1062            #[cfg(all(test, unix))]
1063            {
1064                let pause = {
1065                    let mut slot = handle.plain_identity_policy_pause.lock().unwrap();
1066                    if slot
1067                        .as_ref()
1068                        .is_some_and(|(module, _)| module == &spec.module_id)
1069                    {
1070                        slot.take().map(|(_, pause)| pause)
1071                    } else {
1072                        None
1073                    }
1074                };
1075                if let Some(pause) = pause {
1076                    pause.reached.send(()).unwrap();
1077                    pause.release.recv().unwrap();
1078                }
1079            }
1080            // A rescan preserves the running child's nonce and reservation.
1081            // Replacement spawn preparation applies the new protocol now,
1082            // before protocol:none can return without minting a nonce.
1083            handle.apply_identity_policy(spec, spec.protocol);
1084        }
1085    }
1086    if spec.protocol == ModuleProtocol::None {
1087        return Ok(None);
1088    }
1089    if let Some(connection_file_path) = connection_file_path {
1090        command.arg(SUBC_ARG).arg(connection_file_path);
1091    }
1092
1093    if admission.is_some_and(|admission| admission.launch.is_some()) {
1094        if let Some(handle) = handle {
1095            match role {
1096                SpawnRole::Plain => {
1097                    handle
1098                        .spawn_nonces
1099                        .lock()
1100                        .unwrap_or_else(|p| p.into_inner())
1101                        .remove(&spec.module_id);
1102                    if spec.reserved {
1103                        handle
1104                            .reserved_nonces
1105                            .lock()
1106                            .unwrap_or_else(|p| p.into_inner())
1107                            .insert(spec.module_id.clone(), None);
1108                    }
1109                }
1110                // Swaps still need their lifecycle record, but the empty value
1111                // is not a bearer token and is never accepted by nonce HELLO.
1112                SpawnRole::SwapCandidate => handle.open_swap(&spec.module_id, String::new()),
1113            }
1114        }
1115        return Ok(None);
1116    }
1117    // Every subc-wire spawn receives a fresh one-time launch nonce for consumer
1118    // route.open attestation. Reserved modules additionally use the same nonce
1119    // for HELLO id-squatting protection. A respawn rotates both records.
1120    let nonce = generate_launch_nonce()?;
1121    if let Some(handle) = handle {
1122        match role {
1123            SpawnRole::Plain => {
1124                handle.set_spawn_nonce(&spec.module_id, nonce.clone());
1125                if spec.reserved {
1126                    handle.set_reserved_nonce(&spec.module_id, nonce.clone());
1127                }
1128            }
1129            SpawnRole::SwapCandidate => handle.open_swap(&spec.module_id, nonce.clone()),
1130        }
1131    }
1132    #[cfg(unix)]
1133    let handoff = {
1134        let handoff =
1135            subc_os::LaunchNonceHandoff::new(&nonce).map_err(|source| SuperviseError::Spawn {
1136                program: spec.program.clone(),
1137                source,
1138                cgroup_path: None,
1139            })?;
1140        command.env(subc_os::LAUNCH_NONCE_FD_ENV, handoff.fd_env_value());
1141        Some(handoff)
1142    };
1143    #[cfg(windows)]
1144    let handoff = prepare_windows_nonce_pipe(command, spec, &nonce);
1145    #[cfg(not(any(unix, windows)))]
1146    let handoff = None;
1147    // Older modules still read SUBC_LAUNCH_NONCE to register. Keep that copy
1148    // until the daemon's per-spawn delivery records show that every running
1149    // Windows module has read its secret from the named pipe.
1150    #[cfg(not(unix))]
1151    command.env(SUBC_LAUNCH_NONCE_ENV, nonce);
1152    Ok(handoff)
1153}
1154
1155pub(crate) fn apply_child_env(command: &mut Command, spec: &ModuleSpec) {
1156    command.env_remove(CK_LOG_ENV);
1157    // The spawn role is the supervisor's to set, and only on a swap candidate
1158    // (see `apply_spawn_role`). Removing it here, rather than just not setting
1159    // it, is what makes it absent on a plain spawn: the daemon's own
1160    // environment could carry it, and so could a spec built outside daemon
1161    // config (config refuses it as an `env` key). A module reading it on a
1162    // plain restart would pick the long swap budget and leave callers waiting.
1163    command.env_remove(SUBC_SPAWN_ROLE_ENV);
1164    for (key, value) in &spec.env {
1165        // cortexkit-log currently exposes retention only as a Rust struct, not
1166        // environment names. These values are daemon-private sink metadata and
1167        // must never become a public child-process contract by being inherited.
1168        if matches!(
1169            key.as_str(),
1170            CAPTURE_MAX_FILE_MB_ENV | CAPTURE_KEEP_ENV | CAPTURE_MAX_AGE_DAYS_ENV
1171        ) || key == SUBC_SPAWN_ROLE_ENV
1172        {
1173            continue;
1174        }
1175        command.env(key, value);
1176    }
1177}
1178
1179#[cfg(windows)]
1180pub(super) fn prepare_windows_registration_pipe(
1181    command: &mut Command,
1182    spec: &ModuleSpec,
1183) -> Result<Option<SpawnRegistrationChannel>, SuperviseError> {
1184    if spec.protocol == ModuleProtocol::None {
1185        return Ok(None);
1186    }
1187    let pipe = subc_os::registration_channel::RegistrationPipe::new().map_err(|source| {
1188        SuperviseError::Spawn {
1189            program: spec.program.clone(),
1190            source,
1191            cgroup_path: None,
1192        }
1193    })?;
1194    command
1195        .env(
1196            subc_os::registration_channel::REGISTRATION_PIPE_ENV,
1197            pipe.name(),
1198        )
1199        .env(
1200            subc_os::registration_channel::DAEMON_PID_ENV,
1201            std::process::id().to_string(),
1202        );
1203    Ok(Some(pipe))
1204}
1205
1206#[cfg(windows)]
1207fn prepare_windows_nonce_pipe(
1208    command: &mut Command,
1209    spec: &ModuleSpec,
1210    nonce: &str,
1211) -> Option<NonceHandoff> {
1212    match subc_os::LaunchNoncePipeHandoff::new(nonce) {
1213        Ok(handoff) => {
1214            command.env(subc_os::LAUNCH_NONCE_PIPE_ENV, handoff.name());
1215            // Let a failed pipe read use SUBC_LAUNCH_NONCE so the process can
1216            // still register until every module reads the pipe. A reader without
1217            // this variable set to env returns the pipe error instead of using
1218            // an inherited or configured environment copy.
1219            command.env(subc_os::LAUNCH_NONCE_PIPE_FALLBACK_ENV, "env");
1220            Some(handoff)
1221        }
1222        Err(error) => {
1223            warn!(module_id = %spec.module_id, %error, "could not prepare launch nonce pipe; retaining the environment handoff");
1224            None
1225        }
1226    }
1227}
1228
1229#[cfg(windows)]
1230fn start_windows_nonce_pipe(
1231    handoff: Option<NonceHandoff>,
1232    pid: u32,
1233    spec: &ModuleSpec,
1234) -> Option<subc_os::LaunchNoncePipeDelivery> {
1235    // Close an unread pipe after REGISTRY_RELEASE_TIMEOUT (one second), the
1236    // same maximum wait used for registration during a reload. Older modules
1237    // may register using SUBC_LAUNCH_NONCE without ever connecting to the pipe.
1238    handoff.and_then(|handoff| match handoff.serve(pid, REGISTRY_RELEASE_TIMEOUT) {
1239        Ok(delivery) => Some(delivery),
1240        Err(error) => {
1241            warn!(module_id = %spec.module_id, %error, "could not serve launch nonce pipe; retaining the environment handoff");
1242            None
1243        }
1244    })
1245}
1246
1247pub(super) fn observed_launch_nonce_source(snapshot: &SupervisorSnapshot) -> Option<String> {
1248    #[cfg(windows)]
1249    if snapshot.process_alive && snapshot.spawned_protocol == Some(ModuleProtocol::Subc) {
1250        return Some(
1251            if snapshot
1252                .pipe_consumed
1253                .as_ref()
1254                .is_some_and(|consumed| consumed.get().is_some())
1255            {
1256                "pipe"
1257            } else {
1258                "env"
1259            }
1260            .to_owned(),
1261        );
1262    }
1263    let _ = snapshot;
1264    None
1265}
1266
1267/// Which slot a spawn fills: the module's ordinary one, or the candidate slot
1268/// of a blue/green swap.
1269#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1270pub(super) enum SpawnRole {
1271    Plain,
1272    SwapCandidate,
1273}
1274
1275/// Set the spawn role for a swap candidate. A plain spawn gets nothing here;
1276/// `apply_child_env` has already removed the variable for every spawn.
1277pub(super) fn apply_spawn_role(command: &mut Command, role: SpawnRole) {
1278    if role == SpawnRole::SwapCandidate {
1279        command.env(SUBC_SPAWN_ROLE_ENV, SPAWN_ROLE_SWAP_CANDIDATE);
1280    }
1281}
1282
1283pub(super) fn previous_instance_error(
1284    spec: &ModuleSpec,
1285    pid: u32,
1286    reason: crate::live_children::RetainedReason,
1287) -> SuperviseError {
1288    SuperviseError::Spawn {
1289        program: spec.program.clone(),
1290        source: io::Error::new(io::ErrorKind::WouldBlock, reason.waiting_message(pid)),
1291        cgroup_path: None,
1292    }
1293}
1294
1295pub(super) fn carries_containment(configured: bool, has_container: bool) -> bool {
1296    configured || has_container
1297}
1298
1299pub(super) fn recovery_block_error(
1300    spec: &ModuleSpec,
1301    roster: &ChildRoster,
1302) -> Option<SuperviseError> {
1303    if !carries_containment(
1304        spec.carry_containment,
1305        containment::current(&roster.containment).is_some(),
1306    ) {
1307        return None;
1308    }
1309    Some(SuperviseError::Spawn {
1310        program: spec.program.clone(),
1311        source: io::Error::new(io::ErrorKind::WouldBlock, roster.recovery_block()?),
1312        cgroup_path: None,
1313    })
1314}
1315
1316#[allow(clippy::too_many_arguments)]
1317pub(super) fn spawn_child(
1318    spec: &ModuleSpec,
1319    connection_file_path: Option<&std::path::Path>,
1320    handle: Option<&SupervisorHandle>,
1321    ring: &Arc<Mutex<StderrRing>>,
1322    capture_logs_dir: Option<&std::path::Path>,
1323    roster: &ChildRoster,
1324    config_delivery: Option<config_delivery::SpawnDelivery<'_>>,
1325    #[cfg(target_os = "linux")] cgroup_placement: Option<&subc_cgroup::Placement>,
1326    register_timeout: Duration,
1327) -> Result<SupervisedChild, SuperviseError> {
1328    #[cfg(all(test, unix))]
1329    if let Some(source) = containment_tests::join_failure(spec, roster) {
1330        containment::terminate_blocking(&roster.containment);
1331        return Err(SuperviseError::Spawn {
1332            program: spec.program.clone(),
1333            source,
1334            cgroup_path: None,
1335        });
1336    }
1337    let result = spawn_child_in_slot(
1338        spec,
1339        connection_file_path,
1340        handle,
1341        ring,
1342        capture_logs_dir,
1343        roster,
1344        config_delivery,
1345        #[cfg(target_os = "linux")]
1346        cgroup_placement,
1347        SpawnRole::Plain,
1348        false,
1349        register_timeout,
1350    );
1351    if result
1352        .as_ref()
1353        .is_err_and(|error| !is_launch_deferral(error))
1354    {
1355        if roster.admission_pending(&spec.module_id) {
1356            containment::terminate_deferred(&roster.containment);
1357        } else {
1358            containment::terminate_blocking(&roster.containment);
1359        }
1360    }
1361    result
1362}
1363
1364/// A configuration deferral means the launch never started: the module gate
1365/// or the configuration owner was briefly busy, and every caller schedules
1366/// the same launch again shortly. A carried container stays for that retry,
1367/// as it does across a restart backoff; ending it here would kill the
1368/// module's helpers and give up the group the retry is meant to join.
1369pub(super) fn is_launch_deferral(error: &SuperviseError) -> bool {
1370    matches!(error, SuperviseError::ConfigDeliveryDeferred { .. })
1371}
1372
1373/// Spawn one process of `spec` into a slot.
1374///
1375/// `alternate_slot` picks the process's cgroup label on Linux (see `swap::cgroup_name`).
1376/// A swap candidate needs a different cgroup from the process it is replacing,
1377/// which is still alive: in the same cgroup the two would be one kill domain,
1378/// and killing a failed candidate could take the incumbent with it.
1379///
1380/// The stderr capture file is `<module_id>.stderr.log` for every process of
1381/// the module, whichever slot it is in, because that is the one file
1382/// `ck module logs` reads. During a swap's overlap both processes append to it;
1383/// the daemon writes whole lines, so the two interleave by line, which is also
1384/// the merged view an operator wants while a swap runs.
1385#[allow(clippy::too_many_arguments)]
1386pub(super) fn spawn_child_in_slot(
1387    spec: &ModuleSpec,
1388    connection_file_path: Option<&std::path::Path>,
1389    handle: Option<&SupervisorHandle>,
1390    ring: &Arc<Mutex<StderrRing>>,
1391    capture_logs_dir: Option<&std::path::Path>,
1392    roster: &ChildRoster,
1393    config_delivery: Option<config_delivery::SpawnDelivery<'_>>,
1394    #[cfg(target_os = "linux")] cgroup_placement: Option<&subc_cgroup::Placement>,
1395    role: SpawnRole,
1396    alternate_slot: bool,
1397    register_timeout: Duration,
1398) -> Result<SupervisedChild, SuperviseError> {
1399    let prepared = prepare_child_in_slot(
1400        spec,
1401        connection_file_path,
1402        handle,
1403        capture_logs_dir,
1404        roster,
1405        config_delivery,
1406        #[cfg(target_os = "linux")]
1407        cgroup_placement,
1408        role,
1409        alternate_slot,
1410        false,
1411    )?;
1412    let gate = config_delivery
1413        .map(|delivery| delivery.module_gate(spec))
1414        .transpose()?;
1415    let _gate = gate
1416        .as_ref()
1417        .map(|gate| {
1418            gate.try_lock()
1419                .map_err(|_| SuperviseError::ConfigDeliveryDeferred {
1420                    module_id: spec.module_id.clone(),
1421                })
1422        })
1423        .transpose()?;
1424    if let (Some(delivery), Some(admission)) = (config_delivery, &prepared.spawn_admission) {
1425        delivery.check(spec, admission)?;
1426    }
1427    let checked_base = prepared
1428        .spawn_admission
1429        .as_ref()
1430        .and_then(|admission| admission.approved_base())
1431        .cloned();
1432    let mut result = launch_child_in_slot(spec, ring, roster, prepared, register_timeout);
1433    drop(_gate);
1434    if let (Some(delivery), Err(SuperviseError::ConfigHeld { code, detail, .. })) =
1435        (config_delivery, &result)
1436    {
1437        if let Some(base) = checked_base.as_ref().filter(|_| code == "program_refused") {
1438            if !delivery.record_refusal(spec, base, detail)? {
1439                result = Err(spawn_plan_stale(spec));
1440            }
1441        }
1442    }
1443    result
1444}
1445
1446struct AsyncInitialIdentity<'a> {
1447    supervisor: &'a Supervisor,
1448    module: String,
1449    committed: bool,
1450}
1451impl Drop for AsyncInitialIdentity<'_> {
1452    fn drop(&mut self) {
1453        if !self.committed {
1454            self.supervisor.abandon_unrostered(&self.module);
1455        }
1456    }
1457}
1458
1459/// Child-free preparation can be abandoned without orphaning a process. After
1460/// this value returns, the async caller validates its launch witness and creates
1461/// and publishes the child without another await.
1462pub(super) struct PreparedChild {
1463    script_delivery: Option<script::Delivery>,
1464    registration_spawn: Option<Arc<RegistrationSpawn>>,
1465    registration_handle: Option<SupervisorHandle>,
1466    #[cfg(any(unix, windows))]
1467    registration_channel: Option<SpawnRegistrationChannel>,
1468    config_context: Option<config_delivery::ConfigDelivery>,
1469    binding_publication: Option<ProgramBindingPublication>,
1470    launch_spec: ModuleSpec,
1471    spawn_admission: Option<crate::config_gate::runtime::SpawnAdmission>,
1472    pub(super) command: Command,
1473    carrying: bool,
1474    carried: Option<Arc<containment::CarriedContainment>>,
1475    #[cfg(unix)]
1476    launch_identity: Option<containment::LaunchIdentity>,
1477    #[cfg(unix)]
1478    group_target: containment::GroupTarget,
1479    #[cfg(target_os = "linux")]
1480    pub(super) cgroup_placement: Option<subc_cgroup::Placement>,
1481    #[cfg(target_os = "linux")]
1482    pub(super) cgroup_name: String,
1483    #[cfg(target_os = "linux")]
1484    cgroup_cleanup: PreparedCgroup,
1485    pub(super) cgroup_path: Option<PathBuf>,
1486    #[cfg(unix)]
1487    admission_gate: Option<admission::Gate>,
1488    output_sink: ChildOutputSink,
1489    #[cfg(target_os = "macos")]
1490    privacy_exec: Option<PrivacyExec>,
1491    #[cfg(windows)]
1492    image_capture: subc_os::ExecutableCapture,
1493    #[cfg(windows)]
1494    nonce_handoff: Option<NonceHandoff>,
1495    spawned_at: Instant,
1496    config_delivery: Option<crate::config_gate::runtime::DeliverySpawn>,
1497    delivery_registration: Option<config_delivery::RegistrationGuard>,
1498    program_binding: Option<SpawnProgramBinding>,
1499}
1500
1501#[cfg(target_os = "linux")]
1502struct PreparedCgroup(Option<(subc_cgroup::Placement, String)>);
1503#[cfg(target_os = "linux")]
1504impl Drop for PreparedCgroup {
1505    fn drop(&mut self) {
1506        if let Some((placement, name)) = &self.0 {
1507            remove_module_cgroup(placement, name);
1508        }
1509    }
1510}
1511
1512pub(crate) struct SpawnProgramBinding {
1513    pub(crate) path: PathBuf,
1514    // Keep the inode alive if the configured name is replaced while preparation
1515    // is suspended, so replacement cannot pass through inode reuse.
1516    pub(super) _file: std::fs::File,
1517    pub(crate) identity: subc_os::RetainedFileIdentity,
1518}
1519
1520impl SpawnProgramBinding {
1521    pub(crate) fn capture(spec: &ModuleSpec) -> Result<Self, SuperviseError> {
1522        Self::capture_after_resolution(spec, |_| {})
1523    }
1524
1525    pub(super) fn capture_after_resolution(
1526        spec: &ModuleSpec,
1527        before_open: impl FnOnce(&std::path::Path),
1528    ) -> Result<Self, SuperviseError> {
1529        require_program_search_path(spec)?;
1530        #[cfg(windows)]
1531        let windows_capture =
1532            windows_spawn_capture(spec).map_err(|source| SuperviseError::Spawn {
1533                program: spec.program.clone(),
1534                source,
1535                cgroup_path: None,
1536            })?;
1537        #[cfg(windows)]
1538        let path = windows_capture.path().to_path_buf();
1539        #[cfg(not(windows))]
1540        let path = if spec.program.is_absolute() || spec.program.components().count() > 1 {
1541            spec.program.clone()
1542        } else {
1543            let path = spec
1544                .env
1545                .iter()
1546                .rev()
1547                .find(|(key, _)| key == "PATH")
1548                .map(|(_, path)| std::ffi::OsString::from(path))
1549                .or_else(|| std::env::var_os("PATH"))
1550                .unwrap_or_else(|| {
1551                    if cfg!(target_os = "macos") {
1552                        // Match Darwin's spawn search when PATH is absent, not
1553                        // the current-directory search of an explicitly empty PATH.
1554                        "/usr/bin:/bin".into()
1555                    } else {
1556                        Default::default()
1557                    }
1558                });
1559            std::env::split_paths(&path)
1560                .map(|dir| dir.join(&spec.program))
1561                .find(|path| {
1562                    if !path.is_file() {
1563                        return false;
1564                    }
1565                    #[cfg(unix)]
1566                    {
1567                        rustix::fs::accessat(
1568                            rustix::fs::CWD,
1569                            path,
1570                            rustix::fs::Access::EXEC_OK,
1571                            rustix::fs::AtFlags::EACCESS,
1572                        )
1573                        .is_ok()
1574                    }
1575                    #[cfg(not(unix))]
1576                    {
1577                        true
1578                    }
1579                })
1580                .ok_or_else(|| SuperviseError::Spawn {
1581                    program: spec.program.clone(),
1582                    source: io::Error::new(io::ErrorKind::NotFound, "executable not found in PATH"),
1583                    cgroup_path: None,
1584                })?
1585        };
1586        let resolved = std::fs::canonicalize(&path).map_err(|source| SuperviseError::Spawn {
1587            program: spec.program.clone(),
1588            source,
1589            cgroup_path: None,
1590        })?;
1591        before_open(&resolved);
1592        // Resolving links does not open their target. The descriptor open must
1593        // remain nonblocking and no-follow if that resolved name is substituted.
1594        let file =
1595            subc_os::open_regular_nofollow(&resolved).map_err(|source| SuperviseError::Spawn {
1596                program: spec.program.clone(),
1597                source: io::Error::other(source),
1598                cgroup_path: None,
1599            })?;
1600        let identity =
1601            subc_os::retained_file_identity(&file).map_err(|source| SuperviseError::Spawn {
1602                program: spec.program.clone(),
1603                source,
1604                cgroup_path: None,
1605            })?;
1606        Ok(Self {
1607            path,
1608            _file: file,
1609            identity,
1610        })
1611    }
1612    pub(super) fn current(&self) -> bool {
1613        #[cfg(unix)]
1614        {
1615            subc_os::file_identity(&self.path) == Some(self.identity)
1616        }
1617        #[cfg(windows)]
1618        {
1619            std::fs::canonicalize(&self.path)
1620                .ok()
1621                .and_then(|path| subc_os::open_regular_nofollow(&path).ok())
1622                .and_then(|file| subc_os::retained_file_identity(&file).ok())
1623                == Some(self.identity)
1624        }
1625    }
1626}
1627
1628pub(super) fn spawn_plan_stale(spec: &ModuleSpec) -> SuperviseError {
1629    SuperviseError::ConfigDeliveryDeferred {
1630        module_id: spec.module_id.clone(),
1631    }
1632}
1633
1634fn require_program_search_path(spec: &ModuleSpec) -> Result<(), SuperviseError> {
1635    if !cfg!(target_os = "macos")
1636        && !spec.program.is_absolute()
1637        && spec.program.components().count() == 1
1638        && !spec.env.iter().any(|(key, _)| {
1639            if cfg!(windows) {
1640                key.eq_ignore_ascii_case("PATH")
1641            } else {
1642                key == "PATH"
1643            }
1644        })
1645        && std::env::var_os("PATH").is_none()
1646    {
1647        // The OS default search is not a current-directory search. Refusing an
1648        // unspecified search path prevents approving a decoy in the current directory.
1649        return Err(SuperviseError::Spawn {
1650            program: spec.program.clone(),
1651            source: io::Error::new(io::ErrorKind::InvalidInput, "bare program requires PATH"),
1652            cgroup_path: None,
1653        });
1654    }
1655    Ok(())
1656}
1657
1658pub(super) async fn spawn_child_async(
1659    spec: &ModuleSpec,
1660    runtime: &SupervisorRuntimeConfig,
1661) -> Result<SupervisedChild, SuperviseError> {
1662    #[cfg(all(test, unix))]
1663    if let Some(source) = containment_tests::join_failure(spec, &runtime.child_roster) {
1664        containment::terminate_blocking(&runtime.child_roster.containment);
1665        return Err(SuperviseError::Spawn {
1666            program: spec.program.clone(),
1667            source,
1668            cgroup_path: None,
1669        });
1670    }
1671    let result = spawn_child_in_slot_async(spec, runtime, SpawnRole::Plain, false).await;
1672    if result
1673        .as_ref()
1674        .is_err_and(|error| !is_launch_deferral(error))
1675    {
1676        if runtime.child_roster.admission_pending(&spec.module_id) {
1677            containment::terminate_deferred(&runtime.child_roster.containment);
1678        } else {
1679            containment::terminate_blocking(&runtime.child_roster.containment);
1680        }
1681    }
1682    result
1683}
1684
1685pub(super) async fn spawn_child_in_slot_async(
1686    spec: &ModuleSpec,
1687    runtime: &SupervisorRuntimeConfig,
1688    role: SpawnRole,
1689    alternate_slot: bool,
1690) -> Result<SupervisedChild, SuperviseError> {
1691    let gate = runtime
1692        .config_delivery
1693        .as_ref()
1694        .map(|delivery| delivery.0.module_gate(&spec.module_id))
1695        .transpose()
1696        .map_err(|error| SuperviseError::InvalidSpec {
1697            reason: error.to_string(),
1698        })?;
1699    if gate.as_ref().is_some_and(|gate| gate.try_lock().is_err()) {
1700        return Err(SuperviseError::ConfigDeliveryDeferred {
1701            module_id: spec.module_id.clone(),
1702        });
1703    }
1704    let prepared_spec = spec.clone();
1705    let prepared_runtime = runtime.clone();
1706    let prepared = tokio::task::spawn_blocking(move || {
1707        let prepared = prepare_child_in_slot(
1708            &prepared_spec,
1709            prepared_runtime.connection_file_path.as_deref(),
1710            prepared_runtime.supervisor_handle.as_ref(),
1711            prepared_runtime.capture_logs_dir.as_deref(),
1712            &prepared_runtime.child_roster,
1713            prepared_runtime.spawn_delivery(),
1714            #[cfg(target_os = "linux")]
1715            prepared_runtime.cgroup_placement.as_ref(),
1716            role,
1717            alternate_slot,
1718            true,
1719        );
1720        prepared
1721    })
1722    .await
1723    .map_err(|_| SuperviseError::InvalidSpec {
1724        reason: "configuration launch preparation stopped".into(),
1725    })??;
1726    if let Some(registration) = &prepared.delivery_registration {
1727        if !registration.launch_current()? {
1728            return Err(spawn_plan_stale(spec));
1729        }
1730    }
1731    let _gate = match gate {
1732        Some(gate) => {
1733            Some(
1734                gate.try_lock_owned()
1735                    .map_err(|_| SuperviseError::ConfigDeliveryDeferred {
1736                        module_id: spec.module_id.clone(),
1737                    })?,
1738            )
1739        }
1740        None => None,
1741    };
1742    if let (Some(delivery), Some(admission)) = (runtime.spawn_delivery(), &prepared.spawn_admission)
1743    {
1744        delivery.check(spec, admission)?;
1745    }
1746    if prepared
1747        .spawn_admission
1748        .as_ref()
1749        .is_none_or(|admission| admission.launch.is_none())
1750        && prepared
1751            .program_binding
1752            .as_ref()
1753            .is_some_and(|binding| !binding.current())
1754    {
1755        return Err(spawn_plan_stale(spec));
1756    }
1757    // No await may separate this last identity check from ownership publication.
1758    let checked_base = prepared
1759        .spawn_admission
1760        .as_ref()
1761        .and_then(|admission| admission.approved_base())
1762        .cloned();
1763    let mut result = launch_child_in_slot(
1764        spec,
1765        &runtime.stderr_ring,
1766        &runtime.child_roster,
1767        prepared,
1768        runtime.register_timeout,
1769    );
1770    drop(_gate);
1771    if let (Some(delivery), Err(SuperviseError::ConfigHeld { code, detail, .. })) =
1772        (runtime.config_delivery.as_ref(), &result)
1773    {
1774        if let Some(base) = checked_base.filter(|_| code == "program_refused") {
1775            let module = spec.module_id.clone();
1776            let identity = subc_config::raw_digest(detail.as_bytes());
1777            let recorded = delivery
1778                .0
1779                .on_blocking(move |owner| owner.record_program_refusal(&module, &base, identity))
1780                .await;
1781            match recorded {
1782                Ok(true) => {}
1783                Ok(false) => result = Err(spawn_plan_stale(spec)),
1784                Err(error) => {
1785                    result = Err(config_delivery::gate_hold_error(
1786                        spec,
1787                        error,
1788                        Some(delivery),
1789                    ))
1790                }
1791            }
1792        }
1793    }
1794    result
1795}
1796
1797fn validate_spawn_program(
1798    spec: &ModuleSpec,
1799    admission: Option<&crate::config_gate::runtime::SpawnAdmission>,
1800    delivery: Option<config_delivery::SpawnDelivery<'_>>,
1801) -> Result<(), SuperviseError> {
1802    if let Some(admission) = admission {
1803        if let Some(program) = &admission.launch {
1804            if let Err(error) = program.validate_for_spawn() {
1805                // A captured unsigned image is a definite refusal. Uncertain
1806                // reads are deferred by validate_for_spawn, not attributed to
1807                // the operator as a changed or unapprovable program.
1808                if let (Some(context), Some(base)) = (delivery, admission.approved_base()) {
1809                    if error.code == "program_refused"
1810                        && !context.record_refusal(spec, base, &error.detail)?
1811                    {
1812                        return Err(spawn_plan_stale(spec));
1813                    }
1814                }
1815                return Err(config_delivery::gate_hold_error(
1816                    spec,
1817                    error,
1818                    delivery.map(|context| context.runtime()).as_ref(),
1819                ));
1820            }
1821        }
1822    }
1823    Ok(())
1824}
1825
1826#[allow(clippy::too_many_arguments)]
1827pub(super) fn prepare_child_in_slot(
1828    spec: &ModuleSpec,
1829    connection_file_path: Option<&std::path::Path>,
1830    handle: Option<&SupervisorHandle>,
1831    capture_logs_dir: Option<&std::path::Path>,
1832    roster: &ChildRoster,
1833    config_delivery: Option<config_delivery::SpawnDelivery<'_>>,
1834    #[cfg(target_os = "linux")] cgroup_placement: Option<&subc_cgroup::Placement>,
1835    role: SpawnRole,
1836    alternate_slot: bool,
1837    asynchronous: bool,
1838) -> Result<PreparedChild, SuperviseError> {
1839    require_program_search_path(spec)?;
1840    let spawn_admission = config_delivery
1841        .map(|delivery| delivery.prepare(spec))
1842        .transpose()?;
1843    #[cfg(target_os = "macos")]
1844    let gated = spawn_admission
1845        .as_ref()
1846        .is_some_and(|admission| admission.approved_base().is_some());
1847    let mut launch_spec = spawn_admission
1848        .as_ref()
1849        .and_then(|admission| admission.launch.as_ref())
1850        .map(|launch| launch.spec.clone())
1851        .unwrap_or_else(|| spec.clone());
1852    if let Some(script) = &launch_spec.script {
1853        launch_spec.program =
1854            script::runner_path(script.runtime).map_err(|source| SuperviseError::Spawn {
1855                program: launch_spec.program.clone(),
1856                source,
1857                cgroup_path: None,
1858            })?;
1859    }
1860    let script_content = if let Some(entry) = &launch_spec.script {
1861        Some(
1862            spawn_admission
1863                .as_ref()
1864                .and_then(|admission| admission.launch.as_ref())
1865                .and_then(|launch| launch.script.clone())
1866                .map_or_else(|| script::ScriptBytes::read(&entry.path), Ok)
1867                .map_err(|error| config_delivery::gate_hold_error(&launch_spec, error, None))?,
1868        )
1869    } else {
1870        None
1871    };
1872    let spec = &launch_spec;
1873    if let Some(error) = recovery_block_error(spec, roster) {
1874        return Err(error);
1875    }
1876    if let Some((pid, reason)) = roster.previous_instance(&spec.module_id) {
1877        return Err(previous_instance_error(spec, pid, reason));
1878    }
1879    if roster.is_closed() {
1880        return Err(SuperviseError::Spawn {
1881            program: spec.program.clone(),
1882            source: io::Error::other("the daemon is shutting down; not starting a new process"),
1883            cgroup_path: None,
1884        });
1885    }
1886    let carried = containment::current(&roster.containment);
1887    let carrying = carries_containment(spec.carry_containment, carried.is_some());
1888    if role != SpawnRole::Plain && carrying {
1889        return Err(SuperviseError::InvalidSpec {
1890            reason: "a carried container cannot overlap a swap candidate".to_owned(),
1891        });
1892    }
1893    #[cfg(unix)]
1894    let launch_identity = if carrying && carried.is_none() {
1895        Some(
1896            containment::LaunchIdentity::capture().map_err(|source| SuperviseError::Spawn {
1897                program: spec.program.clone(),
1898                source,
1899                cgroup_path: None,
1900            })?,
1901        )
1902    } else {
1903        None
1904    };
1905    #[cfg(target_os = "linux")]
1906    let cgroup_placement = match &carried {
1907        Some(container) => container.cgroup().map(|(placement, _)| placement),
1908        None => cgroup_placement,
1909    };
1910    #[cfg(unix)]
1911    let group_target = if let Some(container) = carried
1912        .as_ref()
1913        .filter(|container| container.group().is_some())
1914    {
1915        containment::GroupTarget::Pinned(Arc::clone(container))
1916    } else {
1917        #[cfg(target_os = "linux")]
1918        let cgroup_container = carrying && cgroup_placement.is_some();
1919        #[cfg(not(target_os = "linux"))]
1920        let cgroup_container = false;
1921        if cgroup_container {
1922            containment::GroupTarget::NoGroup
1923        } else {
1924            containment::GroupTarget::OwnLeader
1925        }
1926    };
1927    #[cfg(target_os = "linux")]
1928    let cgroup_name = {
1929        // Slot names alone are not kill domains: a retired incumbent may still
1930        // be draining when a later enable/restart spawns into the same slot.
1931        // Decimal entropy keeps the suffix unambiguous; Placement performs
1932        // the module-id escaping and constructs the filesystem path.
1933        if let Some((_, name)) = carried.as_ref().and_then(|container| container.cgroup()) {
1934            name.to_owned()
1935        } else if cgroup_placement.is_none() {
1936            swap::cgroup_name(&spec.module_id, alternate_slot)
1937        } else {
1938            let nonce = generate_launch_nonce()?;
1939            let suffix = u128::from_str_radix(&nonce[..32], 16).expect("hex launch nonce");
1940            cgroup_label::generation_label(&spec.module_id, alternate_slot, suffix)
1941        }
1942    };
1943    #[cfg(not(target_os = "linux"))]
1944    let _ = alternate_slot;
1945    #[cfg(windows)]
1946    let image_capture = windows_spawn_capture(spec).map_err(|source| SuperviseError::Spawn {
1947        program: spec.program.clone(),
1948        source,
1949        cgroup_path: None,
1950    })?;
1951    #[cfg(windows)]
1952    let program_binding = if asynchronous {
1953        let mut resolved = spec.clone();
1954        resolved.program = image_capture.path().to_path_buf();
1955        Some(SpawnProgramBinding::capture(&resolved)?)
1956    } else {
1957        None
1958    };
1959    #[cfg(not(windows))]
1960    let program_binding = (asynchronous || cfg!(target_os = "macos"))
1961        .then(|| SpawnProgramBinding::capture(spec))
1962        .transpose()?;
1963    #[cfg(target_os = "macos")]
1964    validate_spawn_program(spec, spawn_admission.as_ref(), config_delivery)?;
1965    #[cfg(target_os = "macos")]
1966    let (mut command, privacy_exec, exec_ack) = privacy_command(
1967        spec,
1968        program_binding
1969            .as_ref()
1970            .expect("macOS captures every launch"),
1971        roster,
1972        // Ungated launches retain legacy unsuspended exec, including scripts. Suspended
1973        // verification admits approved programs only. prepare() above fails
1974        // closed if the gate cannot decide; an image sample is not authority.
1975        gated,
1976    )?;
1977    #[cfg(windows)]
1978    let mut command = Command::new(image_capture.path());
1979    #[cfg(not(any(target_os = "macos", windows)))]
1980    let mut command = Command::new(
1981        program_binding
1982            .as_ref()
1983            .map_or(spec.program.as_path(), |binding| binding.path.as_path()),
1984    );
1985    command.args(&spec.args);
1986    // AMBIENT `CK_LOG` MUST NOT LEAK INTO AN OTHERWISE UNCONFIGURED MODULE — but
1987    // that is the whole of the intent, so remove that one key rather than the
1988    // environment.
1989    //
1990    // This was `env_clear()` from 0.17.41 until 0.18.3, which achieved the goal
1991    // and took the POSIX environment with it. Modules spawned that way had no
1992    // HOME, XDG_RUNTIME_DIR, TMPDIR or USER, and the consequences ran past
1993    // logging:
1994    //
1995    //   * `connection_file::discover` reads XDG_RUNTIME_DIR and HOME, so with
1996    //     both unset it fell back to the temp dir alone and `ck` could not find
1997    //     a daemon running on the same machine from inside any module's process
1998    //     tree — reporting a path the file has never lived at, which reads as
1999    //     "the daemon did not write its file".
2000    //   * `default_data_home()` with HOME and XDG_DATA_HOME both unset returns
2001    //     the RELATIVE `.local/share`, so a module deriving its own store path
2002    //     resolved it against its own CWD. That is the store-fragmentation
2003    //     defect the daemon already refuses in config (`parse_doc` rejects a
2004    //     relative `storage.data_home`) arriving by derivation instead.
2005    //   * anything a module spawns inherited it: git without ~/.gitconfig,
2006    //     cargo without CARGO_HOME, ssh, python user dirs — all degrading
2007    //     quietly rather than erroring.
2008    //
2009    // Reported by iceteaSA as #104 after deploying 0.18.2, where `ck daemon`
2010    // offered one candidate under /tmp while the file sat in /run/user/1000.
2011    //
2012    // A configured module is unaffected either way: `module_spec()` puts the
2013    // resolved CK_LOG into `spec.env`, which is applied below and therefore
2014    // wins over anything ambient.
2015    apply_child_env(&mut command, spec);
2016    if spec.script.is_some() {
2017        script::remove_runtime_env(&mut command, spec);
2018    }
2019    let origin_witness = crate::program_origin::LaunchWitness::capture_command(spec, &command)
2020        .map_err(|source| SuperviseError::Spawn {
2021            program: spec.program.clone(),
2022            source,
2023            cgroup_path: None,
2024        })?;
2025    command.current_dir(&origin_witness.working_directory);
2026    apply_spawn_role(&mut command, role);
2027    let nonce_handoff = apply_wire_spawn_args_for_admission(
2028        &mut command,
2029        spec,
2030        connection_file_path,
2031        handle,
2032        role,
2033        spawn_admission.as_ref(),
2034    )?;
2035    #[cfg(unix)]
2036    let mut slots = subc_os::registration_channel::ChildDescriptorSlots::default();
2037    command.env_remove(subc_os::script_pipe::SCRIPT_FD_ENV);
2038    let script_delivery = script_content
2039        .map(|content| {
2040            script::Delivery::prepare(
2041                content,
2042                &mut command,
2043                #[cfg(unix)]
2044                &mut slots,
2045            )
2046        })
2047        .transpose()
2048        .map_err(|source| SuperviseError::Spawn {
2049            program: spec.program.clone(),
2050            source,
2051            cgroup_path: None,
2052        })?;
2053    #[cfg(unix)]
2054    let registration_channel = if spec.protocol == ModuleProtocol::Subc {
2055        let (parent, child, metadata) = subc_os::registration_channel::registration_socketpair()
2056            .map_err(|source| SuperviseError::Spawn {
2057                program: spec.program.clone(),
2058                source,
2059                cgroup_path: None,
2060            })?;
2061        slots
2062            .channel(child)
2063            .map_err(|source| SuperviseError::Spawn {
2064                program: spec.program.clone(),
2065                source,
2066                cgroup_path: None,
2067            })?;
2068        command
2069            .env(subc_os::registration_channel::REGISTRATION_FD_ENV, metadata)
2070            .env(
2071                subc_os::registration_channel::DAEMON_PID_ENV,
2072                std::process::id().to_string(),
2073            );
2074        Some(parent)
2075    } else {
2076        None
2077    };
2078    #[cfg(windows)]
2079    let registration_channel = prepare_windows_registration_pipe(&mut command, spec)?;
2080    let binding_publication = if spawn_admission
2081        .as_ref()
2082        .is_some_and(|admission| admission.launch.is_some())
2083    {
2084        handle.and_then(|handle| handle.begin_program_binding(&spec.module_id, role))
2085    } else {
2086        None
2087    };
2088    let registration_spawn = (spec.protocol == ModuleProtocol::Subc)
2089        .then(|| {
2090            handle.map(|handle| {
2091                let spawn = RegistrationSpawn::new_with_binding_requirement(
2092                    handle,
2093                    &spec.module_id,
2094                    role,
2095                    binding_publication.clone(),
2096                    spawn_admission
2097                        .as_ref()
2098                        .is_some_and(|admission| admission.launch.is_some()),
2099                );
2100                if let Some(admission) = &spawn_admission {
2101                    admission.initialize_origin(&spawn.authority, &origin_witness);
2102                }
2103                handle.record_nonce_launch(&spawn);
2104                spawn
2105            })
2106        })
2107        .flatten();
2108
2109    #[cfg(target_os = "linux")]
2110    let cgroup_path = cgroup_placement
2111        .map(|placement| {
2112            if let Some(container) = &carried {
2113                let path = container
2114                    .cgroup_path()
2115                    .ok_or_else(|| io::Error::other("carried container has no cgroup path"))?;
2116                placement.existing_module_path(path)?.ok_or_else(|| {
2117                    io::Error::new(
2118                        io::ErrorKind::NotFound,
2119                        "carried cgroup disappeared before replacement",
2120                    )
2121                })
2122            } else {
2123                if carrying {
2124                    containment::prepare_cgroup_path(placement, &cgroup_name)
2125                } else {
2126                    placement.module_path(&cgroup_name)
2127                }
2128            }
2129        })
2130        .transpose()
2131        .map_err(|source| SuperviseError::Cgroup {
2132            module_id: spec.module_id.clone(),
2133            source,
2134        })?;
2135    #[cfg(not(target_os = "linux"))]
2136    let cgroup_path: Option<PathBuf> = None;
2137    // Own a newly created directory before any fallible admission or command
2138    // preparation. Existing carried containment must never be removed here.
2139    #[cfg(target_os = "linux")]
2140    let cgroup_cleanup = PreparedCgroup(
2141        cgroup_placement
2142            .filter(|_| carried.is_none())
2143            .map(|placement| (placement.clone(), cgroup_name.clone())),
2144    );
2145    #[cfg(unix)]
2146    let mut admission_gate = if carrying {
2147        Some(
2148            admission::Gate::install(&mut command, spec, roster).map_err(|source| {
2149                SuperviseError::Spawn {
2150                    program: spec.program.clone(),
2151                    source,
2152                    cgroup_path: cgroup_path.clone(),
2153                }
2154            })?,
2155        )
2156    } else {
2157        None
2158    };
2159    #[cfg(target_os = "linux")]
2160    if let Some(path) = &cgroup_path {
2161        apply_cgroup_placement(&mut command, spec, path)?;
2162    }
2163
2164    let output_sink = if let Some(logs_dir) = capture_logs_dir {
2165        let path = logs_dir.join(format!("{}.stderr.log", spec.module_id));
2166        match ChildOutputSink::open(&path, capture_retention(spec)) {
2167            Ok(sink) => sink,
2168            Err(error) => {
2169                warn!(
2170                    module_id = %spec.module_id,
2171                    path = %path.display(),
2172                    error = %error,
2173                    "could not open child output capture file; forwarding to stderr"
2174                );
2175                ChildOutputSink::Stderr
2176            }
2177        }
2178    } else {
2179        ChildOutputSink::Stderr
2180    };
2181
2182    command.stdout(Stdio::piped());
2183    command.stderr(Stdio::piped());
2184    command.kill_on_drop(!carrying);
2185    // EACH MODULE LEADS ITS OWN PROCESS GROUP (the child calls setpgid(0, 0)
2186    // before exec). In the daemon's group, a service manager that kills the
2187    // job's process group when the daemon exits (launchd's default) killed
2188    // every module at the same moment its control connection closed, so no
2189    // module ever ran its EOF teardown on a daemon stop. Outside that group a
2190    // module is reached only by the daemon: the EOF it sees when its
2191    // connection closes, and the bounded stop in `child_roster` for anything
2192    // still running after that. On Linux this composes with the cgroup
2193    // placement above: that is a pre_exec write to cgroup.procs, std performs
2194    // setpgid in the child before running pre_exec callbacks, and the two
2195    // change independent process attributes.
2196    //
2197    // stdin is /dev/null because a process outside the terminal's foreground
2198    // group is stopped (SIGTTIN) if it reads the terminal, which a daemon run
2199    // by hand would otherwise hand down. Under a service manager stdin is
2200    // already /dev/null.
2201    #[cfg(unix)]
2202    command.process_group(
2203        carried
2204            .as_ref()
2205            .map(|container| container.verified_join_group())
2206            .transpose()
2207            .map_err(|source| SuperviseError::Spawn {
2208                program: spec.program.clone(),
2209                source,
2210                cgroup_path: cgroup_path.clone(),
2211            })?
2212            .flatten()
2213            .unwrap_or(0) as i32,
2214    );
2215    command.stdin(Stdio::null());
2216    #[cfg(unix)]
2217    if let Some(gate) = &mut admission_gate {
2218        gate.install_placement(&mut command);
2219    }
2220    // Fill all reserved slots in one allocation-free step, after placement has
2221    // stopped using descriptors that the fixed slots may replace.
2222    #[cfg(unix)]
2223    {
2224        if let Some(handoff) = nonce_handoff {
2225            slots.nonce(handoff);
2226        }
2227        #[cfg(target_os = "macos")]
2228        slots
2229            .acknowledgement(exec_ack.into_descriptor())
2230            .map_err(|source| SuperviseError::Spawn {
2231                program: spec.program.clone(),
2232                source,
2233                cgroup_path: cgroup_path.clone(),
2234            })?;
2235        slots.install(command.as_std_mut());
2236    }
2237    #[cfg(not(any(unix, windows)))]
2238    let _ = nonce_handoff;
2239
2240    // Containment, step 1 of 3 (issue #109): create the child suspended so it
2241    // cannot run a single instruction -- and therefore cannot spawn a
2242    // grandchild -- before it is in the job. See `contain_spawned_child` for the
2243    // other two steps and why the window matters.
2244    #[cfg(windows)]
2245    {
2246        subc_jobobject::ensure_root_job().map_err(|source| SuperviseError::Spawn {
2247            program: spec.program.clone(),
2248            source,
2249            cgroup_path: None,
2250        })?;
2251        subc_jobobject::suspend_on_create_async(&mut command);
2252    }
2253    // Timestamp before the spawn call: on Unix the child can serve before that
2254    // call even returns. This conservative bound never labels an older child
2255    // as a replacement for a request received during process creation.
2256    let spawned_at = Instant::now();
2257    let delivery_context = config_delivery;
2258    let config_delivery = config_delivery
2259        .map(|delivery| {
2260            delivery.spawned(
2261                spec,
2262                spawn_admission
2263                    .as_ref()
2264                    .expect("delivery prepares spawn admission"),
2265                spawned_at,
2266                role,
2267                registration_spawn
2268                    .as_ref()
2269                    .map(|spawn| spawn.authority.clone()),
2270            )
2271        })
2272        .transpose()?
2273        .flatten();
2274    let mut delivery_registration =
2275        delivery_context.map(|context| context.registration_guard(config_delivery.as_ref(), role));
2276    if let Some(registration) = &mut delivery_registration {
2277        registration.defer_cleanup();
2278    }
2279    if asynchronous {
2280        #[cfg(test)]
2281        if let Some(context) = delivery_context {
2282            context.pause_preflight_for_test();
2283        }
2284    }
2285    validate_spawn_program(spec, spawn_admission.as_ref(), delivery_context)?;
2286    Ok(PreparedChild {
2287        script_delivery,
2288        registration_spawn,
2289        registration_handle: handle.cloned(),
2290        #[cfg(any(unix, windows))]
2291        registration_channel,
2292        config_context: delivery_context.map(|delivery| delivery.runtime()),
2293        binding_publication,
2294        launch_spec,
2295        spawn_admission,
2296        command,
2297        carrying,
2298        carried: carried.clone(),
2299        #[cfg(unix)]
2300        launch_identity,
2301        #[cfg(unix)]
2302        group_target,
2303        #[cfg(target_os = "linux")]
2304        cgroup_placement: cgroup_placement.cloned(),
2305        #[cfg(target_os = "linux")]
2306        cgroup_cleanup,
2307        #[cfg(target_os = "linux")]
2308        cgroup_name,
2309        cgroup_path,
2310        #[cfg(unix)]
2311        admission_gate,
2312        output_sink,
2313        #[cfg(target_os = "macos")]
2314        privacy_exec,
2315        #[cfg(windows)]
2316        image_capture,
2317        #[cfg(windows)]
2318        nonce_handoff,
2319        spawned_at,
2320        config_delivery,
2321        delivery_registration,
2322        program_binding,
2323    })
2324}
2325
2326pub(super) fn launch_child_in_slot(
2327    _spec: &ModuleSpec,
2328    ring: &Arc<Mutex<StderrRing>>,
2329    roster: &ChildRoster,
2330    prepared: PreparedChild,
2331    register_timeout: Duration,
2332) -> Result<SupervisedChild, SuperviseError> {
2333    let launch_spec = prepared.launch_spec.clone();
2334    let registration_declaration = prepared
2335        .spawn_admission
2336        .as_ref()
2337        .and_then(|admission| admission.registration_declaration(&launch_spec.module_id));
2338    let admission_base = prepared
2339        .spawn_admission
2340        .as_ref()
2341        .and_then(|admission| admission.approved_base())
2342        .cloned();
2343    let spec = &launch_spec;
2344    let expected_image = prepared
2345        .spawn_admission
2346        .as_ref()
2347        .and_then(|admission| admission.launch.as_ref())
2348        .map(|launch| launch.image);
2349    let program_launch = prepared
2350        .spawn_admission
2351        .and_then(|admission| admission.launch);
2352    let config_owner = prepared
2353        .config_context
2354        .as_ref()
2355        .map(|context| context.0.clone());
2356    let binding_publication = prepared.binding_publication;
2357    #[cfg(test)]
2358    if let Some(context) = &prepared.config_context {
2359        context.0.before_spawn_exec_for_test();
2360    }
2361    #[cfg(feature = "test-support")]
2362    if let Some(context) = &prepared.config_context {
2363        context
2364            .0
2365            .pause_spawn_before_exec()
2366            .map_err(|error| config_delivery::gate_hold_error(spec, error, Some(context)))?;
2367    }
2368    let mut command = prepared.command;
2369    let carrying = prepared.carrying;
2370    let carried = prepared.carried;
2371    #[cfg(unix)]
2372    let launch_identity = prepared.launch_identity;
2373    #[cfg(unix)]
2374    let group_target = prepared.group_target;
2375    #[cfg(target_os = "linux")]
2376    let cgroup_placement = prepared.cgroup_placement.as_ref();
2377    #[cfg(target_os = "linux")]
2378    let cgroup_name = prepared.cgroup_name;
2379    #[cfg(target_os = "linux")]
2380    let mut cgroup_cleanup = prepared.cgroup_cleanup;
2381    #[cfg(target_os = "linux")]
2382    let _ = cgroup_cleanup.0.take();
2383    let cgroup_path = prepared.cgroup_path;
2384    #[cfg(unix)]
2385    let admission_gate = prepared.admission_gate;
2386    let output_sink = prepared.output_sink;
2387    #[cfg(target_os = "macos")]
2388    let mut privacy_exec = prepared.privacy_exec;
2389    #[cfg(target_os = "macos")]
2390    if let Some(pending) = &mut privacy_exec {
2391        pending.admission_binding = binding_publication.clone();
2392        if expected_image.is_some() {
2393            pending.expected = expected_image;
2394        }
2395    }
2396    #[cfg(any(unix, windows))]
2397    let registration_channel = prepared.registration_channel;
2398    let registration_spawn = prepared.registration_spawn;
2399    let registration_handle = prepared.registration_handle;
2400    #[cfg(windows)]
2401    let image_capture = prepared.image_capture;
2402    #[cfg(windows)]
2403    let nonce_handoff = prepared.nonce_handoff;
2404    let spawned_at = prepared.spawned_at;
2405    let config_delivery = prepared.config_delivery;
2406    let delivery_registration = prepared.delivery_registration;
2407    let _program_binding = prepared.program_binding;
2408    #[cfg(all(test, unix))]
2409    containment_tests::record_spawn_attempt(spec, &mut command);
2410    #[cfg(unix)]
2411    let spawned = match admission_gate {
2412        Some(gate) => gate
2413            .spawn(
2414                command,
2415                spec,
2416                roster,
2417                launch_identity,
2418                #[cfg(target_os = "linux")]
2419                cgroup_placement
2420                    .zip(cgroup_path.as_ref())
2421                    .map(|(placement, path)| {
2422                        (placement.clone(), cgroup_name.clone(), path.clone())
2423                    }),
2424            )
2425            .map(|(child, admitted)| (child, Some(admitted))),
2426        None => {
2427            let spawned =
2428                subc_os::child_spawn::tokio_spawn(&mut command).map(|child| (child, None));
2429            // The callback owns all child-only sources. Closing them here is
2430            // necessary for channel EOF and macOS exec acknowledgement EOF.
2431            drop(command);
2432            spawned
2433        }
2434    };
2435    #[cfg(not(unix))]
2436    let spawned = subc_os::child_spawn::tokio_spawn(&mut command);
2437    let spawned = match spawned {
2438        Ok(child) => child,
2439        Err(source) => {
2440            if carried
2441                .as_ref()
2442                .and_then(|container| container.group())
2443                .is_some()
2444            {
2445                containment::terminate_blocking(&roster.containment);
2446            }
2447            #[cfg(target_os = "linux")]
2448            if let Some(placement) = cgroup_placement.filter(|_| carried.is_none()) {
2449                remove_module_cgroup(placement, &cgroup_name);
2450            }
2451            return Err(SuperviseError::Spawn {
2452                program: spec.program.clone(),
2453                source,
2454                cgroup_path,
2455            });
2456        }
2457    };
2458    #[cfg(unix)]
2459    let (mut child, mut admitted) = spawned;
2460    #[cfg(unix)]
2461    let group_target = admitted
2462        .as_ref()
2463        .map(|attempt| attempt.group_target())
2464        .unwrap_or(group_target);
2465    #[cfg(not(unix))]
2466    let mut child = spawned;
2467    if let Some(delivery) = prepared.script_delivery {
2468        delivery.start(child.id().expect("spawned child has a pid"));
2469    }
2470    #[cfg(test)]
2471    spawn_record_tests::after_create(&child, spec);
2472
2473    // Bind while the child is still suspended, before job assignment resumes it.
2474    // Keeping the executable handle open across CreateProcessW denies rename
2475    // and deletion, so the file cannot be exchanged during spawn. Bind that
2476    // file ID to the process handle returned by spawn, never a reopened PID.
2477    #[cfg(windows)]
2478    let windows_image = match image_capture.bind_tokio(&child) {
2479        Ok(image) => Arc::new(image),
2480        Err(source) => {
2481            kill_and_reap_rejected_child(&mut child);
2482            return Err(SuperviseError::Spawn {
2483                program: spec.program.clone(),
2484                source,
2485                cgroup_path: None,
2486            });
2487        }
2488    };
2489    // Assign the suspended child to its module job; resume only after its
2490    // process identity has been durably recorded for orphan recovery.
2491    #[cfg(windows)]
2492    let job = contain_spawned_child(&mut child, spec, carried.as_ref())?;
2493    let spawned_at_ms = unix_ms_now();
2494    #[cfg(not(windows))]
2495    let spawned_from = spec.program.clone();
2496    #[cfg(windows)]
2497    let spawned_from = windows_image.path().to_path_buf();
2498    #[cfg(not(windows))]
2499    let spawned_file_identity = spawned_file_identity(&spawned_from);
2500    #[cfg(windows)]
2501    let spawned_file_identity = Some(SpawnedFileIdentity {
2502        device: 0,
2503        inode: 0,
2504        windows_image: Some(Arc::clone(&windows_image)),
2505    });
2506    let pid = child.id().ok_or_else(|| SuperviseError::Spawn {
2507        program: spec.program.clone(),
2508        source: io::Error::other("spawned child exposed no live pid"),
2509        cgroup_path: cgroup_path.clone(),
2510    })?;
2511    #[cfg(unix)]
2512    let plain_group = (!carrying
2513        && cgroup_path.is_none()
2514        && matches!(group_target, containment::GroupTarget::OwnLeader))
2515    .then(|| plain_group::PlainGroup::from_spawn(pid).map(Arc::new))
2516    .flatten();
2517    #[cfg(windows)]
2518    let nonce_delivery = start_windows_nonce_pipe(nonce_handoff, pid, spec);
2519    #[cfg(not(windows))]
2520    let process_start_time = admitted
2521        .as_ref()
2522        .map(|admitted| admitted.birth)
2523        .or_else(|| crate::provenance::process_start_time(pid));
2524    #[cfg(windows)]
2525    let process_start_time = Some(windows_image.start_time());
2526    let process_identity = process_start_time.map(|start_time| ProcessIdentity { pid, start_time });
2527    #[cfg(all(test, target_os = "macos"))]
2528    privacy_exec_boundary_tests::before_image_sample(spec, pid);
2529    #[cfg(all(test, target_os = "linux"))]
2530    assert!(roster.admission_event_for_test(&spec.module_id, "before_image_binding", Some(pid)));
2531    // Record the committed kernel image, not the configured pathname: PATH
2532    // lookup and shebang interpretation can select a different executable.
2533    // Linux's posix_spawn can return before that image is installed, so the
2534    // observer also waits for the kernel's first-exec flag to clear.
2535    #[cfg(not(windows))]
2536    let recorded_image = observe_spawned_image(pid);
2537    #[cfg(all(test, target_os = "linux"))]
2538    let recorded_image = if roster.admission_event_for_test(
2539        &spec.module_id,
2540        "after_spawn_image_sample",
2541        Some(pid),
2542    ) {
2543        recorded_image
2544    } else {
2545        None
2546    };
2547    #[cfg(target_os = "linux")]
2548    // An exited child cannot receive HELLO service and has no readable /proc/exe.
2549    // Keep its real exit for the supervisor instead of turning a crash into a hold.
2550    let exited_before_binding = expected_image.is_some()
2551        && recorded_image.and_then(|image| image.executable) != expected_image
2552        && subc_os::child_exit::observe(pid).ok().flatten().is_some();
2553    #[cfg(target_os = "linux")]
2554    let unavailable_initial_image = expected_image.is_some()
2555        && recorded_image.and_then(|image| image.executable).is_none()
2556        && !exited_before_binding;
2557    #[cfg(not(target_os = "linux"))]
2558    let unavailable_initial_image = false;
2559    #[cfg(target_os = "linux")]
2560    if expected_image
2561        .is_some_and(|expected| recorded_image.and_then(|image| image.executable) != Some(expected))
2562        && !exited_before_binding
2563        && !unavailable_initial_image
2564    {
2565        kill_module_cgroup(cgroup_placement, &cgroup_name);
2566        kill_and_reap_rejected_child(&mut child, group_target.clone());
2567        return Err(SuperviseError::ConfigHeld {
2568            module_id: spec.module_id.clone(),
2569            code: "program_refused".into(),
2570            detail: format!(
2571                "spawned executable {:?} does not match hashed program {:?}",
2572                recorded_image.and_then(|image| image.executable),
2573                expected_image
2574            ),
2575        });
2576    }
2577    #[cfg(not(target_os = "linux"))]
2578    let _ = expected_image;
2579    #[cfg(target_os = "macos")]
2580    let binding_ready = privacy_exec.is_none();
2581    #[cfg(target_os = "linux")]
2582    let binding_ready = !exited_before_binding;
2583    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
2584    let binding_ready = cfg!(windows);
2585    // spawn() confirms only the first exec, into the trampoline. Never persist
2586    // the trampoline image; the asynchronous acknowledgement publishes the
2587    // module image once the trampoline has replaced itself with the module.
2588    #[cfg(target_os = "macos")]
2589    let recorded_image = if privacy_exec.is_some() {
2590        None
2591    } else {
2592        recorded_image
2593    };
2594    #[cfg(target_os = "linux")]
2595    let recorded_cgroup_name = cgroup_path.as_ref().map(|_| cgroup_name.clone());
2596    #[cfg(not(target_os = "linux"))]
2597    let recorded_cgroup_name = None;
2598    #[cfg(unix)]
2599    let preadmitted = admitted
2600        .as_mut()
2601        .and_then(|admitted| admitted.leader.take());
2602    #[cfg(not(unix))]
2603    let preadmitted: Option<crate::child_roster::RosterGuard> = None;
2604    let roster_guard = if let Some(guard) = preadmitted {
2605        Ok(guard)
2606    } else {
2607        roster.admit(
2608            spec.module_id.clone(),
2609            pid,
2610            spec.protocol,
2611            process_start_time,
2612            crate::child_roster::RecordedIdentity {
2613                #[cfg(target_os = "linux")]
2614                container: cgroup_path
2615                    .clone()
2616                    .filter(|_| !carrying)
2617                    .map(ordinary_cgroup::recorded_identity),
2618                #[cfg(not(target_os = "linux"))]
2619                container: None,
2620                #[cfg(unix)]
2621                carried: None,
2622                #[cfg(unix)]
2623                plain_group: plain_group.as_ref().map(Arc::downgrade),
2624                #[cfg(not(windows))]
2625                start_time: recorded_image.map(|image| image.start_time),
2626                #[cfg(windows)]
2627                start_time: process_start_time,
2628                #[cfg(not(windows))]
2629                executable: recorded_image
2630                    .and_then(|image| image.executable)
2631                    .map(crate::live_children::ExecutableIdentity::from),
2632                #[cfg(windows)]
2633                executable: Some(crate::live_children::ExecutableIdentity::from(
2634                    windows_image.identity(),
2635                )),
2636                cgroup_name: recorded_cgroup_name,
2637                #[cfg(target_os = "linux")]
2638                cgroup_placement: cgroup_placement.cloned(),
2639            },
2640        )
2641    };
2642    let roster_guard = match roster_guard {
2643        Ok(guard) => guard,
2644        Err(failure) => {
2645            return failure.with_cleanup(|source| {
2646                #[cfg(windows)]
2647                if let Some(job) = &job {
2648                    let _ = job.lock().unwrap_or_else(|p| p.into_inner()).terminate();
2649                }
2650                #[cfg(target_os = "linux")]
2651                kill_module_cgroup(cgroup_placement, &cgroup_name);
2652                #[cfg(unix)]
2653                let rejected_group = group_target.clone();
2654                kill_and_reap_rejected_child(
2655                    &mut child,
2656                    #[cfg(unix)]
2657                    rejected_group,
2658                );
2659                #[cfg(target_os = "linux")]
2660                if let Some(placement) = cgroup_placement.filter(|_| carried.is_none()) {
2661                    remove_module_cgroup(placement, &cgroup_name);
2662                }
2663                Err(SuperviseError::Spawn {
2664                    program: spec.program.clone(),
2665                    source: io::Error::other(format!(
2666                        "could not durably record module child: {source}"
2667                    )),
2668                    cgroup_path,
2669                })
2670            });
2671        }
2672    };
2673    #[cfg(unix)]
2674    if admitted.is_some() {
2675        if let Some(image) = recorded_image {
2676            if let Err(source) = roster_guard.confirm_executable(image) {
2677                kill_and_reap_rejected_child(&mut child, group_target.clone());
2678                return Err(SuperviseError::Spawn {
2679                    program: spec.program.clone(),
2680                    source,
2681                    cgroup_path,
2682                });
2683            }
2684        }
2685    }
2686    // The pre-spawn check can pass just before shutdown begins. Ownership is
2687    // published at the start of admission, even while a record write is queued.
2688    // If shutdown already saw an empty roster before that publication, this
2689    // check sees the roster closed and ends the child before starting a module.
2690    if roster.is_closed() {
2691        if carrying {
2692            #[cfg(unix)]
2693            let rejected_group = admitted
2694                .as_ref()
2695                .map(|admitted| admitted.rejection_target())
2696                .unwrap_or_else(|| group_target.clone());
2697            #[cfg(windows)]
2698            if let Some(job) = &job {
2699                let _ = job.lock().unwrap_or_else(|p| p.into_inner()).terminate();
2700            }
2701            kill_and_reap_rejected_child(
2702                &mut child,
2703                #[cfg(unix)]
2704                rejected_group,
2705            );
2706            #[cfg(all(test, unix))]
2707            let _ =
2708                roster.admission_event_for_test(&spec.module_id, "after_rejected_child", Some(pid));
2709            drop(roster_guard);
2710            return Err(SuperviseError::Spawn {
2711                program: spec.program.clone(),
2712                source: io::Error::other(
2713                    "the daemon began shutting down during carried admission; ended the container",
2714                ),
2715                cgroup_path,
2716            });
2717        }
2718        // This child was never admitted, so there is no module protocol shutdown to wait for.
2719        #[cfg(target_os = "linux")]
2720        kill_module_cgroup(cgroup_placement, &cgroup_name);
2721        if let Err(error) = child.start_kill() {
2722            debug!(module_id = %spec.module_id, pid, %error, "kill of a process spawned during daemon shutdown failed; it may already have exited");
2723        }
2724        #[cfg(target_os = "linux")]
2725        if let Some(placement) = cgroup_placement.filter(|_| carried.is_none()) {
2726            // This spawn was never admitted, so shutdown has no roster entry
2727            // to await. Do not detach its cleanup: the runtime could exit
2728            // before that task reaps the rejected child and removes its group.
2729            while matches!(child.try_wait(), Ok(None)) {
2730                std::thread::yield_now();
2731            }
2732            if matches!(
2733                subc_cgroup::kill_module(Some(placement), &cgroup_name),
2734                subc_cgroup::KillOutcome::Killed
2735            ) {
2736                if let Ok(path) = placement.module_path(&cgroup_name) {
2737                    while std::fs::read_to_string(path.join("cgroup.events"))
2738                        .ok()
2739                        .is_some_and(|events| events.lines().any(|line| line == "populated 1"))
2740                    {
2741                        std::thread::yield_now();
2742                    }
2743                }
2744            }
2745            remove_module_cgroup(placement, &cgroup_name);
2746        }
2747        drop(roster_guard);
2748        return Err(SuperviseError::Spawn {
2749            program: spec.program.clone(),
2750            source: io::Error::other(
2751                "the daemon began shutting down while this process was starting; ended it",
2752            ),
2753            cgroup_path,
2754        });
2755    }
2756
2757    let pumps = crate::child_output::start(
2758        &mut child,
2759        output_sink,
2760        ring,
2761        &spec.module_id,
2762        #[cfg(unix)]
2763        plain_group.is_some(),
2764    );
2765
2766    let exec = Arc::new(crate::activity::ExecOutcome::new());
2767    #[cfg(target_os = "macos")]
2768    let pending_exec = privacy_exec.is_some();
2769    #[cfg(not(target_os = "macos"))]
2770    let pending_exec = false;
2771    if !pending_exec {
2772        exec.finish(crate::activity::ExecState::CommittedExec);
2773    }
2774    #[cfg(windows)]
2775    let subtree_target = job
2776        .as_ref()
2777        .map(|job| crate::subtree_resources::Target::Job(Arc::downgrade(job)))
2778        .unwrap_or(crate::subtree_resources::Target::Unavailable("no_job"));
2779    #[cfg(target_os = "linux")]
2780    let subtree_target = cgroup_path
2781        .map(crate::subtree_resources::Target::Cgroup)
2782        .unwrap_or(crate::subtree_resources::Target::Unavailable("no_cgroup"));
2783    #[cfg(not(any(target_os = "linux", windows)))]
2784    let subtree_target = crate::subtree_resources::Target::Unavailable("unsupported_platform");
2785    let mut supervised = SupervisedChild {
2786        registration_spawn,
2787        #[cfg(any(unix, windows))]
2788        registration_channel,
2789        live_program_binding: None,
2790        registered_config_connection: None,
2791        admission_base,
2792        registration_declaration,
2793        _program_binding: binding_publication,
2794        subtree_target,
2795        child: containment::ProcessChild::plain(child, pid),
2796        exec: crate::activity::ExecOwner(exec),
2797        #[cfg(windows)]
2798        nonce_delivery,
2799        protocol: spec.protocol,
2800        #[cfg(target_os = "linux")]
2801        module_id: cgroup_name,
2802        #[cfg(target_os = "linux")]
2803        cgroup_placement: cgroup_placement.cloned(),
2804        #[cfg(target_os = "linux")]
2805        unresolved_cgroup: None,
2806        #[cfg(windows)]
2807        job,
2808        stdout_pump: pumps.stdout,
2809        stderr_pump: pumps.stderr,
2810        #[cfg(unix)]
2811        capture_stop: pumps.stop,
2812        #[cfg(unix)]
2813        late_output_lost: false,
2814        stderr_ring: Arc::clone(ring),
2815        spawned_at,
2816        config_delivery,
2817        registration_deadline: None,
2818        registration_watch: None,
2819        spawned_at_ms,
2820        spawned_from,
2821        launch_spec_digest: LaunchSpecDigest::from_spec(spec),
2822        spawned_file_identity,
2823        process_start_time,
2824        process_identity,
2825        pid,
2826        roster_guard: Some(roster_guard),
2827        #[cfg(target_os = "macos")]
2828        privacy_exec,
2829        #[cfg(target_os = "macos")]
2830        report_ready: Arc::new(OnceLock::new()),
2831        spawn_failure: None,
2832        admission_kill_sent: false,
2833    };
2834    #[cfg(unix)]
2835    {
2836        supervised.child.plain_group = plain_group;
2837    }
2838    if let Err(error) = containment::adopt(&mut supervised, spec, roster) {
2839        supervised.child.reject(
2840            #[cfg(unix)]
2841            group_target,
2842        );
2843        #[cfg(all(test, unix))]
2844        let _ = roster.admission_event_for_test(&spec.module_id, "after_rejected_child", Some(pid));
2845        return Err(error);
2846    }
2847    if let (Some(launch), Some(owner), Some(base)) = (
2848        program_launch,
2849        config_owner,
2850        supervised.admission_base.clone(),
2851    ) {
2852        supervised.live_program_binding =
2853            content_binding::LiveProgramBinding::new(launch, &supervised, owner, base);
2854        if let (Some(publication), Some(live)) = (
2855            &supervised._program_binding,
2856            &supervised.live_program_binding,
2857        ) {
2858            publication.attach(live);
2859        }
2860    }
2861    #[cfg(unix)]
2862    if let Some(admitted) = admitted.take() {
2863        admitted.disarm();
2864    }
2865    #[cfg(windows)]
2866    if let Err(error) = resume_suspended_child(pid, spec) {
2867        containment::terminate_blocking(&roster.containment);
2868        let _ = supervised.child.start_kill();
2869        return Err(error);
2870    }
2871    if binding_ready {
2872        // An unreadable initial image is not a definite mismatch. Keep the
2873        // owned child and delivery registration until its reaped status decides
2874        // whether it crashed on its own or was stopped by admission's kill.
2875        let checked = if unavailable_initial_image {
2876            Err(crate::config_gate::GateError::new(
2877                "config_delivery_deferred",
2878                "initial process image is unavailable",
2879            ))
2880        } else {
2881            match (
2882                &supervised._program_binding,
2883                &supervised.live_program_binding,
2884            ) {
2885                (Some(binding), _) => binding.verify(),
2886                (None, Some(live)) => live.check(),
2887                _ if supervised.admission_base.is_some() => {
2888                    Err(crate::config_gate::GateError::new(
2889                        "config_delivery_deferred",
2890                        "live program witness is unavailable",
2891                    ))
2892                }
2893                _ => Ok(()),
2894            }
2895        };
2896        #[cfg(all(test, target_os = "linux"))]
2897        let checked = if roster.admission_event_for_test(
2898            &spec.module_id,
2899            "after_content_witness_check",
2900            Some(pid),
2901        ) {
2902            checked
2903        } else {
2904            Err(crate::config_gate::GateError::new(
2905                "config_delivery_deferred",
2906                "current process image is unavailable",
2907            ))
2908        };
2909        if let Err(error) = checked {
2910            if let Some(binding) = &mut supervised._program_binding {
2911                binding.reject();
2912            }
2913            // Reap through the normal child-reaping path, retaining the real exit record and
2914            // its roster ownership. A refusal must also end any helpers.
2915            if error.code == "program_refused" || supervised.try_wait().ok().flatten().is_none() {
2916                supervised.spawn_failure = Some(format!("{}: {}", error.code, error.detail));
2917                #[cfg(all(test, target_os = "linux"))]
2918                assert!(roster.admission_event_for_test(
2919                    &spec.module_id,
2920                    if unavailable_initial_image {
2921                        "before_initial_image_kill"
2922                    } else {
2923                        "before_content_witness_kill"
2924                    },
2925                    Some(pid),
2926                ));
2927                let _ = supervised.start_admission_kill();
2928                #[cfg(all(test, target_os = "linux"))]
2929                if supervised.admission_kill_sent {
2930                    assert!(roster.admission_event_for_test(
2931                        &spec.module_id,
2932                        "after_admission_kill_sent",
2933                        Some(pid),
2934                    ));
2935                }
2936            }
2937        }
2938    }
2939    if let Some(registration) = delivery_registration {
2940        registration.commit();
2941    }
2942    if let Some(spawn) = &supervised.registration_spawn {
2943        if let Some(identity) = supervised.process_identity {
2944            let _ = spawn.identity.set(identity);
2945        }
2946        if supervised.spawn_failure.is_some() {
2947            spawn.refuse();
2948        } else if binding_ready {
2949            spawn.ready();
2950        }
2951        #[cfg(any(unix, windows))]
2952        if let (Some(handle), Some(channel)) =
2953            (registration_handle, supervised.registration_channel.take())
2954        {
2955            handle.serve_registration(channel, spawn.clone(), pid, spawned_at + register_timeout);
2956        }
2957    }
2958    Ok(supervised)
2959}
2960
2961#[cfg(target_os = "linux")]
2962pub(crate) fn kill_module_cgroup(placement: Option<&subc_cgroup::Placement>, module_id: &str) {
2963    use subc_cgroup::KillOutcome;
2964    match subc_cgroup::kill_module(placement, module_id) {
2965        KillOutcome::Killed => {}
2966        KillOutcome::NotPlaced | KillOutcome::Unsupported => {
2967            debug!(
2968                module_id,
2969                "cgroup tree kill unavailable; using direct-child kill"
2970            );
2971        }
2972        KillOutcome::IoError { path, error } => {
2973            warn!(module_id, path = %path.display(), %error, "cgroup tree kill failed; using direct-child kill");
2974        }
2975    }
2976}
2977
2978/// Assign a freshly spawned Windows child without ever resuming on failure.
2979///
2980/// Steps 2 and 3 of the suspended-create contract: the job is created and the
2981/// child assigned **while it is still suspended** (step 1 is
2982/// `suspend_on_create_async` at the spawn site). The caller resumes only after
2983/// the child's roster admission is durable. Failed containment kills and reaps
2984/// the suspended child instead of running an unprotected module.
2985#[cfg(windows)]
2986fn contain_spawned_child(
2987    child: &mut Child,
2988    spec: &ModuleSpec,
2989    carried: Option<&Arc<containment::CarriedContainment>>,
2990) -> Result<Option<Arc<Mutex<subc_jobobject::JobObject>>>, SuperviseError> {
2991    let assignment = || {
2992        let job = match carried {
2993            Some(container) => container.job(),
2994            None => Arc::new(Mutex::new(subc_jobobject::JobObject::new()?)),
2995        };
2996        #[cfg(test)]
2997        spawn_record_tests::assignment_failpoint(spec)?;
2998        job.lock()
2999            .unwrap_or_else(|p| p.into_inner())
3000            .assign(child)?;
3001        Ok::<_, io::Error>(job)
3002    };
3003    match assignment() {
3004        Ok(job) => Ok(Some(job)),
3005        Err(source) => {
3006            kill_and_reap_rejected_child(child);
3007            Err(SuperviseError::Spawn {
3008                program: spec.program.clone(),
3009                source: io::Error::other(format!(
3010                    "Windows module job containment failed: {source}"
3011                )),
3012                cgroup_path: None,
3013            })
3014        }
3015    }
3016}
3017
3018/// Rejection is synchronous: do not return a spawn error while the child can
3019/// still run, or rely on kill-on-drop to reap it at some later runtime turn.
3020pub(super) fn kill_and_reap_rejected_child(
3021    child: &mut Child,
3022    #[cfg(unix)] group: containment::GroupTarget,
3023) {
3024    #[cfg(unix)]
3025    group.signal_rejected(child);
3026    let _ = child.start_kill();
3027    while matches!(child.try_wait(), Ok(None)) {
3028        std::thread::yield_now();
3029    }
3030}
3031
3032/// Resume a suspended child, killing it if it cannot be started.
3033///
3034/// A suspended process holds a pid and does nothing, so there is no useful
3035/// state to return: the caller gets an error and the spawn fails.
3036#[cfg(windows)]
3037fn resume_suspended_child(pid: u32, spec: &ModuleSpec) -> Result<(), SuperviseError> {
3038    if let Err(source) = subc_jobobject::resume_main_thread(pid) {
3039        // Kill it here rather than leaving a suspended process for the caller
3040        // to notice; `kill_on_drop` would eventually do this, but the module
3041        // would have been reported as running in between.
3042        let _ = subc_os::child_spawn::status(
3043            std::process::Command::new("taskkill.exe")
3044                .args(["/PID", &pid.to_string(), "/T", "/F"])
3045                .stdin(Stdio::null())
3046                .stdout(Stdio::null())
3047                .stderr(Stdio::null()),
3048        );
3049        return Err(SuperviseError::Spawn {
3050            program: spec.program.clone(),
3051            source,
3052            cgroup_path: None,
3053        });
3054    }
3055    Ok(())
3056}
3057
3058#[cfg(target_os = "linux")]
3059pub(super) fn remove_module_cgroup(placement: &subc_cgroup::Placement, module_id: &str) {
3060    match placement.remove_module(module_id) {
3061        Ok(()) => debug!(module_id, "removed module cgroup after process exit"),
3062        Err(error) => warn!(
3063            module_id,
3064            error = %error,
3065            "could not remove module cgroup after process exit; continuing teardown"
3066        ),
3067    }
3068}
3069
3070#[cfg(target_os = "linux")]
3071pub(super) fn apply_cgroup_placement(
3072    command: &mut Command,
3073    spec: &ModuleSpec,
3074    path: &std::path::Path,
3075) -> Result<(), SuperviseError> {
3076    subc_cgroup::apply(command, path).map_err(|source| SuperviseError::Cgroup {
3077        module_id: spec.module_id.clone(),
3078        source,
3079    })
3080}
3081
3082fn capture_retention(spec: &ModuleSpec) -> Retention {
3083    let defaults = Retention::default();
3084    let value = |name: &str| {
3085        spec.env
3086            .iter()
3087            .rev()
3088            .find_map(|(key, value)| (key == name).then_some(value.as_str()))
3089    };
3090    Retention {
3091        max_file_mb: value(CAPTURE_MAX_FILE_MB_ENV)
3092            .and_then(|value| value.parse().ok())
3093            .unwrap_or(defaults.max_file_mb),
3094        keep: value(CAPTURE_KEEP_ENV)
3095            .and_then(|value| value.parse().ok())
3096            .unwrap_or(defaults.keep),
3097        max_age_days: value(CAPTURE_MAX_AGE_DAYS_ENV)
3098            .and_then(|value| value.parse().ok())
3099            .unwrap_or(defaults.max_age_days),
3100    }
3101}
3102
3103/// A fresh 256-bit CSPRNG launch nonce, lowercase hex. Used to bind a reserved
3104/// module's registration to the exact process the supervisor spawned.
3105fn generate_launch_nonce() -> Result<String, SuperviseError> {
3106    let mut bytes = [0u8; 32];
3107    getrandom::getrandom(&mut bytes).map_err(|source| SuperviseError::LaunchNonce {
3108        reason: source.to_string(),
3109    })?;
3110    let mut hex = String::with_capacity(64);
3111    for b in bytes {
3112        use std::fmt::Write;
3113        let _ = write!(hex, "{b:02x}");
3114    }
3115    Ok(hex)
3116}
3117
3118/// The kernel's image after an acknowledged exec, shared by ordinary launches
3119/// and privacy trampolines. PATH and shebang interpretation are kernel facts,
3120/// not identities inferred from a configured pathname.
3121#[cfg(not(windows))]
3122pub(super) fn observe_spawned_image(pid: u32) -> Option<subc_os::Observation> {
3123    let process = subc_os::Process::open(pid).ok().flatten()?;
3124    #[cfg(target_os = "linux")]
3125    return sample_after_linux_exec(
3126        || {
3127            let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
3128            let committed = linux_exec_committed(&stat);
3129            #[cfg(test)]
3130            spawn_image_tests::report_exec_state(committed);
3131            committed
3132        },
3133        || process.observe(),
3134    );
3135    #[cfg(not(target_os = "linux"))]
3136    process.observe()
3137}
3138
3139/// glibc's posix_spawn parent can wake in exec_mmap before the child's new mm
3140/// is installed. PF_FORKNOEXEC is cleared later in begin_new_exec, after that
3141/// installation. Until it clears, /proc/pid/exe can still name the daemon.
3142#[cfg(target_os = "linux")]
3143pub(super) fn linux_exec_committed(stat: &str) -> Option<bool> {
3144    const PF_FORKNOEXEC: u64 = 0x40;
3145    let flags = stat.rsplit_once(')')?.1.split_whitespace().nth(6)?;
3146    Some(flags.parse::<u64>().ok()? & PF_FORKNOEXEC == 0)
3147}
3148
3149#[cfg(target_os = "linux")]
3150pub(super) fn sample_after_linux_exec(
3151    mut exec_committed: impl FnMut() -> Option<bool>,
3152    observe: impl FnOnce() -> Option<subc_os::Observation>,
3153) -> Option<subc_os::Observation> {
3154    let deadline = std::time::Instant::now() + Duration::from_secs(1);
3155    while !exec_committed()? {
3156        // A failed or indefinitely stalled exec must not publish the inherited
3157        // image as authority to signal a future orphan. Missing identity keeps
3158        // the existing conservative orphan-sweep behavior.
3159        if std::time::Instant::now() >= deadline {
3160            return None;
3161        }
3162        std::thread::sleep(Duration::from_micros(50));
3163    }
3164    observe()
3165}
3166
3167/// Resolve once and spawn that exact path, so PATH lookup cannot choose a
3168/// different executable after the no-delete capture was taken.
3169#[cfg(windows)]
3170pub(crate) fn windows_spawn_capture(spec: &ModuleSpec) -> io::Result<subc_os::ExecutableCapture> {
3171    if let Err(error) = require_program_search_path(spec) {
3172        return Err(match error {
3173            SuperviseError::Spawn { source, .. } => source,
3174            error => io::Error::other(error),
3175        });
3176    }
3177    let mut program = spec.program.clone();
3178    if program.is_absolute() || program.components().count() > 1 {
3179        // An explicit path can name a PE image with no extension. Try that
3180        // exact file first, as Command does, before falling back to .exe.
3181        match subc_os::ExecutableCapture::open(&program) {
3182            Ok(capture) => return Ok(capture),
3183            Err(error)
3184                if error.kind() == io::ErrorKind::NotFound && program.extension().is_none() => {}
3185            Err(error) => return Err(error),
3186        }
3187        program.set_extension("exe");
3188        return subc_os::ExecutableCapture::open(&program);
3189    }
3190    if program.extension().is_none() {
3191        program.set_extension("exe");
3192    }
3193    let custom_path = spec
3194        .env
3195        .iter()
3196        .rev()
3197        .find(|(key, _)| key.eq_ignore_ascii_case("PATH"));
3198    let mut directories = Vec::new();
3199    // These are Windows' default executable search locations. A configured
3200    // PATH still overrides the inherited PATH, not the system directories.
3201    if let Some(parent) = std::env::current_exe()?.parent() {
3202        directories.push(parent.to_path_buf());
3203    }
3204    directories.push(std::env::current_dir()?);
3205    if let Some(windows) = std::env::var_os("SystemRoot") {
3206        let windows = PathBuf::from(windows);
3207        directories.push(windows.join("System32"));
3208        directories.push(windows.clone());
3209    }
3210    let path = custom_path
3211        .map(|(_, value)| std::ffi::OsString::from(value))
3212        .or_else(|| std::env::var_os("PATH"));
3213    if let Some(path) = path {
3214        directories.extend(std::env::split_paths(&path));
3215    }
3216    for directory in directories {
3217        match subc_os::ExecutableCapture::open(&directory.join(&program)) {
3218            Ok(capture) => return Ok(capture),
3219            Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
3220            Err(error) => return Err(error),
3221        }
3222    }
3223    Err(io::Error::new(
3224        io::ErrorKind::NotFound,
3225        "resolved executable not found",
3226    ))
3227}
3228
3229#[cfg(test)]
3230pub(super) fn spawn_and_mark_running(
3231    spec: &ModuleSpec,
3232    runtime: &SupervisorRuntimeConfig,
3233    snapshot: &SharedSnapshot,
3234) -> Result<SupervisedChild, SuperviseError> {
3235    let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
3236    let registration_watch = watch_registration(&runtime.registry, spec);
3237    #[cfg(unix)]
3238    let joining_group = containment::current(&runtime.child_roster.containment)
3239        .is_some_and(|container| container.group().is_some());
3240    let spawn = || {
3241        spawn_child(
3242            spec,
3243            runtime.connection_file_path.as_deref(),
3244            runtime.supervisor_handle.as_ref(),
3245            &runtime.stderr_ring,
3246            runtime.capture_logs_dir.as_deref(),
3247            &runtime.child_roster,
3248            runtime.spawn_delivery(),
3249            #[cfg(target_os = "linux")]
3250            runtime.cgroup_placement.as_ref(),
3251            runtime.register_timeout,
3252        )
3253    };
3254    let result = spawn();
3255    #[cfg(unix)]
3256    let result = match result {
3257        Err(error)
3258            if joining_group
3259                && !is_launch_deferral(&error)
3260                && !runtime.child_roster.is_closed()
3261                && lock_snapshot(snapshot).is_ok_and(|state| state.enabled)
3262                && runtime
3263                    .child_roster
3264                    .previous_instance(&spec.module_id)
3265                    .is_none() =>
3266        {
3267            // The failed join already destroyed and verified the old container.
3268            // Try one fresh group as part of this same restart, without spending
3269            // another crash-budget entry. Cgroups and Windows jobs do not retry.
3270            warn!(module_id = %spec.module_id, %error, "carried process-group spawn failed; trying one fresh container");
3271            spawn()
3272        }
3273        other => other,
3274    };
3275    let child = result?;
3276    let mut child = child;
3277    arm_registration_deadline(&mut child, runtime.register_timeout, registration_watch);
3278    if let Err(error) = set_running(snapshot, &child, &spec.module_id, &runtime.spawn_events) {
3279        containment::terminate_blocking(&runtime.child_roster.containment);
3280        return Err(error);
3281    }
3282    if let Some(spawn) = activity_spawn {
3283        spawn.complete(snapshot);
3284    }
3285    Ok(child)
3286}
3287
3288pub(super) fn set_running(
3289    snapshot: &SharedSnapshot,
3290    child: &SupervisedChild,
3291    module_id: &str,
3292    spawn_events: &SpawnEventFeed,
3293) -> Result<(), SuperviseError> {
3294    let mut state = snapshot.lock().map_err(|_| SuperviseError::StatePoisoned {
3295        module_id: Some(module_id.to_string()),
3296    })?;
3297    state.spawn_generation = spawn_events.emit_spawned(
3298        module_id,
3299        child
3300            .registration_spawn
3301            .as_ref()
3302            .map(|spawn| spawn.authority.spawn_number()),
3303        child.pid,
3304        child.spawned_at_ms,
3305    );
3306    if std::mem::take(&mut state.coalesced_restart_pending) {
3307        let generation = state.spawn_generation;
3308        info!(module_id, "restart already satisfied by generation {generation}; coalesced pending request completed");
3309    }
3310    state.drain_disposition_detail = None;
3311    state.spawn_failure = None;
3312    state.admission_refused = None;
3313    state.config_hold_parked = false;
3314    state.config_hold_daemon_initiated = false;
3315    state.config_hold_approval = None;
3316    state.legacy_registration_spawn =
3317        child.registration_spawn.is_some() && child.admission_base.is_none();
3318    state.registration_declaration = child.registration_declaration.clone();
3319    state.stop_reason = None;
3320    state.config_exit_failed_approval = None;
3321    state.waiting_for_previous_pid = None;
3322    state.waiting_for_previous_detail = None;
3323    // Every caller of this is a plain spawn, which always uses the primary key;
3324    // a promoted swap candidate sets the flag itself after this returns.
3325    state.in_alternate_slot = false;
3326    state.configuration_updated_since_spawn = false;
3327    state.spawned_protocol = Some(child.protocol);
3328    state.state = ModuleState::Running;
3329    state.approved_start_failure = None;
3330    state.enabled = true;
3331    state.process_alive = true;
3332    state.pid = child.id();
3333    state.subtree_target = child.subtree_target.clone();
3334    // Probe samples belong to one process. Keep module-level escalation and
3335    // late-answer history, but never charge a new child for its predecessor's misses.
3336    state.health.status = SupervisorHealthStatus::Unknown;
3337    state.last_probe_evidence = None;
3338    state.health.consecutive_failures = 0;
3339    state.health.detail = None;
3340    state.health.metrics = None;
3341    state.health.last_probe_ms = None;
3342    state.failed_retry.healthy_since = None;
3343    state.failed_retry.failed_at = None;
3344    state.failed_retry.running_since = Some(child.spawned_at);
3345    #[cfg(windows)]
3346    {
3347        state.pipe_consumed = child
3348            .nonce_delivery
3349            .as_ref()
3350            .map(|delivery| delivery.consumed());
3351    }
3352    #[cfg(target_os = "macos")]
3353    {
3354        state.report_ready = Some(Arc::clone(&child.report_ready));
3355    }
3356    state.spawned_at_ms = Some(child.spawned_at_ms);
3357    state.exec_outcome = Some(Arc::clone(&child.exec.0));
3358    state.spawned_from = Some(child.spawned_from.clone());
3359    state.launch_spec_digest = Some(child.launch_spec_digest.clone());
3360    state.spawned_file_identity = child.spawned_file_identity.clone();
3361    state.process_start_time = child.process_start_time;
3362    Ok(())
3363}