Skip to main content

subc_daemon/
live_children.rs

1//! The live-children record and the boot-time orphan sweep.
2//!
3//! Supervised modules lead their own process groups (see `spawn_child_in_slot`),
4//! so when the daemon dies without running its shutdown stop (a crash, an OOM
5//! kill, SIGKILL) nothing ends the children that do not exit on EOF: every
6//! `protocol: "none"` child, which has no connection to see EOF on, and any
7//! module that ignores it. The next daemon would then start fresh copies
8//! beside them, fighting over ports and stores.
9//!
10//! So the daemon keeps a record, in its run directory, of every child in its
11//! roster: rewritten whole (temp file, then rename) on each admit and release,
12//! so a reader only ever sees a complete record. At boot, before any module is
13//! spawned, the boot-time sweep reads the previous daemon's record and ends every
14//! listed process that is still the process that was recorded.
15//!
16//! "Still the process that was recorded" is three checks, and a process that
17//! fails any of them is never signalled: the pid, the kernel's start time for
18//! it (a reaped pid can be reused by an unrelated process, which then has a
19//! later start time), and the device and inode of the image it is executing
20//! (which catches a reuse inside one start-time tick). The start time and
21//! image come from the `subc-os` crate, the only place those reads need unsafe
22//! code. On macOS, `/bin/sh` is a launcher that re-execs its selected shell;
23//! when recording that image, also retain the selected interpreter's identity.
24//! Matching never resolves the shell selection again after a crash or upgrade.
25//!
26//! On Windows the job object is the primary crash cleanup. The sweep is a
27//! fallback: only a matching creation time on a retained process handle permits
28//! a forced stop. An inaccessible process or reused PID is left alone.
29
30use std::{
31    collections::{BTreeMap, BTreeSet},
32    fs, io,
33    path::{Path, PathBuf},
34    sync::atomic::{AtomicU64, Ordering},
35    time::Duration,
36};
37
38use serde::{Deserialize, Serialize};
39use subc_control::ModuleProtocol;
40use tracing::{error, info, warn};
41
42use crate::run_dir_lock::RunDirLock;
43
44/// The record's file name inside the daemon run directory.
45pub(crate) const LIVE_CHILDREN_FILE_NAME: &str = "live-children.json";
46
47#[derive(Clone, Copy, Debug, Default)]
48pub(crate) enum ContainerEndReason {
49    DaemonShutdown,
50    Stop,
51    Disable,
52    CleanExit,
53    BudgetExhausted,
54    SpawnFailed,
55    #[default]
56    SupervisorFailure,
57    BootRecovery,
58}
59
60impl ContainerEndReason {
61    fn as_str(self) -> &'static str {
62        match self {
63            Self::DaemonShutdown => "daemon_shutdown",
64            Self::Stop => "stop",
65            Self::Disable => "disable",
66            Self::CleanExit => "clean_exit",
67            Self::BudgetExhausted => "budget_exhausted",
68            Self::SpawnFailed => "spawn_failed",
69            Self::SupervisorFailure => "supervisor_failure",
70            Self::BootRecovery => "boot_recovery",
71        }
72    }
73}
74
75#[derive(Debug, Default)]
76pub(crate) struct ContainerEnd {
77    pub(crate) reason: ContainerEndReason,
78    members: Option<(std::time::Instant, usize)>,
79    pub(crate) failed: bool,
80    signals: Vec<(std::time::Instant, &'static str)>,
81}
82
83impl ContainerEnd {
84    pub(crate) fn signal(&mut self, signal: &'static str) {
85        if self.signals.last().map(|&(_, last)| last) != Some(signal) {
86            self.signals.push((std::time::Instant::now(), signal));
87        }
88    }
89
90    #[cfg(unix)]
91    pub(crate) fn observe_members(&mut self, members: usize) {
92        // The first complete count is closest to the start of teardown.
93        self.members
94            .get_or_insert_with(|| (std::time::Instant::now(), members));
95    }
96
97    #[cfg(unix)]
98    pub(crate) fn merge(&mut self, other: Self) {
99        self.members = self.members.into_iter().chain(other.members).min();
100        self.failed |= other.failed;
101        self.signals.extend(other.signals);
102    }
103
104    pub(crate) fn log(&self, module_id: &str) {
105        let reason = self.reason.as_str();
106        let members = self
107            .members
108            .map_or_else(|| "unknown".into(), |(_, n)| n.to_string());
109        let signals = if self.signals.is_empty() {
110            "none".into()
111        } else {
112            // Shutdown can send KILL while container recovery is still waiting
113            // for members to respond to TERM.
114            let mut ordered = self.signals.clone();
115            ordered.sort_by_key(|&(at, _)| at);
116            let mut signals: Vec<_> = ordered.into_iter().map(|(_, signal)| signal).collect();
117            signals.dedup();
118            signals.join(",")
119        };
120        if self.failed {
121            warn!(%module_id, %reason, %members, %signals, "carried container teardown incomplete or signal failed");
122        } else {
123            info!(%module_id, %reason, %members, %signals, "ended a carried container");
124        }
125    }
126}
127
128/// Bumped on any change a previous daemon's reader would misread. A record
129/// with another version is not swept: nothing in it is trusted enough to
130/// signal on.
131const RECORD_VERSION: u32 = 2;
132
133/// The device and inode of the executable a child was recorded running.
134///
135/// On macOS, `/bin/sh` re-execs the shell `/private/var/select/sh` points to
136/// (see `man sh`), so a `#!/bin/sh` module's image changes once after launch.
137/// For that image only, the identity also records the selected shell, read at
138/// launch.
139#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
140pub struct ExecutableIdentity {
141    /// Device number on Unix; zero for a Windows file identity.
142    pub device: u64,
143    /// Inode number on Unix; zero for a Windows file identity.
144    pub inode: u64,
145    /// The selected shell for a `/bin/sh` image, read when the child was
146    /// recorded; the orphan check never looks it up again, so a selection
147    /// changed after a crash cannot make an unrelated process match. Absent on
148    /// every other image and in records written before this field existed,
149    /// which then match only the executable itself. Daemons that predate the
150    /// field ignore it when reading.
151    #[serde(default, skip_serializing_if = "Option::is_none")]
152    macos_sh_interpreter: Option<InterpreterIdentity>,
153    /// Older daemons reading version-1 `live-children.json` ignore unknown
154    /// executable fields, so adding this does not lose the roster on rollback.
155    /// Unix omits it, preserving its record bytes. Windows IDs stay here in full;
156    /// the legacy device/inode slots are zero, not a truncated Windows file ID.
157    #[serde(default, skip_serializing_if = "Option::is_none")]
158    windows_file_identity: Option<WindowsFileIdentity>,
159}
160
161#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
162struct WindowsFileIdentity {
163    volume_serial_number: u64,
164    file_id: [u8; 16],
165}
166
167#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
168struct InterpreterIdentity {
169    device: u64,
170    inode: u64,
171}
172
173impl From<subc_os::FileIdentity> for ExecutableIdentity {
174    fn from(identity: subc_os::FileIdentity) -> Self {
175        // This runs when the supervisor records a confirmed module image, so the
176        // shell selection is read at launch time, never at sweep time.
177        #[cfg(target_os = "macos")]
178        let macos_sh_interpreter = recorded_sh_interpreter(identity);
179        #[cfg(not(target_os = "macos"))]
180        let macos_sh_interpreter = None;
181        Self {
182            device: identity.device,
183            inode: identity.inode,
184            macos_sh_interpreter,
185            windows_file_identity: None,
186        }
187    }
188}
189
190#[cfg(windows)]
191impl From<subc_os::WindowsFileIdentity> for ExecutableIdentity {
192    fn from(identity: subc_os::WindowsFileIdentity) -> Self {
193        Self {
194            device: 0,
195            inode: 0,
196            macos_sh_interpreter: None,
197            windows_file_identity: Some(WindowsFileIdentity {
198                volume_serial_number: identity.volume_serial_number,
199                file_id: identity.file_id,
200            }),
201        }
202    }
203}
204
205#[cfg(target_os = "macos")]
206fn recorded_sh_interpreter(image: subc_os::FileIdentity) -> Option<InterpreterIdentity> {
207    if subc_os::file_identity(Path::new("/bin/sh")) != Some(image) {
208        return None;
209    }
210    // `man sh` names bash, dash and zsh as the only shells `/bin/sh` re-execs.
211    // Any other or missing selection records nothing extra, so the orphan check
212    // matches only `/bin/sh` itself.
213    let selected = fs::canonicalize("/private/var/select/sh").ok()?;
214    if !["/bin/bash", "/bin/dash", "/bin/zsh"]
215        .iter()
216        .any(|shell| selected == Path::new(shell))
217    {
218        return None;
219    }
220    let interpreter = subc_os::file_identity(&selected)?;
221    Some(InterpreterIdentity {
222        device: interpreter.device,
223        inode: interpreter.inode,
224    })
225}
226
227impl ExecutableIdentity {
228    fn matches(self, running: subc_os::FileIdentity) -> bool {
229        let direct = self.device == running.device && self.inode == running.inode;
230        #[cfg(target_os = "macos")]
231        let via_interpreter = self.macos_sh_interpreter.is_some_and(|interpreter| {
232            interpreter.device == running.device && interpreter.inode == running.inode
233        });
234        #[cfg(not(target_os = "macos"))]
235        let via_interpreter = false;
236        direct || via_interpreter
237    }
238}
239
240/// A container entry outlives its original leader and every launch generation.
241#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
242pub struct ContainerIdentity {
243    pub pgid: Option<u32>,
244    pub created_start_time: Option<u64>,
245    #[serde(default, skip_serializing_if = "Option::is_none")]
246    pub boot_id: Option<String>,
247    #[serde(default, skip_serializing_if = "Option::is_none")]
248    pub session_id: Option<u32>,
249    #[serde(default, skip_serializing_if = "Option::is_none")]
250    pub cgroup_path: Option<PathBuf>,
251}
252
253#[cfg(unix)]
254impl ContainerIdentity {
255    fn current_boot(&self) -> io::Result<bool> {
256        let current = subc_os::boot_id::is_current(self.boot_id.as_deref().ok_or_else(|| {
257            io::Error::new(
258                io::ErrorKind::InvalidData,
259                "recorded container has no boot identity",
260            )
261        })?)?;
262        if current && self.session_id.is_none() {
263            return Err(io::Error::new(
264                io::ErrorKind::InvalidData,
265                "recorded container has no session identity",
266            ));
267        }
268        Ok(current)
269    }
270
271    fn group(&self) -> io::Result<crate::group_recovery::RecordedGroup<'_>> {
272        let missing = || {
273            io::Error::new(
274                io::ErrorKind::InvalidData,
275                "recorded container has no complete boot, session and process-group identity",
276            )
277        };
278        Ok(crate::group_recovery::RecordedGroup {
279            pgid: self.pgid.ok_or_else(missing)?,
280            created_start_time: self.created_start_time.ok_or_else(missing)?,
281            boot_id: self.boot_id.as_deref().ok_or_else(missing)?,
282            session_id: self.session_id.ok_or_else(missing)?,
283        })
284    }
285
286    #[cfg(test)]
287    pub(crate) fn test_metadata() -> Self {
288        Self {
289            boot_id: Some(subc_os::boot_id::current().unwrap()),
290            session_id: subc_os::process_group::session_id(std::process::id()).unwrap(),
291            ..Self::default()
292        }
293    }
294}
295
296/// One roster entry as recorded on disk.
297#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
298pub struct LiveChild {
299    pub module_id: String,
300    pub pid: u32,
301    pub protocol: ModuleProtocol,
302    /// `subc_os::start_time` read right after spawn. `None` where the platform
303    /// has no source, and then the entry is never signalled.
304    pub start_time: Option<u64>,
305    /// The running image's device and inode, read after exec at spawn. This
306    /// includes PATH resolution and a script's interpreter. `None` if the image
307    /// could not be read, and then the entry is never signalled.
308    pub executable: Option<ExecutableIdentity>,
309    /// The child's cgroup directory name, when it was placed in one (Linux).
310    pub cgroup_name: Option<String>,
311    #[serde(default, skip_serializing_if = "Option::is_none")]
312    pub container: Option<ContainerIdentity>,
313}
314
315impl LiveChild {
316    /// Whether this row records a carried process-group container rather than
317    /// a module process. Such a row is written under the group's first module
318    /// process, whose pid is the group id.
319    pub(crate) fn is_group_container(&self) -> bool {
320        self.container
321            .as_ref()
322            .is_some_and(|container| container.pgid == Some(self.pid))
323    }
324}
325
326/// Daemon-private fields travel with the child's identity in the v2 record,
327/// but aren't part of the public inspection API.
328#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
329pub(crate) struct RecordedChild {
330    #[serde(flatten)]
331    pub(crate) child: LiveChild,
332    #[serde(
333        default,
334        skip_serializing_if = "Option::is_none",
335        deserialize_with = "read_resume_token_sha256"
336    )]
337    pub(crate) resume_token_sha256: Option<String>,
338}
339
340pub(crate) fn valid_resume_token_sha256(hash: &str) -> bool {
341    hash.len() == 64
342        && hash
343            .bytes()
344            .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
345}
346
347fn read_resume_token_sha256<'de, D: serde::Deserializer<'de>>(
348    deserializer: D,
349) -> Result<Option<String>, D::Error> {
350    // A damaged hash cannot resume a child, but must not prevent a cold start
351    // from using that child's process identity for orphan recovery.
352    Ok(match serde_json::Value::deserialize(deserializer)? {
353        serde_json::Value::String(hash) if valid_resume_token_sha256(&hash) => Some(hash),
354        _ => None,
355    })
356}
357
358#[derive(Debug, Serialize, Deserialize)]
359struct RecordFile<Child> {
360    version: u32,
361    children: Vec<Child>,
362    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
363    retained_reasons: BTreeMap<u32, RetainedReason>,
364}
365
366/// Replace the record at `path` with `children`.
367#[cfg(test)]
368pub(crate) fn write_record(path: &Path, children: &[LiveChild]) -> io::Result<()> {
369    write_record_with_reasons(path, children, BTreeMap::new())
370}
371
372pub(crate) fn write_record_with_reasons<Child: Serialize>(
373    path: &Path,
374    children: &[Child],
375    retained_reasons: BTreeMap<u32, RetainedReason>,
376) -> io::Result<()> {
377    let bytes = serde_json::to_vec_pretty(&RecordFile {
378        version: RECORD_VERSION,
379        children: children.iter().collect(),
380        retained_reasons,
381    })
382    .map_err(io::Error::other)?;
383    write_atomically(path, &bytes, |_| Ok(()))
384}
385
386/// Why a record could not be used.
387#[derive(Debug)]
388pub enum RecordReadError {
389    /// The file could not be read for a reason other than being absent.
390    Io(io::Error),
391    /// The contents could not be decoded as a roster record.
392    Malformed(serde_json::Error),
393    /// The record decoded, but its version is not supported.
394    UnknownVersion(u32),
395}
396
397impl std::fmt::Display for RecordReadError {
398    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
399        match self {
400            Self::Io(error) => write!(f, "could not read the record: {error}"),
401            Self::Malformed(error) => write!(f, "the record is not valid: {error}"),
402            Self::UnknownVersion(version) => {
403                write!(
404                    f,
405                    "the record has version {version}, expected {RECORD_VERSION}"
406                )
407            }
408        }
409    }
410}
411
412impl std::error::Error for RecordReadError {
413    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
414        match self {
415            Self::Io(error) => Some(error),
416            Self::Malformed(error) => Some(error),
417            Self::UnknownVersion(_) => None,
418        }
419    }
420}
421
422/// A snapshot of a decoded `live-children.json` record, not a liveness check.
423#[derive(Debug)]
424pub struct LiveChildrenRoster {
425    /// The version recorded on disk.
426    pub version: u32,
427    pub children: Vec<LiveChild>,
428    /// Reasons why entries were retained, keyed by pid.
429    pub retained_reasons: BTreeMap<u32, RetainedReason>,
430}
431
432/// Read the daemon's `live-children.json` at `path` without modifying it.
433///
434/// A missing file returns `Ok(None)`, distinct from a present roster with no
435/// children. Versions 1 and 2 are supported. This reader never sweeps processes
436/// or quarantines the record.
437///
438/// # Errors
439///
440/// Returns [`RecordReadError::Io`] for other read failures,
441/// [`RecordReadError::Malformed`] if the file cannot be decoded, or
442/// [`RecordReadError::UnknownVersion`] if it decodes with an unsupported version.
443pub fn read_live_children_roster(
444    path: &Path,
445) -> Result<Option<LiveChildrenRoster>, RecordReadError> {
446    let bytes = match fs::read(path) {
447        Ok(bytes) => bytes,
448        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
449        Err(error) => return Err(RecordReadError::Io(error)),
450    };
451    let record: RecordFile<LiveChild> =
452        serde_json::from_slice(&bytes).map_err(RecordReadError::Malformed)?;
453    if !matches!(record.version, 1 | 2) {
454        return Err(RecordReadError::UnknownVersion(record.version));
455    }
456    Ok(Some(LiveChildrenRoster {
457        version: record.version,
458        children: record.children,
459        retained_reasons: record.retained_reasons,
460    }))
461}
462
463/// The children listed at `path`. A missing file is an empty record: the
464/// previous daemon never spawned anything, or this is the first boot.
465#[cfg(test)]
466pub(crate) fn read_record(path: &Path) -> Result<Vec<LiveChild>, RecordReadError> {
467    read_record_with_reasons(path).map(|(children, _)| children)
468}
469
470#[cfg(test)]
471pub(crate) fn read_record_with_reasons(
472    path: &Path,
473) -> Result<(Vec<LiveChild>, BTreeMap<u32, RetainedReason>), RecordReadError> {
474    read_record_entries(path).map(|(children, reasons)| {
475        (
476            children.into_iter().map(|entry| entry.child).collect(),
477            reasons,
478        )
479    })
480}
481
482pub(crate) fn read_record_entries(
483    path: &Path,
484) -> Result<(Vec<RecordedChild>, BTreeMap<u32, RetainedReason>), RecordReadError> {
485    let bytes = match fs::read(path) {
486        Ok(bytes) => bytes,
487        Err(error) if error.kind() == io::ErrorKind::NotFound => {
488            return Ok((Vec::new(), BTreeMap::new()))
489        }
490        Err(error) => return Err(RecordReadError::Io(error)),
491    };
492    let record: RecordFile<RecordedChild> =
493        serde_json::from_slice(&bytes).map_err(RecordReadError::Malformed)?;
494    if !matches!(record.version, 1 | RECORD_VERSION) {
495        return Err(RecordReadError::UnknownVersion(record.version));
496    }
497    Ok((record.children, record.retained_reasons))
498}
499
500/// Preserve an unusable record as a durable fail-closed marker. Only offline
501/// administration may remove it after establishing that no old module processes
502/// or helpers remain.
503pub(crate) fn quarantine_record(path: &Path, error: &RecordReadError) -> io::Result<PathBuf> {
504    quarantine_record_named(path, error, "", false)
505}
506
507#[cfg(unix)]
508pub(crate) fn quarantine_failed_admission(
509    path: &Path,
510    reason: &str,
511    source: &io::Error,
512) -> io::Result<PathBuf> {
513    // The filename remains the durable marker. Keep a readable cause there as
514    // well, so a restart can explain the failure without modifying the evidence.
515    let label: String = source
516        .to_string()
517        .chars()
518        .take(96)
519        .map(|character| {
520            if character.is_ascii_alphanumeric() || character == '-' {
521                character
522            } else {
523                '_'
524            }
525        })
526        .collect();
527    let suffix = format!(".failed-late-admission-write.{label}");
528    quarantine_record_named(
529        path,
530        &RecordReadError::Io(io::Error::other(reason)),
531        &suffix,
532        true,
533    )
534}
535
536fn quarantine_record_named(
537    path: &Path,
538    error: &RecordReadError,
539    suffix: &str,
540    allow_missing: bool,
541) -> io::Result<PathBuf> {
542    static SEQUENCE: AtomicU64 = AtomicU64::new(0);
543    let directory = path.parent().unwrap_or_else(|| Path::new("."));
544    let name = path.file_name().unwrap_or_default().to_string_lossy();
545    loop {
546        let quarantine = directory.join(format!(
547            "{name}.quarantined.{}.{}{suffix}",
548            std::process::id(),
549            SEQUENCE.fetch_add(1, Ordering::Relaxed)
550        ));
551        match fs::symlink_metadata(&quarantine) {
552            Ok(_) => continue,
553            Err(found) if found.kind() == io::ErrorKind::NotFound => {}
554            Err(found) => return Err(found),
555        }
556        // The daemon owns the run-directory lock. Never replace a quarantine
557        // from an earlier boot, even if its PID and sequence were reused.
558        match replace_record(path, &quarantine, directory) {
559            Err(found) if allow_missing && found.kind() == io::ErrorKind::NotFound => {
560                // A failed first write may have left no original record. There
561                // is then no evidence to rename, but absence must not erase the
562                // failure marker at the next daemon start.
563                use std::io::Write;
564                let mut marker = fs::OpenOptions::new()
565                    .write(true)
566                    .create_new(true)
567                    .open(&quarantine)?;
568                writeln!(marker, "{error}")?;
569                marker.sync_all()?;
570                #[cfg(unix)]
571                fs::File::open(directory)?.sync_all()?;
572            }
573            result => result?,
574        }
575        error!(path = %path.display(), quarantine = %quarantine.display(), %error,
576            "live-children record quarantined; carried modules remain blocked until offline clearance");
577        return Ok(quarantine);
578    }
579}
580
581pub(crate) fn quarantine_block(path: &Path) -> Option<String> {
582    let directory = path.parent().unwrap_or_else(|| Path::new("."));
583    let name = path.file_name().unwrap_or_default().to_string_lossy();
584    let prefix = format!("{name}.quarantined.");
585    let entries = match fs::read_dir(directory) {
586        Ok(entries) => entries,
587        Err(error) if error.kind() == io::ErrorKind::NotFound => return None,
588        Err(error) => return Some(format!("cannot verify recovery quarantines: {error}")),
589    };
590    for entry in entries {
591        let entry = match entry {
592            Ok(entry) => entry,
593            Err(error) => return Some(format!("cannot verify recovery quarantines: {error}")),
594        };
595        if entry.file_name().to_string_lossy().starts_with(&prefix) {
596            let cause = if entry
597                .file_name()
598                .to_string_lossy()
599                .contains(".failed-late-admission-write.")
600            {
601                "failed late admission write; "
602            } else {
603                ""
604            };
605            return Some(format!(
606                "{cause}unknown previous container identity: quarantined recovery record {}; offline clearance is required",
607                entry.path().display()
608            ));
609        }
610    }
611    None
612}
613
614/// Write `bytes` to a new file beside `path`, then rename it over `path`.
615///
616/// Rename within one directory is atomic, so `path` always holds either the
617/// previous complete record or the new one, never a prefix, whenever the
618/// daemon dies. `before_rename` runs between the two steps; it exists so a
619/// test can fail the write at that point. Sync the file before replacement and
620/// the containing directory afterwards so successful admission is durable.
621fn write_atomically(
622    path: &Path,
623    bytes: &[u8],
624    before_rename: impl FnOnce(&Path) -> io::Result<()>,
625) -> io::Result<()> {
626    static SEQUENCE: AtomicU64 = AtomicU64::new(0);
627    let directory = path.parent().unwrap_or_else(|| Path::new("."));
628    fs::create_dir_all(directory)?;
629    let file_name = path
630        .file_name()
631        .map(|name| name.to_string_lossy().into_owned())
632        .unwrap_or_else(|| LIVE_CHILDREN_FILE_NAME.to_owned());
633    let temp = directory.join(format!(
634        ".{file_name}.{}.{}.tmp",
635        std::process::id(),
636        SEQUENCE.fetch_add(1, Ordering::Relaxed)
637    ));
638    let result = write_new_owner_only(&temp, bytes)
639        .and_then(|()| before_rename(&temp))
640        .and_then(|()| replace_record(&temp, path, directory));
641    if result.is_err() {
642        let _ = fs::remove_file(&temp);
643    }
644    result
645}
646
647fn replace_record(temp: &Path, path: &Path, directory: &Path) -> io::Result<()> {
648    #[cfg(windows)]
649    {
650        let _ = directory;
651        // The temp file's bytes were synced before this point. Plain rename
652        // (MoveFileExW with replace) is used rather than a write-through
653        // replace helper because it succeeds while another process holds the
654        // destination open with the default share mode, which a concurrent
655        // reader of this record does. Windows has no directory fsync.
656        fs::rename(temp, path)
657    }
658    #[cfg(not(windows))]
659    {
660        fs::rename(temp, path)?;
661        #[cfg(unix)]
662        fs::File::open(directory)?.sync_all()?;
663        Ok(())
664    }
665}
666
667#[cfg(test)]
668thread_local! {
669    static FAIL_NEXT_FILE_SYNC: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
670}
671
672#[cfg(test)]
673pub(crate) fn fail_next_file_sync() {
674    FAIL_NEXT_FILE_SYNC.set(true);
675}
676
677fn write_new_owner_only(path: &Path, bytes: &[u8]) -> io::Result<()> {
678    use std::io::Write;
679
680    let mut options = fs::OpenOptions::new();
681    options.write(true).create_new(true);
682    #[cfg(unix)]
683    {
684        use std::os::unix::fs::OpenOptionsExt;
685        // Pids and module ids of a user's processes: nobody else's business.
686        options.mode(0o600);
687    }
688    let mut file = options.open(path)?;
689    file.write_all(bytes)?;
690    #[cfg(test)]
691    if FAIL_NEXT_FILE_SYNC.replace(false) {
692        return Err(io::Error::other("injected live-children file sync failure"));
693    }
694    file.sync_all()
695}
696
697/// Children owned by the new daemon image after a handover. The orphan sweep
698/// must leave both verified adoptees and unresolved children alone.
699#[derive(Debug, Clone, Default)]
700pub(crate) struct AdoptedPids {
701    adopted: BTreeSet<u32>,
702    held: BTreeSet<u32>,
703}
704
705#[derive(Debug, Clone, Copy, PartialEq, Eq)]
706pub(crate) enum ProtectedChild {
707    Adopted,
708    Held,
709}
710
711impl AdoptedPids {
712    pub(crate) fn none() -> Self {
713        Self::default()
714    }
715
716    // The startup adoption path supplies the two sets after reconciliation.
717    #[allow(dead_code)]
718    pub(crate) fn from_classes(
719        adopted: impl IntoIterator<Item = u32>,
720        held: impl IntoIterator<Item = u32>,
721    ) -> Self {
722        Self {
723            adopted: adopted.into_iter().collect(),
724            held: held.into_iter().collect(),
725        }
726    }
727
728    pub(crate) fn protection(&self, pid: u32) -> Option<ProtectedChild> {
729        // If a caller lists a PID in both sets, keep the stricter protection.
730        if self.held.contains(&pid) {
731            Some(ProtectedChild::Held)
732        } else if self.adopted.contains(&pid) {
733            Some(ProtectedChild::Adopted)
734        } else {
735            None
736        }
737    }
738}
739
740/// Whether a live process is the one a record entry describes.
741// Only the Linux and macOS sweep compares identities and signals; elsewhere
742// the record is logged and these go unused.
743#[cfg_attr(not(any(target_os = "linux", target_os = "macos")), allow(dead_code))]
744#[derive(Debug, Clone, Copy, PartialEq, Eq)]
745pub(crate) enum IdentityVerdict {
746    Matches,
747    #[cfg(target_os = "linux")]
748    MatchesWithExecutablePermissionDenied,
749    #[cfg(target_os = "linux")]
750    ProcessHidden,
751    PidDiffers,
752    StartTimeUnrecorded,
753    StartTimeDiffers,
754    ExecutableUnrecorded,
755    ExecutableUnreadable,
756    ExecutableDiffers,
757}
758
759impl IdentityVerdict {
760    #[cfg_attr(not(any(target_os = "linux", target_os = "macos")), allow(dead_code))]
761    fn permits_signal(self) -> bool {
762        match self {
763            Self::Matches => true,
764            #[cfg(target_os = "linux")]
765            Self::MatchesWithExecutablePermissionDenied => true,
766            _ => false,
767        }
768    }
769
770    fn describe(self) -> &'static str {
771        match self {
772            Self::Matches => "matches",
773            #[cfg(target_os = "linux")]
774            Self::MatchesWithExecutablePermissionDenied => {
775                "pid and start time match; executable not readable (non-dumpable)"
776            }
777            #[cfg(target_os = "linux")]
778            Self::ProcessHidden => "process still exists but its procfs entry is hidden",
779            Self::PidDiffers => "the observed process has another pid",
780            Self::StartTimeUnrecorded => "no start time was recorded at spawn",
781            Self::StartTimeDiffers => {
782                "the pid now belongs to a process with another start time (pid reused)"
783            }
784            Self::ExecutableUnrecorded => "no executable identity was recorded at spawn",
785            Self::ExecutableUnreadable => "the process's executable could not be read",
786            Self::ExecutableDiffers => "the process is running another executable",
787        }
788    }
789
790    fn refusal(self) -> SweepDecision {
791        match self {
792            Self::PidDiffers | Self::StartTimeDiffers | Self::ExecutableDiffers => {
793                SweepDecision::Mismatched(self)
794            }
795            _ => SweepDecision::Unverifiable(self.describe().to_owned()),
796        }
797    }
798}
799
800/// Compare a record entry with what is running at `observed_pid` now. Only
801/// [`IdentityVerdict::Matches`] permits a signal; a field the record lacks or
802/// the platform cannot read refuses, like a field that differs.
803#[cfg_attr(not(any(target_os = "linux", target_os = "macos")), allow(dead_code))]
804pub(crate) fn identity_verdict(
805    recorded: &LiveChild,
806    observed_pid: u32,
807    observed: &subc_os::Observation,
808) -> IdentityVerdict {
809    if observed_pid != recorded.pid {
810        return IdentityVerdict::PidDiffers;
811    }
812    let Some(start_time) = recorded.start_time else {
813        return IdentityVerdict::StartTimeUnrecorded;
814    };
815    if observed.start_time != start_time {
816        return IdentityVerdict::StartTimeDiffers;
817    }
818    let Some(executable) = recorded.executable else {
819        return IdentityVerdict::ExecutableUnrecorded;
820    };
821    let Some(running) = observed.executable else {
822        return IdentityVerdict::ExecutableUnreadable;
823    };
824    if !executable.matches(running) {
825        return IdentityVerdict::ExecutableDiffers;
826    }
827    IdentityVerdict::Matches
828}
829
830/// What the sweep did with one record entry.
831#[cfg_attr(not(any(target_os = "linux", target_os = "macos")), allow(dead_code))]
832#[derive(Debug, Clone, PartialEq, Eq)]
833pub(crate) enum SweepDecision {
834    /// Claimed by a handover; left running.
835    Adopted,
836    /// Still owned but not verified at handover; left unsignalled.
837    Held,
838    /// No process holds the pid any more, or it has exited.
839    Gone,
840    /// Something holds the pid, but not the recorded process; not signalled.
841    Mismatched(IdentityVerdict),
842    /// The process could not be inspected; not signalled.
843    Unverifiable(String),
844    #[cfg(target_os = "linux")]
845    AliveButUnobservable,
846    /// Matched; exited after SIGTERM.
847    Terminated,
848    /// Matched; still running at the SIGTERM grace, exited after SIGKILL.
849    Killed,
850    /// Windows forced stop, confirmed by waiting on the checked process handle.
851    #[cfg(windows)]
852    ForcedStopped,
853    /// Matched and signalled, but still observed at the end of the bound.
854    Survived,
855    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
856    ContainerSurvivors(Vec<u32>),
857    #[cfg(target_os = "linux")]
858    EmptyContainerDirectory,
859    /// No process identity source on this platform; not signalled.
860    #[cfg_attr(any(target_os = "linux", target_os = "macos"), allow(dead_code))]
861    NotSignalledOnThisPlatform,
862}
863
864/// Why a previous instance remains recorded. An empty directory awaiting
865/// removal is housekeeping only and does not prevent a fresh instance.
866/// Kept separately from identity evidence so it can never authorize a signal.
867#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
868#[serde(rename_all = "snake_case")]
869pub enum RetainedReason {
870    Hidden,
871    Unverifiable,
872    Survived,
873    ContainerSurvivors(Vec<u32>),
874    ContainerUnverifiable(String),
875    EmptyContainerDirectory,
876}
877
878impl RetainedReason {
879    pub(crate) fn blocks_fresh_copy(&self) -> bool {
880        !matches!(self, Self::EmptyContainerDirectory)
881    }
882
883    pub(crate) fn waiting_message(&self, pid: u32) -> String {
884        let reason = match self {
885            Self::Hidden => "is still running but hidden; it cannot be identified",
886            Self::Unverifiable => "is still running but could not be verified",
887            Self::Survived => "did not stop",
888            Self::ContainerSurvivors(pids) => {
889                return format!("waiting: container survivors (pids {pids:?})")
890            }
891            Self::ContainerUnverifiable(error) => {
892                return format!("waiting: container survivors could not be verified: {error}")
893            }
894            Self::EmptyContainerDirectory => {
895                return "container stopped; directory removal pending".into()
896            }
897        };
898        format!("waiting: previous instance (pid {pid}) {reason}")
899    }
900}
901
902#[cfg(unix)]
903pub(crate) fn recheck_container(
904    entry: &LiveChild,
905    #[cfg(target_os = "linux")] placement: Option<&subc_cgroup::Placement>,
906) -> Option<RetainedReason> {
907    let container = entry.container.as_ref()?;
908    match container.current_boot() {
909        Ok(false) => return None,
910        Ok(true) => {}
911        Err(error) => return Some(RetainedReason::ContainerUnverifiable(error.to_string())),
912    }
913    #[cfg(target_os = "linux")]
914    if let Some(path) = &container.cgroup_path {
915        return crate::cgroup_recovery::recheck(placement, path);
916    }
917    match container.group() {
918        Ok(group) => crate::group_recovery::recheck(group),
919        Err(error) => Some(RetainedReason::ContainerUnverifiable(error.to_string())),
920    }
921}
922
923impl SweepDecision {
924    fn is_protected(&self) -> bool {
925        matches!(self, Self::Adopted | Self::Held)
926    }
927
928    pub(crate) fn retained_reason(&self) -> Option<RetainedReason> {
929        match self {
930            #[cfg(target_os = "linux")]
931            Self::EmptyContainerDirectory => Some(RetainedReason::EmptyContainerDirectory),
932            #[cfg(target_os = "linux")]
933            Self::AliveButUnobservable => Some(RetainedReason::Hidden),
934            Self::Unverifiable(_) => Some(RetainedReason::Unverifiable),
935            Self::Survived => Some(RetainedReason::Survived),
936            Self::ContainerSurvivors(pids) => {
937                Some(RetainedReason::ContainerSurvivors(pids.clone()))
938            }
939            _ => None,
940        }
941    }
942}
943
944/// How long the sweep waits after each signal.
945#[cfg_attr(not(any(target_os = "linux", target_os = "macos")), allow(dead_code))]
946#[derive(Debug, Clone, Copy)]
947pub(crate) struct SweepBounds {
948    /// Between SIGTERM and SIGKILL. An orphan's daemon is already gone, so
949    /// this only has to let a module finish a clean exit (flush, remove its
950    /// socket) that a SIGKILL would skip; it also delays boot, but only when
951    /// there is an orphan to end.
952    pub(crate) term_grace: Duration,
953    /// After SIGKILL. SIGKILL cannot be ignored, so this covers scheduling
954    /// and the orphan's new parent reaping it.
955    pub(crate) kill_bound: Duration,
956}
957
958impl Default for SweepBounds {
959    fn default() -> Self {
960        Self {
961            term_grace: Duration::from_secs(2),
962            kill_bound: Duration::from_secs(1),
963        }
964    }
965}
966
967#[cfg_attr(not(any(target_os = "linux", target_os = "macos")), allow(dead_code))]
968const POLL: Duration = Duration::from_millis(20);
969
970/// End every process the previous daemon's record lists that is still
971/// exactly the process recorded, except those in `adopted`, then replace the
972/// record with protected children and instances that could not be verified or
973/// stopped. Runs before any module is spawned.
974///
975/// The record is the one in the run directory `owner` locks. Requiring the
976/// lock means the record cannot belong to a daemon that is still running:
977/// such a daemon would hold the lock itself.
978///
979/// Every entry is logged with its decision. Returns the decisions for tests.
980#[cfg(any(test, not(target_os = "linux")))]
981pub(crate) async fn sweep_orphans(
982    owner: &RunDirLock,
983    adopted: &AdoptedPids,
984    bounds: SweepBounds,
985) -> Vec<(LiveChild, SweepDecision)> {
986    sweep_orphans_with(owner, adopted, bounds, sweep_entries).await
987}
988
989#[cfg(target_os = "linux")]
990pub(crate) async fn sweep_orphans_with_placement(
991    owner: &RunDirLock,
992    adopted: &AdoptedPids,
993    bounds: SweepBounds,
994    placement: Option<&subc_cgroup::Placement>,
995) -> Vec<(LiveChild, SweepDecision)> {
996    sweep_orphans_with(owner, adopted, bounds, |entries, bounds| async move {
997        let mut decisions = Vec::new();
998        let mut other = Vec::new();
999        for entry in entries {
1000            if let Some(container) = &entry.child.container {
1001                let decision = match container.current_boot() {
1002                    Ok(false) => Some(SweepDecision::Gone),
1003                    Ok(true) => None,
1004                    Err(error) => Some(SweepDecision::Unverifiable(error.to_string())),
1005                };
1006                if let Some(decision) = decision {
1007                    decisions.push((entry, decision));
1008                    continue;
1009                }
1010            }
1011            if let Some(path) = entry
1012                .child
1013                .container
1014                .as_ref()
1015                .and_then(|container| container.cgroup_path.as_ref())
1016            {
1017                let mut end = ContainerEnd {
1018                    reason: ContainerEndReason::BootRecovery,
1019                    ..Default::default()
1020                };
1021                let decision =
1022                    crate::cgroup_recovery::sweep(placement, path, bounds, &mut end).await;
1023                if !matches!(decision, SweepDecision::Gone) || end.members.is_some() {
1024                    end.failed |= matches!(
1025                        decision,
1026                        SweepDecision::Unverifiable(_) | SweepDecision::ContainerSurvivors(_)
1027                    );
1028                    end.log(&entry.child.module_id);
1029                }
1030                decisions.push((entry, decision));
1031            } else {
1032                other.push(entry);
1033            }
1034        }
1035        decisions.extend(sweep_entries(other, bounds).await);
1036        decisions
1037    })
1038    .await
1039}
1040
1041async fn sweep_orphans_with<F, Fut>(
1042    owner: &RunDirLock,
1043    adopted: &AdoptedPids,
1044    bounds: SweepBounds,
1045    sweep: F,
1046) -> Vec<(LiveChild, SweepDecision)>
1047where
1048    F: FnOnce(Vec<RecordedChild>, SweepBounds) -> Fut,
1049    Fut: std::future::Future<Output = Vec<(RecordedChild, SweepDecision)>>,
1050{
1051    let path = owner.live_children_record();
1052    let (entries, previous_reasons) = match read_record_entries(path) {
1053        Ok(entries) => entries,
1054        Err(error) => {
1055            let quarantine = quarantine_record(path, &error);
1056            error!(
1057                path = %path.display(),
1058                %error,
1059                ?quarantine,
1060                "live-children record unusable; no orphan sweep, nothing signalled; carried modules must remain blocked"
1061            );
1062            // Do not reset an unreadable identity to an empty record. A failed
1063            // rename leaves the original evidence in place for the next boot.
1064            return Vec::new();
1065        }
1066    };
1067    // A Held child has no verified identity. Filter it out before passing any
1068    // entries to platform recovery, which may inspect or signal containers.
1069    let mut decisions = Vec::new();
1070    let mut orphans = Vec::new();
1071    for entry in entries {
1072        match adopted.protection(entry.child.pid) {
1073            Some(ProtectedChild::Adopted) => decisions.push((entry, SweepDecision::Adopted)),
1074            Some(ProtectedChild::Held) => decisions.push((entry, SweepDecision::Held)),
1075            None => orphans.push(entry),
1076        }
1077    }
1078    decisions.extend(sweep(orphans, bounds).await);
1079    for (entry, decision) in &decisions {
1080        log_decision(&entry.child, decision);
1081    }
1082    let retained: Vec<_> = decisions
1083        .iter()
1084        .filter(|(_, decision)| decision.is_protected() || decision.retained_reason().is_some())
1085        .map(|(entry, _)| entry.clone())
1086        .collect();
1087    let reasons = decisions
1088        .iter()
1089        .filter_map(|(entry, decision)| {
1090            let reason = match decision {
1091                SweepDecision::Unverifiable(error) if entry.child.container.is_some() => {
1092                    Some(RetainedReason::ContainerUnverifiable(error.clone()))
1093                }
1094                _ if decision.is_protected() => previous_reasons.get(&entry.child.pid).cloned(),
1095                _ => decision.retained_reason(),
1096            };
1097            reason.map(|reason| (entry.child.pid, reason))
1098        })
1099        .collect();
1100    if let Err(error) = write_record_with_reasons(path, &retained, reasons) {
1101        warn!(path = %path.display(), %error, "could not reset the live-children record after the orphan sweep");
1102    }
1103    decisions
1104        .into_iter()
1105        .map(|(entry, decision)| (entry.child, decision))
1106        .collect()
1107}
1108
1109#[cfg(any(target_os = "linux", target_os = "macos"))]
1110async fn sweep_entries(
1111    entries: Vec<RecordedChild>,
1112    bounds: SweepBounds,
1113) -> Vec<(RecordedChild, SweepDecision)> {
1114    sweep_entries_with_verdict(entries, bounds, current_verdict).await
1115}
1116
1117#[cfg(any(target_os = "linux", target_os = "macos"))]
1118async fn sweep_entries_with_verdict(
1119    entries: Vec<RecordedChild>,
1120    bounds: SweepBounds,
1121    verdict_for: impl Fn(&LiveChild, &subc_os::Process) -> Option<IdentityVerdict>,
1122) -> Vec<(RecordedChild, SweepDecision)> {
1123    sweep_entries_with_hooks(entries, bounds, verdict_for, |process, signal| {
1124        process.signal(signal)
1125    })
1126    .await
1127}
1128
1129#[cfg(any(target_os = "linux", target_os = "macos"))]
1130async fn sweep_entries_with_hooks(
1131    entries: Vec<RecordedChild>,
1132    bounds: SweepBounds,
1133    verdict_for: impl Fn(&LiveChild, &subc_os::Process) -> Option<IdentityVerdict>,
1134    signal: impl Fn(&subc_os::Process, subc_os::Signal) -> io::Result<bool>,
1135) -> Vec<(RecordedChild, SweepDecision)> {
1136    use subc_os::{Process, Signal};
1137    use tokio::time::{sleep, Instant};
1138
1139    let mut decisions = Vec::new();
1140    let mut signalled = Vec::new();
1141    for entry in entries {
1142        if let Some(container) = &entry.child.container {
1143            let mut end = ContainerEnd {
1144                reason: ContainerEndReason::BootRecovery,
1145                ..Default::default()
1146            };
1147            let decision = match container.current_boot() {
1148                Ok(false) => SweepDecision::Gone,
1149                Err(error) => SweepDecision::Unverifiable(error.to_string()),
1150                Ok(true) => match container.group() {
1151                    Ok(group) => crate::group_recovery::sweep(group, bounds, &mut end).await,
1152                    Err(error) => SweepDecision::Unverifiable(error.to_string()),
1153                },
1154            };
1155            if !matches!(decision, SweepDecision::Gone) {
1156                end.failed |= matches!(decision, SweepDecision::Unverifiable(_));
1157                end.log(&entry.child.module_id);
1158            }
1159            decisions.push((entry, decision));
1160            continue;
1161        }
1162        // Opened before any check, so on Linux the checks and the signal
1163        // below all refer to one process through its pidfd.
1164        let process = match Process::open(entry.child.pid) {
1165            Ok(Some(process)) => process,
1166            Ok(None) => {
1167                decisions.push((entry, SweepDecision::Gone));
1168                continue;
1169            }
1170            Err(error) => {
1171                decisions.push((entry, SweepDecision::Unverifiable(error.to_string())));
1172                continue;
1173            }
1174        };
1175        match verdict_for(&entry.child, &process) {
1176            None => decisions.push((entry, SweepDecision::Gone)),
1177            #[cfg(target_os = "linux")]
1178            Some(IdentityVerdict::ProcessHidden) => {
1179                decisions.push((entry, SweepDecision::AliveButUnobservable))
1180            }
1181            Some(verdict) if verdict.permits_signal() => {
1182                let result = signal(&process, Signal::Terminate);
1183                #[cfg(target_os = "linux")]
1184                if verdict == IdentityVerdict::MatchesWithExecutablePermissionDenied {
1185                    info!(
1186                        module_id = %entry.child.module_id,
1187                        pid = entry.child.pid,
1188                        pidfd = process.signals_through_pidfd(),
1189                        "orphan sweep: pid and start time matched; executable not readable (non-dumpable); requested SIGTERM"
1190                    );
1191                } else {
1192                    info!(
1193                        module_id = %entry.child.module_id,
1194                        pid = entry.child.pid,
1195                        pidfd = process.signals_through_pidfd(),
1196                        "orphan sweep: previous daemon's child matched pid, start time and executable; requested SIGTERM"
1197                    );
1198                }
1199                #[cfg(not(target_os = "linux"))]
1200                info!(
1201                    module_id = %entry.child.module_id,
1202                    pid = entry.child.pid,
1203                    pidfd = process.signals_through_pidfd(),
1204                    "orphan sweep: previous daemon's child matched pid, start time and executable; requested SIGTERM"
1205                );
1206                match result {
1207                    Ok(true) => signalled.push((entry, process)),
1208                    // It exited between the check and the signal.
1209                    Ok(false) => decisions.push((entry, SweepDecision::Gone)),
1210                    Err(error) => {
1211                        decisions.push((entry, SweepDecision::Unverifiable(error.to_string())))
1212                    }
1213                }
1214            }
1215            Some(verdict) => decisions.push((entry, verdict.refusal())),
1216        }
1217    }
1218
1219    let departed = |entry: &LiveChild, process: &Process, exited| {
1220        let verdict = verdict_for(entry, process);
1221        #[cfg(target_os = "linux")]
1222        if verdict == Some(IdentityVerdict::ProcessHidden) {
1223            return Some(SweepDecision::AliveButUnobservable);
1224        }
1225        // This process was verified before it was signalled, so a positive
1226        // mismatch now means the pid has gone (and may already be reused). An
1227        // unreadable executable is usually the process mid-exit; keep polling
1228        // rather than recording a verified, signalled child as unverifiable.
1229        // Whatever is still present at the kill deadline is Survived.
1230        match verdict {
1231            None => Some(exited),
1232            Some(verdict) if verdict.permits_signal() => None,
1233            Some(verdict) => match verdict.refusal() {
1234                SweepDecision::Mismatched(_) => Some(exited),
1235                _ => None,
1236            },
1237        }
1238    };
1239    let term_deadline = Instant::now() + bounds.term_grace;
1240    loop {
1241        signalled.retain(|(entry, process)| {
1242            if let Some(decision) = departed(&entry.child, process, SweepDecision::Terminated) {
1243                decisions.push((entry.clone(), decision));
1244                false
1245            } else {
1246                true
1247            }
1248        });
1249        if signalled.is_empty() || Instant::now() >= term_deadline {
1250            break;
1251        }
1252        sleep(POLL).await;
1253    }
1254
1255    for (entry, process) in &signalled {
1256        // Recheck immediately before delivery, not before the log: without a
1257        // pidfd, the PID could be reused after the earlier check for SIGTERM.
1258        if !verdict_for(&entry.child, process).is_some_and(IdentityVerdict::permits_signal) {
1259            continue;
1260        }
1261        let _ = signal(process, Signal::Kill);
1262        warn!(
1263            module_id = %entry.child.module_id,
1264            pid = entry.child.pid,
1265            grace_ms = bounds.term_grace.as_millis() as u64,
1266            "orphan sweep: previous daemon's child still running after SIGTERM grace; requested SIGKILL"
1267        );
1268    }
1269    let kill_deadline = Instant::now() + bounds.kill_bound;
1270    loop {
1271        signalled.retain(|(entry, process)| {
1272            if let Some(decision) = departed(&entry.child, process, SweepDecision::Killed) {
1273                decisions.push((entry.clone(), decision));
1274                false
1275            } else {
1276                true
1277            }
1278        });
1279        if signalled.is_empty() || Instant::now() >= kill_deadline {
1280            break;
1281        }
1282        sleep(POLL).await;
1283    }
1284    decisions.extend(
1285        signalled
1286            .into_iter()
1287            .map(|(entry, _)| (entry, SweepDecision::Survived)),
1288    );
1289    decisions
1290}
1291
1292/// `None` once the process has exited; otherwise whether it is still the
1293/// recorded one.
1294#[cfg(any(target_os = "linux", target_os = "macos"))]
1295fn current_verdict(entry: &LiveChild, process: &subc_os::Process) -> Option<IdentityVerdict> {
1296    let Some((observed, access)) = process.observe_with_executable_access() else {
1297        #[cfg(target_os = "linux")]
1298        if process.is_alive_but_unobservable() {
1299            return Some(IdentityVerdict::ProcessHidden);
1300        }
1301        return None;
1302    };
1303    Some(verdict_with_executable_access(
1304        entry,
1305        process.pid(),
1306        &observed,
1307        access,
1308    ))
1309}
1310
1311#[cfg(any(target_os = "linux", target_os = "macos"))]
1312fn verdict_with_executable_access(
1313    entry: &LiveChild,
1314    pid: u32,
1315    observed: &subc_os::Observation,
1316    _access: subc_os::ExecutableAccess,
1317) -> IdentityVerdict {
1318    let verdict = identity_verdict(entry, pid, observed);
1319    // An ExecutableUnreadable verdict already confirms the recorded PID and
1320    // Linux start time, ruling out PID reuse. Only permission denial permits
1321    // signalling without the image; other read failures remain unverifiable.
1322    #[cfg(target_os = "linux")]
1323    if verdict == IdentityVerdict::ExecutableUnreadable
1324        && _access == subc_os::ExecutableAccess::PermissionDenied
1325    {
1326        return IdentityVerdict::MatchesWithExecutablePermissionDenied;
1327    }
1328    verdict
1329}
1330
1331#[cfg(windows)]
1332async fn sweep_entries(
1333    entries: Vec<RecordedChild>,
1334    bounds: SweepBounds,
1335) -> Vec<(RecordedChild, SweepDecision)> {
1336    let mut decisions = Vec::new();
1337    for entry in entries {
1338        let recorded = entry.child.clone();
1339        let decision =
1340            tokio::task::spawn_blocking(move || sweep_windows_entry(&recorded, bounds.kill_bound))
1341                .await
1342                .unwrap_or_else(|error| SweepDecision::Unverifiable(error.to_string()));
1343        if entry.child.container.is_some()
1344            && matches!(
1345                decision,
1346                SweepDecision::ForcedStopped
1347                    | SweepDecision::Survived
1348                    | SweepDecision::Unverifiable(_)
1349            )
1350        {
1351            let mut end = ContainerEnd {
1352                reason: ContainerEndReason::BootRecovery,
1353                ..Default::default()
1354            };
1355            end.failed = !matches!(decision, SweepDecision::ForcedStopped);
1356            if matches!(
1357                decision,
1358                SweepDecision::ForcedStopped | SweepDecision::Survived
1359            ) {
1360                end.signal("TerminateProcess");
1361            }
1362            end.log(&entry.child.module_id);
1363        }
1364        decisions.push((entry, decision));
1365    }
1366    decisions
1367}
1368
1369#[cfg(windows)]
1370fn sweep_windows_entry(entry: &LiveChild, wait_bound: Duration) -> SweepDecision {
1371    let Some(expected) = entry.start_time else {
1372        return IdentityVerdict::StartTimeUnrecorded.refusal();
1373    };
1374    // Open once: creation-time validation, the forced stop and its wait all use
1375    // this handle even if the PID is subsequently reused.
1376    let process = match subc_os::Process::open(entry.pid) {
1377        Ok(Some(process)) => process,
1378        Ok(None) => return SweepDecision::Gone,
1379        Err(error) => return SweepDecision::Unverifiable(error.to_string()),
1380    };
1381    let Some(observed) = process.observe() else {
1382        return match process.wait_for_exit(Duration::ZERO) {
1383            Ok(true) => SweepDecision::Gone,
1384            _ => SweepDecision::Unverifiable("process creation time unavailable".to_owned()),
1385        };
1386    };
1387    if observed.start_time != expected {
1388        return SweepDecision::Mismatched(IdentityVerdict::StartTimeDiffers);
1389    }
1390    match process.force_stop(expected, wait_bound) {
1391        Ok(true) => SweepDecision::ForcedStopped,
1392        Ok(false) => SweepDecision::Survived,
1393        Err(error) => SweepDecision::Unverifiable(error.to_string()),
1394    }
1395}
1396
1397#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
1398async fn sweep_entries(
1399    entries: Vec<RecordedChild>,
1400    _bounds: SweepBounds,
1401) -> Vec<(RecordedChild, SweepDecision)> {
1402    entries
1403        .into_iter()
1404        .map(|entry| (entry, SweepDecision::NotSignalledOnThisPlatform))
1405        .collect()
1406}
1407
1408fn log_decision(entry: &LiveChild, decision: &SweepDecision) {
1409    let module_id = entry.module_id.as_str();
1410    let pid = entry.pid;
1411    match decision {
1412        SweepDecision::Adopted => {
1413            info!(module_id, pid, "orphan sweep: child adopted by the handover; left running")
1414        }
1415        SweepDecision::Held => {
1416            info!(module_id, pid, "orphan sweep: handover child could not be adopted; left unsignalled")
1417        }
1418        SweepDecision::Gone => {
1419            info!(module_id, pid, "orphan sweep: previous daemon's child is gone; dropped from the record")
1420        }
1421        SweepDecision::Mismatched(verdict) => info!(
1422            module_id,
1423            pid,
1424            reason = verdict.describe(),
1425            "orphan sweep: pid does not match the recorded child; not signalled"
1426        ),
1427        SweepDecision::Unverifiable(error) if entry.container.is_some() => tracing::error!(
1428            module_id, pid, container = ?entry.container, %error,
1429            "orphan sweep: container could not be verified; retaining its record and blocking fresh starts"
1430        ),
1431        SweepDecision::Unverifiable(error) => warn!(
1432            module_id,
1433            pid,
1434            %error,
1435            "orphan sweep: could not verify or stop the recorded pid; keeping its record and blocking its module"
1436        ),
1437        #[cfg(target_os = "linux")]
1438        SweepDecision::AliveButUnobservable => info!(
1439            module_id, pid,
1440            "orphan sweep: previous child is alive but unobservable (process hidden); not signalled; keeping its record"
1441        ),
1442        SweepDecision::Terminated => {
1443            info!(module_id, pid, "orphan sweep: previous daemon's child exited after SIGTERM")
1444        }
1445        SweepDecision::Killed => {
1446            info!(module_id, pid, "orphan sweep: previous daemon's child exited after SIGKILL")
1447        }
1448        #[cfg(windows)]
1449        SweepDecision::ForcedStopped => {
1450            info!(module_id, pid, "orphan sweep: previous daemon's child exited after a forced stop")
1451        }
1452        SweepDecision::Survived => warn!(
1453            module_id,
1454            pid,
1455            "orphan sweep: previous daemon's child still observed after SIGKILL; keeping its record and blocking its module"
1456        ),
1457        SweepDecision::ContainerSurvivors(pids) => tracing::error!(
1458            module_id, pid, ?pids, container = ?entry.container,
1459            "orphan sweep: container survivors block a fresh instance"
1460        ),
1461        #[cfg(target_os = "linux")]
1462        SweepDecision::EmptyContainerDirectory => warn!(
1463            module_id, container = ?entry.container,
1464            "orphan sweep: container is stopped; retaining only a directory-removal retry, without blocking fresh starts"
1465        ),
1466        SweepDecision::NotSignalledOnThisPlatform => info!(
1467            module_id,
1468            pid,
1469            "orphan sweep: previous daemon's child recorded; not signalled, the job object ends a crashed daemon's children on this platform"
1470        ),
1471    }
1472}
1473
1474/// The record's path inside a daemon run directory.
1475pub(crate) fn record_path(run_dir: &Path) -> PathBuf {
1476    run_dir.join(LIVE_CHILDREN_FILE_NAME)
1477}
1478
1479#[cfg(test)]
1480mod strict_roster_reader_tests {
1481    use super::record_path;
1482    use crate::{read_live_children_roster, RecordReadError, RetainedReason};
1483    use cortexkit_test_support::ScratchDir;
1484    use std::{fs, path::Path};
1485
1486    #[test]
1487    fn reads_v1_without_container_or_retained_metadata() {
1488        let dir = ScratchDir::new("strict-roster-v1");
1489        let path = record_path(&dir);
1490        let bytes = br#"{
1491            "version": 1,
1492            "children": [{
1493                "module_id": "worker", "pid": 41, "protocol": "none",
1494                "start_time": 1000, "executable": {"device": 7, "inode": 11},
1495                "cgroup_name": "worker-a"
1496            }]
1497        }"#;
1498        fs::write(&path, bytes).unwrap();
1499
1500        let roster = read_live_children_roster(&path).unwrap().unwrap();
1501        assert_eq!(roster.version, 1);
1502        let [child] = roster.children.as_slice() else {
1503            panic!("expected one roster child");
1504        };
1505        assert_eq!(child.module_id, "worker");
1506        assert_eq!(child.pid, 41);
1507        assert_eq!(child.protocol, subc_control::ModuleProtocol::None);
1508        assert_eq!(child.start_time, Some(1000));
1509        let image = child.executable.unwrap();
1510        assert_eq!((image.device, image.inode), (7, 11));
1511        assert_eq!(child.cgroup_name.as_deref(), Some("worker-a"));
1512        assert!(child.container.is_none());
1513        assert!(roster.retained_reasons.is_empty());
1514        assert_eq!(fs::read(&path).unwrap(), bytes);
1515        assert_eq!(fs::read_dir(&*dir).unwrap().count(), 1);
1516    }
1517
1518    #[test]
1519    fn reads_v2_with_container_and_retained_metadata() {
1520        let dir = ScratchDir::new("strict-roster-v2");
1521        let path = record_path(&dir);
1522        let bytes = br#"{
1523            "version": 2,
1524            "children": [{
1525                "module_id": "worker", "pid": 41, "protocol": "subc",
1526                "container": {
1527                    "pgid": 41, "created_start_time": 1000, "boot_id": "recorded-boot",
1528                    "session_id": 40, "cgroup_path": "worker-a"
1529                }
1530            }],
1531            "retained_reasons": {"41": {"container_survivors": [42]}}
1532        }"#;
1533        fs::write(&path, bytes).unwrap();
1534
1535        let roster = read_live_children_roster(&path).unwrap().unwrap();
1536        assert_eq!(roster.version, 2);
1537        let [child] = roster.children.as_slice() else {
1538            panic!("expected one roster child");
1539        };
1540        let container = child.container.as_ref().unwrap();
1541        assert_eq!(container.pgid, Some(41));
1542        assert_eq!(container.created_start_time, Some(1000));
1543        assert_eq!(container.boot_id.as_deref(), Some("recorded-boot"));
1544        assert_eq!(container.session_id, Some(40));
1545        assert_eq!(
1546            container.cgroup_path.as_deref(),
1547            Some(Path::new("worker-a"))
1548        );
1549        assert_eq!(
1550            roster.retained_reasons.get(&41),
1551            Some(&RetainedReason::ContainerSurvivors(vec![42]))
1552        );
1553        assert_eq!(fs::read(&path).unwrap(), bytes);
1554        assert_eq!(fs::read_dir(&*dir).unwrap().count(), 1);
1555    }
1556
1557    #[test]
1558    fn absent_is_distinct_from_present_and_empty() {
1559        let dir = ScratchDir::new("strict-roster-absent");
1560        let path = record_path(&dir);
1561        assert!(read_live_children_roster(&path).unwrap().is_none());
1562        assert_eq!(fs::read_dir(&*dir).unwrap().count(), 0);
1563
1564        fs::write(&path, br#"{"version":2,"children":[]}"#).unwrap();
1565        let roster = read_live_children_roster(&path).unwrap().unwrap();
1566        assert_eq!(roster.version, 2);
1567        assert!(roster.children.is_empty());
1568    }
1569
1570    #[test]
1571    fn reports_io_errors_without_quarantine() {
1572        let dir = ScratchDir::new("strict-roster-unreadable");
1573        let path = record_path(&dir);
1574        // A directory fails a byte read even when the process is privileged.
1575        fs::create_dir(&path).unwrap();
1576        assert!(matches!(
1577            read_live_children_roster(&path),
1578            Err(RecordReadError::Io(_))
1579        ));
1580        assert!(path.is_dir());
1581        assert_eq!(fs::read_dir(&*dir).unwrap().count(), 1);
1582    }
1583
1584    #[test]
1585    fn reports_malformed_before_unknown_version_without_quarantine() {
1586        let dir = ScratchDir::new("strict-roster-invalid");
1587        let path = record_path(&dir);
1588        for bytes in [
1589            &b"{"[..],
1590            br#"{"version":2,"children":[{"pid":41}]}"#,
1591            br#"{"version":3,"children":null}"#,
1592        ] {
1593            fs::write(&path, bytes).unwrap();
1594            assert!(matches!(
1595                read_live_children_roster(&path),
1596                Err(RecordReadError::Malformed(_))
1597            ));
1598            assert_eq!(fs::read(&path).unwrap(), bytes);
1599            assert_eq!(fs::read_dir(&*dir).unwrap().count(), 1);
1600        }
1601
1602        let bytes = br#"{"version":3,"children":[]}"#;
1603        fs::write(&path, bytes).unwrap();
1604        assert!(matches!(
1605            read_live_children_roster(&path),
1606            Err(RecordReadError::UnknownVersion(3))
1607        ));
1608        assert_eq!(fs::read(&path).unwrap(), bytes);
1609        assert_eq!(fs::read_dir(&*dir).unwrap().count(), 1);
1610    }
1611}
1612
1613#[cfg(test)]
1614#[path = "live_children/quarantine_tests.rs"]
1615mod quarantine_tests;
1616
1617#[cfg(test)]
1618#[path = "live_children/boot_session_tests.rs"]
1619mod boot_session_tests;
1620
1621#[cfg(test)]
1622mod roster_resume_hash_tests {
1623    use super::*;
1624    use cortexkit_test_support::ScratchDir;
1625
1626    fn child(module_id: &str, pid: u32, hash_digit: char) -> RecordedChild {
1627        RecordedChild {
1628            child: LiveChild {
1629                module_id: module_id.into(),
1630                pid,
1631                protocol: ModuleProtocol::Subc,
1632                start_time: Some(1000),
1633                executable: None,
1634                cgroup_name: None,
1635                container: None,
1636            },
1637            resume_token_sha256: Some(hash_digit.to_string().repeat(64)),
1638        }
1639    }
1640
1641    #[test]
1642    fn last_release_startup_and_inspection_read_inline_hash_records() {
1643        let dir = ScratchDir::new("released-roster-readers");
1644        let path = record_path(&dir);
1645        let recorded = child("worker", 41, 'a');
1646        let reasons = BTreeMap::from([(41, RetainedReason::Unverifiable)]);
1647        write_record_with_reasons(&path, std::slice::from_ref(&recorded), reasons.clone()).unwrap();
1648        let bytes = fs::read(&path).unwrap();
1649        let wire: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
1650        assert_eq!(wire["version"], 2);
1651        assert_eq!(wire["children"][0]["resume_token_sha256"], "a".repeat(64));
1652
1653        let (startup_children, startup_reasons) =
1654            released_v2::read_record_with_reasons(&path).unwrap();
1655        let inspection = released_v2::read_live_children_roster(&path)
1656            .unwrap()
1657            .unwrap();
1658        assert_eq!(inspection.version, 2);
1659        let expected = serde_json::to_value([&recorded.child]).unwrap();
1660        assert_eq!(serde_json::to_value(startup_children).unwrap(), expected);
1661        assert_eq!(serde_json::to_value(inspection.children).unwrap(), expected);
1662        assert_eq!(startup_reasons, reasons);
1663        assert_eq!(inspection.retained_reasons, reasons);
1664        assert_eq!(fs::read(&path).unwrap(), bytes);
1665        assert!(quarantine_block(&path).is_none());
1666    }
1667
1668    #[test]
1669    fn public_inspection_does_not_return_the_hash() {
1670        let dir = ScratchDir::new("inspect-roster-with-hash");
1671        let path = record_path(&dir);
1672        let recorded = child("worker", 41, 'b');
1673        let hash = recorded.resume_token_sha256.as_deref().unwrap();
1674        write_record_with_reasons(&path, std::slice::from_ref(&recorded), BTreeMap::new()).unwrap();
1675        assert!(fs::read_to_string(&path).unwrap().contains(hash));
1676        #[cfg(unix)]
1677        {
1678            use std::os::unix::fs::PermissionsExt;
1679            assert_eq!(
1680                fs::metadata(&path).unwrap().permissions().mode() & 0o777,
1681                0o600
1682            );
1683        }
1684
1685        let inspection = read_live_children_roster(&path).unwrap().unwrap();
1686        assert!(!format!("{inspection:?}").contains(hash));
1687        assert_eq!(inspection.children, [recorded.child]);
1688        let child = serde_json::to_value(&inspection.children[0]).unwrap();
1689        assert!(child.get("resume_token_sha256").is_none());
1690    }
1691
1692    #[tokio::test]
1693    async fn protected_sweep_keeps_both_identities_hashes_and_reasons() {
1694        let dir = ScratchDir::new("sweep-protected-children");
1695        let path = record_path(&dir);
1696        let owner = RunDirLock::acquire(&path).unwrap();
1697        let adopted = child("adopted", 41, 'a');
1698        let held = child("held", 42, 'b');
1699        let orphan = child("orphan", 43, 'c');
1700        let entries = [adopted.clone(), held.clone(), orphan.clone()];
1701        let reasons = BTreeMap::from([(42, RetainedReason::Unverifiable)]);
1702        write_record_with_reasons(&path, &entries, reasons.clone()).unwrap();
1703
1704        let decisions = sweep_orphans_with(
1705            &owner,
1706            &AdoptedPids::from_classes([41], [42]),
1707            SweepBounds::default(),
1708            |entered_recovery, _| async move {
1709                assert_eq!(entered_recovery, [orphan]);
1710                entered_recovery
1711                    .into_iter()
1712                    .map(|entry| (entry, SweepDecision::Gone))
1713                    .collect()
1714            },
1715        )
1716        .await;
1717
1718        assert_eq!(
1719            decisions,
1720            [
1721                (adopted.child.clone(), SweepDecision::Adopted),
1722                (held.child.clone(), SweepDecision::Held),
1723                (entries[2].child.clone(), SweepDecision::Gone),
1724            ]
1725        );
1726        assert_eq!(
1727            read_record_entries(&path).unwrap(),
1728            (vec![adopted, held], reasons)
1729        );
1730    }
1731
1732    #[tokio::test]
1733    async fn missing_record_and_damaged_optional_hash_do_not_block_cold_recovery() {
1734        let dir = ScratchDir::new("sweep-without-usable-hash");
1735        let path = record_path(&dir);
1736        let owner = RunDirLock::acquire(&path).unwrap();
1737        let protected = AdoptedPids::none();
1738        let bounds = SweepBounds::default();
1739        let decisions = sweep_orphans_with(&owner, &protected, bounds, |entries, _| async move {
1740            assert!(entries.is_empty());
1741            Vec::new()
1742        })
1743        .await;
1744        assert!(decisions.is_empty());
1745
1746        let expected = child("worker", 41, 'a').child;
1747        for hash in [
1748            serde_json::json!({"damaged": true}),
1749            serde_json::json!("not a digest"),
1750        ] {
1751            let mut wire = serde_json::to_value(&expected).unwrap();
1752            wire["resume_token_sha256"] = hash;
1753            fs::write(
1754                &path,
1755                serde_json::json!({"version": 2, "children": [wire]}).to_string(),
1756            )
1757            .unwrap();
1758            let decisions =
1759                sweep_orphans_with(&owner, &protected, bounds, |mut entries, _| async move {
1760                    assert_eq!(entries.len(), 1);
1761                    let entry = entries.pop().unwrap();
1762                    assert!(entry.resume_token_sha256.is_none());
1763                    vec![(entry, SweepDecision::Gone)]
1764                })
1765                .await;
1766            assert_eq!(decisions, [(expected.clone(), SweepDecision::Gone)]);
1767            assert!(read_record(&path).unwrap().is_empty());
1768            assert!(quarantine_block(&path).is_none());
1769        }
1770    }
1771
1772    // Frozen v0.50.49 readers and record shape from crates/subc-daemon/src/live_children.rs
1773    // (tag subc-daemon-v0.50.49, commit a92c126175d7081bc9706c26c77af427909925d5).
1774    mod released_v2 {
1775        use super::{
1776            ContainerIdentity, ExecutableIdentity, ModuleProtocol, RecordReadError, RetainedReason,
1777        };
1778        use serde::{Deserialize, Serialize};
1779        use std::{collections::BTreeMap, fs, io, path::Path};
1780
1781        const RECORD_VERSION: u32 = 2;
1782
1783        #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1784        pub struct LiveChild {
1785            pub module_id: String,
1786            pub pid: u32,
1787            pub protocol: ModuleProtocol,
1788            pub start_time: Option<u64>,
1789            pub executable: Option<ExecutableIdentity>,
1790            pub cgroup_name: Option<String>,
1791            #[serde(default, skip_serializing_if = "Option::is_none")]
1792            pub container: Option<ContainerIdentity>,
1793        }
1794
1795        #[derive(Debug, Serialize, Deserialize)]
1796        struct RecordFile {
1797            version: u32,
1798            children: Vec<LiveChild>,
1799            #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1800            retained_reasons: BTreeMap<u32, RetainedReason>,
1801        }
1802
1803        #[derive(Debug)]
1804        pub struct LiveChildrenRoster {
1805            pub version: u32,
1806            pub children: Vec<LiveChild>,
1807            pub retained_reasons: BTreeMap<u32, RetainedReason>,
1808        }
1809
1810        pub fn read_live_children_roster(
1811            path: &Path,
1812        ) -> Result<Option<LiveChildrenRoster>, RecordReadError> {
1813            let bytes = match fs::read(path) {
1814                Ok(bytes) => bytes,
1815                Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
1816                Err(error) => return Err(RecordReadError::Io(error)),
1817            };
1818            let record: RecordFile =
1819                serde_json::from_slice(&bytes).map_err(RecordReadError::Malformed)?;
1820            if !matches!(record.version, 1 | 2) {
1821                return Err(RecordReadError::UnknownVersion(record.version));
1822            }
1823            Ok(Some(LiveChildrenRoster {
1824                version: record.version,
1825                children: record.children,
1826                retained_reasons: record.retained_reasons,
1827            }))
1828        }
1829
1830        pub(crate) fn read_record_with_reasons(
1831            path: &Path,
1832        ) -> Result<(Vec<LiveChild>, BTreeMap<u32, RetainedReason>), RecordReadError> {
1833            let bytes = match fs::read(path) {
1834                Ok(bytes) => bytes,
1835                Err(error) if error.kind() == io::ErrorKind::NotFound => {
1836                    return Ok((Vec::new(), BTreeMap::new()))
1837                }
1838                Err(error) => return Err(RecordReadError::Io(error)),
1839            };
1840            let record: RecordFile =
1841                serde_json::from_slice(&bytes).map_err(RecordReadError::Malformed)?;
1842            if !matches!(record.version, 1 | RECORD_VERSION) {
1843                return Err(RecordReadError::UnknownVersion(record.version));
1844            }
1845            Ok((record.children, record.retained_reasons))
1846        }
1847    }
1848}
1849
1850#[cfg(test)]
1851pub(crate) mod tests {
1852    use super::*;
1853    use cortexkit_test_support::ScratchDir;
1854
1855    #[cfg(unix)]
1856    #[test]
1857    fn carried_end_log_orders_overlapping_teardown_actions() {
1858        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
1859        let before = std::time::Instant::now();
1860        let after = before + Duration::from_millis(1);
1861        let mut shutdown = ContainerEnd {
1862            reason: ContainerEndReason::DaemonShutdown,
1863            members: Some((after, 0)),
1864            signals: vec![(after, "KILL")],
1865            ..Default::default()
1866        };
1867        shutdown.merge(ContainerEnd {
1868            members: Some((before, 4)),
1869            signals: vec![(before, "TERM")],
1870            ..Default::default()
1871        });
1872        shutdown.log("sample");
1873        let captured = crate::router::test_log::captured_logs(&logs);
1874        assert!(
1875            captured.contains("INFO ended a carried container module_id=sample reason=daemon_shutdown members=4 signals=TERM,KILL"),
1876            "{captured}"
1877        );
1878    }
1879
1880    #[cfg(target_os = "linux")]
1881    pub(crate) struct NonDumpableChild {
1882        pub(crate) child: std::process::Child,
1883        pub(crate) entry: LiveChild,
1884        pub(crate) program: PathBuf,
1885    }
1886
1887    #[cfg(target_os = "linux")]
1888    impl Drop for NonDumpableChild {
1889        fn drop(&mut self) {
1890            let _ = self.child.kill();
1891            let _ = self.child.wait();
1892        }
1893    }
1894
1895    #[cfg(target_os = "linux")]
1896    pub(crate) async fn spawn_non_dumpable_child(dir: &Path) -> NonDumpableChild {
1897        let ready = dir.join("ready");
1898        let program = std::env::current_exe().unwrap();
1899        let child = std::process::Command::new(&program)
1900            .args([
1901                "--exact",
1902                "live_children::tests::linux_non_dumpable_child_is_swept_and_image_is_not_readable",
1903                "--ignored",
1904                "--nocapture",
1905                "--test-threads=1",
1906            ])
1907            .env("SUBC_NON_DUMPABLE_CHILD_READY", &ready)
1908            .stdin(std::process::Stdio::piped())
1909            .stdout(std::process::Stdio::null())
1910            .spawn()
1911            .unwrap();
1912        let mut fixture = NonDumpableChild {
1913            entry: LiveChild {
1914                container: None,
1915                module_id: "previous".to_owned(),
1916                pid: child.id(),
1917                protocol: ModuleProtocol::None,
1918                start_time: None,
1919                executable: subc_os::file_identity(&program).map(ExecutableIdentity::from),
1920                cgroup_name: None,
1921            },
1922            child,
1923            program,
1924        };
1925        let deadline = std::time::Instant::now() + Duration::from_secs(5);
1926        loop {
1927            let observed = subc_os::Process::open(fixture.child.id())
1928                .unwrap()
1929                .and_then(|process| process.observe());
1930            if let Some(observed) = observed.filter(|observed| {
1931                observed.executable.map(ExecutableIdentity::from) == fixture.entry.executable
1932            }) {
1933                fixture.entry.start_time = Some(observed.start_time);
1934                break;
1935            }
1936            assert!(
1937                std::time::Instant::now() < deadline,
1938                "helper never completed exec"
1939            );
1940            tokio::time::sleep(Duration::from_millis(5)).await;
1941        }
1942        // Capture the executable inode and process start time before the child
1943        // calls PR_SET_DUMPABLE, which can hide both from this parent.
1944        std::io::Write::write_all(fixture.child.stdin.as_mut().unwrap(), b"x").unwrap();
1945        while !ready.exists() {
1946            assert!(
1947                fixture.child.try_wait().unwrap().is_none(),
1948                "helper exited before readiness"
1949            );
1950            assert!(
1951                std::time::Instant::now() < deadline,
1952                "helper never became non-dumpable"
1953            );
1954            tokio::time::sleep(Duration::from_millis(5)).await;
1955        }
1956        fixture
1957    }
1958
1959    #[cfg(target_os = "linux")]
1960    #[tokio::test]
1961    #[ignore = "requires an unprivileged Linux process with procfs hidepid=0"]
1962    async fn linux_non_dumpable_child_is_swept_and_image_is_not_readable() {
1963        if let Some(ready) = std::env::var_os("SUBC_NON_DUMPABLE_CHILD_READY") {
1964            let mut release = [0u8; 1];
1965            std::io::Read::read_exact(&mut std::io::stdin(), &mut release).unwrap();
1966            rustix::process::set_dumpable_behavior(rustix::process::DumpableBehavior::NotDumpable)
1967                .unwrap();
1968            std::fs::write(ready, b"ready").unwrap();
1969            std::io::Read::read_exact(&mut std::io::stdin(), &mut release).unwrap();
1970            return;
1971        }
1972        let dir = ScratchDir::new("non-dumpable-sweep");
1973        let mut fixture = spawn_non_dumpable_child(&dir).await;
1974        let pid = fixture.child.id();
1975        let program = &fixture.program;
1976        let entry = fixture.entry.clone();
1977        let process = subc_os::Process::open(pid).unwrap().unwrap();
1978        let (observed, access) = process.observe_with_executable_access().unwrap_or_else(|| {
1979            panic!(
1980                "non-dumpable child must remain observable: stat={:?}, status={:?}, wait={:?}",
1981                std::fs::read_to_string(format!("/proc/{pid}/stat")),
1982                std::fs::read_to_string(format!("/proc/{pid}/status")),
1983                fixture.child.try_wait()
1984            );
1985        });
1986        assert_eq!(access, subc_os::ExecutableAccess::PermissionDenied);
1987        assert_eq!(observed.executable, None);
1988        assert_eq!(process.observe(), Some(observed));
1989        let error = std::fs::File::open(format!("/proc/{pid}/exe")).unwrap_err();
1990        assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
1991        assert!(std::fs::read_to_string(format!("/proc/{pid}/status")).is_ok());
1992
1993        assert!(entry.executable.is_some());
1994        assert_eq!(
1995            current_verdict(&entry, &process),
1996            Some(IdentityVerdict::MatchesWithExecutablePermissionDenied)
1997        );
1998        let mut reused = entry.clone();
1999        reused.start_time = Some(observed.start_time + 1);
2000        assert_eq!(
2001            current_verdict(&reused, &process),
2002            Some(IdentityVerdict::StartTimeDiffers)
2003        );
2004        reused.start_time = None;
2005        assert_eq!(
2006            current_verdict(&reused, &process),
2007            Some(IdentityVerdict::StartTimeUnrecorded)
2008        );
2009        reused = entry.clone();
2010        reused.pid += 1;
2011        assert_eq!(
2012            current_verdict(&reused, &process),
2013            Some(IdentityVerdict::PidDiffers)
2014        );
2015        reused = entry.clone();
2016        reused.executable = None;
2017        assert_eq!(
2018            current_verdict(&reused, &process),
2019            Some(IdentityVerdict::ExecutableUnrecorded)
2020        );
2021
2022        let probe = crate::provenance::ExecutableIdentityProbe::default();
2023        assert_eq!(
2024            probe
2025                .observe(Some(pid), Some(program), None, Some(observed.start_time))
2026                .await,
2027            subc_control::RunningImageAgreement::Unavailable {
2028                reason:
2029                    subc_control::RunningImageUnavailableReason::RunningExecutablePermissionDenied,
2030            }
2031        );
2032        assert_eq!(
2033            probe
2034                .observe(
2035                    Some(pid),
2036                    Some(program),
2037                    None,
2038                    Some(observed.start_time + 1)
2039                )
2040                .await,
2041            subc_control::RunningImageAgreement::Unavailable {
2042                reason: subc_control::RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
2043            }
2044        );
2045
2046        let path = record_path(&dir);
2047        write_record(&path, std::slice::from_ref(&entry)).unwrap();
2048        let decisions = sweep_orphans(
2049            &RunDirLock::acquire(&path).unwrap(),
2050            &AdoptedPids::none(),
2051            SweepBounds {
2052                term_grace: Duration::from_millis(300),
2053                kill_bound: Duration::from_secs(2),
2054            },
2055        )
2056        .await;
2057        assert_eq!(decisions, vec![(entry, SweepDecision::Terminated)]);
2058        use std::os::unix::process::ExitStatusExt;
2059        assert_eq!(fixture.child.wait().unwrap().signal(), Some(15));
2060        assert!(read_record(&path).unwrap().is_empty());
2061    }
2062
2063    #[cfg(target_os = "linux")]
2064    mod hidden_processes {
2065        use super::*;
2066        use crate::registry::Registry;
2067        use crate::supervise::{ModuleOverlap, ModuleSpec, RestartPolicy, Supervisor};
2068        use std::sync::Arc;
2069
2070        fn spec(module_id: &str) -> ModuleSpec {
2071            ModuleSpec {
2072                script: None,
2073                carry_containment: false,
2074                module_id: module_id.to_owned(),
2075                program: PathBuf::from("/bin/sleep"),
2076                args: vec!["60".to_owned()],
2077                env: vec![],
2078                reserved: false,
2079                reserved_prefixes: vec![],
2080                protocol: ModuleProtocol::None,
2081                overlap: ModuleOverlap::Exclusive,
2082            }
2083        }
2084
2085        async fn retained_fixture(dir: &Path) -> NonDumpableChild {
2086            let fixture = spawn_non_dumpable_child(dir).await;
2087            assert!(
2088                subc_os::Process::open(fixture.entry.pid)
2089                    .unwrap()
2090                    .unwrap()
2091                    .is_alive_but_unobservable(),
2092                "this gate requires procfs hidepid=invisible"
2093            );
2094            let path = record_path(dir);
2095            write_record(&path, std::slice::from_ref(&fixture.entry)).unwrap();
2096            sweep_orphans(
2097                &RunDirLock::acquire(&path).unwrap(),
2098                &AdoptedPids::none(),
2099                SweepBounds::default(),
2100            )
2101            .await;
2102            fixture
2103        }
2104
2105        #[tokio::test]
2106        #[ignore = "requires Linux procfs hidepid=invisible"]
2107        async fn linux_hidden_non_dumpable_child_is_retained_and_image_is_hidden() {
2108            let dir = ScratchDir::new("hidden-sweep");
2109            let mut fixture = spawn_non_dumpable_child(&dir).await;
2110            let process = subc_os::Process::open(fixture.entry.pid).unwrap().unwrap();
2111            assert!(process.is_alive_but_unobservable());
2112            rustix::process::test_kill_process(
2113                rustix::process::Pid::from_raw(fixture.entry.pid as i32).unwrap(),
2114            )
2115            .unwrap();
2116            assert_eq!(
2117                std::fs::metadata(format!("/proc/{}/stat", fixture.entry.pid))
2118                    .unwrap_err()
2119                    .kind(),
2120                std::io::ErrorKind::NotFound
2121            );
2122            assert!(process.observe().is_none());
2123            let identity = subc_os::process_identity::ProcessStart::parse(&format!(
2124                "linux-v1-{}",
2125                fixture.entry.start_time.unwrap()
2126            ))
2127            .unwrap();
2128            assert_eq!(
2129                subc_os::process_identity::liveness(fixture.entry.pid, Some(&identity)),
2130                subc_os::process_identity::Liveness::Unknown
2131            );
2132            let image = crate::provenance::ExecutableIdentityProbe::default()
2133                .observe(
2134                    Some(fixture.entry.pid),
2135                    Some(&fixture.program),
2136                    None,
2137                    fixture.entry.start_time,
2138                )
2139                .await;
2140            assert_eq!(
2141                image,
2142                subc_control::RunningImageAgreement::Unavailable {
2143                    reason: subc_control::RunningImageUnavailableReason::ProcessHidden,
2144                }
2145            );
2146            let path = record_path(&dir);
2147            write_record(&path, std::slice::from_ref(&fixture.entry)).unwrap();
2148            let decisions = sweep_orphans(
2149                &RunDirLock::acquire(&path).unwrap(),
2150                &AdoptedPids::none(),
2151                SweepBounds::default(),
2152            )
2153            .await;
2154            assert_eq!(
2155                decisions,
2156                vec![(fixture.entry.clone(), SweepDecision::AliveButUnobservable)]
2157            );
2158            assert_eq!(read_record(&path).unwrap(), vec![fixture.entry.clone()]);
2159            assert!(
2160                fixture.child.try_wait().unwrap().is_none(),
2161                "hidden child must never be signalled"
2162            );
2163        }
2164
2165        #[tokio::test]
2166        #[ignore = "requires Linux procfs hidepid=invisible"]
2167        async fn linux_hidden_orphan_blocks_only_its_module_and_refuses_start_requests() {
2168            let dir = ScratchDir::new("hidden-blocks-one");
2169            let mut fixture = retained_fixture(&dir).await;
2170            let supervisor =
2171                Supervisor::new(Arc::new(Registry::default()), RestartPolicy::default())
2172                    .with_live_children_record(record_path(&dir));
2173            let waiting = supervisor
2174                .supervise_configured_with_health(
2175                    spec("previous"),
2176                    true,
2177                    crate::supervise::HealthConfig::default(),
2178                    None,
2179                    RestartPolicy::default(),
2180                )
2181                .unwrap();
2182            let other = supervisor
2183                .supervise_configured(spec("unrelated"), true)
2184                .unwrap();
2185            let other_live = other.status().unwrap().live;
2186            let refused = waiting.set_enabled(true).await.unwrap_err().to_string();
2187            assert!(refused.contains(&format!("waiting: previous instance (pid {}) is still running but hidden; it cannot be identified", fixture.entry.pid)));
2188            assert!(waiting.restart(None).await.is_err());
2189            assert!(waiting.reload().await.is_err());
2190            assert!(waiting.swap(None).await.is_err());
2191            assert!(supervisor.spawn(spec("previous")).is_err());
2192            tokio::time::sleep(Duration::from_millis(5200)).await;
2193            let status = waiting.status().unwrap();
2194            let orphan_alive = fixture.child.try_wait().unwrap().is_none();
2195            waiting.stop().await.unwrap();
2196            other.stop().await.unwrap();
2197            assert!(
2198                other_live,
2199                "an unrelated configured module must start normally"
2200            );
2201            assert!(!status.process_alive && status.pid.is_none());
2202            assert_eq!(status.waiting_for_previous_pid, Some(fixture.entry.pid));
2203            assert_eq!(status.spawn_generation, 0);
2204            assert!(
2205                orphan_alive,
2206                "blocking must never signal the previous instance"
2207            );
2208        }
2209
2210        #[tokio::test]
2211        #[ignore = "requires Linux procfs hidepid=invisible"]
2212        async fn linux_hidden_orphan_module_starts_after_previous_pid_exits() {
2213            let dir = ScratchDir::new("hidden-starts-after-exit");
2214            let mut fixture = retained_fixture(&dir).await;
2215            let supervisor =
2216                Supervisor::new(Arc::new(Registry::default()), RestartPolicy::default())
2217                    .with_live_children_record(record_path(&dir));
2218            let waiting = supervisor
2219                .supervise_configured(spec("previous"), true)
2220                .unwrap();
2221            assert_eq!(
2222                waiting.status().unwrap().waiting_for_previous_pid,
2223                Some(fixture.entry.pid)
2224            );
2225            fixture.child.kill().unwrap();
2226            fixture.child.wait().unwrap();
2227            let deadline = tokio::time::Instant::now() + Duration::from_secs(8);
2228            let status = loop {
2229                let status = waiting.status().unwrap();
2230                if status.process_alive {
2231                    break status;
2232                }
2233                if tokio::time::Instant::now() >= deadline {
2234                    waiting.stop().await.unwrap();
2235                    panic!("module never started after the orphan exited");
2236                }
2237                tokio::time::sleep(Duration::from_millis(10)).await;
2238            };
2239            let record = read_record(&record_path(&dir)).unwrap();
2240            waiting.stop().await.unwrap();
2241            assert_eq!(status.waiting_for_previous_pid, None);
2242            assert_eq!(status.restart_count, 0);
2243            assert_eq!(status.lifetime_restarts, 0);
2244            assert_eq!(status.spawn_generation, 1);
2245            assert_eq!(record.len(), 1);
2246            assert_eq!(record[0].pid, status.pid.unwrap());
2247            assert_ne!(record[0].pid, fixture.entry.pid);
2248        }
2249
2250        #[tokio::test]
2251        #[ignore = "requires Linux procfs hidepid=invisible"]
2252        async fn linux_hidden_orphan_record_survives_roster_rewrites() {
2253            let dir = ScratchDir::new("hidden-record-rewrite");
2254            let mut fixture = retained_fixture(&dir).await;
2255            let path = record_path(&dir);
2256            let roster = crate::child_roster::ChildRoster::default();
2257            roster.record_to(path.clone());
2258            let guard = roster.admit(
2259                "unrelated".to_owned(),
2260                std::process::id(),
2261                ModuleProtocol::None,
2262                None,
2263                crate::child_roster::RecordedIdentity::default(),
2264            );
2265            assert!(read_record(&path).unwrap().contains(&fixture.entry));
2266            drop(guard);
2267            assert_eq!(read_record(&path).unwrap(), vec![fixture.entry.clone()]);
2268            fixture.child.kill().unwrap();
2269            fixture.child.wait().unwrap();
2270            assert_eq!(roster.previous_instance_pid("previous"), None);
2271            assert!(read_record(&path).unwrap().is_empty());
2272        }
2273    }
2274
2275    fn child(module_id: &str, pid: u32) -> LiveChild {
2276        LiveChild {
2277            container: None,
2278            module_id: module_id.to_owned(),
2279            pid,
2280            protocol: ModuleProtocol::None,
2281            start_time: Some(1_000),
2282            executable: Some(ExecutableIdentity {
2283                device: 7,
2284                inode: 11,
2285                macos_sh_interpreter: None,
2286                windows_file_identity: None,
2287            }),
2288            cgroup_name: Some(format!("{module_id}-a")),
2289        }
2290    }
2291
2292    fn observed(start_time: u64, device: u64, inode: u64) -> subc_os::Observation {
2293        subc_os::Observation {
2294            start_time,
2295            executable: Some(subc_os::FileIdentity { device, inode }),
2296        }
2297    }
2298
2299    #[cfg(target_os = "macos")]
2300    #[test]
2301    fn macos_sh_reexec_matches_the_interpreter_recorded_at_launch() {
2302        // A `#!/bin/sh` child is first seen as `/bin/sh` and then, after the
2303        // re-exec, as the selected shell. Build both observations from the
2304        // real files instead of trying to catch the brief `/bin/sh` phase,
2305        // which some macOS versions don't expose to a sampler.
2306        let launcher = subc_os::file_identity(Path::new("/bin/sh")).unwrap();
2307        let interpreter = subc_os::file_identity(Path::new("/private/var/select/sh")).unwrap();
2308        assert_ne!(
2309            launcher, interpreter,
2310            "the fixture must model a real image change"
2311        );
2312        let mut entry = child("sh-script", 40);
2313        entry.executable = Some(ExecutableIdentity::from(launcher));
2314        let dir = ScratchDir::new("sh-interpreter-record");
2315        let path = record_path(&dir);
2316        write_record(&path, &[entry]).unwrap();
2317        let recorded = read_record(&path).unwrap().pop().unwrap();
2318        let after_reexec = observed(1_000, interpreter.device, interpreter.inode);
2319        assert_eq!(
2320            identity_verdict(&recorded, 40, &after_reexec),
2321            IdentityVerdict::Matches
2322        );
2323        assert_eq!(
2324            identity_verdict(&recorded, 41, &after_reexec),
2325            IdentityVerdict::PidDiffers
2326        );
2327        assert_eq!(
2328            identity_verdict(
2329                &recorded,
2330                40,
2331                &observed(1_001, interpreter.device, interpreter.inode)
2332            ),
2333            IdentityVerdict::StartTimeDiffers
2334        );
2335    }
2336
2337    #[cfg(target_os = "macos")]
2338    #[test]
2339    fn macos_sh_reexec_refuses_an_unrelated_system_binary() {
2340        let launcher = subc_os::file_identity(Path::new("/bin/sh")).unwrap();
2341        let unrelated = subc_os::file_identity(Path::new("/usr/bin/true")).unwrap();
2342        let interpreter = subc_os::file_identity(Path::new("/private/var/select/sh")).unwrap();
2343        let mut entry = child("sh-script", 40);
2344        entry.executable = Some(ExecutableIdentity::from(launcher));
2345        assert_eq!(
2346            identity_verdict(
2347                &entry,
2348                40,
2349                &observed(1_000, unrelated.device, unrelated.inode)
2350            ),
2351            IdentityVerdict::ExecutableDiffers
2352        );
2353        let ordinary = ExecutableIdentity::from(unrelated);
2354        assert!(ordinary.macos_sh_interpreter.is_none());
2355        entry.executable = Some(ordinary);
2356        assert_eq!(
2357            identity_verdict(
2358                &entry,
2359                40,
2360                &observed(1_000, interpreter.device, interpreter.inode)
2361            ),
2362            IdentityVerdict::ExecutableDiffers
2363        );
2364    }
2365
2366    #[cfg(target_os = "macos")]
2367    #[test]
2368    fn macos_sh_legacy_record_does_not_infer_an_unrecorded_interpreter() {
2369        let launcher = subc_os::file_identity(Path::new("/bin/sh")).unwrap();
2370        let interpreter = subc_os::file_identity(Path::new("/private/var/select/sh")).unwrap();
2371        let mut entry = child("legacy-sh-script", 40);
2372        // The old shape lacks the interpreter field, even on a host where the
2373        // current shell selection would match. Matching must use recorded facts.
2374        entry.executable = Some(
2375            serde_json::from_value(serde_json::json!({
2376                "device": launcher.device, "inode": launcher.inode,
2377            }))
2378            .unwrap(),
2379        );
2380        assert_eq!(
2381            identity_verdict(
2382                &entry,
2383                40,
2384                &observed(1_000, interpreter.device, interpreter.inode)
2385            ),
2386            IdentityVerdict::ExecutableDiffers
2387        );
2388        assert_eq!(
2389            identity_verdict(
2390                &entry,
2391                40,
2392                &observed(1_000, launcher.device, launcher.inode)
2393            ),
2394            IdentityVerdict::Matches
2395        );
2396    }
2397
2398    #[test]
2399    fn a_roster_with_a_recorded_sh_interpreter_is_readable_by_the_previous_shape() {
2400        // The previous serde shapes still decode the image identity. A released
2401        // reader rejects the v2 header before using any decoded child to signal.
2402        #[derive(Debug, Deserialize, PartialEq, Eq)]
2403        struct PreviousExecutableIdentity {
2404            device: u64,
2405            inode: u64,
2406        }
2407        #[derive(Debug, Deserialize, PartialEq, Eq)]
2408        struct PreviousLiveChild {
2409            module_id: String,
2410            pid: u32,
2411            protocol: ModuleProtocol,
2412            start_time: Option<u64>,
2413            executable: Option<PreviousExecutableIdentity>,
2414            cgroup_name: Option<String>,
2415        }
2416        #[derive(Debug, Deserialize, PartialEq, Eq)]
2417        struct PreviousRecordFile {
2418            version: u32,
2419            children: Vec<PreviousLiveChild>,
2420        }
2421
2422        let mut entry = child("sh-script", 40);
2423        entry.executable.as_mut().unwrap().macos_sh_interpreter = Some(InterpreterIdentity {
2424            device: 7,
2425            inode: 12,
2426        });
2427        let dir = ScratchDir::new("previous-roster-reader");
2428        let path = record_path(&dir);
2429        write_record(&path, &[entry]).unwrap();
2430        let bytes = fs::read(&path).unwrap();
2431        let new: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
2432        assert_eq!(
2433            new["children"][0]["executable"]["macos_sh_interpreter"]["inode"],
2434            12
2435        );
2436        let previous: PreviousRecordFile = serde_json::from_slice(&bytes).unwrap();
2437        assert_eq!(
2438            previous,
2439            PreviousRecordFile {
2440                version: 2,
2441                children: vec![PreviousLiveChild {
2442                    module_id: "sh-script".to_owned(),
2443                    pid: 40,
2444                    protocol: ModuleProtocol::None,
2445                    start_time: Some(1_000),
2446                    executable: Some(PreviousExecutableIdentity {
2447                        device: 7,
2448                        inode: 11
2449                    }),
2450                    cgroup_name: Some("sh-script-a".to_owned()),
2451                }],
2452            }
2453        );
2454    }
2455
2456    #[test]
2457    fn record_round_trips() {
2458        let dir = ScratchDir::new("live-children-round-trip");
2459        let path = record_path(&dir);
2460        let mut subc = child("aft", 41);
2461        subc.protocol = ModuleProtocol::Subc;
2462        subc.start_time = None;
2463        subc.executable = None;
2464        subc.cgroup_name = None;
2465        let children = vec![child("nats", 40), subc];
2466        write_record(&path, &children).unwrap();
2467        assert_eq!(read_record(&path).unwrap(), children);
2468        write_record(&path, &[]).unwrap();
2469        assert_eq!(read_record(&path).unwrap(), Vec::new());
2470    }
2471
2472    #[test]
2473    fn windows_file_id_record_is_full_width_and_decodable_by_previous_serde_shape() {
2474        #[derive(Deserialize)]
2475        struct PreviousImage {
2476            device: u64,
2477            inode: u64,
2478        }
2479        #[derive(Deserialize)]
2480        struct PreviousChild {
2481            module_id: String,
2482            pid: u32,
2483            protocol: ModuleProtocol,
2484            start_time: Option<u64>,
2485            executable: Option<PreviousImage>,
2486            cgroup_name: Option<String>,
2487        }
2488        #[derive(Deserialize)]
2489        struct PreviousRecord {
2490            version: u32,
2491            children: Vec<PreviousChild>,
2492        }
2493        let dir = ScratchDir::new("windows-file-id-rollback");
2494        let path = record_path(&dir);
2495        let mut entry = child("windows-child", 40);
2496        let image = entry.executable.as_mut().unwrap();
2497        image.device = 0;
2498        image.inode = 0;
2499        image.windows_file_identity = Some(WindowsFileIdentity {
2500            volume_serial_number: u64::MAX,
2501            file_id: [
2502                0, 1, 2, 3, 4, 5, 6, 7, 128, 129, 130, 131, 252, 253, 254, 255,
2503            ],
2504        });
2505        write_record(&path, std::slice::from_ref(&entry)).unwrap();
2506        assert_eq!(read_record(&path).unwrap(), vec![entry]);
2507        let previous: PreviousRecord = serde_json::from_slice(&fs::read(path).unwrap()).unwrap();
2508        assert_eq!(previous.version, 2);
2509        let previous = &previous.children[0];
2510        assert_eq!(previous.module_id, "windows-child");
2511        assert_eq!(previous.pid, 40);
2512        assert_eq!(previous.protocol, ModuleProtocol::None);
2513        assert_eq!(previous.start_time, Some(1_000));
2514        assert_eq!(previous.cgroup_name.as_deref(), Some("windows-child-a"));
2515        assert_eq!(previous.executable.as_ref().unwrap().device, 0);
2516        assert_eq!(previous.executable.as_ref().unwrap().inode, 0);
2517    }
2518
2519    #[test]
2520    fn unix_record_without_windows_identity_keeps_original_child_bytes() {
2521        let dir = ScratchDir::new("unix-record-bytes");
2522        let path = record_path(&dir);
2523        write_record(&path, &[child("nats", 40)]).unwrap();
2524        assert_eq!(fs::read_to_string(path).unwrap(), "{\n  \"version\": 2,\n  \"children\": [\n    {\n      \"module_id\": \"nats\",\n      \"pid\": 40,\n      \"protocol\": \"none\",\n      \"start_time\": 1000,\n      \"executable\": {\n        \"device\": 7,\n        \"inode\": 11\n      },\n      \"cgroup_name\": \"nats-a\"\n    }\n  ]\n}");
2525    }
2526
2527    #[cfg(windows)]
2528    mod windows_processes {
2529        use super::*;
2530        use std::os::windows::process::CommandExt;
2531
2532        struct ChildGuard(std::process::Child);
2533        impl Drop for ChildGuard {
2534            fn drop(&mut self) {
2535                let _ = self.0.kill();
2536                let _ = self.0.wait();
2537            }
2538        }
2539
2540        fn spawn_recorded() -> (ChildGuard, LiveChild) {
2541            // Suspended test executable: a real process identity without running
2542            // another test suite or depending on an installed helper program.
2543            let child = std::process::Command::new(std::env::current_exe().unwrap())
2544                .creation_flags(0x4)
2545                .spawn()
2546                .unwrap();
2547            let entry = LiveChild {
2548                container: None,
2549                module_id: "previous".to_owned(),
2550                pid: child.id(),
2551                protocol: ModuleProtocol::None,
2552                start_time: subc_os::start_time(child.id()),
2553                executable: None,
2554                cgroup_name: None,
2555            };
2556            assert!(entry.start_time.is_some());
2557            (ChildGuard(child), entry)
2558        }
2559
2560        #[tokio::test]
2561        async fn windows_orphan_sweep_leaves_different_creation_time_alone() {
2562            let (mut child, mut entry) = spawn_recorded();
2563            entry.start_time = entry.start_time.map(|time| time + 1);
2564            let dir = ScratchDir::new("windows-sweep-reused-pid");
2565            let path = record_path(&dir);
2566            write_record(&path, std::slice::from_ref(&entry)).unwrap();
2567            let owner = RunDirLock::acquire(&path).unwrap();
2568            let decisions =
2569                sweep_orphans(&owner, &AdoptedPids::none(), SweepBounds::default()).await;
2570            assert_eq!(
2571                decisions,
2572                vec![(
2573                    entry,
2574                    SweepDecision::Mismatched(IdentityVerdict::StartTimeDiffers)
2575                )]
2576            );
2577            assert!(
2578                child.0.try_wait().unwrap().is_none(),
2579                "unrelated process was terminated"
2580            );
2581        }
2582
2583        #[tokio::test]
2584        async fn windows_orphan_sweep_force_stops_matching_creation_time() {
2585            let (mut child, entry) = spawn_recorded();
2586            let dir = ScratchDir::new("windows-sweep-matched");
2587            let path = record_path(&dir);
2588            write_record(&path, std::slice::from_ref(&entry)).unwrap();
2589            let owner = RunDirLock::acquire(&path).unwrap();
2590            let decisions =
2591                sweep_orphans(&owner, &AdoptedPids::none(), SweepBounds::default()).await;
2592            assert_eq!(decisions, vec![(entry, SweepDecision::ForcedStopped)]);
2593            assert!(
2594                child.0.try_wait().unwrap().is_some(),
2595                "sweep did not await forced exit"
2596            );
2597        }
2598    }
2599
2600    #[test]
2601    fn a_missing_record_is_empty_and_an_unknown_version_is_refused() {
2602        let dir = ScratchDir::new("live-children-missing");
2603        let path = record_path(&dir);
2604        assert_eq!(read_record(&path).unwrap(), Vec::new());
2605        fs::write(&path, br#"{"version":99,"children":[]}"#).unwrap();
2606        assert!(matches!(
2607            read_record(&path),
2608            Err(RecordReadError::UnknownVersion(99))
2609        ));
2610    }
2611
2612    /// A write that fails after the new bytes are on disk but before the
2613    /// rename must leave the previous record whole and no temp file behind.
2614    #[test]
2615    fn a_failed_write_leaves_the_previous_record_whole() {
2616        let dir = ScratchDir::new("live-children-failed-write");
2617        let path = record_path(&dir);
2618        let previous = vec![child("nats", 40)];
2619        write_record(&path, &previous).unwrap();
2620        let before = fs::read(&path).unwrap();
2621
2622        let error = write_atomically(&path, b"{\"version\":1,\"chil", |temp| {
2623            assert!(temp.exists(), "the new bytes are written before the rename");
2624            Err(io::Error::other("simulated crash before rename"))
2625        })
2626        .unwrap_err();
2627        assert_eq!(error.to_string(), "simulated crash before rename");
2628        assert_eq!(fs::read(&path).unwrap(), before);
2629        assert_eq!(read_record(&path).unwrap(), previous);
2630        let leftovers: Vec<_> = fs::read_dir(&*dir)
2631            .unwrap()
2632            .map(|entry| entry.unwrap().file_name())
2633            .filter(|name| name != LIVE_CHILDREN_FILE_NAME)
2634            .collect();
2635        assert!(
2636            leftovers.is_empty(),
2637            "temp files left behind: {leftovers:?}"
2638        );
2639    }
2640
2641    /// A reader racing a writer only ever sees a complete record. Records of
2642    /// different lengths alternate, so a reader of a file written in place
2643    /// would sooner or later see a torn one.
2644    #[test]
2645    fn a_concurrent_reader_never_sees_a_partial_record() {
2646        let dir = ScratchDir::new("live-children-concurrent");
2647        let path = record_path(&dir);
2648        let short = vec![child("nats", 40)];
2649        let long: Vec<LiveChild> = (0..200).map(|pid| child("module", pid)).collect();
2650        write_record(&path, &short).unwrap();
2651        let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
2652        let rounds = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
2653        let writer = {
2654            let (path, stop, rounds, short, long) = (
2655                path.clone(),
2656                stop.clone(),
2657                rounds.clone(),
2658                short.clone(),
2659                long.clone(),
2660            );
2661            std::thread::spawn(move || {
2662                let mut round = 0usize;
2663                while !stop.load(Ordering::Relaxed) {
2664                    let children = if round.is_multiple_of(2) {
2665                        &long
2666                    } else {
2667                        &short
2668                    };
2669                    write_record(&path, children).unwrap();
2670                    round += 1;
2671                    rounds.store(round, Ordering::Relaxed);
2672                }
2673            })
2674        };
2675        // Keep reading until the writer has really overlapped the reads. A
2676        // fixed number of reads can finish before a busy machine schedules the
2677        // writer at all, which proves nothing about torn records and used to
2678        // fail the "writer ran" check instead.
2679        const MIN_READS: usize = 2_000;
2680        const MIN_WRITER_ROUNDS: usize = 50;
2681        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60);
2682        let mut reads = 0usize;
2683        while reads < MIN_READS || rounds.load(Ordering::Relaxed) < MIN_WRITER_ROUNDS {
2684            assert!(
2685                std::time::Instant::now() < deadline,
2686                "writer completed only {} rounds in 60 s",
2687                rounds.load(Ordering::Relaxed)
2688            );
2689            let read = read_record(&path).expect("every read sees a complete record");
2690            assert!(
2691                read == short || read == long,
2692                "read a torn record: {read:?}"
2693            );
2694            reads += 1;
2695        }
2696        stop.store(true, Ordering::Relaxed);
2697        writer.join().unwrap();
2698    }
2699
2700    #[test]
2701    fn matcher_accepts_only_when_pid_start_time_and_executable_all_match() {
2702        let recorded = child("nats", 40);
2703        assert_eq!(
2704            identity_verdict(&recorded, 40, &observed(1_000, 7, 11)),
2705            IdentityVerdict::Matches
2706        );
2707    }
2708
2709    #[test]
2710    fn matcher_refuses_another_pid() {
2711        let recorded = child("nats", 40);
2712        assert_eq!(
2713            identity_verdict(&recorded, 41, &observed(1_000, 7, 11)),
2714            IdentityVerdict::PidDiffers
2715        );
2716    }
2717
2718    #[test]
2719    fn matcher_refuses_a_reused_pid_with_another_start_time() {
2720        let recorded = child("nats", 40);
2721        assert_eq!(
2722            identity_verdict(&recorded, 40, &observed(1_001, 7, 11)),
2723            IdentityVerdict::StartTimeDiffers
2724        );
2725    }
2726
2727    #[test]
2728    fn matcher_refuses_same_pid_and_start_time_running_another_executable() {
2729        let recorded = child("nats", 40);
2730        assert_eq!(
2731            identity_verdict(&recorded, 40, &observed(1_000, 7, 12)),
2732            IdentityVerdict::ExecutableDiffers
2733        );
2734        assert_eq!(
2735            identity_verdict(&recorded, 40, &observed(1_000, 8, 11)),
2736            IdentityVerdict::ExecutableDiffers
2737        );
2738    }
2739
2740    #[test]
2741    fn matcher_refuses_whatever_it_cannot_compare() {
2742        let mut no_start = child("nats", 40);
2743        no_start.start_time = None;
2744        assert_eq!(
2745            identity_verdict(&no_start, 40, &observed(1_000, 7, 11)),
2746            IdentityVerdict::StartTimeUnrecorded
2747        );
2748        let mut no_exe = child("nats", 40);
2749        no_exe.executable = None;
2750        assert_eq!(
2751            identity_verdict(&no_exe, 40, &observed(1_000, 7, 11)),
2752            IdentityVerdict::ExecutableUnrecorded
2753        );
2754        let unreadable = subc_os::Observation {
2755            start_time: 1_000,
2756            executable: None,
2757        };
2758        assert_eq!(
2759            identity_verdict(&child("nats", 40), 40, &unreadable),
2760            IdentityVerdict::ExecutableUnreadable
2761        );
2762    }
2763
2764    /// The roster rewrites the record on every admit and release, so it
2765    /// always lists exactly the processes the daemon has running.
2766    #[test]
2767    fn the_roster_keeps_the_record_in_step_with_admits_and_releases() {
2768        let dir = ScratchDir::new("roster-record");
2769        let path = record_path(&dir);
2770        let roster = crate::child_roster::ChildRoster::default();
2771        roster.record_to(path.clone());
2772        let recorded = crate::child_roster::RecordedIdentity {
2773            container: None,
2774            #[cfg(unix)]
2775            carried: None,
2776            #[cfg(unix)]
2777            plain_group: None,
2778            start_time: Some(5),
2779            executable: Some(ExecutableIdentity {
2780                device: 1,
2781                inode: 2,
2782                macos_sh_interpreter: None,
2783                windows_file_identity: None,
2784            }),
2785            cgroup_name: Some("nats-a".to_owned()),
2786            #[cfg(target_os = "linux")]
2787            cgroup_placement: None,
2788        };
2789        let first = roster.admit(
2790            "nats".to_owned(),
2791            40,
2792            ModuleProtocol::None,
2793            None,
2794            recorded.clone(),
2795        );
2796        let second = roster.admit(
2797            "aft".to_owned(),
2798            41,
2799            ModuleProtocol::Subc,
2800            None,
2801            crate::child_roster::RecordedIdentity::default(),
2802        );
2803        let pids = |path: &Path| -> Vec<u32> {
2804            read_record(path)
2805                .unwrap()
2806                .iter()
2807                .map(|child| child.pid)
2808                .collect()
2809        };
2810        assert_eq!(pids(&path), vec![40, 41]);
2811        assert_eq!(
2812            read_record(&path).unwrap()[0],
2813            LiveChild {
2814                module_id: "nats".to_owned(),
2815                pid: 40,
2816                protocol: ModuleProtocol::None,
2817                start_time: Some(5),
2818                executable: recorded.executable,
2819                cgroup_name: Some("nats-a".to_owned()),
2820                container: None,
2821            }
2822        );
2823        drop(first);
2824        assert_eq!(pids(&path), vec![41]);
2825        drop(second);
2826        assert_eq!(pids(&path), Vec::<u32>::new());
2827    }
2828
2829    #[cfg(any(target_os = "linux", target_os = "macos"))]
2830    mod real_processes {
2831        use std::{
2832            os::unix::process::ExitStatusExt,
2833            path::Path,
2834            process::{Child, Command, Stdio},
2835            time::Instant,
2836        };
2837
2838        use super::*;
2839
2840        fn executable(name: &str) -> PathBuf {
2841            ["/bin", "/usr/bin"]
2842                .into_iter()
2843                .map(|dir| Path::new(dir).join(name))
2844                .find(|path| path.exists())
2845                .unwrap_or_else(|| panic!("{name} is installed"))
2846        }
2847
2848        /// A child of this test standing in for a previous daemon's child,
2849        /// recorded the way the daemon records one at spawn: the start time
2850        /// read right after spawn and the spawned path's device and inode.
2851        fn spawn_recorded(program: &Path, args: &[&str]) -> (Child, LiveChild) {
2852            let child = Command::new(program)
2853                .args(args)
2854                .stdin(Stdio::piped())
2855                .spawn()
2856                .unwrap();
2857            let entry = LiveChild {
2858                container: None,
2859                module_id: "previous".to_owned(),
2860                pid: child.id(),
2861                protocol: ModuleProtocol::None,
2862                start_time: subc_os::start_time(child.id()),
2863                executable: subc_os::file_identity(program).map(ExecutableIdentity::from),
2864                cgroup_name: None,
2865            };
2866            assert!(entry.start_time.is_some() && entry.executable.is_some());
2867            // Until its exec completes the child still runs this test's image.
2868            let deadline = Instant::now() + Duration::from_secs(5);
2869            while subc_os::Process::open(child.id())
2870                .unwrap()
2871                .and_then(|process| process.observe())
2872                .and_then(|observation| observation.executable)
2873                .map(ExecutableIdentity::from)
2874                != entry.executable
2875            {
2876                assert!(Instant::now() < deadline, "child never ran {program:?}");
2877                std::thread::sleep(Duration::from_millis(5));
2878            }
2879            (child, entry)
2880        }
2881
2882        fn quick() -> SweepBounds {
2883            SweepBounds {
2884                term_grace: Duration::from_millis(300),
2885                kill_bound: Duration::from_secs(2),
2886            }
2887        }
2888
2889        fn still_running(child: &mut Child) -> bool {
2890            child.try_wait().unwrap().is_none()
2891        }
2892
2893        #[tokio::test]
2894        async fn a_recorded_child_still_running_is_terminated_at_boot() {
2895            let dir = ScratchDir::new("sweep-terminates");
2896            let path = record_path(&dir);
2897            let (mut child, entry) = spawn_recorded(&executable("sleep"), &["60"]);
2898            write_record(&path, std::slice::from_ref(&entry)).unwrap();
2899
2900            let decisions = sweep_orphans(
2901                &RunDirLock::acquire(&path).unwrap(),
2902                &AdoptedPids::none(),
2903                quick(),
2904            )
2905            .await;
2906
2907            assert_eq!(decisions, vec![(entry, SweepDecision::Terminated)]);
2908            let status = child.wait().unwrap();
2909            assert_eq!(status.signal(), Some(15), "ended by SIGTERM: {status}");
2910            assert_eq!(read_record(&path).unwrap(), Vec::new());
2911        }
2912
2913        #[cfg(target_os = "linux")]
2914        #[tokio::test]
2915        async fn linux_child_with_other_executable_read_failure_is_not_signalled() {
2916            let (mut child, entry) = spawn_recorded(&executable("sleep"), &["60"]);
2917            // Inject an unavailable image into a live child's observation. Unlike
2918            // EACCES/EPERM, an ENOENT or I/O failure must still prevent signalling
2919            // even when the recorded PID and start time match.
2920            let recorded = RecordedChild {
2921                child: entry,
2922                resume_token_sha256: None,
2923            };
2924            let decisions =
2925                sweep_entries_with_verdict(vec![recorded.clone()], quick(), |entry, process| {
2926                    let mut observed = process.observe().unwrap();
2927                    observed.executable = None;
2928                    Some(verdict_with_executable_access(
2929                        entry,
2930                        process.pid(),
2931                        &observed,
2932                        subc_os::ExecutableAccess::Unavailable,
2933                    ))
2934                })
2935                .await;
2936            let alive = still_running(&mut child);
2937            child.kill().unwrap();
2938            child.wait().unwrap();
2939            assert_eq!(
2940                decisions,
2941                vec![(
2942                    recorded,
2943                    SweepDecision::Unverifiable(
2944                        IdentityVerdict::ExecutableUnreadable.describe().to_owned()
2945                    )
2946                )]
2947            );
2948            assert!(alive, "the sweep must leave the unreadable child running");
2949        }
2950
2951        #[cfg(target_os = "linux")]
2952        async fn retained_orphan_blocks_only_its_module(survived: bool) {
2953            use crate::supervise::{ModuleOverlap, ModuleSpec, RestartPolicy, Supervisor};
2954            use std::sync::Arc;
2955
2956            let dir = ScratchDir::new("unverified-orphan-blocks-one");
2957            let path = record_path(&dir);
2958            let program = executable("sleep");
2959            let (child, entry) = spawn_recorded(&program, &["60"]);
2960            let mut fixture = NonDumpableChild {
2961                child,
2962                entry,
2963                program: program.clone(),
2964            };
2965            write_record(&path, std::slice::from_ref(&fixture.entry)).unwrap();
2966            let owner = RunDirLock::acquire(&path).unwrap();
2967            let decisions = sweep_orphans_with(
2968                &owner,
2969                &AdoptedPids::none(),
2970                SweepBounds {
2971                    term_grace: Duration::ZERO,
2972                    kill_bound: Duration::ZERO,
2973                },
2974                |entries, bounds| async move {
2975                    sweep_entries_with_hooks(
2976                        entries,
2977                        bounds,
2978                        |entry, process| {
2979                            if survived {
2980                                current_verdict(entry, process)
2981                            } else {
2982                                let mut observed = process.observe().unwrap();
2983                                observed.executable = None;
2984                                Some(verdict_with_executable_access(
2985                                    entry,
2986                                    process.pid(),
2987                                    &observed,
2988                                    subc_os::ExecutableAccess::Unavailable,
2989                                ))
2990                            }
2991                        },
2992                        |_process, signal| {
2993                            // Simulate successful TERM delivery without exiting, then
2994                            // a failed KILL. The real child stays killable for cleanup.
2995                            if signal == subc_os::Signal::Terminate {
2996                                Ok(true)
2997                            } else {
2998                                Err(io::Error::other("injected signal failure"))
2999                            }
3000                        },
3001                    )
3002                    .await
3003                },
3004            )
3005            .await;
3006            let reason = if survived {
3007                RetainedReason::Survived
3008            } else {
3009                RetainedReason::Unverifiable
3010            };
3011            assert_eq!(decisions.len(), 1);
3012            assert_eq!(decisions[0].1.retained_reason(), Some(reason.clone()));
3013            assert_eq!(
3014                read_record(&path).unwrap(),
3015                vec![fixture.entry.clone()],
3016                "the top-level sweep must retain the blocker"
3017            );
3018            assert!(still_running(&mut fixture.child));
3019
3020            let roster = crate::child_roster::ChildRoster::default();
3021            roster.record_to(path.clone());
3022            assert_eq!(
3023                roster.previous_instance("previous"),
3024                Some((fixture.entry.pid, reason.clone()))
3025            );
3026            assert_eq!(roster.previous_instance_pid("unrelated"), None);
3027            let guard = roster.admit(
3028                "unrelated".to_owned(),
3029                std::process::id(),
3030                ModuleProtocol::None,
3031                None,
3032                crate::child_roster::RecordedIdentity::default(),
3033            );
3034            assert!(read_record(&path).unwrap().contains(&fixture.entry));
3035            drop(guard);
3036            let supervisor = Supervisor::new(
3037                Arc::new(crate::registry::Registry::default()),
3038                RestartPolicy::default(),
3039            )
3040            .with_live_children_record(path.clone());
3041            let spec = |module_id: &str| ModuleSpec {
3042                script: None,
3043                carry_containment: false,
3044                module_id: module_id.to_owned(),
3045                program: program.clone(),
3046                args: vec!["60".to_owned()],
3047                env: vec![],
3048                reserved: false,
3049                reserved_prefixes: vec![],
3050                protocol: ModuleProtocol::None,
3051                overlap: ModuleOverlap::Exclusive,
3052            };
3053            let waiting = supervisor
3054                .supervise_configured(spec("previous"), true)
3055                .unwrap();
3056            let other = supervisor
3057                .supervise_configured(spec("unrelated"), true)
3058                .unwrap();
3059            let status = waiting.status().unwrap();
3060            assert_eq!(status.waiting_for_previous_pid, Some(fixture.entry.pid));
3061            assert_eq!(
3062                status.waiting_for_previous_detail,
3063                Some(reason.waiting_message(fixture.entry.pid))
3064            );
3065            assert!(!status.process_alive && status.pid.is_none());
3066            assert_eq!(status.spawn_generation, 0);
3067            assert!(
3068                other.status().unwrap().live,
3069                "an unrelated module must start"
3070            );
3071            let refusal = waiting.set_enabled(true).await.unwrap_err().to_string();
3072            assert!(refusal.contains(&reason.waiting_message(fixture.entry.pid)));
3073            assert!(waiting.restart(None).await.is_err());
3074            assert!(waiting.reload().await.is_err());
3075            assert!(waiting.swap(None).await.is_err());
3076            assert!(supervisor.spawn(spec("previous")).is_err());
3077            other.stop().await.unwrap();
3078            waiting.stop().await.unwrap();
3079            assert_eq!(read_record(&path).unwrap(), vec![fixture.entry.clone()]);
3080            assert!(still_running(&mut fixture.child));
3081            fixture.child.kill().unwrap();
3082            fixture.child.wait().unwrap();
3083            assert_eq!(roster.previous_instance_pid("previous"), None);
3084            assert!(read_record(&path).unwrap().is_empty());
3085        }
3086
3087        #[cfg(target_os = "linux")]
3088        #[tokio::test]
3089        async fn live_unverifiable_orphan_is_retained_and_blocks_only_its_module() {
3090            retained_orphan_blocks_only_its_module(false).await;
3091        }
3092
3093        #[cfg(target_os = "linux")]
3094        #[tokio::test]
3095        async fn surviving_orphan_is_retained_and_blocks_only_its_module() {
3096            retained_orphan_blocks_only_its_module(true).await;
3097        }
3098
3099        #[tokio::test]
3100        async fn a_recorded_child_ignoring_sigterm_is_killed_after_the_grace() {
3101            let dir = ScratchDir::new("sweep-kills");
3102            let path = record_path(&dir);
3103            // `read` is a shell builtin, so the shell itself waits on the
3104            // piped stdin with SIGTERM ignored; nothing else is exec'd. The
3105            // marker (the script's `$0`) appears once the trap is in place.
3106            let ready = dir.join("ready");
3107            let (mut child, entry) = spawn_recorded(
3108                &executable("bash"),
3109                &[
3110                    "-c",
3111                    "trap '' TERM; : > \"$0\"; read -r _",
3112                    ready.to_str().unwrap(),
3113                ],
3114            );
3115            let deadline = Instant::now() + Duration::from_secs(5);
3116            while !ready.exists() {
3117                assert!(Instant::now() < deadline, "shell never installed its trap");
3118                std::thread::sleep(Duration::from_millis(5));
3119            }
3120            write_record(&path, std::slice::from_ref(&entry)).unwrap();
3121
3122            let started = Instant::now();
3123            let decisions = sweep_orphans(
3124                &RunDirLock::acquire(&path).unwrap(),
3125                &AdoptedPids::none(),
3126                quick(),
3127            )
3128            .await;
3129
3130            assert_eq!(decisions, vec![(entry, SweepDecision::Killed)]);
3131            assert!(started.elapsed() >= quick().term_grace);
3132            let status = child.wait().unwrap();
3133            assert_eq!(status.signal(), Some(9), "ended by SIGKILL: {status}");
3134        }
3135
3136        #[tokio::test]
3137        async fn a_pid_now_held_by_an_unrelated_process_is_not_signalled() {
3138            let dir = ScratchDir::new("sweep-reused-pid");
3139            let path = record_path(&dir);
3140            let (mut child, entry) = spawn_recorded(&executable("sleep"), &["60"]);
3141            // The record says the pid belonged to a process started at
3142            // another time: what a reaped pid handed to a new process reads as.
3143            let mut reused = entry.clone();
3144            reused.start_time = reused.start_time.map(|start| start + 1);
3145            write_record(&path, std::slice::from_ref(&reused)).unwrap();
3146
3147            let decisions = sweep_orphans(
3148                &RunDirLock::acquire(&path).unwrap(),
3149                &AdoptedPids::none(),
3150                quick(),
3151            )
3152            .await;
3153
3154            assert_eq!(
3155                decisions,
3156                vec![(
3157                    reused,
3158                    SweepDecision::Mismatched(IdentityVerdict::StartTimeDiffers)
3159                )]
3160            );
3161            assert!(
3162                still_running(&mut child),
3163                "an unrelated process was signalled"
3164            );
3165            child.kill().unwrap();
3166            child.wait().unwrap();
3167        }
3168
3169        #[tokio::test]
3170        async fn same_pid_and_start_time_running_another_executable_is_not_signalled() {
3171            let dir = ScratchDir::new("sweep-other-executable");
3172            let path = record_path(&dir);
3173            let (mut child, entry) = spawn_recorded(&executable("sleep"), &["60"]);
3174            let mut other = entry.clone();
3175            other.executable = subc_os::file_identity(&std::env::current_exe().unwrap())
3176                .map(ExecutableIdentity::from);
3177            write_record(&path, std::slice::from_ref(&other)).unwrap();
3178
3179            let decisions = sweep_orphans(
3180                &RunDirLock::acquire(&path).unwrap(),
3181                &AdoptedPids::none(),
3182                quick(),
3183            )
3184            .await;
3185
3186            assert_eq!(
3187                decisions,
3188                vec![(
3189                    other,
3190                    SweepDecision::Mismatched(IdentityVerdict::ExecutableDiffers)
3191                )]
3192            );
3193            assert!(
3194                still_running(&mut child),
3195                "an unrelated process was signalled"
3196            );
3197            child.kill().unwrap();
3198            child.wait().unwrap();
3199        }
3200
3201        #[tokio::test]
3202        async fn an_entry_for_a_gone_process_is_dropped() {
3203            let dir = ScratchDir::new("sweep-gone");
3204            let path = record_path(&dir);
3205            let (mut child, entry) = spawn_recorded(&executable("sleep"), &["60"]);
3206            child.kill().unwrap();
3207            child.wait().unwrap();
3208            write_record(&path, std::slice::from_ref(&entry)).unwrap();
3209
3210            let decisions = sweep_orphans(
3211                &RunDirLock::acquire(&path).unwrap(),
3212                &AdoptedPids::none(),
3213                quick(),
3214            )
3215            .await;
3216
3217            assert_eq!(decisions, vec![(entry, SweepDecision::Gone)]);
3218            assert_eq!(read_record(&path).unwrap(), Vec::new());
3219        }
3220
3221        #[tokio::test]
3222        async fn an_adopted_pid_is_left_running() {
3223            let dir = ScratchDir::new("sweep-adopted");
3224            let path = record_path(&dir);
3225            let (mut child, entry) = spawn_recorded(&executable("sleep"), &["60"]);
3226            write_record(&path, std::slice::from_ref(&entry)).unwrap();
3227
3228            let decisions = sweep_orphans(
3229                &RunDirLock::acquire(&path).unwrap(),
3230                &AdoptedPids::from_classes([entry.pid], []),
3231                quick(),
3232            )
3233            .await;
3234
3235            assert_eq!(decisions, vec![(entry, SweepDecision::Adopted)]);
3236            assert!(still_running(&mut child), "an adopted child was signalled");
3237            child.kill().unwrap();
3238            child.wait().unwrap();
3239        }
3240
3241        #[tokio::test]
3242        async fn an_unconfirmed_trampoline_image_is_never_signalled_by_orphan_cleanup() {
3243            let dir = ScratchDir::new("sweep-unconfirmed-trampoline");
3244            let path = record_path(&dir);
3245            let (mut child, mut entry) = spawn_recorded(&executable("sleep"), &["60"]);
3246            entry.executable = None;
3247            write_record(&path, std::slice::from_ref(&entry)).unwrap();
3248            let decisions = sweep_orphans(
3249                &RunDirLock::acquire(&path).unwrap(),
3250                &AdoptedPids::none(),
3251                quick(),
3252            )
3253            .await;
3254            assert_eq!(
3255                decisions,
3256                vec![(
3257                    entry,
3258                    SweepDecision::Unverifiable(
3259                        IdentityVerdict::ExecutableUnrecorded.describe().to_owned()
3260                    )
3261                )]
3262            );
3263            assert!(
3264                still_running(&mut child),
3265                "a pid without a confirmed module image was signalled"
3266            );
3267            child.kill().unwrap();
3268            child.wait().unwrap();
3269        }
3270    }
3271}