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
//! What to sample: thread filters, rate, window, placement and the stall recorder budget.

use crate::Error;

/// The environment variable prefix [`Config::from_env`] reads.
pub const DEFAULT_PREFIX: &str = "MAPSAMPLE";
/// Samples per second when the spec gives none.
pub const DEFAULT_HZ: u32 = 1000;
/// The most samples per second accepted (the pacing timer cannot go faster).
pub const MAX_HZ: u32 = 2000;
/// Seconds of samples the rolling recorder keeps by default.
pub const DEFAULT_RING_SECONDS: u64 = 40;
/// The longest rolling recorder accepted, in seconds.
pub const MAX_RING_SECONDS: u64 = 3600;
/// Dumps written per run at most, by default.
pub const DEFAULT_MAX_DUMPS: usize = 8;
/// Busiest threads the placement section reports by default, besides the highlighted ones.
pub const DEFAULT_BUSIEST_THREADS: usize = 4;

/// A span of the run, in seconds after the sampler started: `start <= t < end`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Window {
    start: f64,
    end: f64,
}

impl Window {
    /// A window from `start` to `end` seconds; `0 <= start < end`, both finite.
    pub fn new(start: f64, end: f64) -> Result<Self, Error> {
        if start.is_finite() && end.is_finite() && start >= 0.0 && end > start {
            Ok(Self { start, end })
        } else {
            Err(Error::InvalidConfig(format!(
                "window {start}-{end}: expected 0 <= start < end, both finite"
            )))
        }
    }

    /// Parse `<start>-<end>` in seconds, for example `12.5-20`.
    pub fn parse(text: &str) -> Result<Self, Error> {
        let bad = || {
            Error::InvalidConfig(format!(
                "window {text:?}: expected <start>-<end> in seconds"
            ))
        };
        let (start, end) = text.trim().split_once('-').ok_or_else(bad)?;
        let start: f64 = start.trim().parse().map_err(|_| bad())?;
        let end: f64 = end.trim().parse().map_err(|_| bad())?;
        Self::new(start, end).map_err(|_| bad())
    }

    /// The first second inside.
    #[must_use]
    pub fn start(&self) -> f64 {
        self.start
    }

    /// The first second past the end.
    #[must_use]
    pub fn end(&self) -> f64 {
        self.end
    }

    /// Whether `seconds` after the start lies inside.
    #[must_use]
    pub fn contains(&self, seconds: f64) -> bool {
        seconds >= self.start && seconds < self.end
    }
}

/// Whether placement readings are taken.
///
/// A reading is the logical processor a thread was running on and the time stamp counter at
/// that moment, taken by a special user-mode APC (`QueueUserAPC2`, Windows 11).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PlacementMode {
    /// No readings.
    #[default]
    Off,
    /// Readings and stack samples.
    WithSamples,
    /// Readings only: no thread is paused.
    Only,
}

impl PlacementMode {
    /// Parse `0` (or empty) for off, `1` for with samples, `only` for readings only.
    pub fn parse(text: &str) -> Result<Self, Error> {
        match text.trim() {
            "" | "0" => Ok(Self::Off),
            "1" => Ok(Self::WithSamples),
            "only" => Ok(Self::Only),
            other => Err(Error::InvalidConfig(format!(
                "placement {other:?}: expected 0, 1 or only"
            ))),
        }
    }
}

/// What to sample.
///
/// Built from a spec, `<name substring[,substring...] or *>[:hz]`, then adjusted with the
/// `with_*` methods:
///
/// ```
/// use mapsample::{Config, PlacementMode, Window};
///
/// let config = Config::parse("worker,io:500")?
///     .with_window(Window::parse("2-10")?)
///     .with_placement(PlacementMode::WithSamples)
///     .with_highlight_threads(["render"]);
/// assert_eq!(config.hz(), 500);
/// assert!(config.matches("IO-pool-3"));
/// assert!(!config.matches("main"));
/// # Ok::<(), mapsample::Error>(())
/// ```
#[derive(Clone, Debug, PartialEq)]
pub struct Config {
    spec: String,
    /// Lowercased name substrings.
    filters: Vec<String>,
    /// `*`: every thread but the sampler's own.
    all: bool,
    hz: u32,
    window: Option<Window>,
    placement: PlacementMode,
    highlight: Vec<String>,
    busiest: usize,
    ring_seconds: u64,
    max_dumps: usize,
}

impl Config {
    /// Parse `<substring[,substring...] or *>[:hz]`.
    ///
    /// Substrings match thread names case-insensitively; `*` matches every thread, named or
    /// not. The rate is clamped to [`MAX_HZ`] and must be at least 1; without one it is
    /// [`DEFAULT_HZ`]. A trailing `:text` that is not all digits stays part of the name.
    pub fn parse(spec: &str) -> Result<Self, Error> {
        let text = spec.trim();
        let (names, hz) = match text.rsplit_once(':') {
            Some((names, rate)) if !rate.is_empty() && rate.bytes().all(|b| b.is_ascii_digit()) => {
                // All digits: only too many of them fail to parse.
                let hz = rate.parse::<u32>().unwrap_or(u32::MAX);
                if hz == 0 {
                    return Err(Error::InvalidConfig(format!(
                        "spec {text:?}: the rate must be at least 1"
                    )));
                }
                (names, hz.min(MAX_HZ))
            }
            _ => (text, DEFAULT_HZ),
        };
        let mut filters = Vec::new();
        let mut all = false;
        for name in names.split(',').map(str::trim).filter(|n| !n.is_empty()) {
            if name == "*" {
                all = true;
            } else {
                filters.push(name.to_lowercase());
            }
        }
        if !all && filters.is_empty() {
            return Err(Error::InvalidConfig(format!(
                "spec {text:?}: give a thread name substring or *"
            )));
        }
        Ok(Self {
            spec: text.to_owned(),
            filters,
            all,
            hz,
            window: None,
            placement: PlacementMode::Off,
            highlight: Vec::new(),
            busiest: DEFAULT_BUSIEST_THREADS,
            ring_seconds: DEFAULT_RING_SECONDS,
            max_dumps: DEFAULT_MAX_DUMPS,
        })
    }

    /// The configuration in `MAPSAMPLE`, `MAPSAMPLE_WINDOW`, `MAPSAMPLE_PLACEMENT` and
    /// `MAPSAMPLE_HIGHLIGHT`; `Ok(None)` when `MAPSAMPLE` is unset or blank.
    pub fn from_env() -> Result<Option<Self>, Error> {
        Self::from_env_prefix(DEFAULT_PREFIX)
    }

    /// As [`from_env`](Self::from_env), with `prefix` in place of `MAPSAMPLE`: `<PREFIX>`
    /// holds the spec, `<PREFIX>_WINDOW` a [`Window`], `<PREFIX>_PLACEMENT` a
    /// [`PlacementMode`] and `<PREFIX>_HIGHLIGHT` comma-separated thread name substrings.
    ///
    /// The prefix is ASCII letters, digits and underscores, not starting with a digit.
    pub fn from_env_prefix(prefix: &str) -> Result<Option<Self>, Error> {
        Self::from_vars(prefix, |name| match std::env::var(name) {
            Ok(value) => Ok(Some(value)),
            Err(std::env::VarError::NotPresent) => Ok(None),
            Err(std::env::VarError::NotUnicode(_)) => {
                Err(Error::InvalidConfig(format!("{name} is not valid Unicode")))
            }
        })
    }

    pub(crate) fn from_vars(
        prefix: &str,
        lookup: impl Fn(&str) -> Result<Option<String>, Error>,
    ) -> Result<Option<Self>, Error> {
        let valid = prefix
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'_')
            && prefix.bytes().next().is_some_and(|b| !b.is_ascii_digit());
        if !valid {
            return Err(Error::InvalidConfig(format!(
                "environment prefix {prefix:?}: use ASCII letters, digits and _, not starting with a digit"
            )));
        }
        let Some(spec) = lookup(prefix)?.filter(|spec| !spec.trim().is_empty()) else {
            return Ok(None);
        };
        let var = |suffix: &str| lookup(&format!("{prefix}_{suffix}"));
        let named = |suffix: &str, error: Error| match error {
            Error::InvalidConfig(message) => {
                Error::InvalidConfig(format!("{prefix}_{suffix}: {message}"))
            }
            other => other,
        };
        let mut config = Self::parse(&spec).map_err(|error| match error {
            Error::InvalidConfig(message) => Error::InvalidConfig(format!("{prefix}: {message}")),
            other => other,
        })?;
        if let Some(window) = var("WINDOW")?.filter(|text| !text.trim().is_empty()) {
            config.window = Some(Window::parse(&window).map_err(|e| named("WINDOW", e))?);
        }
        if let Some(mode) = var("PLACEMENT")? {
            config.placement = PlacementMode::parse(&mode).map_err(|e| named("PLACEMENT", e))?;
        }
        if let Some(names) = var("HIGHLIGHT")? {
            config = config.with_highlight_threads(names.split(','));
        }
        Ok(Some(config))
    }

    /// Sample only inside `window`.
    #[must_use]
    pub fn with_window(mut self, window: Window) -> Self {
        self.window = Some(window);
        self
    }

    /// Take placement readings.
    #[must_use]
    pub fn with_placement(mut self, placement: PlacementMode) -> Self {
        self.placement = placement;
        self
    }

    /// Threads the placement section always reports, by case-insensitive name substring.
    /// Blank entries are ignored.
    #[must_use]
    pub fn with_highlight_threads<I, S>(mut self, names: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        self.highlight = names
            .into_iter()
            .map(|name| name.as_ref().trim().to_owned())
            .filter(|name| !name.is_empty())
            .collect();
        self
    }

    /// How many of the busiest other threads the placement section reports (default
    /// [`DEFAULT_BUSIEST_THREADS`]).
    #[must_use]
    pub fn with_busiest_threads(mut self, count: usize) -> Self {
        self.busiest = count;
        self
    }

    /// Seconds the rolling stall recorder keeps, clamped to `1..=`[`MAX_RING_SECONDS`].
    #[must_use]
    pub fn with_ring_seconds(mut self, seconds: u64) -> Self {
        self.ring_seconds = seconds.clamp(1, MAX_RING_SECONDS);
        self
    }

    /// Dumps accepted per run.
    #[must_use]
    pub fn with_max_dumps(mut self, max: usize) -> Self {
        self.max_dumps = max;
        self
    }

    /// The spec text, for the report.
    #[must_use]
    pub fn spec(&self) -> &str {
        &self.spec
    }

    /// Samples per second, per thread.
    #[must_use]
    pub fn hz(&self) -> u32 {
        self.hz
    }

    /// The sampling window, if any.
    #[must_use]
    pub fn window(&self) -> Option<Window> {
        self.window
    }

    /// The placement mode.
    #[must_use]
    pub fn placement(&self) -> PlacementMode {
        self.placement
    }

    /// The highlighted thread name substrings.
    #[must_use]
    pub fn highlight_threads(&self) -> &[String] {
        &self.highlight
    }

    /// How many busiest threads the placement section reports.
    #[must_use]
    pub fn busiest_threads(&self) -> usize {
        self.busiest
    }

    /// Seconds the rolling stall recorder keeps.
    #[must_use]
    pub fn ring_seconds(&self) -> u64 {
        self.ring_seconds
    }

    /// Dumps accepted per run.
    #[must_use]
    pub fn max_dumps(&self) -> usize {
        self.max_dumps
    }

    /// Whether a thread called `name` (`""` if it has none) is sampled.
    #[must_use]
    pub fn matches(&self, name: &str) -> bool {
        if self.all {
            return true;
        }
        if name.is_empty() {
            return false;
        }
        let lower = name.to_lowercase();
        self.filters.iter().any(|filter| lower.contains(filter))
    }
}

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

    #[test]
    fn spec_parses_names_rate_and_star() {
        let config = Config::parse("worker:500").unwrap();
        assert_eq!(config.hz(), 500);
        assert!(config.matches("Worker-Pool-2"));
        assert!(!config.matches("main"));
        assert!(!config.matches(""));
        let two = Config::parse(" worker , io ").unwrap();
        assert_eq!(two.hz(), DEFAULT_HZ);
        assert!(two.matches("async-io-1"));
        assert_eq!(two.spec(), "worker , io");
        let star = Config::parse("*:2").unwrap();
        assert!(star.matches("") && star.matches("anything"));
        assert_eq!(star.hz(), 2);
    }

    #[test]
    fn spec_rate_boundaries() {
        assert_eq!(Config::parse("*:1").unwrap().hz(), 1);
        assert_eq!(Config::parse("*:2000").unwrap().hz(), MAX_HZ);
        assert_eq!(Config::parse("*:2001").unwrap().hz(), MAX_HZ);
        assert_eq!(Config::parse("*:99999999999999").unwrap().hz(), MAX_HZ);
        assert!(matches!(Config::parse("a:0"), Err(Error::InvalidConfig(_))));
        assert!(Config::parse("a:00").is_err());
        // A colon not followed by digits stays part of the name.
        let colon = Config::parse("a:b").unwrap();
        assert_eq!(colon.hz(), DEFAULT_HZ);
        assert!(colon.matches("xa:by"));
        assert!(Config::parse("a:").unwrap().matches("a:"));
    }

    #[test]
    fn spec_needs_a_name() {
        for bad in ["", "   ", ":100", ",", " , :5"] {
            assert!(Config::parse(bad).is_err(), "{bad:?}");
        }
    }

    #[test]
    fn builders_clamp_and_keep() {
        let config = Config::parse("x")
            .unwrap()
            .with_ring_seconds(0)
            .with_max_dumps(2)
            .with_busiest_threads(0)
            .with_highlight_threads([" a ", "", "b"]);
        assert_eq!(config.ring_seconds(), 1);
        assert_eq!(config.max_dumps(), 2);
        assert_eq!(config.busiest_threads(), 0);
        assert_eq!(config.highlight_threads(), ["a", "b"]);
        assert_eq!(
            config.with_ring_seconds(u64::MAX).ring_seconds(),
            MAX_RING_SECONDS
        );
    }

    #[test]
    fn window_bounds() {
        let window = Window::parse(" 0.5 - 2 ").unwrap();
        assert_eq!((window.start(), window.end()), (0.5, 2.0));
        assert!(window.contains(0.5));
        assert!(window.contains(1.999));
        assert!(!window.contains(2.0));
        assert!(!window.contains(0.4));
        assert!(Window::parse("0-0.001").is_ok());
        for bad in ["57-48", "48", "a-b", "1-1", "-1-2", "1-inf", "nan-2", ""] {
            assert!(Window::parse(bad).is_err(), "{bad:?}");
        }
        assert!(Window::new(f64::NAN, 1.0).is_err());
        assert!(Window::new(0.0, f64::INFINITY).is_err());
    }

    #[test]
    fn placement_mode_text() {
        assert_eq!(PlacementMode::parse("").unwrap(), PlacementMode::Off);
        assert_eq!(PlacementMode::parse("0").unwrap(), PlacementMode::Off);
        assert_eq!(
            PlacementMode::parse("1").unwrap(),
            PlacementMode::WithSamples
        );
        assert_eq!(PlacementMode::parse(" only ").unwrap(), PlacementMode::Only);
        assert!(PlacementMode::parse("yes").is_err());
        assert!(PlacementMode::parse("ONLY").is_err());
    }

    fn vars(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Result<Option<String>, Error> {
        let map: HashMap<String, String> = pairs
            .iter()
            .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
            .collect();
        move |name| Ok(map.get(name).cloned())
    }

    #[test]
    fn env_prefix_reads_all_variables() {
        let config = Config::from_vars(
            "APP",
            vars(&[
                ("APP", "worker:250"),
                ("APP_WINDOW", "1-3"),
                ("APP_PLACEMENT", "only"),
                ("APP_HIGHLIGHT", "render, audio"),
                ("MAPSAMPLE", "*"),
            ]),
        )
        .unwrap()
        .unwrap();
        assert_eq!(config.hz(), 250);
        assert_eq!(config.window(), Some(Window::new(1.0, 3.0).unwrap()));
        assert_eq!(config.placement(), PlacementMode::Only);
        assert_eq!(config.highlight_threads(), ["render", "audio"]);
    }

    #[test]
    fn env_unset_or_blank_is_none() {
        assert!(Config::from_vars("APP", vars(&[])).unwrap().is_none());
        assert!(
            Config::from_vars("APP", vars(&[("APP", "  "), ("APP_WINDOW", "bad")]))
                .unwrap()
                .is_none()
        );
    }

    #[test]
    fn env_errors_name_the_variable() {
        let error = Config::from_vars("APP", vars(&[("APP", "x"), ("APP_WINDOW", "9-1")]))
            .unwrap_err()
            .to_string();
        assert!(error.contains("APP_WINDOW"), "{error}");
        let error = Config::from_vars("APP", vars(&[("APP", "x"), ("APP_PLACEMENT", "2")]))
            .unwrap_err()
            .to_string();
        assert!(error.contains("APP_PLACEMENT"), "{error}");
        let error = Config::from_vars("APP", vars(&[("APP", ":5")]))
            .unwrap_err()
            .to_string();
        assert!(error.contains("APP:"), "{error}");
        let blank_window =
            Config::from_vars("APP", vars(&[("APP", "x"), ("APP_WINDOW", " ")])).unwrap();
        assert_eq!(blank_window.unwrap().window(), None);
    }

    #[test]
    fn env_prefix_is_checked() {
        for bad in ["", "1APP", "MY-APP", "A B", "\u{e9}"] {
            assert!(Config::from_vars(bad, vars(&[])).is_err(), "{bad:?}");
        }
        assert!(Config::from_vars("_A1", vars(&[])).is_ok());
    }

    #[test]
    fn real_environment_unset_prefix() {
        // A prefix nobody sets: reading the real environment gives no configuration.
        assert!(
            Config::from_env_prefix("MAPSAMPLE_TEST_UNSET_7F3A")
                .unwrap()
                .is_none()
        );
    }
}