hopper-cli 0.3.0

Command-line tooling for Hopper account inspection, schema export, and migration planning
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
//! `hopper profile` subcommand tree.
//!
//! Two shipping subcommands:
//!
//! - `profile bench`. Runs the primitive-benchmark lab against a live
//!   cluster and emits JSON/CSV regression artifacts. Existing code.
//! - `profile elf`. Parses a compiled SBF ELF, resolves DWARF function
//!   names, and emits flamegraph-compatible folded-stack output plus a
//!   human-readable "top N functions by static size" table. Matches
//!   Quasar's `quasar profile` command ergonomically. With `--inlines`
//!   it additionally walks DWARF `DW_TAG_inlined_subroutine` trees (see
//!   [`crate::cmd::profile_dwarf`]) and attributes every `.text`
//!   instruction's bytes to its deepest inline frame - the view that makes
//!   `#[inline(always)]`-heavy programs actionable, where the symbol table
//!   alone shows one giant entrypoint.
//!
//! The flamegraph output is the standard folded-stack format the
//! Brendan Gregg `FlameGraph.pl` and `inferno-flamegraph` consume:
//! `<stack_frames>;<semicolon_separated> <value>`.

use std::collections::BTreeMap;
use std::fs;
use std::path::Path;
use std::process;

use crate::bench;

pub fn cmd_profile(args: &[String]) {
    if args.iter().any(|arg| arg == "--help" || arg == "-h") {
        print_profile_usage();
        return;
    }

    // Pull `-w` / `--watch` out of the arg list before sub-dispatch so
    // the inner runners never see it. The watcher then wraps the
    // sub-command's normal entry point and re-fires on source changes.
    let mut filtered: Vec<String> = args.to_vec();
    let watch_mode = crate::cmd::watch::extract_watch_flag(&mut filtered);

    if filtered.is_empty() || filtered.first().map(String::as_str) == Some("bench") {
        let bench_args: Vec<String> = if filtered.first().map(String::as_str) == Some("bench") {
            filtered[1..].to_vec()
        } else {
            filtered.clone()
        };

        let run_once = move || {
            if let Err(err) = bench::run_primitive_bench(&bench_args) {
                eprintln!("hopper profile bench failed: {err}");
            }
        };
        if watch_mode {
            run_under_watch(run_once);
        } else {
            run_once();
        }
        return;
    }

    if filtered[0] == "elf" {
        let elf_args: Vec<String> = filtered[1..].to_vec();
        let run_once = move || {
            if let Err(err) = cmd_profile_elf(&elf_args) {
                eprintln!("hopper profile elf failed: {err}");
            }
        };
        if watch_mode {
            run_under_watch(run_once);
        } else {
            run_once();
        }
        return;
    }

    eprintln!("Unknown profile subcommand: {}", filtered[0]);
    print_profile_usage();
    process::exit(1);
}

fn run_under_watch<F>(run_once: F)
where
    F: FnMut(),
{
    let cwd = match crate::workspace::current_dir() {
        Ok(c) => c,
        Err(err) => {
            eprintln!("{err}");
            process::exit(1);
        }
    };
    let project_root = match crate::workspace::find_project_root(&cwd) {
        Ok(r) => r,
        Err(_) => cwd.clone(),
    };
    crate::cmd::watch::watch(&project_root, run_once);
}

fn print_profile_usage() {
    eprintln!("Usage: hopper profile <subcommand> [options]");
    eprintln!();
    eprintln!("Subcommands:");
    eprintln!("  bench                         Primitive benchmark lab with JSON/CSV artifacts");
    eprintln!("  elf <path/to/program.so>      Static SBF ELF analysis: symbol sizes, DWARF");
    eprintln!("                                names, flamegraph-compatible folded output");
    eprintln!();
    eprintln!("Global options:");
    eprintln!("  -w, --watch                   Re-run on source change (Ctrl-C to exit)");
    eprintln!();
    eprintln!("`profile bench` options:");
    eprintln!("  --bench-root <dir>           hopper-bench checkout (auto-detects sibling repo)");
    eprintln!(
        "  --rpc <url>                   RPC endpoint (default: SOLANA_RPC_URL or localhost)"
    );
    eprintln!(
        "  --keypair <path>             Fee payer keypair (default: ~/.config/solana/id.json)"
    );
    eprintln!("  --out-dir <dir>              Output directory for JSON/CSV artifacts");
    eprintln!("  --program-id <pubkey>        Reuse an existing deployed hopper-bench program");
    eprintln!("  --no-build                   Reuse the current hopper-bench .so");
    eprintln!("  --no-deploy                  Skip deploy (requires --program-id)");
    eprintln!("  --fail-on-regression <pct>   Override tolerated regression percentage");
    eprintln!();
    eprintln!("`profile elf` options:");
    eprintln!("  --top <N>                    Print the top N symbols by size (default 20)");
    eprintln!(
        "  --folded <out.txt>           Write Brendan-Gregg folded-stack output for flamegraph"
    );
    eprintln!("  --html <out.html>            Write self-contained interactive HTML flamegraph");
    eprintln!(
        "                               (hover for tooltips, click to highlight, search box)"
    );
    eprintln!(
        "  --baseline <folded.txt>      Compare symbol sizes against a saved baseline folded file"
    );
    eprintln!("  --sections                   Print ELF section size summary");
    eprintln!("  --fail-on-growth <bytes>     With --baseline: exit 2 when .text grew by more");
    eprintln!("                               than this many bytes AND more than");
    eprintln!("                               --fail-on-growth-pct (defaults 512 bytes, 10%)");
    eprintln!("  --fail-on-growth-pct <pct>   Relative half of the growth gate");
    eprintln!("  --inlines                    DWARF inline-frame attribution: rank .text bytes by");
    eprintln!("                               deepest inline frame (needs an unstripped .so built");
    eprintln!(
        "                               with debug info); folded/HTML output switches to full"
    );
    eprintln!("                               inline stacks");
    eprintln!("  --open                       Open the HTML flamegraph in the default browser");
    eprintln!("  --no-demangle                Leave mangled symbol names intact");
}

struct ElfArgs<'a> {
    path: &'a str,
    top: usize,
    folded_out: Option<&'a str>,
    html_out: Option<&'a str>,
    baseline: Option<&'a str>,
    open_html: bool,
    demangle: bool,
    sections: bool,
    inlines: bool,
    /// Growth gate against `--baseline`: fail (exit 2) only when the total
    /// `.text` growth exceeds BOTH the absolute byte floor and the relative
    /// percentage, so a 12% jump on a 40-byte helper and a 30-byte jump on a
    /// large program are both ignored while a real regression is not.
    growth_gate: Option<GrowthGate>,
}

/// Dual threshold for the `--baseline` growth gate.
#[derive(Clone, Copy, Debug, PartialEq)]
struct GrowthGate {
    /// Absolute growth in bytes that must be exceeded.
    bytes: u64,
    /// Relative growth in percent of the baseline that must be exceeded.
    pct: f64,
}

impl GrowthGate {
    /// Defaults when only one of the two flags is given.
    const DEFAULT_BYTES: u64 = 512;
    const DEFAULT_PCT: f64 = 10.0;

    /// Whether growing from `baseline` to `current` bytes trips the gate.
    fn trips(&self, baseline: u64, current: u64) -> bool {
        let delta = current.saturating_sub(baseline);
        if delta == 0 {
            return false;
        }
        let pct = if baseline == 0 {
            f64::INFINITY
        } else {
            delta as f64 * 100.0 / baseline as f64
        };
        delta > self.bytes && pct > self.pct
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct SectionSummary {
    name: String,
    kind: String,
    address: u64,
    size: u64,
    executable: bool,
}

fn parse_elf_args<'a>(args: &'a [String]) -> Result<ElfArgs<'a>, String> {
    if args.is_empty() {
        return Err("missing path to ELF; usage: hopper profile elf <program.so>".into());
    }
    let mut out = ElfArgs {
        path: &args[0],
        top: 20,
        folded_out: None,
        html_out: None,
        baseline: None,
        open_html: false,
        demangle: true,
        sections: false,
        inlines: false,
        growth_gate: None,
    };
    let mut i = 1;
    while i < args.len() {
        match args[i].as_str() {
            "--top" => {
                i += 1;
                out.top = args
                    .get(i)
                    .ok_or("`--top` requires a value")?
                    .parse()
                    .map_err(|e| format!("`--top` must be a usize: {e}"))?;
            }
            "--folded" => {
                i += 1;
                out.folded_out = Some(args.get(i).ok_or("`--folded` requires a path")?.as_str());
            }
            "--html" => {
                i += 1;
                out.html_out = Some(args.get(i).ok_or("`--html` requires a path")?.as_str());
            }
            "--baseline" => {
                i += 1;
                out.baseline = Some(args.get(i).ok_or("`--baseline` requires a path")?.as_str());
            }
            "--fail-on-growth" => {
                i += 1;
                let bytes: u64 = args
                    .get(i)
                    .ok_or("`--fail-on-growth` requires a byte count")?
                    .parse()
                    .map_err(|e| format!("`--fail-on-growth` must be a u64: {e}"))?;
                let gate = out.growth_gate.get_or_insert(GrowthGate {
                    bytes,
                    pct: GrowthGate::DEFAULT_PCT,
                });
                gate.bytes = bytes;
            }
            "--fail-on-growth-pct" => {
                i += 1;
                let pct: f64 = args
                    .get(i)
                    .ok_or("`--fail-on-growth-pct` requires a percentage")?
                    .parse()
                    .map_err(|e| format!("`--fail-on-growth-pct` must be a number: {e}"))?;
                if !pct.is_finite() || pct < 0.0 {
                    return Err("`--fail-on-growth-pct` must be a non-negative number".into());
                }
                let gate = out.growth_gate.get_or_insert(GrowthGate {
                    bytes: GrowthGate::DEFAULT_BYTES,
                    pct,
                });
                gate.pct = pct;
            }
            "--sections" => out.sections = true,
            "--inlines" => out.inlines = true,
            "--open" => out.open_html = true,
            "--no-demangle" => out.demangle = false,
            other => return Err(format!("unknown elf flag: {other}")),
        }
        i += 1;
    }
    if out.open_html && out.html_out.is_none() {
        return Err("`--open` requires `--html <path>`".into());
    }
    if out.growth_gate.is_some() && out.baseline.is_none() {
        return Err(
            "`--fail-on-growth` / `--fail-on-growth-pct` require `--baseline <folded.txt>`".into(),
        );
    }
    Ok(out)
}

fn cmd_profile_elf(args: &[String]) -> Result<(), String> {
    let opts = parse_elf_args(args)?;
    let bytes = fs::read(opts.path).map_err(|e| format!("could not read `{}`: {e}", opts.path))?;

    let (symbols, byte_total) = parse_symbols(&bytes, opts.demangle)?;
    let sections = parse_section_summary(&bytes)?;

    // Optional baseline. Loaded from a previously-saved folded-stack
    // file (the same format `--folded` writes). When present, every
    // symbol gets a `delta` column relative to the baseline. Missing
    // symbols on the baseline side count as `+current`; missing on
    // the current side count as `-baseline`.
    let baseline_map: Option<BTreeMap<String, u64>> = match opts.baseline {
        Some(path) => Some(load_baseline_folded(path)?),
        None => None,
    };

    // Rank and print top-N by size.
    let mut ranked: Vec<(&str, u64)> = symbols.iter().map(|(k, v)| (k.as_str(), *v)).collect();
    ranked.sort_by_key(|&(_, size)| ::core::cmp::Reverse(size));

    println!("hopper profile elf  -  {}", opts.path);
    println!("total code in .text: {} bytes", byte_total);
    println!(
        "estimated SBF instructions: {}",
        estimate_sbf_instructions(byte_total)
    );
    println!(
        "static CU heuristic: {}",
        estimate_static_cu_total(&symbols)
    );
    println!("distinct symbols:    {}", ranked.len());
    if let Some(ref base) = baseline_map {
        let base_total: u64 = base.values().sum();
        let delta = byte_total as i64 - base_total as i64;
        let sign = if delta >= 0 { "+" } else { "" };
        println!(
            "baseline {} bytes ({} symbols) - total delta {sign}{} bytes",
            base_total,
            base.len(),
            delta,
        );
    }
    println!();
    if opts.sections {
        print_section_summary(&sections);
        println!();
    }
    if baseline_map.is_some() {
        println!("top {} symbols by static size (Δ vs. baseline):", opts.top);
        println!(
            "{:>10}  {:>6}  {:>10}  {:>8}  {:>10}  symbol",
            "bytes", "pct", "delta", "sbf-ins", "cu-ish"
        );
    } else {
        println!("top {} symbols by static size:", opts.top);
        println!(
            "{:>10}  {:>6}  {:>8}  {:>10}  symbol",
            "bytes", "pct", "sbf-ins", "cu-ish"
        );
    }
    let total = byte_total.max(1);
    for (name, sz) in ranked.iter().take(opts.top) {
        let pct = (*sz as f64 / total as f64) * 100.0;
        let sbf_ins = estimate_sbf_instructions(*sz);
        let cu = estimate_static_cu(name, *sz);
        match baseline_map.as_ref() {
            Some(base) => {
                let prev = base.get(*name).copied().unwrap_or(0);
                let delta = *sz as i64 - prev as i64;
                let sign = if delta > 0 {
                    "+"
                } else if delta < 0 {
                    ""
                } else {
                    " "
                };
                println!(
                    "{:>10}  {:>5.2}%  {:>9}{}  {:>8}  {:>10}  {}",
                    sz, pct, sign, delta, sbf_ins, cu, name
                );
            }
            None => {
                println!(
                    "{:>10}  {:>5.2}%  {:>8}  {:>10}  {}",
                    sz, pct, sbf_ins, cu, name
                );
            }
        }
    }

    // DWARF inline-frame attribution. Behind `--inlines` so the default
    // output above stays byte-identical; when active it also switches the
    // folded/HTML emitters below from flat symbols to full inline stacks.
    let inline_attr: Option<crate::cmd::profile_dwarf::InlineAttribution> = if opts.inlines {
        println!();
        Some(run_inline_attribution(&bytes, &opts)?)
    } else {
        None
    };

    if let Some(out_path) = opts.folded_out {
        let folded = match inline_attr.as_ref() {
            Some(attr) => render_folded_stacks(&attr.stacks),
            None => render_folded(&ranked),
        };
        fs::write(out_path, folded).map_err(|e| format!("could not write `{}`: {e}", out_path))?;
        println!();
        println!("wrote folded-stack flamegraph input to {}", out_path);
        println!("pipe it to a flamegraph renderer:");
        println!("  cat {} | inferno-flamegraph > profile.svg", out_path);
    }

    if let Some(out_path) = opts.html_out {
        let html = match inline_attr.as_ref() {
            Some(attr) => {
                let ranked_stacks: Vec<(&str, u64)> = attr
                    .stacks
                    .iter()
                    .map(|(stack, bytes)| (stack.as_str(), *bytes))
                    .collect();
                render_html_flamegraph(
                    opts.path,
                    &ranked_stacks,
                    attr.text_bytes,
                    baseline_map.as_ref(),
                )
            }
            None => render_html_flamegraph(opts.path, &ranked, byte_total, baseline_map.as_ref()),
        };
        fs::write(out_path, html).map_err(|e| format!("could not write `{}`: {e}", out_path))?;
        println!();
        println!("wrote interactive HTML flamegraph to {}", out_path);
        if opts.open_html {
            if let Err(err) = open_browser(out_path) {
                eprintln!("warning: could not open browser automatically: {err}");
                eprintln!("open it by hand: {out_path}");
            }
        } else {
            println!("open it in your browser to explore (hover, click, search).");
        }
    }

    if let (Some(gate), Some(base)) = (opts.growth_gate, baseline_map.as_ref()) {
        let base_total: u64 = base.values().sum();
        println!();
        if gate.trips(base_total, byte_total) {
            let mut grown: Vec<(&str, u64, u64)> = symbols
                .iter()
                .map(|(name, size)| (name.as_str(), base.get(name).copied().unwrap_or(0), *size))
                .filter(|(_, prev, size)| size > prev)
                .collect();
            grown.sort_by_key(|(_, prev, size)| ::core::cmp::Reverse(size - prev));
            println!(
                "growth gate: FAIL, .text grew {} bytes ({:.2}%), above both {} bytes and {}%",
                byte_total - base_total,
                (byte_total - base_total) as f64 * 100.0 / base_total.max(1) as f64,
                gate.bytes,
                gate.pct
            );
            for (name, prev, size) in grown.iter().take(10) {
                println!(
                    "  +{:>8}  {:>8} -> {:>8}  {}",
                    size - prev,
                    prev,
                    size,
                    name
                );
            }
            std::process::exit(2);
        }
        println!(
            "growth gate: PASS (limit: more than {} bytes and more than {}% of {} baseline bytes)",
            gate.bytes, gate.pct, base_total
        );
    }
    Ok(())
}

/// Run DWARF inline-frame attribution and print the `--inlines` section:
/// coverage header plus the ranked leaf-frame fix list. Returns the
/// attribution so the folded/HTML emitters can reuse the full stacks.
///
/// Honesty contract: when the ELF has no DWARF (release builds default to
/// `debug = 0`; `target/deploy/*.so` is stripped) we print exactly what is
/// missing and how to get it, then attribute at symbol granularity -
/// inline frames are never fabricated.
fn run_inline_attribution(
    bytes: &[u8],
    opts: &ElfArgs,
) -> Result<crate::cmd::profile_dwarf::InlineAttribution, String> {
    use crate::cmd::profile_dwarf as pd;

    let segments = pd::text_segments(bytes)?;
    let symbols = pd::parse_symbol_ranges(bytes, opts.demangle)?;
    let index = match pd::load_inline_index(bytes, opts.demangle) {
        Ok(pd::DwarfLoad::Index(ix)) => {
            if ix.inline_range_count() == 0 {
                println!("{}", pd::no_inline_ranges_note());
                println!();
                None
            } else {
                Some(ix)
            }
        }
        Ok(pd::DwarfLoad::Missing) => {
            println!("{}", pd::missing_dwarf_note(opts.path));
            println!();
            None
        }
        Err(err) => {
            println!("--inlines: could not read DWARF ({err}).");
            println!("falling back to symbol-granularity attribution; nothing is fabricated.");
            println!();
            None
        }
    };

    let attr = pd::attribute_text(&segments, index.as_ref(), &symbols);
    match index.as_ref() {
        Some(ix) => {
            // Honesty guard, learned the hard way: platform-tools' `-g`
            // measurably CHANGES sBPF codegen (a debug=2 rebuild of the
            // same crate shifted deploy .text by +152 bytes), so a leaf
            // that is fat here can already be optimized away in the
            // debug=0 artifact you deploy. Case in point: this table
            // attributed 880 B to `From<ProgramError> for u64`'s 25-arm
            // match, yet release .text was bit-identical with the match
            // deleted, LLVM had already collapsed it without `-g`.
            println!(
                "note: attribution reflects THIS debuginfo build. `-g` can change sBPF codegen,"
            );
            println!(
                "      so verify a candidate on your debug=0 deploy artifact (e.g. rebuild with"
            );
            println!("      the change and compare `.text` bytes) before crediting a saving.");
            println!();
            println!(
                "inline-frame attribution (DWARF: {} unit{}, {} inline PC range{}):",
                ix.unit_count(),
                if ix.unit_count() == 1 { "" } else { "s" },
                ix.inline_range_count(),
                if ix.inline_range_count() == 1 {
                    ""
                } else {
                    "s"
                },
            );
            let pct = attr.dwarf_bytes as f64 / attr.text_bytes.max(1) as f64 * 100.0;
            println!(
                "  DWARF-attributed bytes: {} / {} ({:.1}%)",
                attr.dwarf_bytes, attr.text_bytes, pct
            );
        }
        None => {
            println!("inline-frame attribution: symbol granularity (no DWARF inline data):");
        }
    }
    println!("  SBF instructions (LDDW-aware): {}", attr.instructions);
    println!();
    print!(
        "{}",
        pd::render_inline_table(&attr.leaf_rows, attr.text_bytes, opts.top)
    );
    Ok(attr)
}

/// Render pre-folded inline stacks (`root;mid;leaf` keys, already
/// frame-sanitized by [`crate::cmd::profile_dwarf::attribute_text`]) in the
/// same Brendan-Gregg format as [`render_folded`]. Kept separate so the
/// default path's per-symbol sanitization stays byte-identical.
fn render_folded_stacks(stacks: &[(String, u64)]) -> String {
    let mut s = String::new();
    for (stack, sz) in stacks {
        s.push_str(stack);
        s.push(' ');
        s.push_str(&sz.to_string());
        s.push('\n');
    }
    s
}

/// Parse .text-region function symbols out of the ELF and return a
/// `(symbol_name -> bytes)` map plus the total.
///
/// This is deliberately symbol-granularity: it is the fast default view
/// and the one comparable across stripped artifacts. DWARF-based inline
/// expansion lives behind `--inlines` (see [`crate::cmd::profile_dwarf`]).
/// Names are demangled via `rustc-demangle` when the flag is set.
fn parse_symbols(bytes: &[u8], demangle: bool) -> Result<(BTreeMap<String, u64>, u64), String> {
    use object::{Object, ObjectSymbol};

    let file = object::File::parse(bytes).map_err(|e| format!("not a valid ELF: {e}"))?;

    let mut out: BTreeMap<String, u64> = BTreeMap::new();
    let mut total: u64 = 0;
    for sym in file.symbols() {
        let size = sym.size();
        if size == 0 {
            continue;
        }
        if !matches!(sym.kind(), object::SymbolKind::Text) {
            continue;
        }
        let raw_name = sym.name().unwrap_or("?");
        let name = if demangle {
            rustc_demangle::demangle(raw_name).to_string()
        } else {
            raw_name.to_string()
        };
        *out.entry(name).or_insert(0) += size;
        total += size;
    }

    if out.is_empty() {
        return Err(format!(
            "ELF at `{}` has no .text symbols. Was it stripped? Try building with `cargo build-sbf --debug`.",
            "input"
        ));
    }
    Ok((out, total))
}

/// Parse a lightweight ELF section summary. This complements the symbol table:
/// symbols explain which functions dominate code size, while sections show
/// whether growth is coming from executable code, rodata, relocations, or
/// debug/name payloads.
fn parse_section_summary(bytes: &[u8]) -> Result<Vec<SectionSummary>, String> {
    use object::{Object, ObjectSection};

    let file = object::File::parse(bytes).map_err(|e| format!("not a valid ELF: {e}"))?;
    let mut sections = Vec::new();
    for section in file.sections() {
        let name = section.name().unwrap_or("?").to_string();
        let kind = format!("{:?}", section.kind());
        let executable = matches!(section.kind(), object::SectionKind::Text)
            || name == ".text"
            || name.starts_with(".text.");
        sections.push(SectionSummary {
            name,
            kind,
            address: section.address(),
            size: section.size(),
            executable,
        });
    }
    sections.sort_by(|a, b| b.size.cmp(&a.size).then_with(|| a.name.cmp(&b.name)));
    Ok(sections)
}

fn print_section_summary(sections: &[SectionSummary]) {
    println!("ELF sections by size:");
    println!(
        "{:>10}  {:>12}  {:>5}  {:<14}  section",
        "bytes", "address", "exec", "kind"
    );
    for section in sections.iter().filter(|section| section.size > 0).take(16) {
        println!(
            "{:>10}  0x{:010x}  {:>5}  {:<14}  {}",
            section.size,
            section.address,
            if section.executable { "yes" } else { "" },
            section.kind,
            section.name,
        );
    }
}

/// SBF/eBPF instructions are 8 bytes wide - except `lddw` (opcode 0x18),
/// which occupies two slots (16 bytes). This size-only estimate counts
/// every slot, so it is an *upper bound* that over-counts each `lddw` by
/// one. It survives for call sites that only know a byte size (symbol
/// sizes, baseline deltas); wherever the actual instruction bytes are
/// available, the LDDW-aware opcode walk
/// [`crate::cmd::profile_dwarf::count_sbf_instructions`] replaces it
/// (`--inlines` reports that exact count).
fn estimate_sbf_instructions(bytes: u64) -> u64 {
    bytes.saturating_add(7) / 8
}

/// Deliberately simple static CU heuristic. The base signal is instruction
/// count; symbol-name weights flag expensive families that static size alone
/// hides, such as CPI invoke paths and crypto/hash helpers. Treat this as a
/// prioritization score, not a replacement for on-chain measurements.
fn estimate_static_cu(symbol: &str, bytes: u64) -> u64 {
    let instructions = estimate_sbf_instructions(bytes);
    let lower = symbol.to_ascii_lowercase();
    let multiplier = if lower.contains("invoke") || lower.contains("cpi") {
        24
    } else if lower.contains("secp") || lower.contains("ed25519") {
        64
    } else if lower.contains("sha") || lower.contains("hash") || lower.contains("keccak") {
        12
    } else if lower.contains("memcpy") || lower.contains("memmove") || lower.contains("memcmp") {
        4
    } else {
        1
    };
    instructions.saturating_mul(multiplier)
}

fn estimate_static_cu_total(symbols: &BTreeMap<String, u64>) -> u64 {
    symbols
        .iter()
        .map(|(name, bytes)| estimate_static_cu(name, *bytes))
        .sum()
}

/// Render a Brendan-Gregg folded-stack flamegraph input from a
/// symbol-to-size table. Each symbol is one stack frame with its
/// name as the only identifier; nested call frames live in the
/// DWARF-enabled follow-up. Even without nesting, the flamegraph
/// still shows symbol sizes as proportional bars, which is the most
/// useful bird's-eye view of a compiled SBF program.
fn render_folded(ranked: &[(&str, u64)]) -> String {
    let mut s = String::new();
    for (name, sz) in ranked {
        // Sanitize the `;` separator inside demangled names (Rust's
        // generics use `<` `>` but not `;`; this is defensive).
        let safe: String = name.replace(';', ":");
        s.push_str(&safe);
        s.push(' ');
        s.push_str(&sz.to_string());
        s.push('\n');
    }
    s
}

/// Load a previously-saved Brendan-Gregg folded-stack file into a
/// `symbol -> bytes` map. The format is one symbol per line, with
/// the symbol name and the count separated by the last space (so
/// names containing spaces - Rust's `<T as Trait>::method` - still
/// parse correctly). Lines starting with `#` are treated as
/// comments and skipped, and blank lines are ignored. Returns a
/// helpful error if the file is malformed at any line so the user
/// can fix the input rather than getting silent zeros for every
/// symbol.
fn load_baseline_folded(path: &str) -> Result<BTreeMap<String, u64>, String> {
    let raw =
        fs::read_to_string(path).map_err(|e| format!("could not read baseline `{path}`: {e}"))?;
    let mut map: BTreeMap<String, u64> = BTreeMap::new();
    for (lineno, line) in raw.lines().enumerate() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let split_at = match line.rfind(' ') {
            Some(p) => p,
            None => {
                return Err(format!(
                    "baseline `{path}` line {}: missing space-separator before count",
                    lineno + 1
                ))
            }
        };
        let name = line[..split_at].trim();
        let count_str = line[split_at + 1..].trim();
        let count: u64 = count_str.parse().map_err(|e| {
            format!(
                "baseline `{path}` line {}: count `{count_str}` is not a u64: {e}",
                lineno + 1
            )
        })?;
        map.insert(name.to_string(), count);
    }
    Ok(map)
}

/// Render a self-contained interactive HTML flamegraph. No external
/// resources, no CDN, no JS framework - one file the user can open
/// straight in a browser.
///
/// The chart degrades gracefully when DWARF call-tree data isn't
/// available: each symbol becomes a single horizontal bar sized
/// proportionally to its byte count. Hover shows a tooltip with the
/// full demangled name, byte size, and percentage; click highlights
/// the bar and pins the tooltip; the search box filters by
/// substring. When a baseline is supplied, bars are colour-cued
/// (lime if shrunk, orange if grown, neutral if unchanged) and the
/// tooltip carries the delta.
fn render_html_flamegraph(
    program_path: &str,
    ranked: &[(&str, u64)],
    byte_total: u64,
    baseline: Option<&BTreeMap<String, u64>>,
) -> String {
    // Build the per-bar JSON inline. Symbol names can contain
    // characters that need escaping for both HTML and JSON - we
    // escape both via a small helper rather than depending on a
    // crate just for this.
    let mut data_json = String::from("[");
    for (i, (name, sz)) in ranked.iter().enumerate() {
        if i > 0 {
            data_json.push(',');
        }
        let pct = (*sz as f64 / byte_total.max(1) as f64) * 100.0;
        let delta = baseline
            .and_then(|b| b.get(*name).copied())
            .map(|prev| *sz as i64 - prev as i64);
        data_json.push_str(&format!(
            "{{\"n\":\"{}\",\"b\":{},\"p\":{:.4},\"d\":{},\"i\":{},\"c\":{}}}",
            json_escape(name),
            sz,
            pct,
            match delta {
                Some(d) => d.to_string(),
                None => "null".to_string(),
            },
            estimate_sbf_instructions(*sz),
            estimate_static_cu(name, *sz),
        ));
    }
    data_json.push(']');

    let title = html_escape(program_path);
    let total_str = format_human_bytes(byte_total);
    let baseline_note = if baseline.is_some() {
        " (Δ vs. baseline)"
    } else {
        ""
    };

    // Single template string: HTML, CSS, JS. Indentation kept inside
    // the heredoc so the rendered file is readable when a user opens
    // it in a text editor.
    format!(
        r##"<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>hopper profile elf - {title}</title>
<style>
  :root {{
    --bg: #0e1117;
    --fg: #d6deeb;
    --dim: #6b7388;
    --accent: #2dd4bf;
    --bar: #38bdf8;
    --bar-grown: #fb923c;
    --bar-shrunk: #84cc16;
    --hover: #a78bfa;
    --row-h: 22px;
  }}
  * {{ box-sizing: border-box; }}
  html, body {{ margin: 0; padding: 0; background: var(--bg); color: var(--fg); font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 13px; }}
  header {{ padding: 16px 24px; border-bottom: 1px solid #1f2937; display: flex; align-items: baseline; gap: 24px; flex-wrap: wrap; }}
  header h1 {{ font-size: 16px; margin: 0; color: var(--accent); font-weight: 600; }}
  header .meta {{ color: var(--dim); }}
  header .meta strong {{ color: var(--fg); font-weight: 600; }}
  #search {{ background: #1f2937; color: var(--fg); border: 1px solid #374151; border-radius: 4px; padding: 6px 10px; font: inherit; min-width: 220px; }}
  #search:focus {{ outline: 1px solid var(--accent); border-color: var(--accent); }}
  main {{ padding: 16px 24px 64px 24px; }}
  .bars {{ position: relative; }}
  .bar {{ position: relative; height: var(--row-h); margin-bottom: 1px; cursor: pointer; transition: opacity 0.1s; }}
  .bar.dimmed {{ opacity: 0.18; }}
  .bar .fill {{ position: absolute; left: 0; top: 0; bottom: 0; background: var(--bar); border-radius: 2px; transition: background-color 0.1s; }}
  .bar.grown .fill {{ background: var(--bar-grown); }}
  .bar.shrunk .fill {{ background: var(--bar-shrunk); }}
  .bar:hover .fill, .bar.selected .fill {{ background: var(--hover); }}
  .bar .label {{ position: relative; padding: 0 8px; line-height: var(--row-h); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; mix-blend-mode: difference; color: white; }}
  #tooltip {{ position: fixed; background: #111827; border: 1px solid #374151; border-radius: 4px; padding: 8px 12px; pointer-events: none; font-size: 12px; max-width: 480px; white-space: pre-line; box-shadow: 0 4px 12px rgba(0,0,0,0.5); z-index: 100; display: none; }}
  #tooltip strong {{ color: var(--accent); }}
  footer {{ position: fixed; bottom: 0; left: 0; right: 0; padding: 8px 24px; background: #0a0e14; border-top: 1px solid #1f2937; color: var(--dim); font-size: 11px; }}
  footer kbd {{ font-family: inherit; background: #1f2937; padding: 1px 6px; border-radius: 2px; color: var(--fg); }}
</style>
</head>
<body>
<header>
  <h1>hopper · profile · elf</h1>
  <div class="meta"><strong>{title}</strong></div>
  <div class="meta">total <strong>{total_str}</strong> across <strong id="symcount">…</strong> symbols{baseline_note}</div>
  <input id="search" type="search" placeholder="filter by symbol name…" autocomplete="off">
</header>
<main>
  <div class="bars" id="bars"></div>
</main>
<div id="tooltip" role="tooltip"></div>
<footer>
  <kbd>hover</kbd> for tooltip · <kbd>click</kbd> to pin a bar · <kbd>type</kbd> to filter by substring · <kbd>esc</kbd> to clear
</footer>
<script>
const SYMBOLS = {data_json};
const TOTAL = {byte_total};
document.getElementById("symcount").textContent = SYMBOLS.length;

const bars = document.getElementById("bars");
const tooltip = document.getElementById("tooltip");
const search = document.getElementById("search");

const maxBytes = SYMBOLS.length ? SYMBOLS[0].b : 1;

function fmt(n) {{
  if (Math.abs(n) < 1024) return n + " B";
  if (Math.abs(n) < 1024*1024) return (n/1024).toFixed(2) + " KiB";
  return (n/1024/1024).toFixed(2) + " MiB";
}}

let pinned = null;

SYMBOLS.forEach((sym, i) => {{
  const w = (sym.b / maxBytes) * 100;
  const bar = document.createElement("div");
  bar.className = "bar";
  if (sym.d !== null) {{
    if (sym.d > 0) bar.classList.add("grown");
    else if (sym.d < 0) bar.classList.add("shrunk");
  }}
  bar.dataset.index = i;
  bar.innerHTML = `<div class="fill" style="width:${{w}}%"></div><div class="label">${{escapeHtml(sym.n)}}</div>`;
  bars.appendChild(bar);

  bar.addEventListener("mousemove", (e) => {{
    if (pinned !== null) return;
    showTooltip(sym, e.clientX, e.clientY);
  }});
  bar.addEventListener("mouseleave", () => {{ if (pinned === null) hideTooltip(); }});
  bar.addEventListener("click", (e) => {{
    if (pinned === i) {{
      pinned = null;
      bar.classList.remove("selected");
      hideTooltip();
    }} else {{
      if (pinned !== null) document.querySelectorAll(".bar.selected").forEach(b => b.classList.remove("selected"));
      pinned = i;
      bar.classList.add("selected");
      showTooltip(sym, e.clientX, e.clientY);
    }}
    e.stopPropagation();
  }});
}});

document.addEventListener("click", () => {{
  if (pinned !== null) {{
    document.querySelectorAll(".bar.selected").forEach(b => b.classList.remove("selected"));
    pinned = null;
    hideTooltip();
  }}
}});

document.addEventListener("keydown", (e) => {{
  if (e.key === "Escape") {{
    search.value = "";
    applyFilter("");
    if (pinned !== null) {{
      document.querySelectorAll(".bar.selected").forEach(b => b.classList.remove("selected"));
      pinned = null;
      hideTooltip();
    }}
  }}
}});

search.addEventListener("input", (e) => applyFilter(e.target.value.toLowerCase()));

function applyFilter(needle) {{
  const all = bars.children;
  for (let i = 0; i < all.length; i++) {{
    const sym = SYMBOLS[i];
    const match = !needle || sym.n.toLowerCase().includes(needle);
    all[i].classList.toggle("dimmed", !match);
  }}
}}

function showTooltip(sym, x, y) {{
    let body = `<strong>${{escapeHtml(sym.n)}}</strong>\n${{fmt(sym.b)}} (${{sym.p.toFixed(2)}}%)\nSBF insns: ${{sym.i}}\nCU-ish score: ${{sym.c}}`;
  if (sym.d !== null) {{
    const sign = sym.d > 0 ? "+" : "";
    body += `\nΔ vs. baseline: ${{sign}}${{fmt(sym.d)}}`;
  }}
  tooltip.innerHTML = body;
  tooltip.style.display = "block";
  // Clamp the tooltip to the viewport so it never escapes off-screen
  // when a user hovers near an edge.
  const rect = tooltip.getBoundingClientRect();
  const px = Math.min(x + 12, window.innerWidth - rect.width - 12);
  const py = Math.min(y + 12, window.innerHeight - rect.height - 12);
  tooltip.style.left = px + "px";
  tooltip.style.top = py + "px";
}}
function hideTooltip() {{ tooltip.style.display = "none"; }}
function escapeHtml(s) {{ return s.replace(/[&<>"']/g, c => ({{"&":"&amp;","<":"&lt;",">":"&gt;","\"":"&quot;","'":"&#39;"}})[c]); }}
</script>
</body>
</html>
"##
    )
}

/// Format a byte count for human display. Used in the HTML header
/// so authors don't have to mentally divide by 1024.
fn format_human_bytes(b: u64) -> String {
    if b < 1024 {
        format!("{b} B")
    } else if b < 1024 * 1024 {
        format!("{:.2} KiB", b as f64 / 1024.0)
    } else {
        format!("{:.2} MiB", b as f64 / (1024.0 * 1024.0))
    }
}

/// Minimal HTML escaper - sufficient for the metadata strings we
/// embed (program path, symbol names). Avoids pulling in a templating
/// crate.
fn html_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&#39;"),
            other => out.push(other),
        }
    }
    out
}

/// Minimal JSON-string escaper for the inlined data array. Handles
/// only the subset of cases we can encounter from `rustc-demangle`'s
/// output: ASCII printable, plus quotes, backslashes, and control
/// chars (rare but possible). Callers don't pass arbitrary user
/// input.
fn json_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
            other => out.push(other),
        }
    }
    out
}

/// Open `path` in the user's default browser. Cross-platform
/// best-effort: macOS uses `open`, Linux uses `xdg-open`, Windows
/// uses `cmd /c start`. Returns the underlying error if the launch
/// fails so the caller can fall through to "open it by hand"
/// guidance.
fn open_browser(path: &str) -> Result<(), String> {
    use std::process::Command;
    #[cfg(target_os = "macos")]
    let mut cmd = {
        let mut c = Command::new("open");
        c.arg(path);
        c
    };
    #[cfg(target_os = "linux")]
    let mut cmd = {
        let mut c = Command::new("xdg-open");
        c.arg(path);
        c
    };
    #[cfg(target_os = "windows")]
    let mut cmd = {
        let mut c = Command::new("cmd");
        c.args(["/C", "start", "", path]);
        c
    };
    #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
    let mut cmd = {
        // Fall back to xdg-open on unrecognised platforms; if it
        // doesn't exist the spawn itself will error.
        let mut c = Command::new("xdg-open");
        c.arg(path);
        c
    };
    cmd.spawn()
        .map_err(|e| format!("failed to launch browser: {e}"))?;
    Ok(())
}

// Compile-time assertion that the module sees its imports. Rustc emits
// an unused-import warning if `Path` is never referenced; pin it here.
#[allow(dead_code)]
fn _ignore(_: &Path) {}

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

    #[test]
    fn json_escape_preserves_normal_names() {
        assert_eq!(json_escape("plain"), "plain");
    }

    #[test]
    fn json_escape_handles_quotes_and_backslashes() {
        assert_eq!(json_escape(r#"a"b\c"#), r#"a\"b\\c"#);
    }

    #[test]
    fn html_escape_handles_lt_gt_amp() {
        assert_eq!(
            html_escape(r#"<T as Trait>::"x" & y"#),
            "&lt;T as Trait&gt;::&quot;x&quot; &amp; y"
        );
    }

    #[test]
    fn baseline_folded_parses_names_with_spaces() {
        // Sandbox-friendly: write to a temp path and parse back.
        let tmp = std::env::temp_dir().join(format!("hopper-baseline-{}.txt", std::process::id(),));
        std::fs::write(&tmp, "<T as Trait>::method 1024\nplain 256\n").unwrap();
        let map = load_baseline_folded(tmp.to_str().unwrap()).expect("parse");
        assert_eq!(map.get("<T as Trait>::method"), Some(&1024));
        assert_eq!(map.get("plain"), Some(&256));
        let _ = std::fs::remove_file(&tmp);
    }

    #[test]
    fn baseline_folded_skips_comments_and_blanks() {
        let tmp = std::env::temp_dir().join(format!(
            "hopper-baseline-comments-{}.txt",
            std::process::id(),
        ));
        std::fs::write(
            &tmp,
            "# generated 2026-04-25\n\nfoo 100\n# comment\nbar 200\n",
        )
        .unwrap();
        let map = load_baseline_folded(tmp.to_str().unwrap()).expect("parse");
        assert_eq!(map.len(), 2);
        assert_eq!(map.get("foo"), Some(&100));
        assert_eq!(map.get("bar"), Some(&200));
        let _ = std::fs::remove_file(&tmp);
    }

    #[test]
    fn html_flamegraph_embeds_data_inline() {
        let ranked = vec![("foo", 100u64), ("bar", 50u64)];
        let html = render_html_flamegraph("test.so", &ranked, 150, None);
        // Self-contained: no `http://` or `https://` references.
        assert!(!html.contains("https://"), "html must be self-contained");
        // Names appear in the inlined JSON.
        assert!(html.contains("\"n\":\"foo\""));
        assert!(html.contains("\"n\":\"bar\""));
        assert!(html.contains("\"i\":13"));
        assert!(html.contains("CU-ish score"));
    }

    #[test]
    fn sbf_instruction_estimate_rounds_up_to_eight_byte_slots() {
        assert_eq!(estimate_sbf_instructions(0), 0);
        assert_eq!(estimate_sbf_instructions(1), 1);
        assert_eq!(estimate_sbf_instructions(8), 1);
        assert_eq!(estimate_sbf_instructions(9), 2);
    }

    #[test]
    fn static_cu_heuristic_weights_expensive_symbol_families() {
        let plain = estimate_static_cu("deposit", 80);
        let cpi = estimate_static_cu("hopper_runtime::cpi::invoke_signed", 80);
        let hash = estimate_static_cu("sha256_compress", 80);
        assert!(cpi > hash);
        assert!(hash > plain);
    }

    #[test]
    fn elf_args_default_leaves_inlines_off() {
        let args = vec!["program.so".to_string()];
        let opts = parse_elf_args(&args).expect("parse");
        assert!(!opts.inlines, "--inlines must be opt-in");
        assert!(opts.demangle);
    }

    #[test]
    fn elf_args_parse_inlines_alongside_other_flags() {
        let args: Vec<String> = ["program.so", "--inlines", "--top", "5", "--sections"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        let opts = parse_elf_args(&args).expect("parse");
        assert!(opts.inlines);
        assert!(opts.sections);
        assert_eq!(opts.top, 5);
    }

    #[test]
    fn folded_stacks_render_semicolon_separated_frames() {
        let stacks = vec![
            (
                "entrypoint;hopper_runtime::receipt::commit".to_string(),
                4096u64,
            ),
            ("entrypoint".to_string(), 1024u64),
        ];
        assert_eq!(
            render_folded_stacks(&stacks),
            "entrypoint;hopper_runtime::receipt::commit 4096\nentrypoint 1024\n"
        );
    }
}

#[cfg(test)]
mod growth_gate_tests {
    use super::{parse_elf_args, GrowthGate};

    #[test]
    fn gate_trips_only_when_both_thresholds_are_exceeded() {
        let gate = GrowthGate {
            bytes: 512,
            pct: 10.0,
        };
        // Large absolute, small relative: a 600-byte jump on 100 KiB is 0.6%.
        assert!(!gate.trips(100_000, 100_600));
        // Large relative, small absolute: 40 -> 60 bytes is 50% but 20 bytes.
        assert!(!gate.trips(40, 60));
        // Both exceeded.
        assert!(gate.trips(4_000, 4_600));
        // Exactly at the limits does not trip; strictly above does.
        assert!(!gate.trips(5_120, 5_632));
        assert!(gate.trips(5_120, 5_633));
        // Shrinking never trips, and an empty baseline counts as infinite.
        assert!(!gate.trips(4_000, 3_000));
        assert!(gate.trips(0, 513));
        assert!(!gate.trips(0, 512));
    }

    #[test]
    fn growth_flags_fill_the_missing_half_with_defaults_and_need_a_baseline() {
        let args: Vec<String> = ["p.so", "--baseline", "b.txt", "--fail-on-growth", "100"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        let opts = parse_elf_args(&args).unwrap();
        assert_eq!(
            opts.growth_gate,
            Some(GrowthGate {
                bytes: 100,
                pct: GrowthGate::DEFAULT_PCT
            })
        );

        let args: Vec<String> = ["p.so", "--baseline", "b.txt", "--fail-on-growth-pct", "2.5"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        let opts = parse_elf_args(&args).unwrap();
        assert_eq!(
            opts.growth_gate,
            Some(GrowthGate {
                bytes: GrowthGate::DEFAULT_BYTES,
                pct: 2.5
            })
        );

        let args: Vec<String> = ["p.so", "--fail-on-growth", "100"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        assert!(parse_elf_args(&args).is_err());
    }
}