subc-daemon 0.21.0

Embeddable subc daemon: bootstrap, module supervision, and opaque-byte splice routing.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
use std::path::Path;

#[cfg(target_os = "linux")]
use std::{
    collections::HashMap,
    fs::File,
    io::{self, Read},
    path::PathBuf,
    sync::{Arc, Mutex},
};

#[cfg(target_os = "linux")]
use sha2::{Digest, Sha256};
use subc_control::{RunningImageAgreement, RunningImageUnavailableReason};
// Both evidence constructors are cfg-gated to their probing platform, so on a
// platform without a probe this import has no user and -D warnings rejects it.
#[cfg(any(target_os = "linux", target_os = "macos", test))]
use subc_control::RunningImageEvidence;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct SpawnedFileIdentity {
    pub(crate) device: u64,
    pub(crate) inode: u64,
}

pub(crate) fn spawned_file_identity(path: &Path) -> Option<SpawnedFileIdentity> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;

        // Followed metadata identifies the spawn-time target the supervisor executed, not a symlink name.
        std::fs::metadata(path)
            .ok()
            .map(|metadata| SpawnedFileIdentity {
                device: metadata.dev(),
                inode: metadata.ino(),
            })
    }

    #[cfg(not(unix))]
    {
        let _ = path;
        None
    }
}

#[derive(Debug, Clone, Default)]
pub(crate) struct ExecutableIdentityProbe {
    #[cfg(target_os = "linux")]
    cache: Arc<Mutex<ImageDigestCache>>,
}

impl ExecutableIdentityProbe {
    pub(crate) async fn observe(
        &self,
        pid: Option<u32>,
        spawned_from: Option<&Path>,
        _spawned_identity: Option<SpawnedFileIdentity>,
        expected_start_time: Option<u64>,
    ) -> RunningImageAgreement {
        let Some(pid) = pid else {
            return unavailable(RunningImageUnavailableReason::NotRunning);
        };
        let Some(spawned_from) = spawned_from else {
            return unavailable(RunningImageUnavailableReason::SpawnedPathUnreadable);
        };

        #[cfg(target_os = "linux")]
        {
            let Some(expected_start_time) = expected_start_time else {
                return unavailable(RunningImageUnavailableReason::ProcessIdentityUnconfirmed);
            };
            let cache = Arc::clone(&self.cache);
            let running_path = PathBuf::from(format!("/proc/{pid}/exe"));
            let spawned_from = spawned_from.to_path_buf();
            tokio::task::spawn_blocking(move || {
                let running = match File::open(&running_path) {
                    Ok(file) => file,
                    Err(_) => {
                        return unavailable(
                            RunningImageUnavailableReason::RunningExecutableUnreadable,
                        )
                    }
                };
                if process_start_time(pid) != Some(expected_start_time) {
                    return unavailable(RunningImageUnavailableReason::ProcessIdentityUnconfirmed);
                }
                if !exe_link_names_spawned_path(pid, &spawned_from) {
                    return unavailable(RunningImageUnavailableReason::ProcessIdentityUnconfirmed);
                }
                let mut cache = cache
                    .lock()
                    .unwrap_or_else(|poisoned| poisoned.into_inner());
                compare_opened_descriptor(&mut cache, &running_path, running, &spawned_from)
            })
            .await
            .unwrap_or_else(|_| unavailable(RunningImageUnavailableReason::HashFailed))
        }

        #[cfg(target_os = "macos")]
        {
            let _ = (pid, expected_start_time);
            match (_spawned_identity, spawned_file_identity(spawned_from)) {
                (Some(spawned_identity), Some(current_identity)) => {
                    compare_spawn_inode(spawned_identity, current_identity)
                }
                _ => unavailable(RunningImageUnavailableReason::SpawnedPathUnreadable),
            }
        }

        #[cfg(not(any(target_os = "linux", target_os = "macos")))]
        {
            let _ = (pid, spawned_from, _spawned_identity, expected_start_time);
            unavailable(RunningImageUnavailableReason::UnsupportedPlatform)
        }
    }
}

/// Whether `/proc/<pid>/exe` names the path the supervisor spawned, so the
/// image digested through that link is the spawned program's and not some
/// other file the pid happens to be executing.
///
/// The case this exists for is a child observed in the instant after
/// `spawn()` returned. With glibc's `posix_spawn` the parent resumes when the
/// child releases the old address space, which the kernel does in
/// `exec_mmap` before installing the new one, so for a moment the child's
/// exe link still names the parent's own binary. A digest read through the
/// link then is the parent's, it disagrees with the spawned file by
/// construction, and without this check the probe called that a `Mismatch`
/// (twice on GitHub's Ubuntu runners; the running digest changed with every
/// build while the disk digest never did). The same guard covers a program
/// that re-executes another binary, such as a wrapper script: the probe
/// cannot confirm that image against the spawned path, and says so, rather
/// than reporting the wrapper as replaced.
///
/// A replaced binary is not this case: rename-over leaves the link naming
/// the same path with ` (deleted)` appended, which is stripped so the digest
/// comparison still runs and reports the replacement.
#[cfg(target_os = "linux")]
fn exe_link_names_spawned_path(pid: u32, spawned_from: &Path) -> bool {
    let Ok(link) = std::fs::read_link(format!("/proc/{pid}/exe")) else {
        return false;
    };
    let Ok(spawned) = std::fs::canonicalize(spawned_from) else {
        return false;
    };
    let link = link.to_string_lossy();
    let link = link.strip_suffix(" (deleted)").unwrap_or(&link);
    Path::new(link) == spawned
}

#[cfg(target_os = "linux")]
pub(crate) fn process_start_time(pid: u32) -> Option<u64> {
    std::fs::read_to_string(format!("/proc/{pid}/stat"))
        .ok()
        .and_then(|stat| process_start_time_from_stat(&stat))
}

#[cfg(not(target_os = "linux"))]
pub(crate) fn process_start_time(_pid: u32) -> Option<u64> {
    None
}

#[cfg(any(target_os = "linux", test))]
fn process_start_time_from_stat(stat: &str) -> Option<u64> {
    stat.rsplit_once(')')?
        .1
        .split_whitespace()
        .nth(19)?
        .parse()
        .ok()
}

#[cfg(target_os = "linux")]
#[derive(Debug, Default)]
struct ImageDigestCache {
    digests: HashMap<FileCacheKey, String>,
    #[cfg(all(test, target_os = "linux"))]
    digest_computations: usize,
}

#[cfg(target_os = "linux")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct FileCacheKey {
    device: u64,
    inode: u64,
    size: u64,
    mtime_sec: i64,
    mtime_nsec: i64,
}

#[cfg(target_os = "linux")]
fn compare_opened_paths(
    cache: &mut ImageDigestCache,
    running_path: &Path,
    spawned_path: &Path,
) -> RunningImageAgreement {
    let running = match File::open(running_path) {
        Ok(file) => file,
        Err(_) => return unavailable(RunningImageUnavailableReason::RunningExecutableUnreadable),
    };
    compare_opened_descriptor(cache, running_path, running, spawned_path)
}

#[cfg(target_os = "linux")]
fn compare_opened_descriptor(
    cache: &mut ImageDigestCache,
    _running_path: &Path,
    running: File,
    spawned_path: &Path,
) -> RunningImageAgreement {
    let disk = match File::open(spawned_path) {
        Ok(file) => file,
        Err(_) => return unavailable(RunningImageUnavailableReason::SpawnedPathUnreadable),
    };
    let running = match digest_open_file(cache, running) {
        Ok(digest) => digest,
        Err(_) => return unavailable(RunningImageUnavailableReason::HashFailed),
    };
    let disk = match digest_open_file(cache, disk) {
        Ok(digest) => digest,
        Err(_) => return unavailable(RunningImageUnavailableReason::HashFailed),
    };
    let running = RunningImageEvidence::LinuxProcSha256 { digest: running };
    let disk = RunningImageEvidence::LinuxProcSha256 { digest: disk };
    if running == disk {
        RunningImageAgreement::Match { evidence: running }
    } else {
        RunningImageAgreement::Mismatch { running, disk }
    }
}

#[cfg(target_os = "linux")]
fn digest_open_file(cache: &mut ImageDigestCache, mut file: File) -> io::Result<String> {
    let key = cache_key(&file)?;
    if let Some(digest) = cache.digests.get(&key) {
        return Ok(digest.clone());
    }

    let mut hasher = Sha256::new();
    let mut buffer = [0u8; 8192];
    loop {
        let read = file.read(&mut buffer)?;
        if read == 0 {
            break;
        }
        hasher.update(&buffer[..read]);
    }
    let digest = format!("{:x}", hasher.finalize());
    if cache.digests.len() == 64 {
        cache.digests.clear();
    }
    cache.digests.insert(key, digest.clone());
    #[cfg(test)]
    {
        cache.digest_computations += 1;
    }
    Ok(digest)
}

#[cfg(target_os = "linux")]
/// All five fields are load-bearing; none is redundant. Inode numbers are
/// reused after deletion, so a `(device, inode)` key alone would serve a
/// cached digest for replaced content — the same identifier-reuse hazard the
/// start-time pairing above guards against for PIDs. `size` and the
/// nanosecond mtime are what make a recycled inode miss the cache.
fn cache_key(file: &File) -> io::Result<FileCacheKey> {
    use std::os::unix::fs::MetadataExt;

    let metadata = file.metadata()?;
    Ok(FileCacheKey {
        device: metadata.dev(),
        inode: metadata.ino(),
        size: metadata.len(),
        mtime_sec: metadata.mtime(),
        mtime_nsec: metadata.mtime_nsec(),
    })
}

#[cfg(any(target_os = "macos", test))]
fn compare_spawn_inode(
    spawned: SpawnedFileIdentity,
    current: SpawnedFileIdentity,
) -> RunningImageAgreement {
    let running = RunningImageEvidence::MacosSpawnInode {
        device: spawned.device,
        inode: spawned.inode,
    };
    let disk = RunningImageEvidence::MacosSpawnInode {
        device: current.device,
        inode: current.inode,
    };
    if running == disk {
        RunningImageAgreement::Match { evidence: running }
    } else {
        RunningImageAgreement::Mismatch { running, disk }
    }
}

fn unavailable(reason: RunningImageUnavailableReason) -> RunningImageAgreement {
    RunningImageAgreement::Unavailable { reason }
}

#[cfg(all(test, target_os = "linux"))]
impl ImageDigestCache {
    fn len(&self) -> usize {
        self.digests.len()
    }

    fn digest_computations(&self) -> usize {
        self.digest_computations
    }
}

#[cfg(test)]
mod tests {
    // Only the linux sha256 tests open files directly, and only non-linux
    // platforms assert the unavailable arm; each import gates with its users
    // so the other platforms' clippy does not fail them as unused.
    #[cfg(target_os = "linux")]
    use std::fs;
    #[cfg(target_os = "linux")]
    use std::fs::File;
    #[cfg(target_os = "linux")]
    use tokio::process::Command;

    use super::*;
    use crate::test_support::TestTempDir;
    use subc_control::RunningImageAgreement;
    #[cfg(target_os = "linux")]
    use subc_control::RunningImageUnavailableReason;

    fn temp_dir(label: &str) -> TestTempDir {
        TestTempDir::new(label)
    }

    /// A live child running a copy of `sleep` that the test owns, returned
    /// once its exe link names that copy.
    ///
    /// The spawn retries on `ETXTBSY`. Tests run in parallel threads, and a
    /// `Command::spawn` on another thread forks while this thread's
    /// `fs::copy` still holds the file open for write; the forked child
    /// carries that descriptor until its own exec, and during that window
    /// the kernel refuses to execute the file (6 in 80 runs on a two-core
    /// VM). Then the wait: `spawn()` can return while the child's exe link
    /// still names this test binary (see `exe_link_names_spawned_path`), so
    /// the probe is only run once the link has moved. Both bounded, so a
    /// child that never gets there fails the test rather than hanging it.
    #[cfg(target_os = "linux")]
    async fn spawn_owned_sleep(dir: &Path) -> (tokio::process::Child, PathBuf) {
        let executable = dir.join("sleep");
        fs::copy("/bin/sleep", &executable).unwrap();
        let mut attempts = 0;
        let child = loop {
            match Command::new(&executable).arg("60").spawn() {
                Ok(child) => break child,
                Err(err) if err.kind() == io::ErrorKind::ExecutableFileBusy && attempts < 50 => {
                    attempts += 1;
                    tokio::time::sleep(std::time::Duration::from_millis(10)).await;
                }
                Err(err) => panic!("spawn {}: {err}", executable.display()),
            }
        };
        let pid = child.id().unwrap();
        let canonical = fs::canonicalize(&executable).unwrap();
        for _ in 0..200 {
            if fs::read_link(format!("/proc/{pid}/exe")).ok().as_deref() == Some(&*canonical) {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        }
        (child, executable)
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn equal_opened_images_match() {
        let dir = temp_dir("equal");
        let left = dir.join("left");
        let right = dir.join("right");
        fs::write(&left, b"same executable image").unwrap();
        fs::write(&right, b"same executable image").unwrap();

        let mut cache = ImageDigestCache::default();
        let agreement = compare_opened_paths(&mut cache, &left, &right);

        assert!(matches!(agreement, RunningImageAgreement::Match { .. }));
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn changed_opened_image_mismatches_with_distinct_digests() {
        let dir = temp_dir("mismatch");
        let left = dir.join("left");
        let right = dir.join("right");
        fs::write(&left, b"original executable image").unwrap();
        fs::write(&right, b"original executable image").unwrap();
        fs::write(&right, b"mutated executable image with a different size").unwrap();

        let mut cache = ImageDigestCache::default();
        let agreement = compare_opened_paths(&mut cache, &left, &right);

        match agreement {
            RunningImageAgreement::Mismatch { running, disk } => assert_ne!(running, disk),
            other => panic!("expected distinct digests after mutation, got {other:?}"),
        }
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn missing_image_is_typed_unavailable() {
        let dir = temp_dir("missing");
        let left = dir.join("left");
        fs::write(&left, b"existing executable image").unwrap();

        let mut cache = ImageDigestCache::default();
        let agreement = compare_opened_paths(&mut cache, &left, &dir.join("missing"));

        assert_eq!(
            agreement,
            RunningImageAgreement::Unavailable {
                reason: RunningImageUnavailableReason::SpawnedPathUnreadable,
            }
        );
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn missing_running_image_is_typed_unavailable() {
        let dir = temp_dir("missing-running");
        let disk = dir.join("disk");
        fs::write(&disk, b"existing spawned image").unwrap();

        let mut cache = ImageDigestCache::default();
        let agreement = compare_opened_paths(&mut cache, &dir.join("missing"), &disk);

        assert_eq!(
            agreement,
            RunningImageAgreement::Unavailable {
                reason: RunningImageUnavailableReason::RunningExecutableUnreadable,
            }
        );
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn retained_running_descriptor_survives_path_replacement() {
        let dir = temp_dir("retained-descriptor");
        let running_path = dir.join("running");
        let spawned_path = dir.join("spawned");
        fs::write(&running_path, b"content A").unwrap();
        fs::write(&spawned_path, b"content A").unwrap();

        let running = File::open(&running_path).unwrap();
        fs::remove_file(&running_path).unwrap();
        fs::write(&running_path, b"content B").unwrap();

        let agreement = compare_opened_descriptor(
            &mut ImageDigestCache::default(),
            &running_path,
            running,
            &spawned_path,
        );

        assert_eq!(
            agreement,
            RunningImageAgreement::Match {
                evidence: RunningImageEvidence::LinuxProcSha256 {
                    digest: "49114a9a2b7d46ec27be62ae3eade12f78d46cf5a99c52cd4f80381d723eed6e"
                        .to_string(),
                },
            }
        );
    }

    #[test]
    fn proc_stat_parser_ignores_spaces_and_parentheses_in_comm() {
        let stat = "123 (foo) bar) S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 424242 20";

        assert_eq!(process_start_time_from_stat(stat), Some(424242));
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn differing_process_start_time_after_open_is_typed_unavailable() {
        let executable = std::env::current_exe().unwrap();
        let current_start_time = process_start_time(std::process::id()).unwrap();
        let agreement = ExecutableIdentityProbe::default()
            .observe(
                Some(std::process::id()),
                Some(&executable),
                None,
                Some(current_start_time + 1),
            )
            .await;

        assert_eq!(
            agreement,
            RunningImageAgreement::Unavailable {
                reason: RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
            }
        );
        assert!(!matches!(
            agreement,
            RunningImageAgreement::Match { .. } | RunningImageAgreement::Mismatch { .. }
        ));
    }

    /// The child runs a copy of `sleep` that this test owns, so nothing but
    /// the test can change the file. The three CI failures this test has had
    /// were all the pre-exec instant `spawn_owned_sleep` now waits out: each
    /// had a different "running" digest and the same disk digest.
    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn live_spawned_process_with_matching_start_time_still_matches() {
        let dir = temp_dir("live-child");
        let (mut child, executable) = spawn_owned_sleep(&dir).await;
        let pid = child.id().unwrap();
        let start_time = process_start_time(pid).unwrap();
        let agreement = ExecutableIdentityProbe::default()
            .observe(Some(pid), Some(&executable), None, Some(start_time))
            .await;
        let running_target = fs::read_link(format!("/proc/{pid}/exe")).ok();
        child.start_kill().unwrap();
        child.wait().await.unwrap();

        assert!(
            matches!(agreement, RunningImageAgreement::Match { .. }),
            "expected Match for a live child spawned from {}, got {agreement:?}; /proc/{pid}/exe -> {running_target:?}",
            executable.display()
        );
    }

    /// The probe is told the child was spawned from a file other than the
    /// one its exe link names: the pre-exec instant, or a wrapper that
    /// re-executed something else. Both files exist and differ, so without
    /// the link check this reads as a replaced binary; the honest answer is
    /// that the running image cannot be confirmed against the spawned path.
    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn exe_link_naming_another_path_is_unconfirmed_not_a_mismatch() {
        let dir = temp_dir("other-path");
        let claimed = dir.join("claimed");
        fs::write(
            &claimed,
            b"a different image at the path the probe was told about",
        )
        .unwrap();
        let (mut child, _executable) = spawn_owned_sleep(&dir).await;
        let pid = child.id().unwrap();
        let start_time = process_start_time(pid).unwrap();
        let agreement = ExecutableIdentityProbe::default()
            .observe(Some(pid), Some(&claimed), None, Some(start_time))
            .await;
        child.start_kill().unwrap();
        child.wait().await.unwrap();

        assert_eq!(
            agreement,
            RunningImageAgreement::Unavailable {
                reason: RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
            },
        );
    }

    /// A binary replaced by rename-over while the process runs: the exe link
    /// keeps naming the spawned path (with ` (deleted)`), so the link check
    /// must let the digest comparison through to report the replacement.
    /// The control for the test above: same shape, opposite verdict.
    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn a_binary_replaced_under_a_live_process_is_a_mismatch() {
        let dir = temp_dir("replaced");
        let (mut child, executable) = spawn_owned_sleep(&dir).await;
        let pid = child.id().unwrap();
        let start_time = process_start_time(pid).unwrap();
        let replacement = dir.join("sleep.new");
        fs::write(&replacement, b"not the image the child is running").unwrap();
        fs::rename(&replacement, &executable).unwrap();
        let agreement = ExecutableIdentityProbe::default()
            .observe(Some(pid), Some(&executable), None, Some(start_time))
            .await;
        child.start_kill().unwrap();
        child.wait().await.unwrap();

        assert!(
            matches!(agreement, RunningImageAgreement::Mismatch { .. }),
            "expected Mismatch for a replaced binary, got {agreement:?}"
        );
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn differing_start_time_wins_over_a_different_image_digest() {
        let running_executable = PathBuf::from("/bin/sleep");
        let spawned_executable = std::env::current_exe().unwrap();
        let mut child = Command::new(&running_executable).arg("60").spawn().unwrap();
        let pid = child.id().unwrap();
        let start_time = process_start_time(pid).unwrap();
        let agreement = ExecutableIdentityProbe::default()
            .observe(
                Some(pid),
                Some(&spawned_executable),
                None,
                Some(start_time + 1),
            )
            .await;
        child.start_kill().unwrap();
        child.wait().await.unwrap();

        assert_eq!(
            agreement,
            RunningImageAgreement::Unavailable {
                reason: RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
            }
        );
        assert!(!matches!(agreement, RunningImageAgreement::Mismatch { .. }));
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn cache_reuses_an_opened_identity_and_invalidates_changed_metadata() {
        let dir = temp_dir("cache");
        let image = dir.join("image");
        fs::write(&image, b"first executable image").unwrap();

        let mut cache = ImageDigestCache::default();
        let first = digest_open_file(&mut cache, File::open(&image).unwrap()).unwrap();
        let computations_after_first = cache.digest_computations();
        let repeated = digest_open_file(&mut cache, File::open(&image).unwrap()).unwrap();
        assert_eq!(first, repeated);
        assert_eq!(cache.digest_computations(), computations_after_first);

        fs::write(&image, b"second executable image with a different size").unwrap();
        let changed = digest_open_file(&mut cache, File::open(&image).unwrap()).unwrap();
        assert_ne!(first, changed);
        assert_eq!(cache.digest_computations(), computations_after_first + 1);
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn cache_clears_before_storing_the_sixty_fifth_identity() {
        let dir = temp_dir("cache-bound");
        let mut cache = ImageDigestCache::default();
        for index in 0..65 {
            let image = dir.join(format!("image-{index}"));
            fs::write(&image, format!("image-{index}")).unwrap();
            digest_open_file(&mut cache, File::open(image).unwrap()).unwrap();
        }

        assert_eq!(
            cache.len(),
            1,
            "the 65th identity clears the 64-entry cache"
        );
        // No manual cleanup: the TestTempDir guard removes the tree on drop and
        // deliberately preserves it when the test panics.
    }

    #[test]
    fn spawn_inode_comparator_reports_path_replacement_without_claiming_a_hash() {
        let spawned = SpawnedFileIdentity {
            device: 7,
            inode: 11,
        };
        let same_path = SpawnedFileIdentity {
            device: 7,
            inode: 11,
        };
        let replacement = SpawnedFileIdentity {
            device: 7,
            inode: 12,
        };

        assert!(matches!(
            compare_spawn_inode(spawned, same_path),
            RunningImageAgreement::Match { .. }
        ));
        assert!(matches!(
            compare_spawn_inode(spawned, replacement),
            RunningImageAgreement::Mismatch { .. }
        ));
    }
}