nmbrs-metrics 0.7.3

Metrics collection and reporting for nmbrs
Documentation
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! Reading a session's series over a phase (SRD-118 ยง5.1).
//!
//! A series the session records, such as a host measure, has no
//! `phase` label, and one of its samples may have been taken while
//! several phases ran. Which of its samples count toward a phase is
//! decided when the series is read, by the reserved matcher
//! `phase_samples`. This module holds the matcher's values and the
//! rule each stands for; a backend that can answer the matcher applies
//! the rule to the windows it has stored.

use super::{MatchOp, Matcher, QueryError};

/// The reserved matcher's label.
pub const LABEL: &str = "phase_samples";

/// The family whose samples say when a phase ran: every phase records
/// it, one series for each activation, and each of its samples covers
/// an exact stretch of that activation.
pub const ACTIVITY_FAMILY: &str = "result_success";

/// A stretch of time that ends at `end_ms` and began `end_ms -
/// start_ms` before it: after `start_ms`, up to and including
/// `end_ms`. A stored sample covers one, and is *taken* at its end.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Window {
    pub start_ms: i64,
    pub end_ms: i64,
}

impl Window {
    /// The window of a sample stored at `timestamp_ms` over
    /// `interval_ms`.
    pub fn of_sample(timestamp_ms: i64, interval_ms: i64) -> Self {
        Self {
            start_ms: timestamp_ms - interval_ms.max(0),
            end_ms: timestamp_ms,
        }
    }
}

/// How a sample's window must stand to a phase's frame to count.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PhaseSamples {
    /// The sample's window lies wholly inside the frame.
    Within,
    /// The sample's window shares any time with the frame.
    Overlapping,
    /// One sample: the last taken inside the frame, or failing that
    /// the one taken closest to it, before or after.
    Nearest,
    /// One sample: the first taken at or after the frame's end.
    Closing,
}

impl PhaseSamples {
    /// The matcher's values, in the order they are listed to a user.
    pub const NAMES: &'static [&'static str] = &["within", "overlapping", "nearest", "closing"];

    pub fn parse(name: &str) -> Option<Self> {
        Some(match name {
            "within" => Self::Within,
            "overlapping" => Self::Overlapping,
            "nearest" => Self::Nearest,
            "closing" => Self::Closing,
            _ => return None,
        })
    }

    pub fn name(self) -> &'static str {
        match self {
            Self::Within => "within",
            Self::Overlapping => "overlapping",
            Self::Nearest => "nearest",
            Self::Closing => "closing",
        }
    }

    /// The samples that count toward `frame`, as indexes into
    /// `samples`, ascending. `samples` are in the order they were
    /// taken.
    pub fn select(self, frame: Window, samples: &[Window]) -> Vec<usize> {
        let mut indexed = samples.iter().enumerate();
        match self {
            Self::Within => indexed
                .filter(|(_, s)| s.start_ms >= frame.start_ms && s.end_ms <= frame.end_ms)
                .map(|(i, _)| i)
                .collect(),
            Self::Overlapping => indexed
                .filter(|(_, s)| s.start_ms < frame.end_ms && s.end_ms > frame.start_ms)
                .map(|(i, _)| i)
                .collect(),
            Self::Nearest => {
                // How far outside the frame a sample was taken; zero
                // inside it. Of equals the later is kept, so the last
                // one inside wins over the earlier ones inside.
                let outside = |s: &Window| {
                    if s.end_ms <= frame.start_ms {
                        frame.start_ms - s.end_ms
                    } else {
                        (s.end_ms - frame.end_ms).max(0)
                    }
                };
                indexed
                    .min_by_key(|(i, s)| (outside(s), std::cmp::Reverse(*i)))
                    .map(|(i, _)| vec![i])
                    .unwrap_or_default()
            }
            Self::Closing => indexed
                .find(|(_, s)| s.end_ms >= frame.end_ms)
                .map(|(i, _)| vec![i])
                .unwrap_or_default(),
        }
    }
}

/// What a backend says when it is asked for [`LABEL`] and cannot
/// answer it.
pub fn refused_by(backend: &str) -> QueryError {
    QueryError::new(format!(
        "`{LABEL}` reads a session's series over a phase from the session's store, \
         and this read is of {backend}; a phase's samples are not complete until it \
         has ended. Query the store after the run (`nmbrs metrics query`, or a report)."
    ))
}

/// The mode a selector asks for with [`LABEL`], or `None` when it
/// carries no such matcher. The matcher is `phase_samples="<mode>"`:
/// another operator, or a value that is not a mode, is an error that
/// lists the modes.
pub fn requested(matchers: &[Matcher]) -> Result<Option<PhaseSamples>, QueryError> {
    let Some(matcher) = matchers.iter().find(|m| m.label == LABEL) else {
        return Ok(None);
    };
    let mode = (matcher.op == MatchOp::Eq)
        .then(|| PhaseSamples::parse(&matcher.value))
        .flatten();
    mode.map(Some).ok_or_else(|| {
        QueryError::new(format!(
            "`{LABEL}` takes one of {} with `=`, as in {LABEL}=\"overlapping\"; got '{}'",
            PhaseSamples::NAMES.join(", "),
            matcher.value
        ))
    })
}

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

    /// Samples taken every 10 from 10 to 60, each covering the 10
    /// before it.
    fn samples() -> Vec<Window> {
        (1..=6).map(|i| Window::of_sample(i * 10, 10)).collect()
    }

    fn taken(mode: PhaseSamples, start_ms: i64, end_ms: i64) -> Vec<i64> {
        let samples = samples();
        mode.select(Window { start_ms, end_ms }, &samples)
            .into_iter()
            .map(|i| samples[i].end_ms)
            .collect()
    }

    /// A frame from 15 to 45 holds the samples taken at 30 and 40
    /// whole, and touches the ones taken at 20 and 50.
    #[test]
    fn within_is_the_windows_inside_and_overlapping_the_ones_that_touch() {
        assert_eq!(taken(PhaseSamples::Within, 15, 45), vec![30, 40]);
        assert_eq!(
            taken(PhaseSamples::Overlapping, 15, 45),
            vec![20, 30, 40, 50]
        );
        // A window that only meets the frame at its edge shares no time.
        assert_eq!(taken(PhaseSamples::Overlapping, 20, 30), vec![30]);
        assert_eq!(taken(PhaseSamples::Within, 20, 30), vec![30]);
    }

    /// A frame shorter than a sample has nothing within it, and is
    /// still seen by the sample that covers it.
    #[test]
    fn a_short_frame_is_overlapped_and_not_enclosed() {
        assert_eq!(taken(PhaseSamples::Within, 22, 25), Vec::<i64>::new());
        assert_eq!(taken(PhaseSamples::Overlapping, 22, 25), vec![30]);
    }

    #[test]
    fn nearest_is_the_last_inside_or_else_the_closest_outside() {
        assert_eq!(taken(PhaseSamples::Nearest, 15, 45), vec![40]);
        // Nothing taken inside: 30 is 3 after the end, 20 is 4 before
        // the start.
        assert_eq!(taken(PhaseSamples::Nearest, 24, 27), vec![30]);
        assert_eq!(taken(PhaseSamples::Nearest, 21, 27), vec![20]);
        // Before the first sample and after the last.
        assert_eq!(taken(PhaseSamples::Nearest, 0, 5), vec![10]);
        assert_eq!(taken(PhaseSamples::Nearest, 90, 95), vec![60]);
    }

    #[test]
    fn closing_is_the_first_taken_at_or_after_the_end() {
        assert_eq!(taken(PhaseSamples::Closing, 15, 45), vec![50]);
        assert_eq!(taken(PhaseSamples::Closing, 15, 40), vec![40]);
        assert_eq!(taken(PhaseSamples::Closing, 15, 95), Vec::<i64>::new());
    }

    #[test]
    fn no_samples_is_no_selection() {
        let frame = Window {
            start_ms: 0,
            end_ms: 10,
        };
        for name in PhaseSamples::NAMES {
            let mode = PhaseSamples::parse(name).unwrap();
            assert_eq!(mode.name(), *name);
            assert!(mode.select(frame, &[]).is_empty());
        }
    }

    #[test]
    fn the_matcher_is_read_from_a_selector() {
        let name = Matcher::eq("__name__", "sysmon_cpu_util");
        assert_eq!(requested(std::slice::from_ref(&name)).unwrap(), None);
        assert_eq!(
            requested(&[name.clone(), Matcher::eq(LABEL, "closing")]).unwrap(),
            Some(PhaseSamples::Closing)
        );
        for bad in [Matcher::eq(LABEL, "inside"), Matcher::ne(LABEL, "within")] {
            let err = requested(&[name.clone(), bad]).unwrap_err().to_string();
            assert!(
                err.contains("within, overlapping, nearest, closing"),
                "{err}"
            );
        }
    }
}