nornir 0.4.20

Companion to cargo: dependency tracking, release gating, deploy, benchmarks, and documentation assembly. Project-agnostic.
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
//! **Pure model** behind the 🧪 Test pane's per-repo × per-aspect matrix.
//!
//! Everything the gorgeous grid renders is derived here from a flat slice of
//! [`TestResultRow`]s — no egui, no I/O — so it can be unit-tested and folded
//! verbatim into `state_json()["test"]` (THE_BIG_PLAN LAW: "see what the user
//! sees" as data). The renderer in [`super::test_tab`] only paints what these
//! functions compute.
//!
//! The shape:
//!   * **rows = repos**, taken from each repo's *latest run* (newest `ts_micros`).
//!   * **columns = aspects**, in [`ASPECT_ORDER`] (build · unit · doctest · clippy
//!     · fmt · audit · bench-smoke · coverage · feature-powerset · msrv ·
//!     examples), filtered to those actually present in the data.
//!   * each **cell** = the aspect's status + numeric metric in that repo's latest
//!     run (plus the failing cases for drill-down), or "not-run" when absent.
//!   * a **health score** (0–100) per repo, and **sparkline series** per
//!     (repo, aspect) across recent runs so trends are visible.

use crate::warehouse::test_results::{status, summarize_runs, TestResultRow};

/// Aspect columns in canonical display order (matches `Aspect::ALL`'s labels).
pub const ASPECT_ORDER: &[&str] = &[
    "build",
    "unit",
    "doctest",
    "clippy",
    "fmt",
    "audit",
    "bench-smoke",
    "coverage",
    "feature-powerset",
    "msrv",
    "examples",
];

/// How many recent runs (per repo) the trend sparklines span.
pub const SPARK_RUNS: usize = 12;

/// One cell of the matrix: a repo × aspect verdict in that repo's latest run.
#[derive(Debug, Clone, PartialEq)]
pub struct Cell {
    /// `pass` | `fail` | `stalled` | `skip` | `ignored`, or `""` = not run.
    pub status: String,
    /// The aspect's numeric metric (coverage %, warning count, …); 0.0 if N/A.
    pub metric: f64,
    /// How many cases rolled into this cell (1 for synthetic aspects; N for unit).
    pub count: usize,
    /// For the unit aspect: passed / failed sub-counts (else 0 / 0).
    pub passed: usize,
    pub failed: usize,
    /// Failing/stalled cases under this cell (for the drill-down panel).
    pub red_cases: Vec<RedCase>,
}

impl Cell {
    fn not_run() -> Self {
        Self {
            status: String::new(),
            metric: 0.0,
            count: 0,
            passed: 0,
            failed: 0,
            red_cases: Vec::new(),
        }
    }
    /// Was this aspect run at all in the repo's latest run?
    pub fn ran(&self) -> bool {
        !self.status.is_empty()
    }
    pub fn is_red(&self) -> bool {
        status::is_red(&self.status)
    }
    pub fn is_green(&self) -> bool {
        status::is_green(&self.status)
    }

    /// The type-aware badge text for this cell, e.g. `"87%"`, `"⚠3"`, `"🛡0"`,
    /// `"142✓ 2✗"`. Empty when the cell didn't run or has nothing to show.
    pub fn badge(&self, aspect: &str) -> String {
        if !self.ran() {
            return String::new();
        }
        match aspect {
            "coverage" => format!("{:.0}%", self.metric),
            "clippy" => format!("âš {}", self.metric as i64),
            "audit" => format!("🛡{}", self.metric as i64),
            "fmt" => {
                if self.metric > 0.0 {
                    format!("±{}", self.metric as i64)
                } else {
                    String::new()
                }
            }
            "unit" => {
                if self.failed > 0 {
                    format!("{}✓ {}✗", self.passed, self.failed)
                } else {
                    format!("{}✓", self.passed)
                }
            }
            _ => String::new(),
        }
    }
}

/// One failing case under a cell, surfaced in the drill-down.
#[derive(Debug, Clone, PartialEq)]
pub struct RedCase {
    pub test_name: String,
    pub suite: String,
    pub status: String,
    pub message: String,
}

/// One matrix row: a repo, its latest-run cells (one per aspect column), its
/// health score, and its run identity.
#[derive(Debug, Clone)]
pub struct RepoRow {
    pub repo: String,
    pub run_id: String,
    pub ts_micros: i64,
    /// Latest-run verdict per aspect column (parallel to [`Matrix::aspects`]).
    pub cells: Vec<Cell>,
    /// 0–100 derived health (green-ratio + coverage − warnings/advisories).
    pub health: f64,
    /// Per-aspect sparkline series across recent runs (parallel to `aspects`).
    /// Each inner Vec is one normalized point per recent run (oldest → newest).
    pub sparks: Vec<Vec<f64>>,
}

/// The whole grid + the summary strip totals.
#[derive(Debug, Clone)]
pub struct Matrix {
    /// Aspect column labels actually present in the data, in [`ASPECT_ORDER`].
    pub aspects: Vec<String>,
    /// One row per repo, sorted by repo name.
    pub rows: Vec<RepoRow>,
    /// Summary strip: total cells that are green / red / skip / not-run.
    pub total_green: usize,
    pub total_red: usize,
    pub total_skip: usize,
    pub total_blank: usize,
}

impl Matrix {
    /// Build the matrix from a flat slice of rows.
    pub fn build(rows: &[TestResultRow]) -> Self {
        use std::collections::BTreeMap;

        // 1. group rows by repo.
        let mut by_repo: BTreeMap<String, Vec<&TestResultRow>> = BTreeMap::new();
        for r in rows {
            by_repo.entry(r.repo.clone()).or_default().push(r);
        }

        // 2. which aspect columns actually appear (in canonical order).
        let present: std::collections::HashSet<&str> =
            rows.iter().map(|r| r.aspect.as_str()).collect();
        let aspects: Vec<String> = ASPECT_ORDER
            .iter()
            .filter(|a| present.contains(**a))
            .map(|a| a.to_string())
            .collect();

        let mut out_rows = Vec::new();
        let (mut tg, mut tr, mut ts, mut tb) = (0usize, 0usize, 0usize, 0usize);

        for (repo, repo_rows) in &by_repo {
            // newest run for this repo.
            let summaries = summarize_runs(
                &repo_rows.iter().map(|r| (*r).clone()).collect::<Vec<_>>(),
            );
            let Some(latest) = summaries.first() else { continue };
            let latest_id = latest.run_id.clone();

            // cell per aspect, from the latest run's rows.
            let mut cells = Vec::with_capacity(aspects.len());
            for aspect in &aspects {
                let cell = build_cell(repo_rows, &latest_id, aspect);
                match () {
                    _ if !cell.ran() => tb += 1,
                    _ if cell.is_red() => tr += 1,
                    _ if cell.is_green() => tg += 1,
                    _ => ts += 1, // skip / ignored / neutral
                }
                cells.push(cell);
            }

            let health = health_score(&aspects, &cells);
            let sparks = aspects
                .iter()
                .map(|a| spark_series(repo_rows, &summaries, a))
                .collect();

            out_rows.push(RepoRow {
                repo: repo.clone(),
                run_id: latest_id,
                ts_micros: latest.ts_micros,
                cells,
                health,
                sparks,
            });
        }

        Matrix {
            aspects,
            rows: out_rows,
            total_green: tg,
            total_red: tr,
            total_skip: ts,
            total_blank: tb,
        }
    }
}

/// Roll the latest run's rows for one aspect into a [`Cell`].
fn build_cell(repo_rows: &[&TestResultRow], run_id: &str, aspect: &str) -> Cell {
    let hits: Vec<&&TestResultRow> = repo_rows
        .iter()
        .filter(|r| r.run_id == run_id && r.aspect == aspect)
        .collect();
    if hits.is_empty() {
        return Cell::not_run();
    }

    if aspect == "unit" {
        // The unit aspect expands to per-test rows: roll them up.
        let mut passed = 0;
        let mut failed = 0;
        let mut red_cases = Vec::new();
        for r in &hits {
            if status::is_green(&r.status) {
                passed += 1;
            } else if status::is_red(&r.status) {
                failed += 1;
            }
            if status::is_red(&r.status) {
                red_cases.push(RedCase {
                    test_name: r.test_name.clone(),
                    suite: r.suite.clone(),
                    status: r.status.clone(),
                    message: r.message.clone(),
                });
            }
        }
        let cell_status = if failed > 0 { status::FAIL } else { status::PASS };
        return Cell {
            status: cell_status.to_string(),
            metric: failed as f64,
            count: hits.len(),
            passed,
            failed,
            red_cases,
        };
    }

    // Synthetic aspect: a single row carries status + metric.
    let r = hits[0];
    let red_cases = if status::is_red(&r.status) {
        vec![RedCase {
            test_name: r.test_name.clone(),
            suite: r.suite.clone(),
            status: r.status.clone(),
            message: r.message.clone(),
        }]
    } else {
        Vec::new()
    };
    Cell {
        status: r.status.clone(),
        metric: r.metric,
        count: hits.len(),
        passed: usize::from(status::is_green(&r.status)),
        failed: usize::from(status::is_red(&r.status)),
        red_cases,
    }
}

/// A 0–100 health score for a repo from its latest-run cells.
///
/// Blend of three signals over the aspects that actually ran:
///   * **green ratio** (green / (green+red+skip)) — weighted 60.
///   * **coverage** %, if measured — weighted 25 (else that weight redistributes).
///   * a **penalty** for clippy warnings + audit advisories (−4 each, capped).
pub fn health_score(aspects: &[String], cells: &[Cell]) -> f64 {
    let mut green = 0.0;
    let mut considered = 0.0;
    let mut coverage: Option<f64> = None;
    let mut penalty = 0.0;
    for (a, c) in aspects.iter().zip(cells) {
        if !c.ran() {
            continue;
        }
        if c.is_green() || c.is_red() || c.status == status::SKIP {
            considered += 1.0;
            if c.is_green() {
                green += 1.0;
            }
        }
        match a.as_str() {
            "coverage" if c.ran() => coverage = Some(c.metric),
            "clippy" => penalty += c.metric.min(8.0) * 4.0,
            "audit" => penalty += c.metric.min(8.0) * 6.0,
            _ => {}
        }
    }
    if considered == 0.0 {
        return 0.0;
    }
    let green_ratio = green / considered; // 0..1
    let (base, score) = match coverage {
        Some(cov) => {
            // green-ratio 60 pts + coverage 25 pts + 15 pts free baseline.
            let s = green_ratio * 60.0 + (cov / 100.0).clamp(0.0, 1.0) * 25.0 + 15.0;
            (60.0 + 25.0 + 15.0, s)
        }
        None => {
            // no coverage signal: green-ratio takes its 25 pts (weighted 85) + 15.
            let s = green_ratio * 85.0 + 15.0;
            (85.0 + 15.0, s)
        }
    };
    let _ = base;
    (score - penalty).clamp(0.0, 100.0)
}

/// A per-(repo, aspect) sparkline: one normalized point per recent run
/// (oldest → newest, last [`SPARK_RUNS`]). The value is aspect-aware:
///   * coverage → the % itself (0..100),
///   * clippy/audit/fmt → the count, **inverted** so "fewer = up" reads as rising
///     health (mapped to 0..100 via a soft cap),
///   * everything else → 100 for green, 0 for red, 50 for skip/neutral.
pub fn spark_series(
    repo_rows: &[&TestResultRow],
    summaries: &[crate::warehouse::test_results::RunSummary],
    aspect: &str,
) -> Vec<f64> {
    // summaries are newest-first; take the most recent SPARK_RUNS, oldest→newest.
    let mut runs: Vec<&crate::warehouse::test_results::RunSummary> =
        summaries.iter().take(SPARK_RUNS).collect();
    runs.reverse();
    let mut series = Vec::with_capacity(runs.len());
    for run in runs {
        let hits: Vec<&&TestResultRow> = repo_rows
            .iter()
            .filter(|r| r.run_id == run.run_id && r.aspect == aspect)
            .collect();
        if hits.is_empty() {
            continue; // aspect not run in that run — skip the point.
        }
        let v = match aspect {
            "coverage" => hits.iter().map(|r| r.metric).fold(0.0, f64::max),
            "clippy" | "audit" | "fmt" => {
                let count = hits.iter().map(|r| r.metric).fold(0.0, f64::max);
                // fewer = healthier: 0 warnings → 100, 10+ → ~0.
                (1.0 - (count / 10.0).clamp(0.0, 1.0)) * 100.0
            }
            "unit" => {
                let total = hits.len() as f64;
                let pass = hits.iter().filter(|r| status::is_green(&r.status)).count() as f64;
                if total == 0.0 {
                    50.0
                } else {
                    pass / total * 100.0
                }
            }
            _ => {
                // single synthetic verdict.
                let r = hits[0];
                if status::is_green(&r.status) {
                    100.0
                } else if status::is_red(&r.status) {
                    0.0
                } else {
                    50.0
                }
            }
        };
        series.push(v);
    }
    series
}

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

    fn row(run: &str, repo: &str, aspect: &str, name: &str, st: &str, metric: f64, ts: i64) -> TestResultRow {
        TestResultRow {
            run_id: run.into(),
            repo: repo.into(),
            suite: repo.into(),
            test_name: name.into(),
            status: st.into(),
            duration_ms: 1.0,
            ts_micros: ts,
            message: if status::is_red(st) { format!("{name} boom") } else { String::new() },
            aspect: aspect.into(),
            metric,
        }
    }

    #[test]
    fn matrix_rows_are_repos_cols_are_aspects() {
        let rows = vec![
            row("r1", "alpha", "build", "build", status::PASS, 0.0, 100),
            row("r1", "alpha", "clippy", "clippy", status::FAIL, 3.0, 100),
            row("r1", "beta", "build", "build", status::PASS, 0.0, 100),
            row("r1", "beta", "coverage", "coverage", status::PASS, 87.0, 100),
        ];
        let m = Matrix::build(&rows);
        // two repos, sorted.
        assert_eq!(m.rows.iter().map(|r| r.repo.as_str()).collect::<Vec<_>>(), vec!["alpha", "beta"]);
        // aspect columns present, in canonical order.
        assert_eq!(m.aspects, vec!["build", "clippy", "coverage"]);
    }

    #[test]
    fn cells_carry_status_and_metric_badges() {
        let rows = vec![
            row("r1", "alpha", "clippy", "clippy", status::FAIL, 3.0, 100),
            row("r1", "alpha", "coverage", "coverage", status::PASS, 87.0, 100),
            row("r1", "alpha", "audit", "audit", status::PASS, 0.0, 100),
        ];
        let m = Matrix::build(&rows);
        let a = &m.rows[0];
        let clippy = a.cells[m.aspects.iter().position(|x| x == "clippy").unwrap()].clone();
        assert_eq!(clippy.status, status::FAIL);
        assert_eq!(clippy.metric, 3.0);
        assert_eq!(clippy.badge("clippy"), "âš 3");
        let cov = a.cells[m.aspects.iter().position(|x| x == "coverage").unwrap()].clone();
        assert_eq!(cov.badge("coverage"), "87%");
        let audit = a.cells[m.aspects.iter().position(|x| x == "audit").unwrap()].clone();
        assert_eq!(audit.badge("audit"), "🛡0");
    }

    #[test]
    fn unit_cell_rolls_up_pass_fail_counts_and_badge() {
        let rows = vec![
            row("r1", "alpha", "unit", "a::t1", status::PASS, 0.0, 100),
            row("r1", "alpha", "unit", "a::t2", status::PASS, 0.0, 100),
            row("r1", "alpha", "unit", "a::t3", status::FAIL, 0.0, 100),
        ];
        let m = Matrix::build(&rows);
        let unit = &m.rows[0].cells[0];
        assert_eq!(unit.passed, 2);
        assert_eq!(unit.failed, 1);
        assert_eq!(unit.status, status::FAIL);
        assert_eq!(unit.badge("unit"), "2✓ 1✗");
        assert_eq!(unit.red_cases.len(), 1);
        assert_eq!(unit.red_cases[0].test_name, "a::t3");
    }

    #[test]
    fn latest_run_wins_per_repo() {
        let rows = vec![
            row("old", "alpha", "clippy", "clippy", status::FAIL, 5.0, 100),
            row("new", "alpha", "clippy", "clippy", status::PASS, 0.0, 200),
        ];
        let m = Matrix::build(&rows);
        let clippy = &m.rows[0].cells[0];
        assert_eq!(m.rows[0].run_id, "new", "newest run selected");
        assert_eq!(clippy.status, status::PASS, "latest run's verdict");
    }

    #[test]
    fn not_run_cell_is_blank_and_counted() {
        // beta has no clippy column-cell → it's blank.
        let rows = vec![
            row("r1", "alpha", "clippy", "clippy", status::PASS, 0.0, 100),
            row("r1", "beta", "build", "build", status::PASS, 0.0, 100),
        ];
        let m = Matrix::build(&rows);
        let beta = m.rows.iter().find(|r| r.repo == "beta").unwrap();
        let clippy_idx = m.aspects.iter().position(|x| x == "clippy").unwrap();
        assert!(!beta.cells[clippy_idx].ran(), "beta never ran clippy");
        assert!(m.total_blank >= 1, "blank cells counted in the summary strip");
    }

    #[test]
    fn health_high_for_green_high_coverage_low_warnings() {
        let aspects: Vec<String> = vec!["build".into(), "coverage".into(), "clippy".into()];
        let cells = vec![
            Cell { status: status::PASS.into(), metric: 0.0, count: 1, passed: 1, failed: 0, red_cases: vec![] },
            Cell { status: status::PASS.into(), metric: 95.0, count: 1, passed: 1, failed: 0, red_cases: vec![] },
            Cell { status: status::PASS.into(), metric: 0.0, count: 1, passed: 1, failed: 0, red_cases: vec![] },
        ];
        let h = health_score(&aspects, &cells);
        assert!(h > 90.0, "all green + 95% coverage + no warnings → near 100, got {h}");
    }

    #[test]
    fn health_drops_for_failures_and_warnings() {
        let aspects: Vec<String> = vec!["build".into(), "coverage".into(), "clippy".into()];
        let cells = vec![
            Cell { status: status::FAIL.into(), metric: 1.0, count: 1, passed: 0, failed: 1, red_cases: vec![] },
            Cell { status: status::PASS.into(), metric: 40.0, count: 1, passed: 1, failed: 0, red_cases: vec![] },
            Cell { status: status::FAIL.into(), metric: 6.0, count: 1, passed: 0, failed: 1, red_cases: vec![] },
        ];
        let h = health_score(&aspects, &cells);
        assert!(h < 50.0, "a build fail + low coverage + 6 warnings → unhealthy, got {h}");
    }

    #[test]
    fn sparkline_tracks_coverage_over_runs() {
        let rows = vec![
            row("run1", "alpha", "coverage", "coverage", status::PASS, 70.0, 100),
            row("run2", "alpha", "coverage", "coverage", status::PASS, 80.0, 200),
            row("run3", "alpha", "coverage", "coverage", status::PASS, 90.0, 300),
        ];
        let m = Matrix::build(&rows);
        let cov_idx = m.aspects.iter().position(|x| x == "coverage").unwrap();
        let series = &m.rows[0].sparks[cov_idx];
        assert_eq!(series.len(), 3, "one point per run");
        assert_eq!(series, &vec![70.0, 80.0, 90.0], "oldest→newest, rising coverage");
    }

    #[test]
    fn sparkline_inverts_warning_counts() {
        // clippy warnings falling 8 → 0 should read as a RISING (healthier) spark.
        let rows = vec![
            row("run1", "alpha", "clippy", "clippy", status::FAIL, 8.0, 100),
            row("run2", "alpha", "clippy", "clippy", status::PASS, 0.0, 200),
        ];
        let m = Matrix::build(&rows);
        let idx = m.aspects.iter().position(|x| x == "clippy").unwrap();
        let series = &m.rows[0].sparks[idx];
        assert_eq!(series.len(), 2);
        assert!(series[0] < series[1], "fewer warnings later → spark rises: {series:?}");
        assert!((series[1] - 100.0).abs() < 1e-9, "0 warnings = 100");
    }
}