Skip to main content

subc_daemon/supervise/
spawn.rs

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