trueno-explain 0.2.2

PTX/SIMD/wgpu visualization and tracing CLI for Trueno
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
//! Analysis diff and regression detection
//!
//! Compares two analysis reports to detect performance regressions.
//! Supports CI integration with exit codes for automated gating.

use crate::analyzer::AnalysisReport;
use serde::{Deserialize, Serialize};

/// Regression severity levels
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Severity {
    /// Informational change (no action needed)
    Info,
    /// Minor regression (review recommended)
    Warning,
    /// Major regression (CI should fail)
    Critical,
}

/// A detected change between baseline and current
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Change {
    /// What changed
    pub metric: String,
    /// Baseline value
    pub baseline: f32,
    /// Current value
    pub current: f32,
    /// Percentage change (positive = regression)
    pub percent_change: f32,
    /// Severity of the change
    pub severity: Severity,
}

/// Result of comparing two analyses
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiffReport {
    /// Name of the analysis
    pub name: String,
    /// List of detected changes
    pub changes: Vec<Change>,
    /// Whether any regressions were detected
    pub has_regression: bool,
    /// Summary message
    pub summary: String,
}

/// Thresholds for regression detection
#[derive(Debug, Clone)]
pub struct DiffThresholds {
    /// Register increase warning threshold (percentage)
    pub register_increase_warning: f32,
    /// Register increase critical threshold (percentage)
    pub register_increase_critical: f32,
    /// Instruction count increase warning threshold (percentage)
    pub instruction_increase_warning: f32,
    /// Instruction count increase critical threshold (percentage)
    pub instruction_increase_critical: f32,
    /// Occupancy decrease warning threshold (percentage points)
    pub occupancy_decrease_warning: f32,
    /// Occupancy decrease critical threshold (percentage points)
    pub occupancy_decrease_critical: f32,
    /// Warning count increase that triggers concern
    pub warning_count_increase: u32,
}

impl Default for DiffThresholds {
    fn default() -> Self {
        Self {
            register_increase_warning: 10.0,     // 10% more registers = warning
            register_increase_critical: 25.0,    // 25% more = critical
            instruction_increase_warning: 15.0,  // 15% more instructions = warning
            instruction_increase_critical: 50.0, // 50% more = critical
            occupancy_decrease_warning: 10.0,    // 10pp occupancy drop = warning
            occupancy_decrease_critical: 25.0,   // 25pp = critical
            warning_count_increase: 2,           // 2+ new warnings = concern
        }
    }
}

/// Compare two analysis reports
#[must_use]
pub fn compare_reports(
    baseline: &AnalysisReport,
    current: &AnalysisReport,
    thresholds: &DiffThresholds,
) -> DiffReport {
    let mut changes = Vec::new();
    let mut has_regression = false;

    // Compare register usage
    let baseline_regs = baseline.registers.total() as f32;
    let current_regs = current.registers.total() as f32;
    if baseline_regs > 0.0 {
        let percent = (current_regs - baseline_regs) / baseline_regs * 100.0;
        if percent.abs() > 0.1 {
            let severity = if percent > thresholds.register_increase_critical {
                has_regression = true;
                Severity::Critical
            } else if percent > thresholds.register_increase_warning {
                Severity::Warning
            } else {
                Severity::Info
            };
            changes.push(Change {
                metric: "register_count".to_string(),
                baseline: baseline_regs,
                current: current_regs,
                percent_change: percent,
                severity,
            });
        }
    }

    // Compare instruction count
    let baseline_inst = baseline.instruction_count as f32;
    let current_inst = current.instruction_count as f32;
    if baseline_inst > 0.0 {
        let percent = (current_inst - baseline_inst) / baseline_inst * 100.0;
        if percent.abs() > 0.1 {
            let severity = if percent > thresholds.instruction_increase_critical {
                has_regression = true;
                Severity::Critical
            } else if percent > thresholds.instruction_increase_warning {
                Severity::Warning
            } else {
                Severity::Info
            };
            changes.push(Change {
                metric: "instruction_count".to_string(),
                baseline: baseline_inst,
                current: current_inst,
                percent_change: percent,
                severity,
            });
        }
    }

    // Compare estimated occupancy
    let baseline_occ = baseline.estimated_occupancy * 100.0;
    let current_occ = current.estimated_occupancy * 100.0;
    let occ_diff = baseline_occ - current_occ; // Positive = regression (drop)
    if occ_diff.abs() > 0.1 {
        let severity = if occ_diff >= thresholds.occupancy_decrease_critical {
            has_regression = true;
            Severity::Critical
        } else if occ_diff >= thresholds.occupancy_decrease_warning {
            Severity::Warning
        } else {
            Severity::Info
        };
        changes.push(Change {
            metric: "estimated_occupancy".to_string(),
            baseline: baseline_occ,
            current: current_occ,
            percent_change: -occ_diff, // Negative change = regression
            severity,
        });
    }

    // Compare warning counts
    let baseline_warns = baseline.warnings.len() as u32;
    let current_warns = current.warnings.len() as u32;
    if current_warns > baseline_warns {
        let increase = current_warns - baseline_warns;
        let severity = if increase >= thresholds.warning_count_increase {
            Severity::Warning
        } else {
            Severity::Info
        };
        changes.push(Change {
            metric: "muda_warnings".to_string(),
            baseline: baseline_warns as f32,
            current: current_warns as f32,
            percent_change: if baseline_warns > 0 {
                (increase as f32 / baseline_warns as f32) * 100.0
            } else {
                100.0
            },
            severity,
        });
    }

    // Generate summary
    let critical_count = changes
        .iter()
        .filter(|c| c.severity == Severity::Critical)
        .count();
    let warning_count = changes
        .iter()
        .filter(|c| c.severity == Severity::Warning)
        .count();

    let summary = if critical_count > 0 {
        format!(
            "{} critical regression(s), {} warning(s)",
            critical_count, warning_count
        )
    } else if warning_count > 0 {
        format!("{} warning(s), no critical regressions", warning_count)
    } else if changes.is_empty() {
        "No significant changes detected".to_string()
    } else {
        format!("{} minor change(s)", changes.len())
    };

    DiffReport {
        name: current.name.clone(),
        changes,
        has_regression,
        summary,
    }
}

/// Format diff report as text
#[must_use]
pub fn format_diff_text(report: &DiffReport) -> String {
    let mut output = String::new();

    output.push_str(&format!("╔══ Diff Report: {} ══╗\n", report.name));
    output.push_str(&format!("Summary: {}\n\n", report.summary));

    if report.changes.is_empty() {
        output.push_str("  No changes detected.\n");
    } else {
        for change in &report.changes {
            let icon = match change.severity {
                Severity::Critical => "",
                Severity::Warning => "⚠️",
                Severity::Info => "ℹ️",
            };
            let direction = if change.percent_change > 0.0 {
                ""
            } else {
                ""
            };
            output.push_str(&format!(
                "{} {}: {}{} ({}{:.1}%)\n",
                icon,
                change.metric,
                change.baseline,
                change.current,
                direction,
                change.percent_change.abs()
            ));
        }
    }

    if report.has_regression {
        output.push_str("\n🚨 REGRESSION DETECTED - CI should fail\n");
    }

    output
}

/// Format diff report as JSON
#[must_use]
pub fn format_diff_json(report: &DiffReport) -> String {
    serde_json::to_string_pretty(report).unwrap_or_else(|_| "{}".to_string())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::analyzer::{MemoryPattern, MudaType, MudaWarning, RegisterUsage, RooflineMetric};

    fn make_warning() -> MudaWarning {
        MudaWarning {
            muda_type: MudaType::Transport,
            description: "Test warning".to_string(),
            impact: "Minor".to_string(),
            line: None,
            suggestion: None,
        }
    }

    fn make_report(name: &str, regs: u32, inst: u32, occ: f32, warns: usize) -> AnalysisReport {
        AnalysisReport {
            name: name.to_string(),
            target: "test".to_string(),
            registers: RegisterUsage {
                f32_regs: regs,
                f64_regs: 0,
                pred_regs: 0,
                ..Default::default()
            },
            memory: MemoryPattern::default(),
            roofline: RooflineMetric::default(),
            warnings: (0..warns).map(|_| make_warning()).collect(),
            instruction_count: inst,
            estimated_occupancy: occ,
        }
    }

    #[test]
    fn test_no_changes() {
        let baseline = make_report("test", 32, 100, 0.75, 1);
        let current = make_report("test", 32, 100, 0.75, 1);
        let thresholds = DiffThresholds::default();

        let report = compare_reports(&baseline, &current, &thresholds);

        assert!(!report.has_regression);
        assert!(report.changes.is_empty());
    }

    #[test]
    fn test_register_increase_warning() {
        let baseline = make_report("test", 32, 100, 0.75, 1);
        let current = make_report("test", 36, 100, 0.75, 1); // 12.5% increase
        let thresholds = DiffThresholds::default();

        let report = compare_reports(&baseline, &current, &thresholds);

        assert!(!report.has_regression);
        assert!(report
            .changes
            .iter()
            .any(|c| c.metric == "register_count" && c.severity == Severity::Warning));
    }

    #[test]
    fn test_register_increase_critical() {
        let baseline = make_report("test", 32, 100, 0.75, 1);
        let current = make_report("test", 48, 100, 0.75, 1); // 50% increase
        let thresholds = DiffThresholds::default();

        let report = compare_reports(&baseline, &current, &thresholds);

        assert!(report.has_regression);
        assert!(report
            .changes
            .iter()
            .any(|c| c.metric == "register_count" && c.severity == Severity::Critical));
    }

    #[test]
    fn test_occupancy_decrease() {
        let baseline = make_report("test", 32, 100, 0.75, 1);
        let current = make_report("test", 32, 100, 0.50, 1); // 25pp decrease
        let thresholds = DiffThresholds::default();

        let report = compare_reports(&baseline, &current, &thresholds);

        assert!(report.has_regression);
    }

    #[test]
    fn test_warning_count_increase() {
        let baseline = make_report("test", 32, 100, 0.75, 1);
        let current = make_report("test", 32, 100, 0.75, 4); // 3 new warnings
        let thresholds = DiffThresholds::default();

        let report = compare_reports(&baseline, &current, &thresholds);

        assert!(report.changes.iter().any(|c| c.metric == "muda_warnings"));
    }

    #[test]
    fn test_format_text() {
        let baseline = make_report("test", 32, 100, 0.75, 1);
        let current = make_report("test", 40, 100, 0.75, 1);
        let thresholds = DiffThresholds::default();

        let report = compare_reports(&baseline, &current, &thresholds);
        let text = format_diff_text(&report);

        assert!(text.contains("Diff Report"));
        assert!(text.contains("register_count"));
    }

    #[test]
    fn test_format_json() {
        let baseline = make_report("test", 32, 100, 0.75, 1);
        let current = make_report("test", 32, 100, 0.75, 1);
        let thresholds = DiffThresholds::default();

        let report = compare_reports(&baseline, &current, &thresholds);
        let json = format_diff_json(&report);

        assert!(json.contains("\"name\": \"test\""));
    }

    /// F086: Diff detects register regression
    #[test]
    fn f086_diff_detects_register_regression() {
        let baseline = make_report("gemm", 32, 500, 0.75, 0);
        let current = make_report("gemm", 64, 500, 0.75, 0); // 100% increase
        let thresholds = DiffThresholds::default();

        let report = compare_reports(&baseline, &current, &thresholds);

        assert!(report.has_regression, "Should detect register regression");
        assert!(
            report
                .changes
                .iter()
                .any(|c| c.metric == "register_count" && c.severity == Severity::Critical),
            "Register increase should be critical"
        );
    }

    /// F089: Diff returns exit code on regression
    #[test]
    fn f089_diff_exit_code_on_regression() {
        let baseline = make_report("gemm", 32, 500, 0.75, 0);
        let current = make_report("gemm", 64, 800, 0.50, 5); // Multiple regressions
        let thresholds = DiffThresholds::default();

        let report = compare_reports(&baseline, &current, &thresholds);

        // In real CLI, has_regression determines exit code
        assert!(report.has_regression, "Should have regression for CI fail");
    }
}