mapsample 0.1.0

In-process Windows x64 stack sampler with a rolling stall recorder, P/E-core placement readings, and an MSVC /MAP symbolizer
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
820
821
822
823
824
825
826
//! Where threads ran: efficiency-class shares, migrations and hyperthread co-scheduling.

use std::collections::HashMap;
use std::fmt::Write as _;

use crate::config::DEFAULT_BUSIEST_THREADS;

/// Placement readings asked for per thread and second, at most.
pub const PLACEMENT_HZ: u32 = 200;
/// Readings of two threads this close together (microseconds) count as simultaneous.
pub const SIMULTANEOUS_US: f64 = 100.0;

/// One logical processor, from `GetSystemCpuSetInformation`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Cpu {
    /// `group * 64 + number`, as `GetCurrentProcessorNumberEx` names it.
    pub index: u32,
    /// The physical core, `group << 8 | CoreIndex`: the hyperthreads of a core share it.
    pub core: u32,
    /// `EfficiencyClass`: higher is faster; a CPU without core classes has one value.
    pub class: u8,
}

/// The readings are asked for at most every this many sampling passes, so that they stay at
/// or below [`PLACEMENT_HZ`] per thread whatever the sampling rate.
#[must_use]
#[cfg_attr(not(all(windows, target_arch = "x86_64")), allow(dead_code))]
pub(crate) fn placement_stride(hz: u32) -> u64 {
    u64::from(hz.div_ceil(PLACEMENT_HZ).max(1))
}

/// A thread whose placement was read. Each watched thread lifetime gets its own entry, so two
/// threads with the same name (or one id reused by a later thread) stay apart.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct PlacedThread {
    /// The thread's name (its profile label).
    pub name: String,
    /// The operating system's thread id.
    pub tid: u32,
}

impl PlacedThread {
    /// A placed thread called `name` with id `tid`.
    #[must_use]
    pub fn new(name: impl Into<String>, tid: u32) -> Self {
        Self {
            name: name.into(),
            tid,
        }
    }
}

/// Thread `thread` (an index in [`Placement::threads`]) ran on logical processor `cpu` when
/// the time stamp counter read `tsc`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Reading {
    /// Index in [`Placement::threads`].
    pub thread: usize,
    /// [`Cpu::index`] of the processor.
    pub cpu: u32,
    /// Time stamp counter.
    pub tsc: u64,
}

/// The placement readings of a run.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Placement {
    /// Why there are no readings, when there are none for a reason.
    pub unavailable: Option<String>,
    /// The logical processors.
    pub cpus: Vec<Cpu>,
    /// The threads read, one entry per thread lifetime; [`Reading::thread`] indexes it.
    pub threads: Vec<PlacedThread>,
    /// The readings, in the order collected.
    pub readings: Vec<Reading>,
    /// Time stamp counter ticks per second (0 when unknown).
    pub tsc_hz: f64,
    /// Seconds the readings were taken over.
    pub wall: f64,
    /// CPU cycles each thread used while watched (`QueryThreadCycleTime`), by index in
    /// [`threads`](Self::threads).
    pub cycles: HashMap<usize, u64>,
    /// Thread name substrings always reported (case-insensitive).
    pub highlight_threads: Vec<String>,
    /// How many of the busiest other threads are reported.
    pub busiest_threads: usize,
    /// Readings still undelivered when the sampler stopped (their threads were blocked).
    pub pending_at_stop: usize,
}

impl Default for Placement {
    fn default() -> Self {
        Self {
            unavailable: None,
            cpus: Vec::new(),
            threads: Vec::new(),
            readings: Vec::new(),
            tsc_hz: 0.0,
            wall: 0.0,
            cycles: HashMap::new(),
            highlight_threads: Vec::new(),
            busiest_threads: DEFAULT_BUSIEST_THREADS,
            pending_at_stop: 0,
        }
    }
}

/// Placement figures of one thread.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct ThreadPlacement {
    /// Why it is reported: `highlight`, or `busy N` for the N-th busiest.
    pub role: String,
    /// Index in [`Placement::threads`].
    pub thread: usize,
    /// Readings of this thread.
    pub readings: u64,
    /// Readings on a core below the fastest class.
    pub slow_class: u64,
    /// Consecutive readings on different logical processors.
    pub cpu_changes: u64,
    /// Consecutive readings on different physical cores.
    pub core_changes: u64,
}

/// The figures the placement section reports.
#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct PlacementSummary {
    /// The key threads, highlighted first, then the busiest.
    pub threads: Vec<ThreadPlacement>,
    /// Readings of key threads with a simultaneous reading of another key thread.
    pub simultaneous: u64,
    /// Of those, the ones where the other thread ran on another hyperthread of the same core.
    pub siblings: u64,
    /// Key thread pairs seen on sibling hyperthreads, with counts (most first).
    pub sibling_pairs: Vec<(String, String, u64)>,
}

impl Placement {
    /// The name the report shows for thread `index`: its name, with its id and a running
    /// number added when another read thread has the same name.
    #[must_use]
    pub fn label(&self, index: usize) -> String {
        let Some(thread) = self.threads.get(index) else {
            return "?".to_owned();
        };
        let same: Vec<usize> = (0..self.threads.len())
            .filter(|&other| {
                self.threads
                    .get(other)
                    .is_some_and(|t| t.name == thread.name)
            })
            .collect();
        if same.len() < 2 {
            return thread.name.clone();
        }
        let ordinal = same.iter().position(|&other| other == index).unwrap_or(0) + 1;
        format!("{} #{ordinal} (tid {})", thread.name, thread.tid)
    }

    fn cpu(&self, index: u32) -> Option<&Cpu> {
        self.cpus.iter().find(|cpu| cpu.index == index)
    }

    fn fastest_class(&self) -> Option<u8> {
        self.cpus.iter().map(|cpu| cpu.class).max()
    }

    fn is_slow(&self, reading: &Reading, fastest: Option<u8>) -> bool {
        let class = self.cpu(reading.cpu).map(|cpu| cpu.class);
        class.is_some() && class < fastest
    }

    /// The threads the placement section reports, with their roles: every thread whose name
    /// contains a [`highlight_threads`](Self::highlight_threads) entry (case-insensitive), in
    /// thread order, then the [`busiest_threads`](Self::busiest_threads) others that used the
    /// most cycles (most readings breaking ties, then the lower index).
    #[must_use]
    pub fn key_threads(&self) -> Vec<(String, usize)> {
        let highlight: Vec<String> = self
            .highlight_threads
            .iter()
            .map(|name| name.trim().to_lowercase())
            .filter(|name| !name.is_empty())
            .collect();
        let mut keys: Vec<(String, usize)> = self
            .threads
            .iter()
            .enumerate()
            .filter(|(_, thread)| {
                let lower = thread.name.to_lowercase();
                highlight.iter().any(|wanted| lower.contains(wanted))
            })
            .map(|(index, _)| ("highlight".to_owned(), index))
            .collect();
        let mut readings: HashMap<usize, u64> = HashMap::new();
        for reading in &self.readings {
            let count = readings.entry(reading.thread).or_default();
            *count = count.saturating_add(1);
        }
        let mut busy: Vec<(u64, u64, usize)> = (0..self.threads.len())
            .filter(|index| !keys.iter().any(|(_, key)| key == index))
            .map(|index| {
                let cycles = self.cycles.get(&index).copied().unwrap_or(0);
                let count = readings.get(&index).copied().unwrap_or(0);
                (cycles, count, index)
            })
            .filter(|&(cycles, count, _)| cycles > 0 || count > 0)
            .collect();
        busy.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)).then(a.2.cmp(&b.2)));
        for (rank, &(_, _, index)) in busy.iter().take(self.busiest_threads).enumerate() {
            keys.push((format!("busy {}", rank + 1), index));
        }
        keys
    }

    /// Work out the figures for the key threads.
    #[must_use]
    pub fn summarize(&self) -> PlacementSummary {
        let keys = self.key_threads();
        let fastest = self.fastest_class();
        let core = |reading: &Reading| self.cpu(reading.cpu).map(|cpu| cpu.core);
        let mut summary = PlacementSummary::default();
        for (role, thread) in &keys {
            let mut own: Vec<&Reading> = self
                .readings
                .iter()
                .filter(|reading| reading.thread == *thread)
                .collect();
            own.sort_by_key(|reading| reading.tsc);
            let mut entry = ThreadPlacement {
                role: role.clone(),
                thread: *thread,
                readings: own.len() as u64,
                slow_class: own.iter().filter(|r| self.is_slow(r, fastest)).count() as u64,
                cpu_changes: 0,
                core_changes: 0,
            };
            for pair in own.windows(2) {
                let [a, b] = pair else { continue };
                if a.cpu != b.cpu {
                    entry.cpu_changes = entry.cpu_changes.saturating_add(1);
                    if core(a) != core(b) {
                        entry.core_changes = entry.core_changes.saturating_add(1);
                    }
                }
            }
            summary.threads.push(entry);
        }
        if !(self.tsc_hz.is_finite() && self.tsc_hz > 0.0) {
            return summary;
        }
        // Finite and positive, so the cast saturates at worst.
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        let window = (SIMULTANEOUS_US * self.tsc_hz / 1e6) as u64;
        let mut keyed: Vec<&Reading> = self
            .readings
            .iter()
            .filter(|reading| keys.iter().any(|(_, key)| *key == reading.thread))
            .collect();
        keyed.sort_by_key(|reading| reading.tsc);
        let mut pairs: HashMap<(usize, usize), u64> = HashMap::new();
        for (at, reading) in keyed.iter().enumerate() {
            let near = |other: &&&Reading| other.tsc.abs_diff(reading.tsc) <= window;
            let before = keyed.get(..at).unwrap_or_default().iter().rev();
            let after = keyed.get(at + 1..).unwrap_or_default().iter();
            let mut together = false;
            let mut sibling: Option<usize> = None;
            for other in before.take_while(near).chain(after.take_while(near)) {
                if other.thread == reading.thread {
                    continue;
                }
                together = true;
                if other.cpu != reading.cpu && core(other).is_some() && core(other) == core(reading)
                {
                    sibling = Some(other.thread);
                }
            }
            if together {
                summary.simultaneous = summary.simultaneous.saturating_add(1);
            }
            if let Some(other) = sibling {
                summary.siblings = summary.siblings.saturating_add(1);
                let key = (reading.thread.min(other), reading.thread.max(other));
                let count = pairs.entry(key).or_default();
                *count = count.saturating_add(1);
            }
        }
        let mut pairs: Vec<(String, String, u64)> = pairs
            .into_iter()
            .map(|((a, b), count)| (self.label(a), self.label(b), count))
            .collect();
        pairs.sort_by(|a, b| {
            b.2.cmp(&a.2)
                .then_with(|| a.0.cmp(&b.0))
                .then_with(|| a.1.cmp(&b.1))
        });
        summary.sibling_pairs = pairs;
        summary
    }

    /// The placement section of the text report.
    #[must_use]
    pub fn report(&self) -> String {
        let mut text = String::from("=== placement\n");
        if let Some(reason) = &self.unavailable {
            let _ = writeln!(text, "no readings: {reason}\n");
            return text;
        }
        let mut classes: Vec<u8> = self.cpus.iter().map(|cpu| cpu.class).collect();
        classes.sort_unstable();
        classes.dedup();
        let cores = |class: Option<u8>| {
            let mut cores: Vec<u32> = self
                .cpus
                .iter()
                .filter(|cpu| class.is_none_or(|class| cpu.class == class))
                .map(|cpu| cpu.core)
                .collect();
            cores.sort_unstable();
            cores.dedup();
            cores.len()
        };
        let _ = write!(
            text,
            "{} logical processors on {} cores;",
            self.cpus.len(),
            cores(None)
        );
        for class in classes.iter().rev() {
            let logical = self.cpus.iter().filter(|cpu| cpu.class == *class).count();
            let _ = write!(
                text,
                " class {class}: {logical} logical on {} cores;",
                cores(Some(*class))
            );
        }
        text.push('\n');
        if classes.len() < 2 {
            text.push_str("one core class: efficiency-core shares do not apply\n");
        }
        let mut read: Vec<usize> = self.readings.iter().map(|r| r.thread).collect();
        read.sort_unstable();
        read.dedup();
        let _ = writeln!(
            text,
            "{} readings over {:.1} s ({} threads read, {} pending at stop); changes are between consecutive readings, so they undercount",
            self.readings.len(),
            self.wall,
            read.len(),
            self.pending_at_stop,
        );
        let summary = self.summarize();
        let per_second = |count: u64| {
            if self.wall > 0.0 {
                count as f64 / self.wall
            } else {
                0.0
            }
        };
        let percent = |part: u64, whole: u64| {
            if whole == 0 {
                0.0
            } else {
                part as f64 * 100.0 / whole as f64
            }
        };
        for entry in &summary.threads {
            let _ = writeln!(
                text,
                "{:<10} {:<24} {:>7} readings, {:>5.1}% on slower cores, {:>7.1} processor changes/s, {:>7.1} core changes/s",
                entry.role,
                self.label(entry.thread),
                entry.readings,
                percent(entry.slow_class, entry.readings),
                per_second(entry.cpu_changes),
                per_second(entry.core_changes),
            );
        }
        let key_readings = summary
            .threads
            .iter()
            .fold(0_u64, |sum, entry| sum.saturating_add(entry.readings));
        if self.tsc_hz.is_finite() && self.tsc_hz > 0.0 {
            let _ = writeln!(
                text,
                "key threads: {} of {key_readings} readings had another key thread within {SIMULTANEOUS_US} us; {} ({:.1}% of all, {:.1}% of those) on another hyperthread of the same core",
                summary.simultaneous,
                summary.siblings,
                percent(summary.siblings, key_readings),
                percent(summary.siblings, summary.simultaneous),
            );
            for (a, b, count) in summary.sibling_pairs.iter().take(6) {
                let _ = writeln!(text, "  siblings {a} + {b}: {count}");
            }
        }
        let fastest = self.fastest_class();
        let slow = self
            .readings
            .iter()
            .filter(|reading| self.is_slow(reading, fastest))
            .count() as u64;
        let _ = writeln!(
            text,
            "all read threads: {:.1}% of readings on slower cores\n",
            percent(slow, self.readings.len() as u64)
        );
        text
    }
}

/// Parse a `GetSystemCpuSetInformation` buffer: `SYSTEM_CPU_SET_INFORMATION` entries with
/// `Size` (u32) at 0, `Type` (u32) at 4 (0 is a CPU set), `Group` (u16) at 12,
/// `LogicalProcessorIndex` at 14, `CoreIndex` at 15 and `EfficiencyClass` at 18. Other entry
/// types are skipped; a truncated or undersized entry ends the walk.
#[must_use]
pub fn parse_cpu_sets(bytes: &[u8]) -> Vec<Cpu> {
    let u32_at = |entry: &[u8], at: usize| {
        entry
            .get(at..at + 4)
            .and_then(|b| b.try_into().ok())
            .map(u32::from_le_bytes)
    };
    let mut cpus = Vec::new();
    let mut at = 0_usize;
    while let Some(entry) = bytes.get(at..).filter(|rest| !rest.is_empty()) {
        let Some(size) = u32_at(entry, 0).and_then(|size| usize::try_from(size).ok()) else {
            break;
        };
        if size < 20 || entry.len() < size {
            break;
        }
        let group = entry
            .get(12..14)
            .and_then(|b| b.try_into().ok())
            .map(u16::from_le_bytes);
        if let (Some(0), Some(group), Some(&logical), Some(&core), Some(&class)) = (
            u32_at(entry, 4),
            group,
            entry.get(14),
            entry.get(15),
            entry.get(18),
        ) {
            cpus.push(Cpu {
                index: u32::from(group) * 64 + u32::from(logical),
                core: (u32::from(group) << 8) | u32::from(core),
                class,
            });
        }
        let Some(next) = at.checked_add(size) else {
            break;
        };
        at = next;
    }
    cpus
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Two fast cores with two hyperthreads each (processors 0-3) and two slow cores (4, 5),
    /// as on a hybrid desktop part.
    fn hybrid() -> Vec<Cpu> {
        let cpu = |index, core, class| Cpu { index, core, class };
        vec![
            cpu(0, 0, 1),
            cpu(1, 0, 1),
            cpu(2, 1, 1),
            cpu(3, 1, 1),
            cpu(4, 2, 0),
            cpu(5, 3, 0),
        ]
    }

    fn threads() -> Vec<PlacedThread> {
        ["render", "audio", "main", "worker-7", "worker-9", "logger"]
            .into_iter()
            .zip(100..)
            .map(|(name, tid)| PlacedThread::new(name, tid))
            .collect()
    }

    fn reading(thread: usize, cpu: u32, tsc: u64) -> Reading {
        Reading { thread, cpu, tsc }
    }

    #[test]
    fn key_threads_are_highlighted_then_busiest() {
        let mut placement = Placement {
            threads: threads(),
            cpus: hybrid(),
            highlight_threads: vec!["RENDER".into(), "aud".into()],
            busiest_threads: 2,
            ..Placement::default()
        };
        placement.cycles.insert(3, 500);
        placement.cycles.insert(4, 900);
        placement.cycles.insert(2, 10);
        placement.cycles.insert(0, 10_000);
        let keys = placement.key_threads();
        assert_eq!(
            keys,
            vec![
                ("highlight".to_owned(), 0),
                ("highlight".to_owned(), 1),
                ("busy 1".to_owned(), 4),
                ("busy 2".to_owned(), 3),
            ]
        );
    }

    #[test]
    fn busiest_ties_break_by_readings_then_index() {
        let mut placement = Placement {
            threads: threads(),
            busiest_threads: 10,
            ..Placement::default()
        };
        placement.cycles.insert(5, 7);
        placement.cycles.insert(2, 7);
        placement.readings = vec![reading(2, 0, 1), reading(1, 0, 2), reading(1, 0, 3)];
        let keys = placement.key_threads();
        let indexes: Vec<usize> = keys.iter().map(|(_, index)| *index).collect();
        // 2 (7 cycles, 1 reading), 5 (7 cycles, 0), then 1 (0 cycles, 2 readings). Threads
        // with neither cycles nor readings are not busy.
        assert_eq!(indexes, vec![2, 5, 1]);
        placement.busiest_threads = 0;
        assert_eq!(placement.key_threads(), []);
    }

    #[test]
    fn no_highlight_and_no_activity_gives_no_keys() {
        assert_eq!(Placement::default().key_threads(), []);
        assert_eq!(Placement::default().key_threads(), []);
    }

    #[test]
    fn shares_changes_and_siblings() {
        // A 1 GHz counter: 100 us is 100,000 ticks.
        let placement = Placement {
            threads: threads(),
            cpus: hybrid(),
            readings: vec![
                // render: processor 0, then 1 (same core), then 4 (a slow core).
                reading(0, 0, 1_000_000),
                reading(0, 1, 2_000_000),
                reading(0, 4, 3_000_000),
                // audio: on processor 1 next to render on 0 (siblings), then far from every
                // other reading.
                reading(1, 1, 1_010_000),
                reading(1, 2, 9_000_000),
            ],
            tsc_hz: 1e9,
            wall: 2.0,
            highlight_threads: vec!["render".into(), "audio".into()],
            ..Placement::default()
        };
        let summary = placement.summarize();
        assert_eq!(summary.threads.len(), 2);
        let render = &summary.threads[0];
        assert_eq!((render.readings, render.slow_class), (3, 1));
        assert_eq!((render.cpu_changes, render.core_changes), (2, 1));
        let audio = &summary.threads[1];
        assert_eq!(
            (audio.readings, audio.slow_class, audio.core_changes),
            (2, 0, 1)
        );
        // The first render and audio readings are 10 us apart, on the two hyperthreads of
        // core 0; no other reading has a partner within 100 us.
        assert_eq!(summary.simultaneous, 2);
        assert_eq!(summary.siblings, 2);
        assert_eq!(
            summary.sibling_pairs,
            vec![("render".to_owned(), "audio".to_owned(), 2)]
        );
        let text = placement.report();
        assert!(text.contains("6 logical processors on 4 cores"), "{text}");
        assert!(text.contains("class 1: 4 logical on 2 cores"), "{text}");
        assert!(text.contains("class 0: 2 logical on 2 cores"), "{text}");
        assert!(text.contains("siblings render + audio: 2"), "{text}");
        // 1 of 5 readings on a slow core.
        assert!(
            text.contains("all read threads: 20.0% of readings on slower cores"),
            "{text}"
        );
        assert!(text.contains("1.0 processor changes/s"), "{text}");
    }

    #[test]
    fn simultaneity_window_boundary() {
        let base = Placement {
            threads: threads(),
            cpus: hybrid(),
            tsc_hz: 1e9,
            wall: 1.0,
            highlight_threads: vec!["render".into(), "audio".into()],
            ..Placement::default()
        };
        // Exactly 100 us apart counts; 1 tick more does not.
        let mut at_edge = base.clone();
        at_edge.readings = vec![reading(0, 0, 0), reading(1, 1, 100_000)];
        assert_eq!(at_edge.summarize().siblings, 2);
        let mut past = base.clone();
        past.readings = vec![reading(0, 0, 0), reading(1, 1, 100_001)];
        assert_eq!(past.summarize().simultaneous, 0);
        // Same processor at once is simultaneous but not siblings; different cores neither.
        let mut same = base.clone();
        same.readings = vec![reading(0, 0, 0), reading(1, 0, 10)];
        let summary = same.summarize();
        assert_eq!((summary.simultaneous, summary.siblings), (2, 0));
        let mut apart = base;
        apart.readings = vec![reading(0, 0, 0), reading(1, 2, 10)];
        let summary = apart.summarize();
        assert_eq!((summary.simultaneous, summary.siblings), (2, 0));
    }

    #[test]
    fn a_thread_alone_is_never_simultaneous_with_itself() {
        let placement = Placement {
            threads: threads(),
            cpus: hybrid(),
            tsc_hz: 1e9,
            readings: vec![reading(0, 0, 0), reading(0, 1, 1)],
            highlight_threads: vec!["render".into()],
            ..Placement::default()
        };
        let summary = placement.summarize();
        assert_eq!((summary.simultaneous, summary.siblings), (0, 0));
    }

    #[test]
    fn unknown_counter_rate_skips_co_scheduling() {
        let placement = Placement {
            threads: threads(),
            cpus: hybrid(),
            readings: vec![reading(0, 0, 0), reading(1, 1, 1)],
            tsc_hz: f64::NAN,
            highlight_threads: vec!["render".into(), "audio".into()],
            ..Placement::default()
        };
        let summary = placement.summarize();
        assert_eq!(summary.simultaneous, 0);
        let text = placement.report();
        assert!(!text.contains("key threads:"), "{text}");
        assert!(!text.contains("NaN"), "{text}");
    }

    #[test]
    fn readings_on_unknown_processors_are_not_slow() {
        let placement = Placement {
            threads: threads(),
            cpus: hybrid(),
            readings: vec![reading(0, 63, 0), reading(0, 4, 1)],
            highlight_threads: vec!["render".into()],
            ..Placement::default()
        };
        let summary = placement.summarize();
        assert_eq!(summary.threads[0].slow_class, 1);
        // An unknown processor has no core, so the change counts as a core change.
        assert_eq!(summary.threads[0].core_changes, 1);
    }

    #[test]
    fn one_core_class_says_so() {
        let placement = Placement {
            threads: threads(),
            cpus: vec![Cpu {
                index: 0,
                core: 0,
                class: 0,
            }],
            ..Placement::default()
        };
        let text = placement.report();
        assert!(text.contains("one core class"), "{text}");
        assert!(text.contains("0.0% of readings on slower cores"), "{text}");
    }

    #[test]
    fn same_named_threads_stay_apart() {
        let cpu = |index, core| Cpu {
            index,
            core,
            class: 1,
        };
        // Two cores with two hyperthreads each.
        let cpus = vec![cpu(0, 0), cpu(1, 0), cpu(2, 1), cpu(3, 1)];
        let placement = Placement {
            cpus,
            threads: vec![
                PlacedThread::new("worker", 10),
                PlacedThread::new("worker", 11),
            ],
            // Each worker stays on its own processor; their readings interleave in time.
            readings: vec![
                reading(0, 0, 1_000),
                reading(1, 1, 1_010),
                reading(0, 0, 2_000_000),
                reading(1, 1, 2_000_010),
                reading(0, 0, 4_000_000),
                reading(1, 2, 4_000_010),
            ],
            tsc_hz: 1e9,
            wall: 1.0,
            highlight_threads: vec!["worker".into()],
            ..Placement::default()
        };
        let summary = placement.summarize();
        assert_eq!(summary.threads.len(), 2);
        assert_eq!(summary.threads[0].cpu_changes, 0, "no fake migration");
        assert_eq!(summary.threads[1].cpu_changes, 1);
        assert_eq!(summary.threads[1].core_changes, 1);
        // The first two pairs ran on hyperthreads of core 0, the last on different cores.
        assert_eq!(summary.simultaneous, 6);
        assert_eq!(summary.siblings, 4);
        assert_eq!(
            summary.sibling_pairs,
            vec![(
                "worker #1 (tid 10)".to_owned(),
                "worker #2 (tid 11)".to_owned(),
                4
            )]
        );
        let text = placement.report();
        assert!(text.contains("worker #1 (tid 10)"), "{text}");
        assert!(text.contains("worker #2 (tid 11)"), "{text}");
        // A unique name is shown as is.
        assert_eq!(
            Placement {
                threads: threads(),
                ..Placement::default()
            }
            .label(0),
            "render"
        );
        assert_eq!(Placement::default().label(3), "?");
    }

    #[test]
    fn the_placement_rate_stays_under_its_ceiling() {
        for hz in [1, 100, 199, 200, 201, 399, 400, 401, 1000, 1999, 2000] {
            let stride = placement_stride(hz);
            assert!(
                f64::from(hz) / stride as f64 <= f64::from(PLACEMENT_HZ),
                "{hz} Hz every {stride} passes"
            );
        }
        assert_eq!(placement_stride(399), 2);
        assert_eq!(placement_stride(200), 1);
        assert_eq!(placement_stride(0), 1);
    }

    #[test]
    fn huge_counts_saturate() {
        let mut placement = Placement {
            threads: threads(),
            busiest_threads: 1,
            ..Placement::default()
        };
        placement.cycles.insert(0, u64::MAX);
        assert_eq!(placement.key_threads(), vec![("busy 1".to_owned(), 0)]);
    }

    #[test]
    fn unavailable_reason_is_reported() {
        let placement = Placement {
            threads: threads(),
            unavailable: Some("QueueUserAPC2 is missing".into()),
            ..Placement::default()
        };
        assert!(
            placement
                .report()
                .contains("no readings: QueueUserAPC2 is missing")
        );
    }

    fn entry(kind: u32, group: u16, logical: u8, core: u8, class: u8, size: u32) -> Vec<u8> {
        let mut bytes = vec![0_u8; size.max(20) as usize];
        bytes[0..4].copy_from_slice(&size.to_le_bytes());
        bytes[4..8].copy_from_slice(&kind.to_le_bytes());
        bytes[12..14].copy_from_slice(&group.to_le_bytes());
        bytes[14] = logical;
        bytes[15] = core;
        bytes[18] = class;
        bytes
    }

    #[test]
    fn cpu_set_entries_parse() {
        let mut bytes = entry(0, 0, 0, 0, 1, 32);
        bytes.extend(entry(0, 0, 1, 0, 1, 32));
        bytes.extend(entry(7, 0, 2, 1, 1, 32));
        bytes.extend(entry(0, 1, 3, 5, 0, 32));
        bytes.extend([1, 2, 3]);
        let cpu = |index, core, class| Cpu { index, core, class };
        assert_eq!(
            parse_cpu_sets(&bytes),
            vec![cpu(0, 0, 1), cpu(1, 0, 1), cpu(67, (1 << 8) | 5, 0)]
        );
    }

    #[test]
    fn cpu_set_malformed_entries_stop_the_walk() {
        assert_eq!(parse_cpu_sets(&[]), []);
        // Size 0 would loop for ever; it stops instead.
        let mut zero = entry(0, 0, 0, 0, 1, 32);
        zero[0..4].copy_from_slice(&0_u32.to_le_bytes());
        assert_eq!(parse_cpu_sets(&zero), []);
        // Too small for the fields read.
        assert_eq!(parse_cpu_sets(&entry(0, 0, 0, 0, 1, 19)[..19]), []);
        // Claims more bytes than there are.
        let mut long = entry(0, 0, 0, 0, 1, 32);
        long[0..4].copy_from_slice(&64_u32.to_le_bytes());
        assert_eq!(parse_cpu_sets(&long), []);
        // Exactly 20 bytes is enough.
        assert_eq!(parse_cpu_sets(&entry(0, 2, 9, 4, 3, 20)).len(), 1);
        let mut huge = entry(0, 0, 0, 0, 1, 32);
        huge[0..4].copy_from_slice(&u32::MAX.to_le_bytes());
        assert_eq!(parse_cpu_sets(&huge), []);
    }
}