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
//! The rolling stall recorder: the last seconds of samples, one profile per second.

use std::collections::VecDeque;

use crate::Profile;

/// The samples of the last `capacity` seconds of a run, kept in one-second slices.
///
/// A slice for second `s` is dropped once a sample for second `s + capacity` or later
/// arrives, so the ring always covers the newest `capacity` seconds that had samples.
#[derive(Clone, Debug)]
pub struct Ring {
    capacity: u64,
    /// Ascending by second.
    slices: VecDeque<(u64, Profile)>,
}

impl Ring {
    /// A ring of `capacity` seconds (at least 1).
    #[must_use]
    pub fn new(capacity: u64) -> Self {
        Self {
            capacity: capacity.max(1),
            slices: VecDeque::new(),
        }
    }

    /// Seconds kept.
    #[must_use]
    pub fn capacity(&self) -> u64 {
        self.capacity
    }

    /// Slices held now.
    #[must_use]
    pub fn len(&self) -> usize {
        self.slices.len()
    }

    /// Whether no sample is held.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.slices.is_empty()
    }

    /// The newest second with samples.
    #[must_use]
    pub fn newest(&self) -> Option<u64> {
        self.slices.back().map(|(second, _)| *second)
    }

    /// Count one stack taken in second `second` of the run on thread `thread`. A sample older
    /// than the ring covers is dropped; one for a second between held slices is kept in order.
    pub fn add(&mut self, second: u64, thread: &str, on_cpu: bool, leaf_pc: u64, frames: &[u64]) {
        let newest = self.newest();
        if newest.is_some_and(|newest| second.saturating_add(self.capacity) <= newest) {
            return;
        }
        let at = match self.slices.binary_search_by_key(&second, |(s, _)| *s) {
            Ok(at) => at,
            Err(at) => {
                self.slices.insert(at, (second, Profile::default()));
                at
            }
        };
        if newest.is_none_or(|newest| second > newest) {
            while self.slices.front().is_some_and(|(old, _)| {
                *old < second && old.saturating_add(self.capacity) <= second
            }) {
                self.slices.pop_front();
            }
        }
        let at = at.min(self.slices.len().saturating_sub(1));
        if let Some((_, slice)) = self.slices.get_mut(at) {
            let id = slice.thread_id(thread);
            slice.add(id, on_cpu, leaf_pc, frames, 1);
        }
    }

    /// The samples of seconds `from` and later as one profile named `spec` at `hz`.
    #[must_use]
    pub fn window(&self, from: u64, spec: &str, hz: u32) -> Profile {
        self.between(from, u64::MAX, spec, hz)
    }

    /// The samples of seconds `from` to `to`, both included.
    fn between(&self, from: u64, to: u64, spec: &str, hz: u32) -> Profile {
        let mut out = Profile::new(spec, hz);
        for (second, slice) in &self.slices {
            if (from..=to).contains(second) {
                out.merge(slice);
            }
        }
        out
    }

    /// The samples of the last `seconds` seconds up to and including second `now`: the
    /// current (partial) second plus `ceil(seconds)` whole ones, at most the ring's capacity.
    #[must_use]
    pub fn recent(&self, now: u64, seconds: f64, spec: &str, hz: u32) -> Profile {
        let back = if seconds.is_finite() && seconds > 0.0 {
            // Clamped to the capacity before the cast, so it fits.
            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
            let whole = seconds.ceil().min(self.capacity as f64) as u64;
            whole.min(self.capacity - 1)
        } else {
            0
        };
        self.between(now.saturating_sub(back), now, spec, hz)
    }
}

impl Default for Ring {
    fn default() -> Self {
        Self::new(crate::config::DEFAULT_RING_SECONDS)
    }
}

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

    fn filled(capacity: u64, seconds: std::ops::Range<u64>) -> Ring {
        let mut ring = Ring::new(capacity);
        for second in seconds {
            // One distinct leaf per second, so a window shows which seconds it holds.
            ring.add(second, "worker", true, 0x1000 + second, &[0x1000]);
        }
        ring
    }

    #[test]
    fn keeps_the_last_capacity_seconds() {
        let ring = filled(40, 0..45);
        assert_eq!(ring.len(), 40);
        assert_eq!(ring.newest(), Some(44));
        assert_eq!(
            ring.window(0, "x", 1).total(),
            40,
            "older seconds were dropped"
        );
        assert_eq!(ring.window(42, "x", 1).total(), 3);
        assert_eq!(ring.window(45, "x", 1).total(), 0);
    }

    #[test]
    fn capacity_boundaries() {
        let ring = filled(1, 0..5);
        assert_eq!(ring.len(), 1);
        assert_eq!(ring.window(0, "x", 1).total(), 1);
        assert_eq!(Ring::new(0).capacity(), 1);
        let exact = filled(3, 0..3);
        assert_eq!(exact.len(), 3, "exactly capacity seconds fit");
    }

    #[test]
    fn gaps_evict_by_second_not_by_count() {
        let mut ring = Ring::new(10);
        ring.add(0, "t", true, 1, &[1]);
        ring.add(5, "t", true, 2, &[2]);
        assert_eq!(ring.len(), 2);
        ring.add(15, "t", true, 3, &[3]);
        // 0 and 5 are 10 or more seconds older than 15.
        assert_eq!(ring.len(), 1);
        ring.add(16, "t", true, 4, &[4]);
        assert_eq!(ring.window(0, "x", 1).total(), 2);
    }

    #[test]
    fn late_samples_go_to_their_second_or_are_dropped() {
        let mut ring = Ring::new(10);
        ring.add(20, "t", true, 1, &[1]);
        ring.add(18, "t", true, 2, &[2]);
        ring.add(20, "t", true, 3, &[3]);
        // Ten seconds behind the newest: outside the ring.
        ring.add(10, "t", true, 4, &[4]);
        assert_eq!(ring.len(), 2);
        assert_eq!(ring.window(19, "x", 1).total(), 2);
        assert_eq!(ring.window(18, "x", 1).total(), 3);
        ring.add(11, "t", true, 5, &[5]);
        assert_eq!(ring.window(0, "x", 1).total(), 4);
        ring.add(u64::MAX, "t", true, 6, &[6]);
        assert_eq!(ring.len(), 1);
    }

    #[test]
    fn threads_are_kept_apart_by_name() {
        let mut ring = Ring::new(4);
        ring.add(0, "a", true, 1, &[1]);
        ring.add(1, "b", false, 1, &[1]);
        ring.add(1, "a", true, 1, &[1]);
        let profile = ring.window(0, "spec", 100);
        assert_eq!(profile.spec, "spec");
        assert_eq!(profile.hz, 100);
        assert_eq!(profile.threads(), ["a", "b"]);
        assert_eq!(profile.total(), 3);
        assert!(profile.folded().contains("b#wait;jit+0x1 1"));
    }

    #[test]
    fn recent_counts_back_whole_seconds() {
        let ring = filled(40, 0..45);
        let total = |seconds| ring.recent(44, seconds, "x", 1).total();
        assert_eq!(total(0.0), 1, "the current second only");
        assert_eq!(total(0.1), 2);
        assert_eq!(total(1.0), 2);
        assert_eq!(total(2.5), 4);
        assert_eq!(total(1e9), 40, "capped to the ring");
        assert_eq!(total(f64::NAN), 1);
        assert_eq!(total(-3.0), 1);
        assert_eq!(total(f64::INFINITY), 1);
    }

    #[test]
    fn recent_leaves_out_later_seconds() {
        let ring = filled(40, 0..45);
        // Seconds 39 and 40 only: 41 to 44 are after `now`.
        let profile = ring.recent(40, 1.0, "x", 1);
        assert_eq!(profile.total(), 2);
        let leaves: Vec<u64> = profile.stacks().map(|stack| stack.leaf_pc).collect();
        assert!(
            leaves.iter().all(|&leaf| leaf <= 0x1000 + 40),
            "{leaves:x?}"
        );
        assert_eq!(ring.recent(10, 3.0, "x", 1).total(), 4, "seconds 7 to 10");
        assert_eq!(
            ring.recent(2, 0.0, "x", 1).total(),
            0,
            "second 2 was dropped"
        );
    }
}