Skip to main content

subc_daemon/
live_children.rs

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