shep-daemon 0.15.2

The supervision engine behind shep: process spawning, restart policy, the log plane, watch and cron restarts, and the RPC server
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
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
//! Live per-sheep resource readings: the CPU and memory figures every row of
//! `shep flock` carries.
//!
//! [`super::LimitEnforcer`] samples only sheep with `max_memory` set;
//! [`StatsState`] watches every sheep with a pid, off the same
//! [`TreeIndex`] per polling tick.
//!
//! Memory is a level and reads current on demand. CPU is a counter: a percentage needs the
//! last periodic baseline, subtracted without writing one, so its window is usually one
//! `MEMORY_POLL_INTERVAL` old, longer if a full breaches channel paused the poll loop. Both
//! sum the whole tree; see [`limits`](super) for the kill-unit divergence.
//!
//! It also holds the labels sheep give their lambs (`limits::labels`), joined onto
//! `describe`'s lamb walk and pruned on the same tick.

use core::fmt;
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, Mutex, PoisonError};

use shep_core::protocol::{Lamb, LambLabel};
use shep_core::values;
use tokio::time::Instant;

use super::labels::LambLabels;
use super::sample::{MemorySampler, ProcessIdentity, TreeIndex};
use crate::proc_table::ProcInstant;
use crate::sweep::LambSnapshot;

/// One sheep's live resource reading.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct SheepStats {
    /// Tree CPU over the window since the last periodic baseline, as a
    /// percentage of one core.
    ///
    /// `None` when this pid has no baseline yet. A sheep spawned since the
    /// last tick has no honest figure, and one invented from a 50 ms window
    /// is worse than an empty cell.
    ///
    /// A value over 100 is a tree using more than one core, not a bug.
    pub cpu_percent: Option<f32>,
    /// Tree resident set size, current as of the reading that produced this.
    pub memory_bytes: u64,
    /// The tree's cumulative CPU-milliseconds as of this reading.
    pub cpu_ms: u64,
}

/// One watched root's CPU counter, and when it was read.
#[derive(Debug, Clone, Copy)]
struct Baseline {
    cpu_ms: u64,
    at: Instant,
}

/// Which sheep are worth sampling, and what their CPU counters read at the
/// last periodic tick.
///
/// [`Self::record_baseline`] is the ONLY writer of the baseline map. That is
/// the invariant the whole type rests on: [`Self::sample_now`] serves a
/// listing and must leave the baseline alone, or a second listing a
/// millisecond after the first would divide a near-zero CPU delta by a
/// near-zero window and report anything from 0% to thousands.
pub(crate) struct StatsState {
    sampler: Arc<dyn MemorySampler>,
    // `std::sync::Mutex`: every critical section is a map operation, none
    // held across an `.await`. Never held together, and never across the
    // syscall walk, so there is no lock order to get wrong.
    /// Root pid per watched sheep id.
    watched: Mutex<HashMap<u32, u32>>,
    /// The last periodic reading, per watched root pid.
    baselines: Mutex<HashMap<u32, Baseline>>,
    /// Each watched root's lambs as of the last periodic tick, for a sweep
    /// after the root has exited and taken its ppid tree with it.
    lamb_snapshots: Mutex<HashMap<u32, LambSnapshot>>,
    /// What each sheep named its lambs, joined into [`Self::lambs_of`].
    labels: LambLabels,
}

/// An indexed snapshot of the machine's process table: who each process is,
/// and which processes name it as their parent.
///
/// Built once per [`StatsState::lamb_index`] call and shared across
/// [`StatsState::lambs_of`] calls, so a caller walking several roots
/// (`shep describe all`) reuses one scan and one instant instead of
/// re-walking the table per root.
#[derive(Debug)]
pub(crate) struct LambIndex {
    /// Every process by pid, the name a lamb row carries.
    by_pid: HashMap<u32, ProcessIdentity>,
    /// Child pids per parent pid.
    children_of: HashMap<u32, Vec<u32>>,
}

impl StatsState {
    /// A sampler-backed state watching nothing yet.
    pub(crate) fn new(sampler: Arc<dyn MemorySampler>) -> Self {
        Self {
            sampler,
            watched: Mutex::new(HashMap::new()),
            baselines: Mutex::new(HashMap::new()),
            lamb_snapshots: Mutex::new(HashMap::new()),
            labels: LambLabels::default(),
        }
    }

    /// Starts sampling `root_pid` for `id`.
    ///
    /// Re-watching an id replaces the previous pid: a respawn gives the same
    /// id a new one.
    pub(crate) fn watch(&self, id: u32, root_pid: u32) {
        self.watched
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .insert(id, root_pid);
        // A pid entering the watch set starts from no baseline, never one
        // recorded while a different process held that number: the OS
        // recycles pids, and inheriting a stale counter would charge a new
        // sheep with the old one's accumulated CPU.
        self.baselines
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .remove(&root_pid);
        // Likewise for lambs: a sweep must not chase a dead sheep's lambs.
        self.lamb_snapshots
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .remove(&root_pid);
    }

    /// Stops sampling `id`. A no-op for an id never watched.
    ///
    /// Leaves the baseline map alone: see [`Self::watch`] for why nothing can
    /// read a stale entry, and [`Self::record_baseline`] for what clears it.
    /// Drops the lamb snapshot, which a sheep reusing this root pid could
    /// otherwise read before it is watched itself. The sheep task has already
    /// swept: an unwatch follows the exit it reports.
    pub(crate) fn unwatch(&self, id: u32) {
        let root_pid = self
            .watched
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .remove(&id);
        if let Some(root_pid) = root_pid {
            self.lamb_snapshots
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .remove(&root_pid);
        }
    }

    /// Records every watched root's CPU counter from one periodic reading.
    ///
    /// The whole map is replaced rather than updated in place, so an id that
    /// stopped being watched does not leave a baseline sitting in it until
    /// the daemon exits. [`Self::watch`] is what keeps a stale entry from
    /// ever being read.
    pub(crate) fn record_baseline(&self, index: &TreeIndex, now: Instant) {
        let fresh: HashMap<u32, Baseline> = self
            .watched_pids()
            .into_iter()
            .map(|root_pid| {
                let baseline = Baseline {
                    cpu_ms: index.cpu_from(root_pid),
                    at: now,
                };
                (root_pid, baseline)
            })
            .collect();
        *self
            .baselines
            .lock()
            .unwrap_or_else(PoisonError::into_inner) = fresh;
    }

    /// Records the lambs of every watched root `index` shows descending from
    /// `shepherd`, from one periodic reading.
    ///
    /// Replaced wholesale like [`Self::record_baseline`]. `taken_at` is read
    /// before the table `index` was built from. A root outside
    /// `shepherd`'s tree is no sheep of ours, so its children are never
    /// recorded for a sweep to signal.
    pub(crate) fn record_lamb_snapshots(
        &self,
        index: &TreeIndex,
        taken_at: ProcInstant,
        shepherd: u32,
    ) {
        let ours = index.descendants_of(shepherd);
        let fresh: HashMap<u32, LambSnapshot> = self
            .watched_pids()
            .into_iter()
            .filter(|root_pid| ours.contains(root_pid))
            .map(|root_pid| {
                let lambs = index.descendants_of(root_pid);
                (root_pid, LambSnapshot::new(lambs, taken_at))
            })
            .collect();
        *self
            .lamb_snapshots
            .lock()
            .unwrap_or_else(PoisonError::into_inner) = fresh;
    }

    /// What the last periodic tick recorded for `root_pid`, if it was
    /// watched then.
    pub(crate) fn last_lamb_snapshot(&self, root_pid: u32) -> Option<LambSnapshot> {
        self.lamb_snapshots
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .get(&root_pid)
            .cloned()
    }

    /// One fresh walk of `root_pid`'s lambs, empty unless `root_pid`
    /// descends from `shepherd`. Blocking, like [`Self::sample_now`].
    pub(crate) fn lamb_snapshot_now(&self, root_pid: u32, shepherd: u32) -> LambSnapshot {
        let taken_at = ProcInstant::now();
        let table = self.sampler.sample();
        let index = TreeIndex::build(&table);
        if !index.descendants_of(shepherd).contains(&root_pid) {
            return LambSnapshot::default();
        }
        LambSnapshot::new(index.descendants_of(root_pid), taken_at)
    }

    /// One fresh walk of every descendant of `roots`, the roots excluded.
    /// Blocking, like [`Self::sample_now`].
    ///
    /// No shepherd-ancestry check: the lamb sweep calls this with lambs it
    /// already verified, which an exited sheep leaves reparented to init.
    pub(crate) fn lamb_walk_from(&self, roots: &[u32]) -> LambSnapshot {
        let taken_at = ProcInstant::now();
        let table = self.sampler.sample();
        let index = TreeIndex::build(&table);
        let lambs = roots
            .iter()
            .flat_map(|&root| index.descendants_of(root))
            .filter(|pid| !roots.contains(pid));
        LambSnapshot::new(lambs, taken_at)
    }

    /// [`Self::record_baseline`] over a reading this call takes itself.
    ///
    /// For a caller with no index already in hand. The polling tick always
    /// has one and uses [`Self::record_baseline`] directly, so this has no
    /// production caller; it lets a test set a baseline in one line.
    #[cfg(test)]
    pub(crate) fn record_baseline_now(&self, now: Instant) {
        let table = self.sampler.sample();
        self.record_baseline(&TreeIndex::build(&table), now);
    }

    /// One live reading per watched sheep, keyed by root pid.
    ///
    /// Blocking: it performs the syscall walk itself, which is what makes the
    /// memory figure current rather than up to `MEMORY_POLL_INTERVAL` stale.
    /// It writes no baseline: see this type's own doc for why.
    pub(crate) fn sample_now(&self) -> HashMap<u32, SheepStats> {
        let roots = self.watched_pids();
        let table = self.sampler.sample();
        let index = TreeIndex::build(&table);
        let now = Instant::now();
        // Cloned rather than read under the lock: the walks below are the
        // expensive part of this call, and holding the baseline map across
        // them would block the periodic tick's store behind a listing.
        let baselines = self
            .baselines
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .clone();
        roots
            .into_iter()
            .map(|root_pid| {
                let observed_cpu_ms = index.cpu_from(root_pid);
                let stats = SheepStats {
                    cpu_percent: baselines
                        .get(&root_pid)
                        .and_then(|baseline| cpu_percent(*baseline, observed_cpu_ms, now)),
                    memory_bytes: index.sum_from(root_pid),
                    cpu_ms: observed_cpu_ms,
                };
                (root_pid, stats)
            })
            .collect()
    }

    /// Every watched root pid, with the lock released before the caller does
    /// anything with them.
    fn watched_pids(&self) -> Vec<u32> {
        self.watched
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .values()
            .copied()
            .collect()
    }

    /// Every `(id, root_pid)` currently watched, sorted by id.
    ///
    /// Lets a test outside this module assert on the watch set without a
    /// second fake standing in for the sampler.
    #[cfg(test)]
    pub(crate) fn watched_for_test(&self) -> Vec<(u32, u32)> {
        let mut watched: Vec<(u32, u32)> = self
            .watched
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .iter()
            .map(|(&id, &root_pid)| (id, root_pid))
            .collect();
        watched.sort_unstable();
        watched
    }

    /// Indexes one fresh walk of the machine's process table.
    ///
    /// The table refresh lives here rather than in [`Self::lambs_of`], so a
    /// caller answering several sheep pays for it once. See [`LambIndex`].
    pub(crate) fn lamb_index(&self) -> LambIndex {
        let table = self.sampler.identify();
        let mut by_pid = HashMap::with_capacity(table.len());
        let mut children_of: HashMap<u32, Vec<u32>> = HashMap::new();
        for entry in table {
            if let Some(parent) = entry.parent {
                children_of.entry(parent).or_default().push(entry.pid);
            }
            by_pid.insert(entry.pid, entry);
        }
        LambIndex {
            by_pid,
            children_of,
        }
    }

    /// Every process `index` reports as a descendant of `root_pid`, in pid
    /// order, excluding `root_pid` itself.
    ///
    /// Cycle-safe like [`TreeIndex::total_over`]: the kernel does not
    /// produce a cycle in the parent links, but a fixture can and a torn
    /// `/proc` read might.
    ///
    /// Not exactly the set of processes a stop kills. A stop signals the
    /// process group, then sweeps this tree as walked at the stop and at the
    /// last tick. So it also kills a group member that double-forked out of
    /// the tree, unlisted here. Anything rendering this list owes the operator
    /// that caveat.
    pub(crate) fn lambs_of(&self, index: &LambIndex, root_pid: u32) -> Vec<Lamb> {
        // `visited` seeded with the root, which does two things at once: it
        // keeps the sheep out of its own lamb list, and it terminates a
        // cycle that leads back to it.
        let mut visited: HashSet<u32> = HashSet::from([root_pid]);
        let mut stack = vec![root_pid];
        let mut lambs = Vec::new();
        while let Some(pid) = stack.pop() {
            for child in index.children_of.get(&pid).into_iter().flatten() {
                if !visited.insert(*child) {
                    continue;
                }
                if let Some(entry) = index.by_pid.get(child) {
                    lambs.push(Lamb::new(entry.pid, entry.name.clone()));
                }
                stack.push(*child);
            }
        }
        lambs.sort_unstable_by_key(|lamb| lamb.pid);
        let mut labels = self.labels.of(root_pid);
        for lamb in &mut lambs {
            lamb.label = labels.remove(&lamb.pid);
        }
        lambs
    }

    /// Records what the sheep at `root_pid` named its lamb `pid`.
    pub(crate) fn label_lamb(&self, root_pid: u32, pid: u32, label: &LambLabel, now: Instant) {
        self.labels.set(root_pid, pid, label, now);
    }

    /// Drops the labels `index` shows have left their tree.
    ///
    /// `taken_at` is read before the table `index` was built from; see
    /// [`LambLabels::prune`].
    pub(crate) fn prune_labels(&self, index: &TreeIndex, taken_at: Instant) {
        self.labels.prune(index, taken_at);
    }
}

impl fmt::Debug for StatsState {
    // The sampler is a trait object and is not Debug. The two maps are
    // behind locks this does not take, since a formatter called from inside
    // a locked section would deadlock the thread it was meant to debug.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("StatsState")
            .field("sampler", &"<dyn MemorySampler>")
            .finish_non_exhaustive()
    }
}

/// `baseline`'s counter against a later reading of the same tree, as a
/// percentage of one core.
///
/// `None` when no wall time has passed since the baseline: dividing by a
/// zero window would produce a nonsense figure.
fn cpu_percent(baseline: Baseline, cpu_ms: u64, now: Instant) -> Option<f32> {
    // Saturating: a counter that went backwards means the tree under this
    // pid is not the one the baseline was taken from (a lamb exited, or the
    // pid was recycled), and zero is the honest reading for that window.
    let elapsed_cpu_ms = cpu_ms.saturating_sub(baseline.cpu_ms);
    values::cpu_percent(elapsed_cpu_ms, now.saturating_duration_since(baseline.at))
}

#[cfg(test)]
mod tests {
    use core::time::Duration;

    use super::super::MEMORY_POLL_INTERVAL;
    use super::*;
    use crate::testing::{ScriptedSampler, identity, rss, rss_cpu};

    fn at(raw: u64) -> ProcInstant {
        ProcInstant::from_raw(raw)
    }

    /// The pid a scripted table names as the shepherd its sheep descend from.
    const SHEPHERD: u32 = 50;

    #[tokio::test(start_paused = true)]
    async fn a_sheep_with_no_baseline_reports_no_cpu_but_still_reports_memory() {
        let sampler = Arc::new(ScriptedSampler::new(vec![vec![rss_cpu(
            100, None, 4096, 1000,
        )]]));
        let stats = StatsState::new(sampler);
        stats.watch(1, 100);

        let now = stats.sample_now();
        assert_eq!(now[&100].cpu_percent, None);
        assert_eq!(now[&100].memory_bytes, 4096, "memory is always current");
    }

    /// The counter is reported whether or not a baseline exists: it is the
    /// reading itself, not a rate measured against anything.
    #[tokio::test(start_paused = true)]
    async fn a_sample_carries_the_counter_without_a_baseline() {
        let sampler = Arc::new(ScriptedSampler::new(vec![vec![rss_cpu(
            100, None, 1024, 5_000,
        )]]));
        let stats = StatsState::new(sampler);
        stats.watch(1, 100);

        let now = stats.sample_now();
        assert_eq!(now[&100].cpu_ms, 5_000);
        assert_eq!(now[&100].cpu_percent, None);
    }

    /// 1500 CPU-ms over a 15 s window is 10%; the process's whole
    /// accumulated time instead would read 16.7%.
    #[tokio::test(start_paused = true)]
    async fn cpu_is_the_delta_since_the_periodic_baseline() {
        let sampler = Arc::new(ScriptedSampler::new(vec![
            vec![rss_cpu(100, None, 4096, 1_000)],
            vec![rss_cpu(100, None, 4096, 2_500)],
        ]));
        let stats = StatsState::new(sampler);
        stats.watch(1, 100);

        stats.record_baseline_now(Instant::now());
        tokio::time::advance(MEMORY_POLL_INTERVAL).await;

        let now = stats.sample_now();
        let cpu = now[&100].cpu_percent.expect("a baseline exists");
        assert!((cpu - 10.0).abs() < 0.01, "expected ~10%, got {cpu}");
    }

    /// An on-demand read must not write the baseline, or a second call a
    /// moment later would divide a near-zero delta by a near-zero window.
    #[tokio::test(start_paused = true)]
    async fn a_second_read_a_moment_later_still_measures_from_the_periodic_baseline() {
        // Three readings: baseline, then two on-demand reads a millisecond
        // apart, where the CPU counter barely moves. A baseline-writing
        // implementation would divide ~1 CPU-ms by ~1 ms here.
        let sampler = Arc::new(ScriptedSampler::new(vec![
            vec![rss_cpu(100, None, 4096, 1_000)],
            vec![rss_cpu(100, None, 4096, 2_500)],
            vec![rss_cpu(100, None, 4096, 2_501)],
        ]));
        let stats = StatsState::new(sampler);
        stats.watch(1, 100);
        stats.record_baseline_now(Instant::now());
        tokio::time::advance(MEMORY_POLL_INTERVAL).await;

        let first = stats.sample_now()[&100].cpu_percent.unwrap();
        tokio::time::advance(Duration::from_millis(1)).await;
        let second = stats.sample_now()[&100].cpu_percent.unwrap();
        assert!(
            (first - 10.0).abs() < 0.01,
            "1500 CPU-ms over 15 s is 10%, got {first}"
        );
        assert!(
            (second - 10.0).abs() < 0.02,
            "the second read divided by the gap between the two READS rather \
             than by the window since the tick: {first} then {second}"
        );
    }

    #[tokio::test(start_paused = true)]
    async fn an_unwatched_sheep_is_no_longer_sampled() {
        let sampler = Arc::new(ScriptedSampler::new(vec![
            vec![rss_cpu(100, None, 4096, 1_000)],
            vec![rss_cpu(100, None, 4096, 2_500)],
        ]));
        let stats = StatsState::new(sampler);
        stats.watch(1, 100);
        stats.record_baseline_now(Instant::now());
        tokio::time::advance(MEMORY_POLL_INTERVAL).await;

        stats.unwatch(1);
        assert!(
            stats.sample_now().is_empty(),
            "an unwatched sheep must not still be sampled"
        );
    }

    #[tokio::test(start_paused = true)]
    async fn a_recycled_pid_starts_from_no_baseline_rather_than_the_dead_process_counter() {
        let sampler = Arc::new(ScriptedSampler::new(vec![
            vec![rss_cpu(100, None, 4096, 1_000)],
            vec![rss_cpu(100, None, 4096, 9_000)],
        ]));
        let stats = StatsState::new(sampler);
        stats.watch(1, 100);
        stats.record_baseline_now(Instant::now());
        tokio::time::advance(MEMORY_POLL_INTERVAL).await;

        stats.unwatch(1);
        stats.watch(2, 100);
        assert_eq!(
            stats.sample_now()[&100].cpu_percent,
            None,
            "the new process on pid 100 must not be measured against the dead one's counter"
        );
    }

    #[tokio::test(start_paused = true)]
    async fn a_read_in_the_same_instant_as_the_baseline_reports_no_cpu() {
        let sampler = Arc::new(ScriptedSampler::new(vec![
            vec![rss_cpu(100, None, 4096, 1_000)],
            vec![rss_cpu(100, None, 4096, 9_000)],
        ]));
        let stats = StatsState::new(sampler);
        stats.watch(1, 100);
        stats.record_baseline_now(Instant::now());

        // No `advance`: the paused clock has not moved since the baseline.
        assert_eq!(stats.sample_now()[&100].cpu_percent, None);
    }

    // Pins the hand-rolled Debug output so a later edit cannot start
    // printing the maps or the sampler.
    #[tokio::test(start_paused = true)]
    async fn stats_state_debug_names_the_sampler_by_role_and_prints_no_map() {
        let sampler = Arc::new(ScriptedSampler::new(vec![vec![rss_cpu(
            100, None, 4096, 1000,
        )]]));
        let stats = StatsState::new(sampler);
        stats.watch(1, 100);
        assert_eq!(
            format!("{stats:?}"),
            r#"StatsState { sampler: "<dyn MemorySampler>", .. }"#
        );
    }

    // extras.rs's own case asserts on this helper; a helper that lied would
    // take that case with it too.
    #[tokio::test(start_paused = true)]
    async fn watching_reports_each_id_once_against_its_current_pid() {
        let sampler = Arc::new(ScriptedSampler::new(vec![vec![rss_cpu(
            100, None, 4096, 1000,
        )]]));
        let stats = StatsState::new(sampler);
        stats.watch(7, 4242);
        stats.watch(2, 100);
        assert_eq!(stats.watched_for_test(), vec![(2, 100), (7, 4242)]);

        stats.watch(7, 5353);
        assert_eq!(
            stats.watched_for_test(),
            vec![(2, 100), (7, 5353)],
            "a respawn replaces the id's pid rather than adding a second one"
        );

        stats.unwatch(2);
        stats.unwatch(99);
        assert_eq!(
            stats.watched_for_test(),
            vec![(7, 5353)],
            "unwatching an id never watched must leave the rest alone"
        );
    }

    #[test]
    fn a_tick_records_each_watched_roots_lambs_and_drops_the_unwatched() {
        let index = TreeIndex::build(&[
            rss(100, Some(SHEPHERD), 0),
            rss(101, Some(100), 0),
            rss(102, Some(101), 0),
            rss(200, Some(SHEPHERD), 0),
            rss(201, Some(200), 0),
        ]);
        let stats = StatsState::new(Arc::new(ScriptedSampler::new(vec![vec![]])));
        stats.watch(1, 100);
        stats.watch(2, 200);
        stats.record_lamb_snapshots(&index, at(77), SHEPHERD);
        assert_eq!(
            stats.last_lamb_snapshot(100),
            Some(LambSnapshot::new([101, 102], at(77)))
        );

        stats.unwatch(2);
        stats.record_lamb_snapshots(&index, at(78), SHEPHERD);
        assert_eq!(stats.last_lamb_snapshot(200), None);
        assert_eq!(
            stats.last_lamb_snapshot(100),
            Some(LambSnapshot::new([101, 102], at(78)))
        );
    }

    #[test]
    fn an_unwatched_root_leaves_no_lamb_snapshot_behind() {
        let index = TreeIndex::build(&[rss(100, Some(SHEPHERD), 0), rss(101, Some(100), 0)]);
        let stats = StatsState::new(Arc::new(ScriptedSampler::new(vec![vec![]])));
        stats.watch(1, 100);
        stats.record_lamb_snapshots(&index, at(77), SHEPHERD);
        assert!(
            stats.last_lamb_snapshot(100).is_some(),
            "sanity: one was recorded"
        );

        stats.unwatch(1);
        assert_eq!(stats.last_lamb_snapshot(100), None);
    }

    #[test]
    fn a_recycled_pid_starts_with_no_lamb_snapshot() {
        let index = TreeIndex::build(&[rss(100, Some(SHEPHERD), 0), rss(101, Some(100), 0)]);
        let stats = StatsState::new(Arc::new(ScriptedSampler::new(vec![vec![]])));
        stats.watch(1, 100);
        stats.record_lamb_snapshots(&index, at(77), SHEPHERD);
        assert!(
            stats.last_lamb_snapshot(100).is_some(),
            "sanity: one was recorded"
        );

        stats.watch(2, 100);
        assert_eq!(
            stats.last_lamb_snapshot(100),
            None,
            "the new process on pid 100 must not inherit the old one's lambs"
        );
    }

    #[test]
    fn a_walk_from_survivors_finds_their_children_and_not_the_survivors() {
        // 101 and 201 are survivors reparented to init; 102 is 101's child,
        // 202 is 201's, and 300 is nobody's.
        let table = vec![
            rss(1, None, 0),
            rss(101, Some(1), 0),
            rss(102, Some(101), 0),
            rss(103, Some(102), 0),
            rss(201, Some(1), 0),
            rss(202, Some(201), 0),
            rss(300, Some(1), 0),
        ];
        let stats = StatsState::new(Arc::new(ScriptedSampler::new(vec![table])));

        let snapshot = stats.lamb_walk_from(&[101, 201]);

        assert_eq!(snapshot.pids().collect::<Vec<_>>(), vec![102, 103, 202]);
    }

    #[test]
    fn a_fresh_walk_snapshots_every_descendant_and_not_the_root() {
        let table = vec![
            rss(100, Some(SHEPHERD), 0),
            rss(101, Some(100), 0),
            rss(102, Some(101), 0),
            rss(200, Some(SHEPHERD), 0),
        ];
        let stats = StatsState::new(Arc::new(ScriptedSampler::new(vec![table])));
        let before = ProcInstant::now();

        let snapshot = stats.lamb_snapshot_now(100, SHEPHERD);
        let after = ProcInstant::now();

        assert_eq!(snapshot.pids().collect::<Vec<_>>(), vec![101, 102]);
        let taken = snapshot.seen_at(101).expect("101 was seen");
        assert!(
            before <= taken && taken <= after,
            "{before:?} <= {taken:?} <= {after:?}"
        );
    }

    // A scripted runner's pids name real processes on the host. Neither look
    // may hand a sweep their children.
    #[test]
    fn a_root_outside_the_shepherds_tree_is_never_snapshotted() {
        let table = vec![
            rss(100, Some(SHEPHERD), 0),
            rss(101, Some(100), 0),
            rss(200, Some(SHEPHERD + 1), 0),
            rss(201, Some(200), 0),
        ];
        let stats = StatsState::new(Arc::new(ScriptedSampler::new(vec![table.clone()])));
        stats.watch(1, 100);
        stats.watch(2, 200);

        stats.record_lamb_snapshots(&TreeIndex::build(&table), at(77), SHEPHERD);

        assert_eq!(
            stats.last_lamb_snapshot(100),
            Some(LambSnapshot::new([101], at(77)))
        );
        assert_eq!(stats.last_lamb_snapshot(200), None);
        assert!(stats.lamb_snapshot_now(200, SHEPHERD).is_empty());
    }

    #[test]
    fn the_lamb_walk_excludes_the_sheeps_own_pid() {
        let table = vec![
            identity(100, None, "srv"),
            identity(101, Some(100), "node"),
            identity(102, Some(101), "sh"),
        ];
        let stats = StatsState::new(Arc::new(ScriptedSampler::identifying(vec![table])));

        let lambs = stats.lambs_of(&stats.lamb_index(), 100);

        assert_eq!(
            lambs,
            vec![Lamb::new(101, "node"), Lamb::new(102, "sh")],
            "the root pid must not appear among its own lambs"
        );
    }

    /// A `sh` wrapper execing a runtime that forks workers is three deep,
    /// the ordinary case.
    #[test]
    fn the_lamb_walk_reaches_every_generation() {
        let table = vec![
            identity(100, None, "sh"),
            identity(101, Some(100), "node"),
            identity(102, Some(101), "node"),
            identity(103, Some(102), "node"),
        ];
        let stats = StatsState::new(Arc::new(ScriptedSampler::identifying(vec![table])));
        assert_eq!(stats.lambs_of(&stats.lamb_index(), 100).len(), 3);
    }

    /// Both roots are walked off one index, as `shep describe all` does:
    /// index built once, `lambs_of` called per row.
    #[test]
    fn a_sibling_subtree_is_not_this_sheeps() {
        let table = vec![
            identity(100, None, "srv"),
            identity(101, Some(100), "mine"),
            identity(200, None, "srv"),
            identity(201, Some(200), "theirs"),
        ];
        let stats = StatsState::new(Arc::new(ScriptedSampler::identifying(vec![table])));
        let index = stats.lamb_index();
        assert_eq!(stats.lambs_of(&index, 100), vec![Lamb::new(101, "mine")]);
        assert_eq!(stats.lambs_of(&index, 200), vec![Lamb::new(201, "theirs")]);
    }

    /// `lambs_of` is a synchronous `fn`, so a `tokio::time::timeout` wrapper
    /// around it never gets a chance to fire: the call runs to completion or
    /// hangs on its first poll either way. The assertion below is what
    /// actually catches a non-terminating walk.
    #[test]
    fn a_parent_link_cycle_terminates_and_reports_each_pid_once() {
        let table = vec![identity(100, Some(101), "a"), identity(101, Some(100), "b")];
        let stats = StatsState::new(Arc::new(ScriptedSampler::identifying(vec![table])));

        let lambs = stats.lambs_of(&stats.lamb_index(), 100);

        assert_eq!(
            lambs,
            vec![Lamb::new(101, "b")],
            "the root is its own descendant through the cycle and must not be listed"
        );
    }

    #[test]
    fn lambs_come_back_in_pid_order() {
        let table = vec![
            identity(100, None, "srv"),
            identity(103, Some(100), "c"),
            identity(101, Some(100), "a"),
            identity(102, Some(100), "b"),
        ];
        let stats = StatsState::new(Arc::new(ScriptedSampler::identifying(vec![table])));
        assert_eq!(
            stats
                .lambs_of(&stats.lamb_index(), 100)
                .iter()
                .map(|l| l.pid)
                .collect::<Vec<_>>(),
            vec![101, 102, 103]
        );
    }

    /// The default `identify` returns nothing; consumers must read that as
    /// "unknown", never "no lambs".
    #[test]
    fn a_sampler_that_cannot_identify_reports_no_lambs() {
        // `ScriptedSampler::new(..)` implements only `sample`, taking the
        // default `identify`.
        let stats = StatsState::new(Arc::new(ScriptedSampler::new(vec![vec![]])));
        assert!(stats.lambs_of(&stats.lamb_index(), 100).is_empty());
    }
}