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