Skip to content

Building 70 Projects ranging from beginner to advanced so anyone can — learn from, build upon, use as a reference, or even copy directly. Owned by my cybersecurity company 👇

8.8 KB
Raw Blame
// ©AngelaMos | 2026
// bench.rs

use lisdex_core::stats::{self, Comparison, Summary, Underpowered};

pub const CENSORED_MARKER: &str = "censored";

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Metric {
    Edges,
    Crashes,
    TimeToFirstCrash,
}

impl Metric {
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Metric::Edges => "edges_found",
            Metric::Crashes => "saved_crashes",
            Metric::TimeToFirstCrash => "time_to_first_crash_secs",
        }
    }

    #[must_use]
    pub fn higher_is_better(self) -> bool {
        match self {
            Metric::Edges | Metric::Crashes => true,
            Metric::TimeToFirstCrash => false,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Trial {
    pub edges: u64,
    pub crashes: u64,
    pub time_to_first_crash: Option<u64>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Arm {
    pub name: String,
    pub trials: Vec<Trial>,
}

impl Arm {
    #[must_use]
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            trials: Vec::new(),
        }
    }

    // A trial that never crashed has no time-to-first-crash. Substituting the campaign
    // duration would invent a measurement the run did not make and would drag the median
    // toward whatever wall-clock the operator happened to choose, so a censored trial is
    // dropped from this metric and reported as censored instead.
    #[must_use]
    #[allow(clippy::cast_precision_loss)]
    pub fn samples(&self, metric: Metric) -> Vec<f64> {
        self.trials
            .iter()
            .filter_map(|trial| match metric {
                Metric::Edges => Some(trial.edges as f64),
                Metric::Crashes => Some(trial.crashes as f64),
                Metric::TimeToFirstCrash => trial.time_to_first_crash.map(|seconds| seconds as f64),
            })
            .collect()
    }

    #[must_use]
    pub fn censored(&self, metric: Metric) -> usize {
        match metric {
            Metric::Edges | Metric::Crashes => 0,
            Metric::TimeToFirstCrash => self
                .trials
                .iter()
                .filter(|trial| trial.time_to_first_crash.is_none())
                .count(),
        }
    }

    #[must_use]
    pub fn summary(&self, metric: Metric) -> Option<Summary> {
        stats::summarize(&self.samples(metric))
    }
}

#[derive(Debug, Clone)]
pub struct Report {
    pub metric: Metric,
    pub arms: Vec<Arm>,
    pub verdict: Result<Comparison, Underpowered>,
}

#[must_use]
pub fn compare(metric: Metric, arms: Vec<Arm>) -> Report {
    let verdict = if arms.len() < 2 {
        Err(Underpowered::Empty)
    } else {
        stats::mann_whitney(&arms[0].samples(metric), &arms[1].samples(metric))
    };
    Report {
        metric,
        arms,
        verdict,
    }
}

impl Report {
    #[must_use]
    pub fn render(&self) -> String {
        use std::fmt::Write;

        let mut out = String::new();
        let _ = writeln!(out, "metric {}", self.metric.as_str());
        for arm in &self.arms {
            let censored = arm.censored(self.metric);
            let note = if censored > 0 {
                format!("  {censored} {CENSORED_MARKER}")
            } else {
                String::new()
            };
            match arm.summary(self.metric) {
                Some(summary) => {
                    let _ = writeln!(
                        out,
                        "  {:<16} n={:<4} median={:<12.2} q1={:<12.2} q3={:<12.2} min={:<12.2} max={:.2}{note}",
                        arm.name,
                        summary.n,
                        summary.median,
                        summary.q1,
                        summary.q3,
                        summary.min,
                        summary.max,
                    );
                }
                None => {
                    let _ = writeln!(
                        out,
                        "  {:<16} no measurement ({} trial(s), {censored} {CENSORED_MARKER})",
                        arm.name,
                        arm.trials.len()
                    );
                }
            }
        }
        match &self.verdict {
            Ok(comparison) => {
                let _ = writeln!(
                    out,
                    "  mann-whitney u={:.1} z={:.4} p={:.6} a12={:.4}",
                    comparison.u, comparison.z, comparison.p_value, comparison.a12
                );
                if comparison.is_significant() {
                    let _ = writeln!(
                        out,
                        "  VERDICT significant at alpha={} (a12 {:.4})",
                        stats::SIGNIFICANCE,
                        comparison.a12
                    );
                } else {
                    let _ = writeln!(
                        out,
                        "  VERDICT not significant at alpha={}; the arms are indistinguishable on this metric",
                        stats::SIGNIFICANCE
                    );
                }
            }
            Err(reason) => {
                let _ = writeln!(out, "  NO VERDICT {reason}");
            }
        }
        out
    }

    #[must_use]
    pub fn has_verdict(&self) -> bool {
        self.verdict.is_ok()
    }
}

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

    fn arm(name: &str, values: &[(u64, u64, Option<u64>)]) -> Arm {
        Arm {
            name: name.to_owned(),
            trials: values
                .iter()
                .map(|(edges, crashes, ttfc)| Trial {
                    edges: *edges,
                    crashes: *crashes,
                    time_to_first_crash: *ttfc,
                })
                .collect(),
        }
    }

    fn trials(count: u64, edges: u64) -> Vec<(u64, u64, Option<u64>)> {
        (0..count).map(|i| (edges + i, 1, Some(10 + i))).collect()
    }

    #[test]
    fn a_single_trial_per_arm_yields_no_verdict_at_all() {
        let report = compare(
            Metric::Edges,
            vec![arm("a", &[(100, 0, None)]), arm("b", &[(900, 0, None)])],
        );
        assert!(!report.has_verdict());
        assert!(report.render().contains("NO VERDICT"));
        assert!(!report.render().contains("VERDICT significant"));
    }

    #[test]
    fn nineteen_trials_is_still_below_the_power_floor() {
        let report = compare(
            Metric::Edges,
            vec![arm("a", &trials(19, 100)), arm("b", &trials(19, 9000))],
        );
        assert!(!report.has_verdict());
    }

    #[test]
    fn thirty_trials_produces_a_verdict_and_an_effect_size() {
        let report = compare(
            Metric::Edges,
            vec![arm("a", &trials(30, 100)), arm("b", &trials(30, 9000))],
        );
        let comparison = report.verdict.expect("30 trials clears the floor");
        assert!(comparison.is_significant());
        let rendered = report.render();
        assert!(rendered.contains("VERDICT significant"));
        assert!(rendered.contains("a12"));
    }

    // Klees Finding 4: report quartiles, never mean and standard deviation.
    #[test]
    fn the_report_states_quartiles_and_never_a_mean_or_a_deviation() {
        let rendered = compare(
            Metric::Edges,
            vec![arm("a", &trials(30, 100)), arm("b", &trials(30, 100))],
        )
        .render();
        assert!(rendered.contains("median="));
        assert!(rendered.contains("q1="));
        assert!(rendered.contains("q3="));
        assert!(!rendered.contains("mean"));
        assert!(!rendered.contains("stddev"));
    }

    #[test]
    fn a_trial_that_never_crashed_is_censored_rather_than_scored_as_the_duration() {
        let mixed = arm("a", &[(10, 1, Some(30)), (10, 0, None), (10, 1, Some(50))]);
        assert_eq!(mixed.samples(Metric::TimeToFirstCrash), vec![30.0, 50.0]);
        assert_eq!(mixed.censored(Metric::TimeToFirstCrash), 1);
        assert_eq!(mixed.censored(Metric::Edges), 0);
        assert!(mixed.summary(Metric::TimeToFirstCrash).unwrap().median > 0.0);
    }

    #[test]
    fn an_arm_whose_every_trial_is_censored_reports_no_measurement() {
        let none = arm("a", &[(10, 0, None), (10, 0, None)]);
        assert!(none.summary(Metric::TimeToFirstCrash).is_none());
        let report = compare(
            Metric::TimeToFirstCrash,
            vec![none, arm("b", &trials(30, 10))],
        );
        assert!(report.render().contains("no measurement"));
        assert!(!report.has_verdict());
    }

    #[test]
    fn a_faster_time_to_first_crash_is_better_and_more_edges_is_better() {
        assert!(Metric::Edges.higher_is_better());
        assert!(Metric::Crashes.higher_is_better());
        assert!(!Metric::TimeToFirstCrash.higher_is_better());
    }

    #[test]
    fn one_arm_can_never_produce_a_comparison() {
        let report = compare(Metric::Edges, vec![arm("solo", &trials(30, 100))]);
        assert!(!report.has_verdict());
    }
}