piano 0.15.0

Automatic instrumentation-based profiler for Rust. Measures self-time, call counts, and heap allocations per function.
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
use std::collections::HashMap;

use super::{DIM, FnEntry, HEADER, Run};

/// Delta column width. "+12345.67ms" = 11 chars.
const DELTA_W: usize = 11;

/// Truncate a label to `max_len` characters, appending '...' if truncated.
fn truncate_label(label: &str, max_len: usize) -> String {
    if label.chars().count() <= max_len {
        label.to_string()
    } else {
        let truncated: String = label.chars().take(max_len).collect();
        format!("{truncated}\u{2026}")
    }
}

/// Structured JSON entry for a diff comparison.
#[derive(serde::Serialize, serde::Deserialize)]
pub struct JsonDiffEntry {
    pub name: String,
    pub self_ms_a: f64,
    pub self_ms_b: f64,
    pub delta_ms: f64,
    #[serde(default)]
    pub delta_pct: Option<f64>,
    pub calls_a: u64,
    pub calls_b: u64,
    pub alloc_count_a: u64,
    pub alloc_count_b: u64,
    pub alloc_bytes_a: u64,
    pub alloc_bytes_b: u64,
    #[serde(default)]
    pub cpu_self_ms_a: Option<f64>,
    #[serde(default)]
    pub cpu_self_ms_b: Option<f64>,
}

/// Shared setup for diff functions: build lookup maps, collect unique function
/// names sorted by absolute self-time delta, filter zero-call entries, and
/// apply the truncation limit.
struct DiffSetup<'a> {
    a_map: HashMap<&'a str, &'a FnEntry>,
    b_map: HashMap<&'a str, &'a FnEntry>,
    names: Vec<&'a str>,
    /// Total before any filtering.
    total_count: usize,
    /// After zero-call filtering, before truncation.
    after_filter_count: usize,
}

fn prepare_diff<'a>(a: &'a Run, b: &'a Run, show_all: bool, limit: Option<usize>) -> DiffSetup<'a> {
    let a_map: HashMap<&str, &FnEntry> = a.functions.iter().map(|f| (f.name.as_str(), f)).collect();
    let b_map: HashMap<&str, &FnEntry> = b.functions.iter().map(|f| (f.name.as_str(), f)).collect();

    let mut names: Vec<&str> = a_map.keys().chain(b_map.keys()).copied().collect();
    names.sort_unstable();
    names.dedup();
    names.sort_by(|na, nb| {
        let delta_a = (b_map.get(na).map_or(0.0, |e| e.self_ms)
            - a_map.get(na).map_or(0.0, |e| e.self_ms))
        .abs();
        let delta_b = (b_map.get(nb).map_or(0.0, |e| e.self_ms)
            - a_map.get(nb).map_or(0.0, |e| e.self_ms))
        .abs();
        delta_b
            .partial_cmp(&delta_a)
            .unwrap_or(std::cmp::Ordering::Equal)
    });

    let total_count = names.len();
    if !show_all {
        names.retain(|name| {
            let calls_a = a_map.get(name).map_or(0, |e| e.calls);
            let calls_b = b_map.get(name).map_or(0, |e| e.calls);
            calls_a > 0 || calls_b > 0
        });
    }
    let after_filter_count = names.len();

    if let Some(n) = limit {
        names.truncate(n);
    }

    DiffSetup {
        a_map,
        b_map,
        names,
        total_count,
        after_filter_count,
    }
}

/// Serialize a diff between two runs as a JSON array.
///
/// Each entry contains the function name, self time from each run,
/// the absolute delta, and the percentage change (null when the base is zero).
/// When `show_all` is false, entries where both runs have zero calls are hidden.
/// When `limit` is `Some(n)`, only the top `n` entries (by absolute delta) are included.
pub fn diff_runs_json(a: &Run, b: &Run, show_all: bool, limit: Option<usize>) -> String {
    let DiffSetup {
        a_map,
        b_map,
        names,
        ..
    } = prepare_diff(a, b, show_all, limit);

    let json_entries: Vec<JsonDiffEntry> = names
        .iter()
        .map(|name| {
            let self_a = a_map.get(name).map_or(0.0, |e| e.self_ms);
            let self_b = b_map.get(name).map_or(0.0, |e| e.self_ms);
            let delta = self_b - self_a;
            let delta_pct = if self_a > 0.0 {
                Some(delta / self_a * 100.0)
            } else if delta == 0.0 {
                Some(0.0)
            } else {
                None
            };
            JsonDiffEntry {
                name: name.to_string(),
                self_ms_a: self_a,
                self_ms_b: self_b,
                delta_ms: delta,
                delta_pct,
                calls_a: a_map.get(name).map_or(0, |e| e.calls),
                calls_b: b_map.get(name).map_or(0, |e| e.calls),
                alloc_count_a: a_map.get(name).map_or(0, |e| e.alloc_count),
                alloc_count_b: b_map.get(name).map_or(0, |e| e.alloc_count),
                alloc_bytes_a: a_map.get(name).map_or(0, |e| e.alloc_bytes),
                alloc_bytes_b: b_map.get(name).map_or(0, |e| e.alloc_bytes),
                cpu_self_ms_a: a_map.get(name).and_then(|e| e.cpu_self_ms),
                cpu_self_ms_b: b_map.get(name).and_then(|e| e.cpu_self_ms),
            }
        })
        .collect();

    serde_json::to_string_pretty(&json_entries).expect("JSON serialization should not fail")
}

/// Show the delta between two runs, comparing functions by name.
///
/// `label_a` and `label_b` are used as column headers (e.g. tag names or file stems).
/// Labels longer than 20 characters are truncated with '...'.
/// When `show_all` is false, entries where both runs have zero calls are hidden.
/// When `limit` is `Some(n)`, only the top `n` entries (by absolute delta) are shown.
pub fn diff_runs(
    a: &Run,
    b: &Run,
    label_a: &str,
    label_b: &str,
    show_all: bool,
    limit: Option<usize>,
) -> String {
    // Warn if comparing runs from different formats.
    if a.source_format != b.source_format {
        eprintln!("warning: comparing runs with different source formats (JSON vs NDJSON)");
    }

    let DiffSetup {
        a_map,
        b_map,
        names,
        total_count,
        after_filter_count,
    } = prepare_diff(a, b, show_all, limit);

    // Check if either run has alloc data or CPU data.
    let has_allocs = a.functions.iter().any(|f| f.alloc_count > 0)
        || b.functions.iter().any(|f| f.alloc_count > 0);
    let has_cpu = a.functions.iter().any(|f| f.cpu_self_ms.is_some())
        || b.functions.iter().any(|f| f.cpu_self_ms.is_some());

    let label_a = truncate_label(label_a, 20);
    let label_b = truncate_label(label_b, 20);
    // Column width: at least 10 (for data values like "12345.67ms"), or wider to fit label.
    let col_a = label_a.chars().count().max(10);
    let col_b = label_b.chars().count().max(10);

    let cpu_label_a = format!("CPU.{label_a}");
    let cpu_label_b = format!("CPU.{label_b}");
    let cpu_col_a = cpu_label_a.chars().count().max(10);
    let cpu_col_b = cpu_label_b.chars().count().max(10);

    let mut out = String::new();
    // Build header based on available columns.
    {
        let mut header = format!(
            "{:<40} {:>col_a$} {:>col_b$} {:>DELTA_W$}",
            "Function", label_a, label_b, "Delta"
        );
        if has_cpu {
            header.push_str(&format!(
                " {cpu_label_a:>cpu_col_a$} {cpu_label_b:>cpu_col_b$}"
            ));
        }
        if has_allocs {
            header.push_str(&format!(" {:>10} {:>10}", "Allocs", "A.Delta"));
        }
        let width = header.len();
        out.push_str(&format!("{HEADER}{header}{HEADER:#}\n"));
        out.push_str(&format!("{DIM}{}{DIM:#}\n", "-".repeat(width)));
    }

    for name in &names {
        let before = a_map.get(name).map_or(0.0, |e| e.self_ms);
        let after = b_map.get(name).map_or(0.0, |e| e.self_ms);
        let delta = after - before;

        let delta_val = format!("{delta:+.2}ms");
        out.push_str(&format!(
            "{name:<40} {before:>w_a$.2}ms {after:>w_b$.2}ms {delta_val:>DELTA_W$}",
            w_a = col_a - 2,
            w_b = col_b - 2,
        ));

        if has_cpu {
            let cpu_before = a_map.get(name).and_then(|e| e.cpu_self_ms);
            let cpu_after = b_map.get(name).and_then(|e| e.cpu_self_ms);
            let fmt_cpu = |v: Option<f64>, col_w: usize| match v {
                Some(ms) => format!("{ms:>w$.2}ms", w = col_w - 2),
                None => format!("{:>col_w$}", "-"),
            };
            out.push_str(&format!(
                " {} {}",
                fmt_cpu(cpu_before, cpu_col_a),
                fmt_cpu(cpu_after, cpu_col_b)
            ));
        }

        if has_allocs {
            let allocs_after = b_map.get(name).map_or(0u64, |e| e.alloc_count);
            let allocs_before = a_map.get(name).map_or(0u64, |e| e.alloc_count);
            let allocs_delta = allocs_after as i128 - allocs_before as i128;
            out.push_str(&format!(" {allocs_after:>10} {allocs_delta:>+10}"));
        }

        out.push('\n');
    }

    // Append footer for hidden/truncated entries.
    let zero_call_hidden = total_count - after_filter_count;
    let truncated = after_filter_count - names.len();
    let total_hidden = zero_call_hidden + truncated;
    if total_hidden > 0 {
        let label = if total_hidden == 1 {
            "function"
        } else {
            "functions"
        };
        let hint = if truncated > 0 {
            "use --top N or --all to show"
        } else {
            "use --all to show"
        };
        out.push_str(&format!(
            "{DIM}\n{total_hidden} {label} hidden; {hint}\n{DIM:#}"
        ));
    }

    out
}

#[cfg(test)]
mod tests {
    use super::super::load::load_ndjson;
    use super::super::tag::load_tagged_run;
    use super::super::{FnEntry, Run, RunFormat};
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn diff_shows_delta() {
        let a = Run {
            run_id: None,
            timestamp_ms: 1000,
            source_format: RunFormat::default(),
            functions: vec![FnEntry {
                name: "walk".into(),
                calls: 3,
                total_ms: Some(12.0),
                self_ms: 10.0,
                ..Default::default()
            }],
        };
        let b = Run {
            run_id: None,
            timestamp_ms: 2000,
            source_format: RunFormat::default(),
            functions: vec![FnEntry {
                name: "walk".into(),
                calls: 3,
                total_ms: Some(9.0),
                self_ms: 8.0,
                ..Default::default()
            }],
        };
        let diff = diff_runs(&a, &b, "Before", "After", true, None);
        assert!(diff.contains("walk"), "should mention walk");
        assert!(diff.contains("-2.00"), "should show negative delta: {diff}");
    }

    #[test]
    fn diff_shows_alloc_deltas() {
        let a = Run {
            run_id: None,
            timestamp_ms: 1000,
            source_format: RunFormat::default(),
            functions: vec![FnEntry {
                name: "walk".into(),
                calls: 3,
                total_ms: Some(12.0),
                self_ms: 10.0,
                cpu_self_ms: None,
                alloc_count: 100,
                alloc_bytes: 8192,
                ..Default::default()
            }],
        };
        let b = Run {
            run_id: None,
            timestamp_ms: 2000,
            source_format: RunFormat::default(),
            functions: vec![FnEntry {
                name: "walk".into(),
                calls: 3,
                total_ms: Some(9.0),
                self_ms: 8.0,
                cpu_self_ms: None,
                alloc_count: 50,
                alloc_bytes: 4096,
                ..Default::default()
            }],
        };
        let diff = diff_runs(&a, &b, "Before", "After", true, None);
        assert!(diff.contains("Allocs"), "should have Allocs column header");
        assert!(
            diff.contains("-50"),
            "should show alloc count delta: {diff}"
        );
    }

    #[test]
    fn diff_alloc_count_does_not_wrap_above_i64_max() {
        let large_count: u64 = i64::MAX as u64 + 1_000;
        let a = Run {
            run_id: None,
            timestamp_ms: 1000,
            source_format: RunFormat::default(),
            functions: vec![FnEntry {
                name: "alloc_heavy".into(),
                calls: 1,
                total_ms: Some(1.0),
                self_ms: 1.0,
                cpu_self_ms: None,
                alloc_count: large_count,
                alloc_bytes: 0,
                ..Default::default()
            }],
        };
        let b = Run {
            run_id: None,
            timestamp_ms: 2000,
            source_format: RunFormat::default(),
            functions: vec![FnEntry {
                name: "alloc_heavy".into(),
                calls: 1,
                total_ms: Some(1.0),
                self_ms: 1.0,
                cpu_self_ms: None,
                alloc_count: 0,
                alloc_bytes: 0,
                ..Default::default()
            }],
        };
        let diff = diff_runs(&a, &b, "Before", "After", true, None);
        // Extract the A.Delta column value from the alloc_heavy row.
        // Saturating arithmetic prevents u64 wrapping to negative i64
        // (which would produce a large positive delta in the wrong direction).
        let line = diff.lines().find(|l| l.contains("alloc_heavy")).unwrap();
        let fields: Vec<&str> = line.split_whitespace().collect();
        // Last field is A.Delta (alloc delta).
        let delta_str = fields.last().unwrap();
        assert!(
            delta_str.starts_with('-'),
            "alloc delta should be negative (decrease from {large_count} to 0), got: {delta_str}"
        );
    }

    #[test]
    fn diff_shows_cpu_columns_when_present() {
        let a = Run {
            run_id: None,
            timestamp_ms: 1000,
            source_format: RunFormat::default(),
            functions: vec![FnEntry {
                name: "work".into(),
                calls: 1,
                total_ms: Some(10.0),
                self_ms: 10.0,
                cpu_self_ms: Some(8.0),
                ..Default::default()
            }],
        };
        let b = Run {
            run_id: None,
            timestamp_ms: 2000,
            source_format: RunFormat::default(),
            functions: vec![FnEntry {
                name: "work".into(),
                calls: 1,
                total_ms: Some(12.0),
                self_ms: 12.0,
                cpu_self_ms: Some(10.0),
                ..Default::default()
            }],
        };
        let diff = diff_runs(&a, &b, "Before", "After", true, None);
        assert!(
            diff.contains("CPU.Before"),
            "should have CPU.Before column. Got:\n{diff}"
        );
        assert!(
            diff.contains("CPU.After"),
            "should have CPU.After column. Got:\n{diff}"
        );
        assert!(
            diff.contains("8.00"),
            "should show before CPU. Got:\n{diff}"
        );
        assert!(
            diff.contains("10.00"),
            "should show after CPU. Got:\n{diff}"
        );
    }

    #[test]
    fn diff_mixed_cpu_one_with_one_without() {
        let a = Run {
            run_id: None,
            timestamp_ms: 1000,
            source_format: RunFormat::default(),
            functions: vec![FnEntry {
                name: "work".into(),
                calls: 1,
                total_ms: Some(10.0),
                self_ms: 10.0,
                cpu_self_ms: Some(8.0),
                ..Default::default()
            }],
        };
        let b = Run {
            run_id: None,
            timestamp_ms: 2000,
            source_format: RunFormat::default(),
            functions: vec![FnEntry {
                name: "work".into(),
                calls: 1,
                total_ms: Some(12.0),
                self_ms: 12.0,
                // No CPU data.
                ..Default::default()
            }],
        };
        // Should still render CPU columns (because A has CPU data).
        let diff = diff_runs(&a, &b, "Before", "After", true, None);
        assert!(
            diff.contains("CPU.Before"),
            "should show CPU columns when either run has CPU data. Got:\n{diff}"
        );
        assert!(
            diff.contains("8.00"),
            "should show A's CPU value. Got:\n{diff}"
        );
        // B's missing CPU renders as "-", not a misleading 0.00ms.
        // Extract the CPU.After column value from the data row.
        let data_line = diff.lines().find(|l| l.contains("work")).unwrap();
        assert!(
            data_line.ends_with('-'),
            "missing CPU should render as dash, not 0.00ms. Got:\n{data_line}"
        );
    }

    #[test]
    fn diff_neither_has_cpu_hides_cpu_columns() {
        let a = Run {
            run_id: None,
            timestamp_ms: 1000,
            source_format: RunFormat::default(),
            functions: vec![FnEntry {
                name: "work".into(),
                calls: 1,
                total_ms: Some(10.0),
                self_ms: 10.0,
                ..Default::default()
            }],
        };
        let b = Run {
            run_id: None,
            timestamp_ms: 2000,
            source_format: RunFormat::default(),
            functions: vec![FnEntry {
                name: "work".into(),
                calls: 1,
                total_ms: Some(12.0),
                self_ms: 12.0,
                ..Default::default()
            }],
        };
        let diff = diff_runs(&a, &b, "Before", "After", true, None);
        assert!(
            !diff.contains("CPU"),
            "should not show CPU columns when neither run has CPU data. Got:\n{diff}"
        );
    }

    #[test]
    fn diff_uses_custom_labels_in_headers() {
        let a = Run {
            run_id: None,
            timestamp_ms: 1000,
            source_format: RunFormat::default(),
            functions: vec![FnEntry {
                name: "work".into(),
                calls: 1,
                total_ms: Some(10.0),
                self_ms: 10.0,
                ..Default::default()
            }],
        };
        let b = Run {
            run_id: None,
            timestamp_ms: 2000,
            source_format: RunFormat::default(),
            functions: vec![FnEntry {
                name: "work".into(),
                calls: 1,
                total_ms: Some(12.0),
                self_ms: 12.0,
                ..Default::default()
            }],
        };
        let diff = diff_runs(&a, &b, "baseline", "optimized", true, None);
        assert!(
            diff.contains("baseline"),
            "should use label_a as column header. Got:\n{diff}"
        );
        assert!(
            diff.contains("optimized"),
            "should use label_b as column header. Got:\n{diff}"
        );
        assert!(
            !diff.contains("Before"),
            "should not contain hardcoded 'Before'. Got:\n{diff}"
        );
        assert!(
            !diff.contains("After"),
            "should not contain hardcoded 'After'. Got:\n{diff}"
        );
    }

    #[test]
    fn diff_custom_labels_in_cpu_headers() {
        let a = Run {
            run_id: None,
            timestamp_ms: 1000,
            source_format: RunFormat::default(),
            functions: vec![FnEntry {
                name: "work".into(),
                calls: 1,
                total_ms: Some(10.0),
                self_ms: 10.0,
                cpu_self_ms: Some(8.0),
                ..Default::default()
            }],
        };
        let b = Run {
            run_id: None,
            timestamp_ms: 2000,
            source_format: RunFormat::default(),
            functions: vec![FnEntry {
                name: "work".into(),
                calls: 1,
                total_ms: Some(12.0),
                self_ms: 12.0,
                cpu_self_ms: Some(10.0),
                ..Default::default()
            }],
        };
        let diff = diff_runs(&a, &b, "v1", "v2", true, None);
        assert!(
            diff.contains("CPU.v1"),
            "should use CPU.label_a as CPU column header. Got:\n{diff}"
        );
        assert!(
            diff.contains("CPU.v2"),
            "should use CPU.label_b as CPU column header. Got:\n{diff}"
        );
    }

    #[test]
    fn diff_truncates_long_labels() {
        let entry = || FnEntry {
            name: "work".into(),
            calls: 1,
            total_ms: Some(10.0),
            self_ms: 10.0,
            ..Default::default()
        };
        let a = Run {
            run_id: None,
            timestamp_ms: 1000,
            source_format: RunFormat::default(),
            functions: vec![entry()],
        };
        let b = Run {
            run_id: None,
            timestamp_ms: 2000,
            source_format: RunFormat::default(),
            functions: vec![entry()],
        };
        let long_label = "my-really-long-tag-name-that-goes-on";
        let diff = diff_runs(&a, &b, long_label, "short", true, None);
        // Should be truncated to 20 chars with ellipsis.
        assert!(
            diff.contains("my-really-long-tag-n\u{2026}"),
            "should truncate label > 20 chars with ellipsis. Got:\n{diff}"
        );
        assert!(
            !diff.contains(long_label),
            "should not contain the full long label. Got:\n{diff}"
        );
    }

    #[test]
    fn diff_label_column_width_expands_for_label() {
        let entry = || FnEntry {
            name: "work".into(),
            calls: 1,
            total_ms: Some(10.0),
            self_ms: 10.0,
            ..Default::default()
        };
        let a = Run {
            run_id: None,
            timestamp_ms: 1000,
            source_format: RunFormat::default(),
            functions: vec![entry()],
        };
        let b = Run {
            run_id: None,
            timestamp_ms: 2000,
            source_format: RunFormat::default(),
            functions: vec![entry()],
        };
        // "after-refactor" is 14 chars, wider than default 10.
        let diff = diff_runs(&a, &b, "before", "after-refactor", true, None);
        // The "after-refactor" header should appear untruncated.
        assert!(
            diff.contains("after-refactor"),
            "should expand column to fit label. Got:\n{diff}"
        );
    }

    #[test]
    fn ndjson_diff_does_not_produce_misleading_total_ms() {
        // When diffing two NDJSON runs, total_ms is None on both sides,
        // so it should not contaminate the diff output.
        let dir = TempDir::new().unwrap();
        // NDJSON format: header with names, single root measurement, trailer
        let ndjson_a = concat!(
            r#"{"type":"header","run_id":"diff_a","timestamp_ms":1000,"bias_ns":0,"names":{"0":"work"}}"#,
            "\n",
            r#"{"span_id":1,"parent_span_id":0,"name_id":0,"start_ns":0,"end_ns":5000000,"thread_id":1,"cpu_start_ns":0,"cpu_end_ns":0,"alloc_count":0,"alloc_bytes":0,"free_count":0,"free_bytes":0}"#,
            "\n",
            r#"{"type":"trailer","bias_ns":0,"names":{"0":"work"}}"#,
            "\n",
        );
        let ndjson_b = concat!(
            r#"{"type":"header","run_id":"diff_b","timestamp_ms":2000,"bias_ns":0,"names":{"0":"work"}}"#,
            "\n",
            r#"{"span_id":1,"parent_span_id":0,"name_id":0,"start_ns":0,"end_ns":8000000,"thread_id":1,"cpu_start_ns":0,"cpu_end_ns":0,"alloc_count":0,"alloc_bytes":0,"free_count":0,"free_bytes":0}"#,
            "\n",
            r#"{"type":"trailer","bias_ns":0,"names":{"0":"work"}}"#,
            "\n",
        );
        fs::write(dir.path().join("1000.ndjson"), ndjson_a).unwrap();
        fs::write(dir.path().join("2000.ndjson"), ndjson_b).unwrap();

        let (run_a, _) = load_ndjson(&dir.path().join("1000.ndjson"), false).unwrap();
        let (run_b, _) = load_ndjson(&dir.path().join("2000.ndjson"), false).unwrap();

        // Both runs should have total_ms == None
        assert!(run_a.functions[0].total_ms.is_none());
        assert!(run_b.functions[0].total_ms.is_none());

        // Diff should show self_ms delta (8ms - 5ms = +3ms), not total_ms.
        let diff = diff_runs(&run_a, &run_b, "before", "after", true, None);
        assert!(diff.contains("work"), "diff should contain function name");
        assert!(
            diff.contains("+3.00ms"),
            "diff should show +3.00ms self_ms delta"
        );
    }

    #[test]
    fn diff_runs_json_computes_delta() {
        let run_a = Run {
            run_id: None,
            timestamp_ms: 1000,
            source_format: RunFormat::default(),
            functions: vec![FnEntry {
                name: "work".into(),
                calls: 10,
                self_ms: 20.0,
                ..Default::default()
            }],
        };
        let run_b = Run {
            run_id: None,
            timestamp_ms: 2000,
            source_format: RunFormat::default(),
            functions: vec![FnEntry {
                name: "work".into(),
                calls: 12,
                self_ms: 25.0,
                ..Default::default()
            }],
        };
        let json = diff_runs_json(&run_a, &run_b, true, None);
        let entries: Vec<JsonDiffEntry> = serde_json::from_str(&json).unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].name, "work");
        assert!((entries[0].self_ms_a - 20.0).abs() < f64::EPSILON);
        assert!((entries[0].self_ms_b - 25.0).abs() < f64::EPSILON);
        assert!((entries[0].delta_ms - 5.0).abs() < f64::EPSILON);
        assert!((entries[0].delta_pct.unwrap() - 25.0).abs() < f64::EPSILON);
        assert_eq!(entries[0].calls_a, 10);
        assert_eq!(entries[0].calls_b, 12);
    }

    #[test]
    fn diff_runs_json_new_function_has_null_pct() {
        let run_a = Run {
            run_id: None,
            timestamp_ms: 1000,
            source_format: RunFormat::default(),
            functions: vec![],
        };
        let run_b = Run {
            run_id: None,
            timestamp_ms: 2000,
            source_format: RunFormat::default(),
            functions: vec![FnEntry {
                name: "new_fn".into(),
                calls: 1,
                self_ms: 5.0,
                ..Default::default()
            }],
        };
        let json = diff_runs_json(&run_a, &run_b, true, None);
        // Verify delta_pct is present as null (not omitted) via Value parse.
        let raw: Vec<serde_json::Value> = serde_json::from_str(&json).unwrap();
        assert!(
            raw[0].get("delta_pct").unwrap().is_null(),
            "delta_pct should serialize as null, not be omitted. Got:\n{json}"
        );
        let entries: Vec<JsonDiffEntry> = serde_json::from_str(&json).unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].name, "new_fn");
        assert!((entries[0].self_ms_a).abs() < f64::EPSILON);
        assert!(entries[0].delta_pct.is_none());
    }

    #[test]
    fn diff_runs_json_zero_zero_has_zero_pct() {
        let run_a = Run {
            run_id: None,
            timestamp_ms: 1000,
            source_format: RunFormat::default(),
            functions: vec![FnEntry {
                name: "idle".into(),
                calls: 5,
                self_ms: 0.0,
                ..Default::default()
            }],
        };
        let run_b = Run {
            run_id: None,
            timestamp_ms: 2000,
            source_format: RunFormat::default(),
            functions: vec![FnEntry {
                name: "idle".into(),
                calls: 5,
                self_ms: 0.0,
                ..Default::default()
            }],
        };
        let json = diff_runs_json(&run_a, &run_b, true, None);
        let entries: Vec<JsonDiffEntry> = serde_json::from_str(&json).unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].name, "idle");
        assert_eq!(
            entries[0].delta_pct,
            Some(0.0),
            "0/0 case should produce Some(0.0), not None"
        );
    }

    #[test]
    fn diff_tagged_ndjson_runs() {
        let dir = TempDir::new().unwrap();
        let runs_dir = dir.path().join("runs");
        let tags_dir = dir.path().join("tags");
        fs::create_dir_all(&runs_dir).unwrap();
        fs::create_dir_all(&tags_dir).unwrap();

        // Run A: "compute" called twice, self_ns sums to 5ms.
        let ndjson_a = concat!(
            r#"{"type":"header","run_id":"aaa_1000","timestamp_ms":1000,"bias_ns":0,"names":{"0":"compute"}}"#,
            "\n",
            r#"{"span_id":1,"parent_span_id":0,"name_id":0,"start_ns":0,"end_ns":2000000,"thread_id":1,"cpu_start_ns":0,"cpu_end_ns":0,"alloc_count":0,"alloc_bytes":0,"free_count":0,"free_bytes":0}"#,
            "\n",
            r#"{"span_id":2,"parent_span_id":0,"name_id":0,"start_ns":3000000,"end_ns":6000000,"thread_id":1,"cpu_start_ns":0,"cpu_end_ns":0,"alloc_count":0,"alloc_bytes":0,"free_count":0,"free_bytes":0}"#,
            "\n",
            r#"{"type":"trailer","bias_ns":0,"names":{"0":"compute"}}"#,
            "\n",
        );
        // Run B: "compute" called twice, self_ns sums to 8ms.
        let ndjson_b = concat!(
            r#"{"type":"header","run_id":"bbb_2000","timestamp_ms":2000,"bias_ns":0,"names":{"0":"compute"}}"#,
            "\n",
            r#"{"span_id":1,"parent_span_id":0,"name_id":0,"start_ns":0,"end_ns":4000000,"thread_id":1,"cpu_start_ns":0,"cpu_end_ns":0,"alloc_count":0,"alloc_bytes":0,"free_count":0,"free_bytes":0}"#,
            "\n",
            r#"{"span_id":2,"parent_span_id":0,"name_id":0,"start_ns":5000000,"end_ns":9000000,"thread_id":1,"cpu_start_ns":0,"cpu_end_ns":0,"alloc_count":0,"alloc_bytes":0,"free_count":0,"free_bytes":0}"#,
            "\n",
            r#"{"type":"trailer","bias_ns":0,"names":{"0":"compute"}}"#,
            "\n",
        );
        fs::write(runs_dir.join("1000.ndjson"), ndjson_a).unwrap();
        fs::write(runs_dir.join("2000.ndjson"), ndjson_b).unwrap();

        // Tag both runs.
        fs::write(tags_dir.join("before"), "aaa_1000").unwrap();
        fs::write(tags_dir.join("after"), "bbb_2000").unwrap();

        // Load via tag path -- same path as cmd_diff uses.
        let run_a = load_tagged_run(&tags_dir, &runs_dir, "before").unwrap();
        let run_b = load_tagged_run(&tags_dir, &runs_dir, "after").unwrap();

        // Verify NDJSON data was loaded (not empty/zero).
        let compute_a = run_a
            .functions
            .iter()
            .find(|f| f.name == "compute")
            .unwrap();
        assert_eq!(compute_a.calls, 2, "run A should have 2 calls from 2 spans");
        assert!(
            (compute_a.self_ms - 5.0).abs() < 0.01,
            "run A self_ms should be ~5.0ms (from NDJSON), got {}",
            compute_a.self_ms
        );

        let compute_b = run_b
            .functions
            .iter()
            .find(|f| f.name == "compute")
            .unwrap();
        assert_eq!(compute_b.calls, 2, "run B should have 2 calls from 2 spans");
        assert!(
            (compute_b.self_ms - 8.0).abs() < 0.01,
            "run B self_ms should be ~8.0ms (from NDJSON), got {}",
            compute_b.self_ms
        );

        // Diff output should show the NDJSON-derived values.
        let diff = diff_runs(&run_a, &run_b, "before", "after", true, None);
        assert!(
            diff.contains("compute"),
            "diff should contain function name: {diff}"
        );
        assert!(
            diff.contains("+3.00"),
            "diff should show +3.00ms delta (8.0 - 5.0): {diff}"
        );
    }

    #[test]
    fn diff_runs_json_includes_alloc_and_cpu_fields() {
        let run_a = Run {
            run_id: None,
            timestamp_ms: 1000,
            source_format: RunFormat::default(),
            functions: vec![FnEntry {
                name: "work".into(),
                calls: 5,
                total_ms: Some(20.0),
                self_ms: 15.0,
                cpu_self_ms: Some(12.0),
                alloc_count: 100,
                alloc_bytes: 8192,
                ..Default::default()
            }],
        };
        let run_b = Run {
            run_id: None,
            timestamp_ms: 2000,
            source_format: RunFormat::default(),
            functions: vec![FnEntry {
                name: "work".into(),
                calls: 7,
                total_ms: Some(25.0),
                self_ms: 18.0,
                cpu_self_ms: Some(14.0),
                alloc_count: 200,
                alloc_bytes: 16384,
                ..Default::default()
            }],
        };

        let json = diff_runs_json(&run_a, &run_b, true, None);
        let entries: Vec<JsonDiffEntry> = serde_json::from_str(&json).unwrap();
        assert_eq!(entries.len(), 1);

        let e = &entries[0];
        assert_eq!(e.alloc_count_a, 100);
        assert_eq!(e.alloc_count_b, 200);
        assert_eq!(e.alloc_bytes_a, 8192);
        assert_eq!(e.alloc_bytes_b, 16384);
        assert_eq!(e.cpu_self_ms_a, Some(12.0));
        assert_eq!(e.cpu_self_ms_b, Some(14.0));

        // Verify JSON keys are present via raw Value parse.
        let raw: Vec<serde_json::Value> = serde_json::from_str(&json).unwrap();
        let obj = &raw[0];
        assert!(obj.get("alloc_count_a").is_some(), "missing alloc_count_a");
        assert!(obj.get("alloc_count_b").is_some(), "missing alloc_count_b");
        assert!(obj.get("alloc_bytes_a").is_some(), "missing alloc_bytes_a");
        assert!(obj.get("alloc_bytes_b").is_some(), "missing alloc_bytes_b");
        assert!(obj.get("cpu_self_ms_a").is_some(), "missing cpu_self_ms_a");
        assert!(obj.get("cpu_self_ms_b").is_some(), "missing cpu_self_ms_b");
    }

    #[test]
    fn diff_hides_zero_call_entries_by_default() {
        let a = Run {
            run_id: None,
            timestamp_ms: 1000,
            source_format: RunFormat::default(),
            functions: vec![
                FnEntry {
                    name: "active".into(),
                    calls: 5,
                    total_ms: Some(10.0),
                    self_ms: 8.0,
                    ..Default::default()
                },
                FnEntry {
                    name: "unused".into(),
                    ..Default::default()
                },
            ],
        };
        let b = Run {
            run_id: None,
            timestamp_ms: 2000,
            source_format: RunFormat::default(),
            functions: vec![
                FnEntry {
                    name: "active".into(),
                    calls: 7,
                    total_ms: Some(12.0),
                    self_ms: 9.0,
                    ..Default::default()
                },
                FnEntry {
                    name: "unused".into(),
                    ..Default::default()
                },
            ],
        };
        let diff = diff_runs(&a, &b, "Before", "After", false, None);
        assert!(diff.contains("active"), "should show active function");
        assert!(
            !diff.contains("unused"),
            "should hide zero-call entries when show_all=false. Got:\n{diff}"
        );
    }

    #[test]
    fn diff_limit_truncates_output() {
        let a = Run {
            run_id: None,
            timestamp_ms: 1000,
            source_format: RunFormat::default(),
            functions: vec![
                FnEntry {
                    name: "fn_a".into(),
                    calls: 1,
                    total_ms: Some(10.0),
                    self_ms: 10.0,
                    ..Default::default()
                },
                FnEntry {
                    name: "fn_b".into(),
                    calls: 1,
                    total_ms: Some(5.0),
                    self_ms: 5.0,
                    ..Default::default()
                },
                FnEntry {
                    name: "fn_c".into(),
                    calls: 1,
                    total_ms: Some(2.0),
                    self_ms: 2.0,
                    ..Default::default()
                },
            ],
        };
        let b = Run {
            run_id: None,
            timestamp_ms: 2000,
            source_format: RunFormat::default(),
            functions: vec![
                FnEntry {
                    name: "fn_a".into(),
                    calls: 2,
                    total_ms: Some(20.0),
                    self_ms: 20.0,
                    ..Default::default()
                },
                FnEntry {
                    name: "fn_b".into(),
                    calls: 2,
                    total_ms: Some(8.0),
                    self_ms: 8.0,
                    ..Default::default()
                },
                FnEntry {
                    name: "fn_c".into(),
                    calls: 2,
                    total_ms: Some(3.0),
                    self_ms: 3.0,
                    ..Default::default()
                },
            ],
        };
        let diff = diff_runs(&a, &b, "Before", "After", true, Some(2));
        // Only top 2 by absolute delta should appear.
        assert!(
            diff.contains("1 function hidden"),
            "should show truncation footer. Got:\n{diff}"
        );
    }

    #[test]
    fn diff_json_limit_truncates() {
        let a = Run {
            run_id: None,
            timestamp_ms: 1000,
            source_format: RunFormat::default(),
            functions: vec![
                FnEntry {
                    name: "fn_a".into(),
                    calls: 1,
                    total_ms: Some(10.0),
                    self_ms: 10.0,
                    ..Default::default()
                },
                FnEntry {
                    name: "fn_b".into(),
                    calls: 1,
                    total_ms: Some(5.0),
                    self_ms: 5.0,
                    ..Default::default()
                },
                FnEntry {
                    name: "fn_c".into(),
                    calls: 1,
                    total_ms: Some(2.0),
                    self_ms: 2.0,
                    ..Default::default()
                },
            ],
        };
        let b = Run {
            run_id: None,
            timestamp_ms: 2000,
            source_format: RunFormat::default(),
            functions: vec![
                FnEntry {
                    name: "fn_a".into(),
                    calls: 2,
                    total_ms: Some(20.0),
                    self_ms: 20.0,
                    ..Default::default()
                },
                FnEntry {
                    name: "fn_b".into(),
                    calls: 2,
                    total_ms: Some(8.0),
                    self_ms: 8.0,
                    ..Default::default()
                },
                FnEntry {
                    name: "fn_c".into(),
                    calls: 2,
                    total_ms: Some(3.0),
                    self_ms: 3.0,
                    ..Default::default()
                },
            ],
        };
        let json = diff_runs_json(&a, &b, true, Some(2));
        let entries: Vec<JsonDiffEntry> = serde_json::from_str(&json).unwrap();
        assert_eq!(entries.len(), 2, "limit=2 should produce 2 diff entries");
    }

    #[test]
    fn diff_json_hides_zero_call() {
        let a = Run {
            run_id: None,
            timestamp_ms: 1000,
            source_format: RunFormat::default(),
            functions: vec![
                FnEntry {
                    name: "active".into(),
                    calls: 3,
                    total_ms: Some(5.0),
                    self_ms: 4.0,
                    ..Default::default()
                },
                FnEntry {
                    name: "unused".into(),
                    ..Default::default()
                },
            ],
        };
        let b = Run {
            run_id: None,
            timestamp_ms: 2000,
            source_format: RunFormat::default(),
            functions: vec![
                FnEntry {
                    name: "active".into(),
                    calls: 5,
                    total_ms: Some(7.0),
                    self_ms: 6.0,
                    ..Default::default()
                },
                FnEntry {
                    name: "unused".into(),
                    ..Default::default()
                },
            ],
        };
        let json = diff_runs_json(&a, &b, false, None);
        let entries: Vec<JsonDiffEntry> = serde_json::from_str(&json).unwrap();
        assert_eq!(entries.len(), 1, "should hide zero-call entries");
        assert_eq!(entries[0].name, "active");
    }

    #[test]
    fn diff_columns_aligned() {
        use crate::report::test_util::assert_aligned;

        fn run_with(entry: FnEntry) -> Run {
            Run {
                run_id: None,
                timestamp_ms: 1000,
                source_format: RunFormat::default(),
                functions: vec![entry],
            }
        }

        // DA1: base (no cpu, no alloc)
        let a = run_with(FnEntry {
            name: "work".into(),
            calls: 1,
            self_ms: 10.0,
            ..Default::default()
        });
        let b = run_with(FnEntry {
            name: "work".into(),
            calls: 1,
            self_ms: 8.0,
            ..Default::default()
        });
        assert_aligned(&diff_runs(&a, &b, "before", "after", false, None), "base");

        // DA2: cpu only
        let a = run_with(FnEntry {
            name: "work".into(),
            calls: 1,
            self_ms: 10.0,
            cpu_self_ms: Some(9.0),
            ..Default::default()
        });
        let b = run_with(FnEntry {
            name: "work".into(),
            calls: 1,
            self_ms: 8.0,
            cpu_self_ms: Some(7.0),
            ..Default::default()
        });
        assert_aligned(&diff_runs(&a, &b, "before", "after", false, None), "cpu");

        // DA3: alloc only
        let a = run_with(FnEntry {
            name: "work".into(),
            calls: 1,
            self_ms: 10.0,
            alloc_count: 100,
            alloc_bytes: 8192,
            ..Default::default()
        });
        let b = run_with(FnEntry {
            name: "work".into(),
            calls: 1,
            self_ms: 8.0,
            alloc_count: 50,
            alloc_bytes: 4096,
            ..Default::default()
        });
        assert_aligned(&diff_runs(&a, &b, "before", "after", false, None), "alloc");

        // DA4: cpu + alloc
        let a = run_with(FnEntry {
            name: "work".into(),
            calls: 1,
            self_ms: 10.0,
            cpu_self_ms: Some(9.0),
            alloc_count: 100,
            alloc_bytes: 8192,
            ..Default::default()
        });
        let b = run_with(FnEntry {
            name: "work".into(),
            calls: 1,
            self_ms: 8.0,
            cpu_self_ms: Some(7.0),
            alloc_count: 50,
            alloc_bytes: 4096,
            ..Default::default()
        });
        assert_aligned(
            &diff_runs(&a, &b, "before", "after", false, None),
            "cpu+alloc",
        );
    }
}