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