tlparse 0.4.8

Parse TORCH_LOG logs produced by PyTorch torch.compile
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
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
use anyhow::{anyhow, bail};
use chrono::Datelike;
use fxhash::{FxHashMap, FxHashSet};
use md5::{Digest, Md5};
use std::ffi::{OsStr, OsString};

use html_escape::encode_text;
use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
use regex::Regex;
use serde_json::Value;
use std::cell::RefCell;
use std::fmt::Write as FmtWrite;
use std::fs::{self, File};
use std::io::{self, BufRead};
use std::path::{Path, PathBuf};
use std::time::Instant;
use tinytemplate::TinyTemplate;

use crate::parsers::default_parsers;
use crate::parsers::ParserOutput;
use crate::parsers::StructuredLogParser;
use crate::templates::*;
use crate::types::*;
pub mod parsers;
mod templates;
mod types;
pub mod vllm;

pub use types::{
    ArtifactFlags, CollectiveSchedule, CollectivesParityReport, Diagnostics, DivergenceFlags,
    DivergenceGroup, ExecOrderSummary, GraphAnalysis, GraphCollectivesParity, GraphRuntime,
    MultiRankContext, RankMetaData, RuntimeAnalysis, RuntimeRankDetail,
};

pub use execution_order::{
    analyze_execution_order, parse_graph_execution_order, ExecOrderIndexRow, ExecOrderIssue,
    ExecOrderReport,
};

#[derive(Debug)]
enum ParserResult {
    NoPayload,
    PayloadFilename(String),
}

pub struct ParseConfig {
    pub strict: bool,
    pub strict_compile_id: bool,
    pub custom_parsers: Vec<Box<dyn crate::parsers::StructuredLogParser>>,
    pub custom_header_html: String,
    pub verbose: bool,
    pub plain_text: bool,
    pub export: bool,
    pub inductor_provenance: bool,
}

impl Default for ParseConfig {
    fn default() -> Self {
        Self {
            strict: false,
            strict_compile_id: false,
            custom_parsers: Vec::default(),
            custom_header_html: String::default(),
            verbose: false,
            plain_text: false,
            export: false,
            inductor_provenance: false,
        }
    }
}

fn maybe_remove_convert_frame_suffixes(frames: &mut Vec<FrameSummary>) {
    let all_target_frames = [
        [
            ("torch/_dynamo/convert_frame.py", "catch_errors"),
            ("torch/_dynamo/convert_frame.py", "_convert_frame"),
            ("torch/_dynamo/convert_frame.py", "_convert_frame_assert"),
        ],
        [
            ("torch/_dynamo/convert_frame.py", "__call__"),
            ("torch/_dynamo/convert_frame.py", "__call__"),
            ("torch/_dynamo/convert_frame.py", "__call__"),
        ],
    ];

    let len = frames.len();
    for target_frames in all_target_frames {
        if len >= target_frames.len() {
            let suffix = &frames[len - target_frames.len()..];
            if suffix
                .iter()
                .zip(target_frames.iter())
                .all(|(frame, target)| {
                    simplify_filename(unintern_str(frame.filename).as_ref()) == target.0
                        && frame.name == target.1
                })
            {
                frames.truncate(len - target_frames.len());
            }
        }
    }
}

fn add_unique_suffix(raw_filename: PathBuf, output_count: i32) -> PathBuf {
    if let Some(stem) = raw_filename.file_stem() {
        let mut r = OsString::new();
        r.push(stem);
        r.push(OsStr::new("_"));
        r.push(output_count.to_string());
        if let Some(e) = raw_filename.extension() {
            r.push(OsStr::new("."));
            r.push(e);
        };
        raw_filename.with_file_name(r)
    } else {
        raw_filename
    }
}

fn add_file_output(
    filename: PathBuf,
    content: String,
    output: &mut ParseOutput,
    compile_directory: &mut Vec<OutputFile>,
    output_count: &mut i32,
    vllm_state: &vllm::VllmState,
) {
    let is_stack_traces = is_stack_traces_file(&filename);
    let maybe_content = if is_stack_traces {
        Some(content.clone())
    } else {
        None
    };
    output.push((filename.clone(), content));
    let filename_str = filename.to_string_lossy().to_string();

    let suffix = if filename_str.contains("cache_miss") {
        "".to_string()
    } else if filename_str.contains("cache_hit") {
        "".to_string()
    } else if filename_str.contains("cache_bypass") {
        "".to_string()
    } else {
        "".to_string()
    };

    // Track artifact for vLLM summary
    vllm_state.add_artifact(&filename, suffix.clone());

    let readable_url = if let Some(c) = maybe_content {
        Some(add_stack_traces_html(&filename, &c, output, output_count))
    } else {
        None
    };
    compile_directory.push(OutputFile {
        url: filename_str.clone(),
        name: filename_str,
        number: *output_count,
        suffix: suffix,
        readable_url,
    });
    *output_count += 1;
}

fn is_stack_traces_file(path: &PathBuf) -> bool {
    if let Some(name) = path.file_name().and_then(|s| s.to_str()) {
        name.starts_with("inductor_provenance_tracking_kernel_stack_traces")
            && name.ends_with(".json")
    } else {
        false
    }
}

fn add_stack_traces_html(
    json_path: &PathBuf,
    json_content: &str,
    output: &mut ParseOutput,
    output_count: &mut i32,
) -> String {
    let parsed: Value = match serde_json::from_str(json_content) {
        Ok(v) => v,
        Err(_) => return String::new(),
    };
    let mut html = String::from("<html><body>\n");
    if let Some(map) = parsed.as_object() {
        for (kernel, traces) in map {
            html.push_str(&format!("<h3>{}</h3>\n", encode_text(kernel)));
            if let Some(arr) = traces.as_array() {
                for t in arr {
                    if let Some(s) = t.as_str() {
                        // The JSON strings encode newlines as "\\n" sequences, so translate
                        // those into real line breaks for the HTML view.
                        let decoded = s.replace("\\n", "\n");
                        html.push_str("<pre>");
                        html.push_str(&encode_text(decoded.trim_end_matches('\n')));
                        html.push_str("</pre>\n");
                    }
                }
            }
        }
    }
    html.push_str("</body></html>\n");
    let mut html_path = json_path.clone();
    if let Some(stem) = json_path.file_stem().and_then(|s| s.to_str()) {
        html_path.set_file_name(format!("{stem}_readable.html"));
    } else {
        html_path.set_extension("html");
    }
    let html_path_str = html_path.to_string_lossy().to_string();
    output.push((html_path.clone(), html));
    *output_count += 1;
    html_path_str
}

fn run_parser<'t>(
    lineno: usize,
    parser: &Box<dyn StructuredLogParser + 't>,
    e: &Envelope,
    payload: &str,
    output_count: &mut i32,
    output: &mut ParseOutput,
    compile_directory: &mut Vec<OutputFile>,
    multi: &MultiProgress,
    stats: &mut Stats,
    vllm_state: &vllm::VllmState,
) -> ParserResult {
    let mut payload_filename = ParserResult::NoPayload;
    if let Some(md) = parser.get_metadata(&e) {
        let results = parser.parse(lineno, md, e.rank, &e.compile_id, &payload);
        match results {
            Ok(results) => {
                for parser_result in results {
                    match parser_result {
                        ParserOutput::File(raw_filename, out) => {
                            let filename = add_unique_suffix(raw_filename, *output_count);
                            add_file_output(
                                filename,
                                out,
                                output,
                                compile_directory,
                                output_count,
                                vllm_state,
                            );
                        }
                        ParserOutput::GlobalFile(filename, out) => {
                            add_file_output(
                                filename,
                                out,
                                output,
                                compile_directory,
                                output_count,
                                vllm_state,
                            );
                        }
                        ParserOutput::PayloadFile(raw_filename) => {
                            let filename = add_unique_suffix(raw_filename, *output_count);
                            payload_filename = ParserResult::PayloadFilename(
                                filename.to_string_lossy().to_string(),
                            );
                            add_file_output(
                                filename,
                                payload.to_string(),
                                output,
                                compile_directory,
                                output_count,
                                vllm_state,
                            );
                        }
                        ParserOutput::PayloadReformatFile(raw_filename, formatter) => {
                            let filename = add_unique_suffix(raw_filename, *output_count);
                            match formatter(payload) {
                                Ok(formatted_content) => {
                                    payload_filename = ParserResult::PayloadFilename(
                                        filename.to_string_lossy().to_string(),
                                    );
                                    add_file_output(
                                        filename,
                                        formatted_content,
                                        output,
                                        compile_directory,
                                        output_count,
                                        vllm_state,
                                    );
                                }
                                Err(err) => {
                                    multi.suspend(|| {
                                        eprintln!(
                                            "Failed to format payload for {}: {}",
                                            filename.to_string_lossy(),
                                            err
                                        )
                                    });
                                    stats.fail_parser += 1;
                                }
                            }
                        }
                        ParserOutput::Link(name, url) => {
                            compile_directory.push(OutputFile {
                                url: url,
                                name: name,
                                number: *output_count,
                                suffix: "".to_string(),
                                readable_url: None,
                            });
                            *output_count += 1;
                        }
                    }
                }
            }
            Err(err) => match parser.name() {
                "dynamo_guards" => {
                    multi.suspend(|| eprintln!("Failed to parse guards json: {}", err));
                    stats.fail_dynamo_guards_json += 1;
                }
                name => {
                    multi.suspend(|| eprintln!("Parser {name} failed: {err}"));
                    stats.fail_parser += 1;
                }
            },
        }
    }
    payload_filename
}

fn directory_to_json(
    directory: &FxIndexMap<Option<CompileId>, Vec<OutputFile>>,
) -> serde_json::Value {
    let mut json_map = serde_json::Map::new();

    for (compile_id, output_files) in directory {
        let key = compile_id
            .as_ref()
            .map_or_else(|| "unknown".to_string(), |cid| cid.to_string());

        let artifacts: Vec<serde_json::Value> = output_files
            .iter()
            .map(|file| {
                serde_json::json!({
                    "url": file.url,
                    // Strip away any leading directory names, that will just be in the url path anyway
                    "name": file.name.split('/').last().unwrap_or(&file.name),
                    "number": file.number,
                    "suffix": file.suffix,
                    "readable_url": file.readable_url,
                })
            })
            .collect();

        json_map.insert(key, serde_json::json!({"artifacts": artifacts}));
    }
    serde_json::Value::Object(json_map)
}

fn handle_guard(
    failure_type: &str,
    reason: &str,
    lineno: usize,
    e: &Envelope,
    payload: &str,
    output_count: &mut i32,
    output: &mut Vec<(PathBuf, String)>,
    compile_directory: &mut Vec<OutputFile>,
    multi: &MultiProgress,
    stats: &mut Stats,
    tt: &TinyTemplate,
    sym_expr_info_index: &RefCell<SymExprInfoIndex>,
    export_failures: &mut Vec<ExportFailure>,
    vllm_state: &vllm::VllmState,
) {
    let sym_expr_info_index_borrowed = sym_expr_info_index.borrow();
    let parser: Box<dyn StructuredLogParser> =
        Box::new(crate::parsers::PropagateRealTensorsParser {
            tt,
            sym_expr_info_index: &sym_expr_info_index_borrowed,
        });
    let _ = run_parser(
        lineno,
        &parser,
        e,
        payload,
        output_count,
        output,
        compile_directory,
        multi,
        stats,
        vllm_state,
    );

    let filename = format!(
        "symbolic_guard_information_{}.html",
        (*output_count - 1).to_string()
    );
    let compile_id_dir: PathBuf = e
        .compile_id
        .as_ref()
        .map_or(format!("unknown_{lineno}"), |cid| cid.as_directory_name())
        .into();
    let additional_info = format!(
        "Please click <a href='{}/{}'>here</a> for more information.",
        compile_id_dir.display(),
        filename,
    );

    export_failures.push(ExportFailure {
        failure_type: failure_type.to_string(),
        reason: reason.to_string(),
        additional_info,
    });
}

pub fn parse_path(path: &PathBuf, config: &ParseConfig) -> anyhow::Result<ParseOutput> {
    let strict = config.strict;
    if !path.is_file() {
        bail!("{} is not a file", path.display())
    }
    let file = File::open(path)?;
    let metadata = file.metadata()?;
    let file_size = metadata.len();

    // TODO: abstract out this spinner to not be part of the library
    // Instead, add a callback trait for CLIs to implement
    let multi = MultiProgress::new();
    let pb = multi.add(ProgressBar::new(file_size));
    pb.set_style(ProgressStyle::default_bar()
        .template("{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {bytes}/{total_bytes} [{bytes_per_sec}] ({eta})")?
        .progress_chars("#>-"));
    let spinner = multi.add(ProgressBar::new_spinner());

    let reader = io::BufReader::new(file);

    let re_glog = Regex::new(concat!(
        r"(?<level>[VIWEC])(?<month>\d{2})(?<day>\d{2}) ",
        r"(?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2}).(?<millisecond>\d{6}) ",
        r"(?<thread>\d+)",
        r"(?<pathname>[^:]+):(?<line>\d+)\] ",
        r"(?<payload>.)"
    ))?;

    // Helper functions to reduce repetitive serde_json::Value creation
    let make_string_value = |caps: &regex::Captures, name: &str| -> serde_json::Value {
        serde_json::Value::String(caps.name(name).unwrap().as_str().to_string())
    };

    let make_number_value = |caps: &regex::Captures, name: &str| -> serde_json::Value {
        let parsed: u64 = caps.name(name).unwrap().as_str().parse().unwrap();
        serde_json::Value::Number(serde_json::Number::from(parsed))
    };

    // Helper function to format timestamp as ISO-8601
    let format_timestamp = |caps: &regex::Captures| -> String {
        let month: u32 = caps.name("month").unwrap().as_str().parse().unwrap();
        let day: u32 = caps.name("day").unwrap().as_str().parse().unwrap();
        let hour: u32 = caps.name("hour").unwrap().as_str().parse().unwrap();
        let minute: u32 = caps.name("minute").unwrap().as_str().parse().unwrap();
        let second: u32 = caps.name("second").unwrap().as_str().parse().unwrap();
        let microsecond: u32 = caps.name("millisecond").unwrap().as_str().parse().unwrap();

        // Assume current year since glog doesn't include year
        let year = chrono::Utc::now().year();

        // Format as ISO-8601 with microsecond precision
        format!(
            "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}.{:06}Z",
            year, month, day, hour, minute, second, microsecond
        )
    };

    let mut stack_trie = StackTrieNode::default();
    let mut unknown_stack_trie = StackTrieNode::default();

    let mut stats = Stats::default();
    let _mod_count: FxHashMap<String, i32> = FxHashMap::default();

    let mut bytes_read: u64 = 0;

    // Some stuff for profiling
    let mut fastest_time = std::time::Duration::MAX;
    let mut slowest_time = std::time::Duration::ZERO;

    let mut expected_rank: Option<Option<u32>> = None;

    // Each entry is a compile id => (link, rendered name, output number)
    // For files, link and rendered name are the same
    // For links, you can specify a custom name for the link
    let mut directory: FxIndexMap<Option<CompileId>, Vec<OutputFile>> = FxIndexMap::default();

    let mut metrics_index: CompilationMetricsIndex = FxIndexMap::default();
    let stack_index: RefCell<StackIndex> = RefCell::new(FxHashMap::default());

    let symbolic_shape_specialization_index: RefCell<SymbolicShapeSpecializationIndex> =
        RefCell::new(FxHashMap::default());
    let guard_added_fast_index: RefCell<GuardAddedFastIndex> = RefCell::new(FxHashMap::default());
    let sym_expr_info_index: RefCell<SymExprInfoIndex> = RefCell::new(FxHashMap::default());
    let create_symbol_index: RefCell<CreateSymbolIndex> = RefCell::new(FxHashMap::default());
    let unbacked_symbol_index: RefCell<UnbackedSymbolIndex> = RefCell::new(FxHashMap::default());

    // Store results in an output ParseOutput
    let mut output: ParseOutput = Vec::new();

    // Store raw.jsonl content (without payloads)
    let mut shortraw_content = String::new();

    let mut tt: TinyTemplate = TinyTemplate::new();
    tt.add_formatter("format_unescaped", tinytemplate::format_unescaped);
    tt.add_formatter("format_float", |value, output| {
        if let serde_json::Value::Number(n) = value {
            if let Some(f) = n.as_f64() {
                write!(output, "{:.3}", f)?;
                return Ok(());
            }
        }
        write!(output, "{}", value)?;
        Ok(())
    });
    if config.export {
        tt.add_template("index.html", TEMPLATE_EXPORT_INDEX)?;
        tt.add_template(
            "symbolic_guard_information.html",
            TEMPLATE_SYMBOLIC_GUARD_INFO,
        )?;
    } else {
        tt.add_template("index.html", TEMPLATE_INDEX)?;
        tt.add_template("failures_and_restarts.html", TEMPLATE_FAILURES_AND_RESTARTS)?;
        tt.add_template("dynamo_guards.html", TEMPLATE_DYNAMO_GUARDS)?;
        tt.add_template("compilation_metrics.html", TEMPLATE_COMPILATION_METRICS)?;
        tt.add_template(
            "bwd_compilation_metrics.html",
            TEMPLATE_BWD_COMPILATION_METRICS,
        )?;
        tt.add_template(
            "aot_autograd_backward_compilation_metrics.html",
            TEMPLATE_AOT_AUTOGRAD_BACKWARD_COMPILATION_METRICS,
        )?;
    }
    tt.add_template("provenance_tracking.html", TEMPLATE_PROVENANCE_TRACKING)?;
    tt.add_template("vllm_summary.html", vllm::templates::VLLM_SUMMARY_TEMPLATE)?;

    let mut unknown_fields: FxHashSet<String> = FxHashSet::default();

    let mut output_count = 0;

    let mut breaks = RestartsAndFailuresContext {
        css: TEMPLATE_FAILURES_CSS,
        failures: Vec::new(),
        qps: TEMPLATE_QUERY_PARAM_SCRIPT,
    };

    let mut export_failures: Vec<ExportFailure> = Vec::new();

    // NB: Sometimes, the log output we get from Logarithm stutters with a blank line.
    // Filter them out, they're never valid (a blank line in payload will still be \t)
    let mut iter = reader
        .lines()
        .enumerate()
        .filter_map(|(i, l)| match l {
            // 1-indexed line numbers please
            Ok(l) if !l.is_empty() => Some((i + 1, l)),
            _ => None,
        })
        .peekable();

    let default_parsers = default_parsers(&tt, config);
    let vllm_state = vllm::VllmState::new();
    let vllm_parsers = vllm::vllm_parsers_with_state(vllm_state.clone());
    let mut all_parsers: Vec<&Box<dyn StructuredLogParser>> = default_parsers.iter().collect();
    all_parsers.extend(vllm_parsers.iter());
    let mut chromium_events: Vec<serde_json::Value> = Vec::new();
    all_parsers.extend(config.custom_parsers.iter());

    while let Some((lineno, line)) = iter.next() {
        bytes_read += line.len() as u64;
        pb.set_position(bytes_read);
        spinner.set_message(format!("{}", stats));
        //spinner.set_message(format!("{:?} {:?}", slowest_time, fastest_time));
        let start = Instant::now();

        let Some(caps) = re_glog.captures(&line) else {
            multi.suspend(|| eprintln!("Failed to parse glog prefix on line {}", lineno));
            stats.fail_glog += 1;
            continue;
        };

        let end = start.elapsed();
        if end < fastest_time {
            fastest_time = end;
        }
        if end > slowest_time {
            slowest_time = end;
        }
        let payload = &line[caps.name("payload").unwrap().start()..];
        let original_json_envelope = payload; // Store the original JSON envelope

        // Helper function to safely insert keys and detect conflicts
        let try_insert = |obj: &mut serde_json::Map<String, serde_json::Value>,
                          key: &str,
                          value: serde_json::Value,
                          multi: &MultiProgress,
                          stats: &mut Stats|
         -> bool {
            if obj.contains_key(key) {
                multi.suspend(|| {
                    eprintln!("Key conflict: '{}' already exists in JSON payload, skipping raw.jsonl JSONL conversion", key);
                });
                stats.fail_key_conflict += 1;
                false
            } else {
                obj.insert(key.to_string(), value);
                true
            }
        };

        // Create cleanup lambda to handle raw.jsonl writing as JSONL
        let write_to_shortraw = |shortraw_content: &mut String,
                                 payload_filename: Option<String>,
                                 multi: &MultiProgress,
                                 stats: &mut Stats| {
            match serde_json::from_str::<serde_json::Value>(original_json_envelope) {
                Ok(mut json_value) => {
                    if let Some(obj) = json_value.as_object_mut() {
                        // Try to add all log fields, abort on any conflict
                        let success = try_insert(
                            obj,
                            "timestamp",
                            serde_json::Value::String(format_timestamp(&caps)),
                            multi,
                            stats,
                        ) && try_insert(
                            obj,
                            "thread",
                            make_number_value(&caps, "thread"),
                            multi,
                            stats,
                        ) && try_insert(
                            obj,
                            "pathname",
                            make_string_value(&caps, "pathname"),
                            multi,
                            stats,
                        ) && try_insert(
                            obj,
                            "lineno",
                            make_number_value(&caps, "line"),
                            multi,
                            stats,
                        );

                        // Try to add payload filename if provided
                        let success = if let Some(payload_file) = payload_filename {
                            success
                                && try_insert(
                                    obj,
                                    "payload_filename",
                                    serde_json::Value::String(payload_file),
                                    multi,
                                    stats,
                                )
                        } else {
                            success
                        };

                        if !success {
                            // Drop line due to key conflict - don't write anything to maintain JSONL format
                            return;
                        }

                        // Output as JSONL
                        match serde_json::to_string(&json_value) {
                            Ok(jsonl_line) => {
                                shortraw_content.push_str(&jsonl_line);
                                shortraw_content.push('\n');
                            }
                            Err(e) => {
                                multi.suspend(|| {
                                    eprintln!("Failed to serialize JSON for raw.jsonl: {}", e);
                                });
                                stats.fail_json_serialization += 1;
                                // Drop line to maintain JSONL format - don't write anything
                            }
                        }
                    } else {
                        // Not a JSON object, drop line to maintain JSONL format
                        multi.suspend(|| {
                            eprintln!(
                                "JSON payload is not an object, dropping line from raw.jsonl"
                            );
                        });
                        stats.fail_json += 1;
                    }
                }
                Err(e) => {
                    // JSON parsing failed, drop line to maintain JSONL format
                    multi.suspend(|| {
                        eprintln!("Failed to parse JSON envelope for raw.jsonl: {}", e);
                    });
                    stats.fail_json += 1;
                }
            }
        };

        let e = match serde_json::from_str::<Envelope>(payload) {
            Ok(r) => r,
            Err(err) => {
                multi.suspend(|| {
                    eprintln!(
                        "Failed to parse metadata JSON: \n{:?} on line {}",
                        err, lineno
                    );
                });
                stats.fail_json += 1;
                write_to_shortraw(&mut shortraw_content, None, &multi, &mut stats);
                continue;
            }
        };

        stats.unknown += e._other.len() as u64;

        for k in e._other.keys() {
            unknown_fields.insert(k.clone());
            if config.verbose {
                multi.suspend(|| eprintln!("Unknown field {}", k))
            }
        }

        if let Some((s, i)) = e.str {
            let mut intern_table = INTERN_TABLE.lock().unwrap();
            intern_table.insert(i, s);
            continue;
        };

        let mut payload = String::new();
        if let Some(ref expect) = e.has_payload {
            let mut first = true;
            while let Some((_payload_lineno, payload_line)) =
                iter.next_if(|(_, l)| l.starts_with('\t'))
            {
                // Careful! Distinguish between missing EOL and not
                if !first {
                    payload.push('\n');
                }
                first = false;
                payload.push_str(&payload_line[1..]);
            }
            let mut hasher = Md5::new();
            hasher.update(&payload);
            let hash = hasher.finalize();
            let mut expect_buf = [0u8; 16];
            if base16ct::lower::decode(expect, &mut expect_buf).is_ok() {
                if expect_buf != hash[..] {
                    // TODO: error log
                    stats.fail_payload_md5 += 1;
                }
            } else {
                stats.fail_payload_md5 += 1;
            }
        }

        match expected_rank {
            Some(rank) => {
                if rank != e.rank {
                    stats.other_rank += 1;
                    write_to_shortraw(&mut shortraw_content, None, &multi, &mut stats);
                    continue;
                }
            }
            None => {
                // Allow logs with no rank and then some rank to be processed
                // Logs with no rank may be initialized before distributed rank is set
                if e.rank.is_some() {
                    multi.suspend(|| {
                        eprintln!("Detected rank: {:?}", e.rank);
                    });
                    expected_rank = Some(e.rank);
                }
            }
        };

        stats.ok += 1;

        // Some runtime compile ids don't have attempts. Collapse these entries into
        // attempt 0 for now.
        let mut compile_id_entry = e.compile_id.clone();
        if let Some(ref mut entry) = compile_id_entry {
            if entry.frame_compile_id.is_some() && entry.attempt.is_none() {
                entry.attempt = Some(0);
            }
        }

        // TODO: output should be able to generate this without explicitly creating
        let compile_directory = directory.entry(compile_id_entry).or_default();

        let mut parser_payload_filename = ParserResult::NoPayload;
        for parser in &all_parsers {
            let result = run_parser(
                lineno,
                parser,
                &e,
                &payload,
                &mut output_count,
                &mut output,
                compile_directory,
                &multi,
                &mut stats,
                &vllm_state,
            );
            // Take the last PayloadFilename entry as per the requirement
            if matches!(result, ParserResult::PayloadFilename(_)) {
                parser_payload_filename = result;
            }
        }

        if let Some(ref m) = e.compilation_metrics {
            let copied_directory = compile_directory.clone();
            let compile_id_dir: PathBuf = e
                .compile_id
                .as_ref()
                .map_or(format!("unknown_{lineno}"), |cid| cid.as_directory_name())
                .into();
            let parser: Box<dyn StructuredLogParser> =
                Box::new(crate::parsers::CompilationMetricsParser {
                    tt: &tt,
                    stack_index: &stack_index,
                    symbolic_shape_specialization_index: &symbolic_shape_specialization_index,
                    guard_added_fast_index: &guard_added_fast_index,
                    create_symbol_index: &create_symbol_index,
                    unbacked_symbol_index: &unbacked_symbol_index,
                    output_files: &copied_directory,
                    compile_id_dir: &compile_id_dir,
                });
            let result = run_parser(
                lineno,
                &parser,
                &e,
                &payload,
                &mut output_count,
                &mut output,
                compile_directory,
                &multi,
                &mut stats,
                &vllm_state,
            );
            // Take the last PayloadFilename entry as per the requirement
            if matches!(result, ParserResult::PayloadFilename(_)) {
                parser_payload_filename = result;
            }

            // compilation metrics is always the last output, since it just ran
            let metrics_filename = format!(
                "compilation_metrics_{}.html",
                (output_count - 1).to_string(),
            );

            let id = e.compile_id.clone().map_or("(unknown) ".to_string(), |c| {
                format!(
                    "<a href='{}/{}'>{cid}</a> ",
                    compile_id_dir.display(),
                    metrics_filename,
                    cid = c,
                )
            });
            if let Some(rr) = m.restart_reasons.as_ref() {
                for restart in rr {
                    breaks.failures.push((
                        id.clone(),
                        format!("{}", FailureReason::Restart(restart.clone())),
                    ));
                }
            }
            if let Some(f) = m.fail_type.as_ref() {
                let reason = m
                    .fail_reason
                    .clone()
                    .ok_or_else(|| anyhow::anyhow!("Fail reason not found"))?;
                let user_frame_filename = m
                    .fail_user_frame_filename
                    .clone()
                    .unwrap_or(String::from("N/A"));
                let user_frame_lineno = m.fail_user_frame_lineno.unwrap_or(0);
                let failure_reason = FailureReason::Failure((
                    f.clone(),
                    reason.clone(),
                    user_frame_filename.clone(),
                    user_frame_lineno.clone(),
                ));
                breaks
                    .failures
                    .push((id.clone(), format!("{failure_reason}")));
            }
            let mut cid = e.compile_id.clone();
            if let Some(c) = cid.as_mut() {
                if let Some(_frame_id) = c.frame_compile_id {
                    // data migration for old logs that don't have attempt
                    c.attempt = Some(0);
                }
            }
            metrics_index.entry(cid).or_default().push(m.clone());
        }

        if config.export {
            if let Some(ref guard) = e.guard_added {
                if guard.prefix.as_deref() != Some("eval") {
                    write_to_shortraw(&mut shortraw_content, None, &multi, &mut stats);
                    continue;
                }
                let failure_type = "Guard Evaluated";

                let reason = format!(
                    "When exporting, the following guard was evaluated <code>{}</code>. This
                    might've resulted in a constraint violation error.",
                    guard.expr.clone().unwrap(),
                );

                handle_guard(
                    failure_type,
                    &reason,
                    lineno,
                    &e,
                    &payload,
                    &mut output_count,
                    &mut output,
                    compile_directory,
                    &multi,
                    &mut stats,
                    &tt,
                    &sym_expr_info_index,
                    &mut export_failures,
                    &vllm_state,
                );
            }

            if let Some(ref guard) = e.propagate_real_tensors_provenance {
                let failure_type = "Data Dependent Error";

                let reason = format!(
                    "When exporting, we were unable to figure out if the
                    expression <code>{}</code> always holds.<br> As a result, it
                    was specialized to evaluate to <code>{}</code>, and asserts
                    were inserted into the graph.",
                    guard.expr.clone().unwrap(),
                    guard.result.clone().unwrap()
                );

                handle_guard(
                    failure_type,
                    &reason,
                    lineno,
                    &e,
                    &payload,
                    &mut output_count,
                    &mut output,
                    compile_directory,
                    &multi,
                    &mut stats,
                    &tt,
                    &sym_expr_info_index,
                    &mut export_failures,
                    &vllm_state,
                );
            }

            if let Some(fake_kernel) = e.missing_fake_kernel {
                let failure_type = "Missing Fake Kernel";

                let reason = format!(
                    "<code>torch.ops.{}</code> is missing a fake kernel implementation",
                    fake_kernel.op.unwrap()
                );

                let additional_info = "Please refer to <a href='https://docs.google.com/document/d/1_W62p8WJOQQUzPsJYa7s701JXt0qf2OfLub2sbkHOaU/edit#heading=h.ahugy69p2jmz'>this doc</a> for more detailed instructions on how to write a fake kernel.";

                export_failures.push(ExportFailure {
                    failure_type: failure_type.to_string(),
                    reason: reason,
                    additional_info: additional_info.to_string(),
                });
            }

            if let Some(fake_kernel) = e.mismatched_fake_kernel {
                let failure_type = "Mismatched Fake Kernel";

                let reason = format!(
                    "<code>torch.ops.{}</code> has a fake kernel implementation,
                    but it has incorrect behavior, based on the real kernel.<br>
                    The reason for the mismatch is: {}",
                    fake_kernel.op.unwrap(),
                    fake_kernel.reason.unwrap(),
                );

                let additional_info = "Please refer to <a href='https://docs.google.com/document/d/1_W62p8WJOQQUzPsJYa7s701JXt0qf2OfLub2sbkHOaU/edit#heading=h.ahugy69p2jmz'>this doc</a> for more detailed instructions on how to write a fake kernel.";

                export_failures.push(ExportFailure {
                    failure_type: failure_type.to_string(),
                    reason: reason,
                    additional_info: additional_info.to_string(),
                });
            }

            if let Some(sym_expr_info) = e.expression_created {
                sym_expr_info_index
                    .borrow_mut()
                    .insert(sym_expr_info.result_id.unwrap(), sym_expr_info);
            }

            if let Some(ref unbacked_symbol) = e.create_unbacked_symbol {
                sym_expr_info_index.borrow_mut().insert(
                    unbacked_symbol.node_id.unwrap(),
                    SymExprInfoMetadata {
                        result: unbacked_symbol.symbol.clone(),
                        result_id: unbacked_symbol.node_id.clone(),
                        user_stack: unbacked_symbol.user_stack.clone(),
                        stack: unbacked_symbol.stack.clone(),
                        ..Default::default()
                    },
                );
            }
        }

        // Handle symbol creation events OUTSIDE of export block - they should always be collected
        if let Some(unbacked_symbol) = e.create_unbacked_symbol.clone() {
            // Apply same data migration as in CompilationMetricsParser for consistent HashMap keys
            let mut cid = e.compile_id.clone();
            if let Some(c) = cid.as_mut() {
                if c.frame_compile_id.is_some() {
                    c.attempt = Some(c.attempt.unwrap_or(0));
                }
            }
            unbacked_symbol_index
                .borrow_mut()
                .entry(cid)
                .or_default()
                .push(unbacked_symbol);
        }

        // Handle create_symbol events (backed symbols with concrete values)
        if let Some(symbol) = e.create_symbol.clone() {
            // Apply same data migration as in CompilationMetricsParser for consistent HashMap keys
            let mut cid = e.compile_id.clone();
            if let Some(c) = cid.as_mut() {
                if c.frame_compile_id.is_some() {
                    c.attempt = Some(c.attempt.unwrap_or(0));
                }
            }
            create_symbol_index
                .borrow_mut()
                .entry(cid)
                .or_default()
                .push(symbol);
        }

        if let Some(stack) = e.stack {
            unknown_stack_trie.insert(stack.clone(), None);
        }

        if let Some(_) = e.chromium_event {
            // Skip bad json in chromium event. This can happen if log lines are dropped.
            match serde_json::from_str(&payload) {
                Ok(event) => chromium_events.push(event),
                Err(_) => {
                    // Continue processing instead of crashing
                    // If json line is dropped, we should see fail_payload_md5 in result because the
                    // payload doesn't match the md5.
                }
            }
        }

        if let Some(specialization) = e.symbolic_shape_specialization {
            symbolic_shape_specialization_index
                .borrow_mut()
                .entry(e.compile_id.clone())
                .or_default()
                .push(specialization);
        }
        if let Some(guard_added_fast) = e.guard_added_fast {
            guard_added_fast_index
                .borrow_mut()
                .entry(e.compile_id.clone())
                .or_default()
                .push(guard_added_fast)
        }

        if let Some(m) = e.dynamo_start {
            if let Some(mut stack) = m.stack {
                maybe_remove_convert_frame_suffixes(&mut stack);
                stack_index
                    .borrow_mut()
                    .insert(e.compile_id.clone(), stack.clone());
                stack_trie.insert(stack, e.compile_id.clone());
            };
        };

        // Handle payload file writing and determine final payload filename, but skip chromium events
        let final_payload_filename = match parser_payload_filename {
            ParserResult::PayloadFilename(filename) => Some(filename),
            ParserResult::NoPayload => {
                if let Some(ref expect) = e.has_payload {
                    // Only write payload file if no parser generated PayloadFile/PayloadReformatFile output and not a chromium event
                    if !payload.is_empty() && e.chromium_event.is_none() {
                        let hash_str = expect;
                        let payload_path = PathBuf::from(format!("payloads/{}.txt", hash_str));
                        output.push((payload_path, payload.clone()));
                        Some(format!("payloads/{}.txt", hash_str))
                    } else {
                        None
                    }
                } else {
                    None
                }
            }
        };

        // Write to raw.jsonl with optional payload filename, but skip chromium events
        if e.chromium_event.is_none() {
            write_to_shortraw(
                &mut shortraw_content,
                final_payload_filename,
                &multi,
                &mut stats,
            );
        }
    }

    if config.export {
        let num_failures = export_failures.len();

        let exported_program_url = directory
            .values()
            .flatten()
            .find(|output_file| output_file.url.contains("exported_program"))
            .map(|output_file| output_file.url.clone());

        let index_context = ExportIndexContext {
            css: EXPORT_CSS,
            javascript: JAVASCRIPT,
            custom_header_html: config.custom_header_html.clone(),
            directory: directory
                .drain(..)
                .map(|(x, y)| (x.map_or("(unknown)".to_string(), |e| e.to_string()), y))
                .collect(),
            failures: export_failures,
            num_failures: num_failures,
            success: num_failures == 0,
            exported_program_url: exported_program_url.unwrap_or("".to_string()),
            qps: TEMPLATE_QUERY_PARAM_SCRIPT,
        };

        output.push((
            PathBuf::from("index.html"),
            tt.render("index.html", &index_context)?,
        ));

        return Ok(output);
    }

    output.push((
        PathBuf::from("failures_and_restarts.html"),
        tt.render("failures_and_restarts.html", &breaks)?,
    ));
    pb.finish_with_message("done");
    spinner.finish();

    output.push((
        PathBuf::from("chromium_events.json"),
        serde_json::to_string_pretty(&chromium_events).unwrap(),
    ));

    eprintln!("{}", stats);
    if unknown_fields.len() > 0 {
        eprintln!(
            "Unknown fields: {:?} (consider updating tlparse to render these)",
            unknown_fields
        );
    }

    let has_unknown_compile_id = directory.contains_key(&None);

    let directory_names: Vec<String> = directory
        .iter()
        .map(|(x, _)| {
            x.as_ref()
                .map_or("(unknown)".to_string(), |e| e.as_directory_name())
        })
        .collect();
    output.push((
        PathBuf::from("compile_directory.json"),
        serde_json::to_string_pretty(&directory_to_json(&directory))?,
    ));

    // Generate traditional tlparse index
    let index_context = IndexContext {
        css: CSS,
        javascript: JAVASCRIPT,
        custom_header_html: config.custom_header_html.clone(),
        directory: directory
            .drain(..)
            .map(|(x, y)| (x.map_or("(unknown)".to_string(), |e| e.to_string()), y))
            .collect(),
        stack_trie_html: stack_trie
            .fmt(Some(&metrics_index), "Stack", false)
            .unwrap(),
        unknown_stack_trie_html: unknown_stack_trie
            .fmt(Some(&metrics_index), "Stack", false)
            .unwrap(),
        has_unknown_stack_trie: !unknown_stack_trie.is_empty(),
        num_breaks: breaks.failures.len(),
        has_chromium_events: !chromium_events.is_empty(),
        qps: TEMPLATE_QUERY_PARAM_SCRIPT,
        has_inductor_provenance: config.inductor_provenance,
        directory_names: directory_names.clone(),
    };
    let tlparse_index_html = tt.render("index.html", &index_context)?;

    if vllm_state.has_artifacts() {
        // If vLLM artifacts are present, use vLLM summary as index.html and
        // save traditional tlparse index as tlparse_index.html for reference.
        // `has_vllm_artifacts` gets set to true when the vLLM parsers are
        // triggered. This happens when we see the following events:
        // `vllm_subgraph_*`, `vllm_compilation_config`,
        // `vllm_piecewise_split_graph`.
        let vllm_html = vllm::generate_vllm_summary(&vllm_state, &tt, &config.custom_header_html)?;
        output.push((PathBuf::from("index.html"), vllm_html));
        output.push((PathBuf::from("tlparse_index.html"), tlparse_index_html));
    } else {
        output.push((PathBuf::from("index.html"), tlparse_index_html));
    }

    output.push((PathBuf::from("raw.log"), fs::read_to_string(path)?));

    // Create string table from INTERN_TABLE as an array with nulls for missing indices
    let intern_table = INTERN_TABLE.lock().unwrap();
    let max_index = intern_table.keys().max().copied().unwrap_or(0) as usize;
    let mut string_table: Vec<Option<String>> = vec![None; max_index + 1];
    for (&index, value) in intern_table.iter() {
        string_table[index as usize] = Some(value.clone());
    }
    drop(intern_table); // Release the lock early

    // Serialize string table as JSON object
    let string_table_json = serde_json::json!({
        "string_table": string_table
    });
    let string_table_line = serde_json::to_string(&string_table_json)?;

    // Prepend string table to raw.jsonl content
    let mut final_shortraw_content =
        String::with_capacity(string_table_line.len() + 1 + shortraw_content.len());
    final_shortraw_content.push_str(&string_table_line);
    final_shortraw_content.push('\n');
    final_shortraw_content.push_str(&shortraw_content);

    output.push((PathBuf::from("raw.jsonl"), final_shortraw_content));

    // other_rank is included here because you should only have logs from one rank when
    // configured properly
    if strict
        && (stats.fail_glog
            + stats.fail_json
            + stats.fail_payload_md5
            + stats.other_rank
            + stats.fail_dynamo_guards_json
            + stats.fail_parser
            > 0)
    {
        // Report something went wrong
        return Err(anyhow!("Something went wrong"));
    }

    if config.strict_compile_id && has_unknown_compile_id {
        return Err(anyhow!("Some log entries did not have compile id"));
    }

    if config.inductor_provenance {
        // Helper function to get file content for a specific directory name
        fn get_file_content(
            output: &[(PathBuf, String)],
            filename_patterns: &[&str],
            directory_name: &str,
        ) -> String {
            // Try each pattern in order and return the first match found
            for pattern in filename_patterns {
                if let Some((_, content)) = output.iter().rev().find(|(path, _)| {
                    path.to_string_lossy()
                        .contains(&format!("{}/{}", directory_name, pattern))
                }) {
                    return content.clone();
                }
            }
            String::default()
        }

        // Generate HTML for each directory name
        for directory_name in &directory_names {
            let pre_grad_graph_content = get_file_content(
                &output,
                &["before_pre_grad_graph", "inductor_pre_grad_graph"],
                directory_name,
            );
            let post_grad_graph_content = get_file_content(
                &output,
                &["after_post_grad_graph", "inductor_post_grad_graph"],
                directory_name,
            );
            let output_code_content =
                get_file_content(&output, &["inductor_output_code"], directory_name);
            let aot_code_content =
                get_file_content(&output, &["inductor_aot_wrapper_code"], directory_name);
            let node_mappings_content = get_file_content(
                &output,
                &["inductor_provenance_tracking_node_mappings"],
                directory_name,
            );

            // Convert node mappings to line number mappings
            let line_mappings_content = convert_node_mappings_to_line_numbers(
                &node_mappings_content,
                &pre_grad_graph_content,
                &post_grad_graph_content,
                &output_code_content,
                &aot_code_content,
            );
            let line_mappings_content_str = serde_json::to_string_pretty(&line_mappings_content)
                .unwrap_or_else(|_| "{}".to_string());

            output.push((
                PathBuf::from(format!("provenance_tracking_{}.html", directory_name)),
                tt.render(
                    "provenance_tracking.html",
                    &ProvenanceContext {
                        css: PROVENANCE_CSS,
                        js: PROVENANCE_JS,
                        pre_grad_graph_content,
                        post_grad_graph_content,
                        output_code_content,
                        aot_code_content,
                        line_mappings_content: line_mappings_content_str,
                    },
                )?,
            ));
        }
    }

    Ok(output)
}

pub fn read_chromium_events_with_pid(
    path: &std::path::Path,
    rank_num: u32,
) -> anyhow::Result<Vec<serde_json::Value>> {
    use std::fs;

    if !path.exists() {
        return Ok(Vec::new());
    }

    let file_content = fs::read_to_string(path)?;

    match serde_json::from_str::<Vec<serde_json::Value>>(&file_content) {
        Ok(mut events) => {
            for event in &mut events {
                if let Some(obj) = event.as_object_mut() {
                    obj.insert("pid".to_string(), serde_json::json!(rank_num));
                }
            }
            Ok(events)
        }
        Err(_) => Ok(Vec::new()),
    }
}

pub fn generate_multi_rank_html(
    out_path: &PathBuf,
    sorted_ranks: Vec<String>,
    cfg: &ParseConfig,
    has_chromium_events: bool,
    show_desync_warning: bool,
    compile_id_divergence: bool,
    diagnostics: Diagnostics,
) -> anyhow::Result<(PathBuf, String)> {
    // Create the TinyTemplate instance for rendering the landing page.
    let mut tt = TinyTemplate::new();
    tt.add_formatter("format_unescaped", tinytemplate::format_unescaped);
    tt.add_template("multi_rank_index.html", TEMPLATE_MULTI_RANK_INDEX)?;

    let ctx = MultiRankContext {
        css: CSS,
        custom_header_html: &cfg.custom_header_html,
        num_ranks: sorted_ranks.len(),
        ranks: sorted_ranks,
        qps: TEMPLATE_QUERY_PARAM_SCRIPT,
        has_chromium_events,
        show_desync_warning,
        compile_id_divergence,
        diagnostics,
    };
    let html = tt.render("multi_rank_index.html", &ctx)?;
    let landing_page_path = out_path.join("index.html");

    Ok((landing_page_path, html))
}

/// Generate multi-rank landing and aggregated artifacts from pre-parsed rank outputs.
///
/// This mirrors the diagnostics and file emission performed by the CLI `--all-ranks-html` path.
/// It expects that per-rank outputs already exist under `out_dir/rank_<n>` and will:
/// - Combine Chromium events into `chromium_events.json` (if any)
/// - Write `runtime_estimations.json` and `chromium_trace_with_runtime.json` (if any)
/// - Write `collective_schedules.json` (if any) and per-rank `collectives_parity.json`
/// - Analyze runtime deltas and exec order summary
/// - Render `index.html` landing page using the same template and context
pub fn generate_multi_rank_landing(
    cfg: &ParseConfig,
    ctx: &MultiRankContext,
    out_dir: &Path,
) -> anyhow::Result<PathBuf> {
    use std::fs;

    // Parse ranks from context and ensure sorted numerically like the CLI
    let mut rank_nums: Vec<u32> = ctx
        .ranks
        .iter()
        .filter_map(|s| s.parse::<u32>().ok())
        .collect();
    rank_nums.sort_unstable();
    let sorted_ranks: Vec<String> = rank_nums.iter().map(|r| r.to_string()).collect();

    let out_path: PathBuf = out_dir.to_path_buf();

    // Collect compile ids and cache sequences per rank, and chromium events at root
    let mut rank_metadata: FxHashMap<u32, RankMetaData> = FxHashMap::default();
    let mut all_chromium_events: Vec<serde_json::Value> = Vec::new();

    for &rank_num in &rank_nums {
        let subdir = out_path.join(format!("rank_{rank_num}"));
        let chromium_events_path = subdir.join("chromium_events.json");
        let compile_dir_json = subdir.join("compile_directory.json");

        // extract compile IDs and cache sequence from compile_directory.json
        let mut compile_ids: FxHashSet<String> = FxHashSet::default();
        let content = fs::read_to_string(&compile_dir_json)?;
        let mut artifact_entries: Vec<(u64, String)> = Vec::new();

        if let Ok(serde_json::Value::Object(map)) =
            serde_json::from_str::<serde_json::Value>(&content)
        {
            for (key, val) in map.iter() {
                if key != "unknown" && !key.starts_with("unknown_") {
                    compile_ids.insert(key.clone());
                }
                if let Some(arr) = val.get("artifacts").and_then(|v| v.as_array()) {
                    for art in arr {
                        let suffix = art.get("suffix").and_then(|s| s.as_str()).unwrap_or("");
                        if suffix.is_empty() {
                            continue;
                        }
                        if let Some(num) = art.get("number").and_then(|n| n.as_u64()) {
                            artifact_entries.push((num, suffix.to_string()));
                        }
                    }
                }
            }
        }

        artifact_entries.sort_by_key(|(n, _)| *n);
        let cache_sequence: String = artifact_entries.into_iter().map(|(_, s)| s).collect();

        rank_metadata.insert(
            rank_num,
            RankMetaData {
                rank: rank_num,
                compile_ids,
                cache_sequence,
            },
        );

        // collect chromium events for each rank
        if chromium_events_path.exists() {
            let events = read_chromium_events_with_pid(&chromium_events_path, rank_num)?;
            all_chromium_events.extend(events);
        }
    }

    // Determine if there is any divergence in compile IDs across ranks
    let compile_id_divergence =
        if let Some(first) = rank_nums.iter().filter_map(|r| rank_metadata.get(r)).next() {
            rank_metadata
                .values()
                .any(|md| md.compile_ids != first.compile_ids)
        } else {
            false
        };

    // Group ranks by their cache hit/miss sequence
    let cache_seq_groups: FxHashMap<String, Vec<u32>> =
        rank_metadata
            .into_values()
            .fold(FxHashMap::default(), |mut acc, md| {
                acc.entry(md.cache_sequence).or_default().push(md.rank);
                acc
            });

    // Build groups describing cache hit/miss patterns per rank
    let cache_divergence_groups: Vec<DivergenceGroup> = if cache_seq_groups.len() > 1 {
        cache_seq_groups
            .iter()
            .map(|(seq, ranks_vec)| {
                let mut sorted = ranks_vec.clone();
                sorted.sort_unstable();
                DivergenceGroup {
                    sequence: seq.clone(),
                    ranks: sorted
                        .iter()
                        .map(|r| r.to_string())
                        .collect::<Vec<_>>()
                        .join(", "),
                }
            })
            .collect()
    } else {
        Vec::new()
    };

    // combine chromium events from all ranks
    if !all_chromium_events.is_empty() {
        let combined_chromium_path = out_path.join("chromium_events.json");
        let combined_events_json = serde_json::to_string_pretty(&all_chromium_events)?;
        fs::write(combined_chromium_path, combined_events_json)?;
    }

    // Process runtime estimations from all ranks
    let runtime_estimations = crate::parsers::read_runtime_estimations(&out_path, &rank_nums)?;
    if !runtime_estimations.is_empty() {
        let runtime_path = out_path.join("runtime_estimations.json");
        fs::write(
            &runtime_path,
            serde_json::to_string_pretty(&runtime_estimations)?,
        )?;
        println!("Runtime estimations: {}", runtime_path.display());

        // Generate runtime trace events in a single pass
        let mut runtime_events: Vec<serde_json::Value> = Vec::new();
        let mut pid_set: FxHashSet<u32> = FxHashSet::default();
        let mut thread_names: FxHashMap<(u32, u32), String> = FxHashMap::default();

        // Concise, deterministic 32-bit TID from (rank, graph)
        let calc_tid = |rank: u32, graph: &str| -> u32 {
            use std::hash::{Hash, Hasher};
            let mut h = fxhash::FxHasher::default();
            (rank, graph).hash(&mut h);
            (h.finish() & 0xFFFF_FFFF) as u32
        };

        for gr in &runtime_estimations {
            pid_set.insert(gr.rank);
            let tid = calc_tid(gr.rank, &gr.graph);
            thread_names
                .entry((gr.rank, tid))
                .or_insert_with(|| gr.graph.clone());

            let mut time_offset_us: u64 = 0;
            for op in &gr.ops {
                let dur_us = (op.estimated_runtime_ns / 1000.0).ceil().max(1.0) as u64;
                runtime_events.push(serde_json::json!({
                    "name": op.name,
                    "ph": "X",
                    "ts": time_offset_us,
                    "dur": dur_us,
                    "pid": gr.rank,
                    "tid": tid,
                    "cat": "runtime",
                    "args": {
                        "graph": gr.graph,
                        "rank": gr.rank,
                        "runtime_ns": op.estimated_runtime_ns as u64
                    }
                }));
                time_offset_us += dur_us;
            }
        }

        let mut all_events: Vec<serde_json::Value> = runtime_events;

        // Emit process (rank) metadata in ascending pid order
        let mut pids: Vec<u32> = pid_set.into_iter().collect();
        pids.sort_unstable();
        for pid in pids.into_iter() {
            all_events.extend([
                serde_json::json!({
                    "name": "process_name",
                    "ph": "M",
                    "pid": pid,
                    "args": {"name": format!("Rank {}", pid)}
                }),
                serde_json::json!({
                    "name": "process_sort_index",
                    "ph": "M",
                    "pid": pid,
                    "args": {"sort_index": pid as i64}
                }),
            ]);
        }

        // Emit thread names sorted by graph name within each pid
        let mut threads_by_pid: FxHashMap<u32, Vec<(u32, String)>> = FxHashMap::default();
        for ((pid, tid), graph_name) in thread_names.into_iter() {
            threads_by_pid
                .entry(pid)
                .or_default()
                .push((tid, graph_name));
        }
        let mut pids_for_threads: Vec<u32> = threads_by_pid.keys().copied().collect();
        pids_for_threads.sort_unstable();
        for pid in pids_for_threads {
            let entries = threads_by_pid.remove(&pid).unwrap_or_default();
            for (idx, (tid, graph_name)) in entries.into_iter().enumerate() {
                all_events.extend([
                    serde_json::json!({
                        "name": "thread_name",
                        "ph": "M",
                        "pid": pid,
                        "tid": tid,
                        "args": {"name": format!("graph {}", graph_name)}
                    }),
                    serde_json::json!({
                        "name": "thread_sort_index",
                        "ph": "M",
                        "pid": pid,
                        "tid": tid,
                        "args": {"sort_index": idx as i64}
                    }),
                ]);
            }
        }

        fs::write(
            out_path.join("chromium_trace_with_runtime.json"),
            serde_json::to_string_pretty(&all_events)?,
        )?;
    }

    // Analyze graph runtime deltas across ranks
    let runtime_analysis = if !runtime_estimations.is_empty() {
        analyze_graph_runtime_deltas(&runtime_estimations)
    } else {
        None
    };

    // Process collective schedules from all ranks
    let collective_schedules = crate::parsers::read_collective_schedules(&out_path, &rank_nums)?;
    if !collective_schedules.is_empty() {
        let schedules_path = out_path.join("collective_schedules.json");
        fs::write(
            &schedules_path,
            serde_json::to_string_pretty(&collective_schedules)?,
        )?;
        println!("Collective schedules: {}", schedules_path.display());
    }

    crate::parsers::check_collectives_parity(&out_path, &rank_nums)?;

    // Process tensor meta fingerprints from all ranks
    let tensor_meta = crate::parsers::read_tensor_meta_fingerprints(&out_path, &rank_nums)?;
    let mut tensor_meta_groups: FxHashMap<String, Vec<u32>> = FxHashMap::default();
    if !tensor_meta.is_empty() {
        use std::collections::HashMap;
        // rank -> sorted list of (graph_id, fingerprint)
        let mut by_rank: HashMap<u32, Vec<(String, String)>> = HashMap::new();
        for tm in &tensor_meta {
            by_rank
                .entry(tm.rank)
                .or_default()
                .push((tm.graph.clone(), tm.fingerprint.clone()));
        }
        for (&rank, entries) in &mut by_rank {
            // sort by graph id to make cross-rank concatenation consistent
            let mut entries_sorted = entries.clone();
            entries_sorted.sort_by(|a, b| a.0.cmp(&b.0));
            let signature = entries_sorted
                .into_iter()
                .map(|(_, fp)| fp)
                .collect::<Vec<_>>()
                .join(",");
            tensor_meta_groups.entry(signature).or_default().push(rank);
        }
    }

    let tensor_meta_divergence_groups: Vec<DivergenceGroup> = if tensor_meta_groups.len() > 1 {
        tensor_meta_groups
            .iter()
            .map(|(seq, ranks_vec)| {
                let mut sorted = ranks_vec.clone();
                sorted.sort_unstable();
                DivergenceGroup {
                    sequence: seq.clone(),
                    ranks: sorted
                        .iter()
                        .map(|r| r.to_string())
                        .collect::<Vec<_>>()
                        .join(", "),
                }
            })
            .collect()
    } else {
        Vec::new()
    };

    // Group ranks by their collective op sequence
    let mut collective_seq_groups: FxHashMap<String, Vec<u32>> = FxHashMap::default();
    if !collective_schedules.is_empty() {
        for &rank in &rank_nums {
            let ops_concat: String = collective_schedules
                .iter()
                .filter(|s| s.rank == rank)
                .flat_map(|s| s.ops.clone())
                .collect::<Vec<_>>()
                .join(",");
            collective_seq_groups
                .entry(ops_concat)
                .or_default()
                .push(rank);
        }
    }

    let collective_divergence_groups: Vec<DivergenceGroup> = if collective_seq_groups.len() > 1 {
        collective_seq_groups
            .iter()
            .map(|(seq, ranks_vec)| {
                let mut sorted = ranks_vec.clone();
                sorted.sort_unstable();
                DivergenceGroup {
                    sequence: seq.clone(),
                    ranks: sorted
                        .iter()
                        .map(|r| r.to_string())
                        .collect::<Vec<_>>()
                        .join(", "),
                }
            })
            .collect()
    } else {
        Vec::new()
    };

    println!(
        "Multi-rank report generated under {}\nIndividual pages: rank_*/index.html",
        out_path.display()
    );

    let exec_order_summary = build_exec_order_summary(&out_path, &rank_nums, &collective_schedules);

    let diagnostics = Diagnostics {
        divergence: DivergenceFlags {
            cache: cache_seq_groups.len() > 1,
            collective: collective_seq_groups.len() > 1,
            tensor_meta: tensor_meta_groups.len() > 1,
        },
        artifacts: ArtifactFlags {
            runtime_trace: !runtime_estimations.is_empty(),
        },
        analysis: runtime_analysis,
        cache_groups: cache_divergence_groups.clone(),
        collective_groups: collective_divergence_groups.clone(),
        tensor_meta_groups: tensor_meta_divergence_groups.clone(),
        exec_order: exec_order_summary,
    };

    // Emit landing page identical to CLI
    let has_chromium_events = !all_chromium_events.is_empty();
    let show_desync_warning = compile_id_divergence
        || diagnostics.divergence.cache
        || diagnostics.divergence.collective
        || diagnostics.divergence.tensor_meta;

    let (landing_page_path, landing_html) = generate_multi_rank_html(
        &out_path,
        sorted_ranks,
        cfg,
        has_chromium_events,
        show_desync_warning,
        compile_id_divergence,
        diagnostics,
    )?;
    fs::write(&landing_page_path, landing_html)?;

    Ok(landing_page_path)
}

/// Build ExecOrderSummary from artifacts under out_path for the given ranks
pub fn build_exec_order_summary(
    out_path: &PathBuf,
    rank_nums: &[u32],
    collective_schedules: &[CollectiveSchedule],
) -> Option<ExecOrderSummary> {
    use crate::execution_order::{
        analyze_execution_order, parse_graph_execution_order, ExecOrderIssue,
    };
    use std::collections::HashSet;

    // Preload and parse compile_directory.json per rank
    let cd_by_rank: FxHashMap<u32, serde_json::Map<String, serde_json::Value>> = rank_nums
        .iter()
        .filter_map(|&rank| {
            let path = out_path
                .join(format!("rank_{rank}"))
                .join("compile_directory.json");
            std::fs::read_to_string(path)
                .ok()
                .and_then(|content| serde_json::from_str::<serde_json::Value>(&content).ok())
                .and_then(|val| match val {
                    serde_json::Value::Object(map) => Some((rank, map)),
                    _ => None,
                })
        })
        .collect();

    // Collect latest "graph_execution" artifact per rank
    let exec_orders: FxHashMap<u32, Vec<String>> = rank_nums
        .iter()
        .filter_map(|&rank| {
            let map = cd_by_rank.get(&rank)?;
            let rank_dir = out_path.join(format!("rank_{rank}"));

            // Find latest graph_execution artifact
            let best = map
                .values()
                .filter_map(|entry| entry.get("artifacts")?.as_array())
                .flat_map(|arts| arts.iter())
                .filter_map(|a| {
                    let name = a.get("name")?.as_str()?;
                    if !name.contains("graph_execution") || !name.ends_with(".json") {
                        return None;
                    }
                    Some((
                        a.get("number")?.as_u64()?,
                        a.get("url")?.as_str()?.to_string(),
                    ))
                })
                .max_by_key(|(num, _)| *num)?;

            let path = rank_dir.join(best.1);
            let order = std::fs::read_to_string(path)
                .ok()
                .and_then(|payload| parse_graph_execution_order(&payload).ok())
                .map(|order| order.into_iter().map(|s| format!("[{}]", s)).collect())?;
            Some((rank, order))
        })
        .collect();

    if exec_orders.len() < 2 {
        return None;
    }

    // Build dir -> compile_id mapping per rank
    let dir_to_compile_id_per_rank: FxHashMap<u32, FxHashMap<String, String>> = rank_nums
        .iter()
        .filter_map(|&rank| {
            let obj = cd_by_rank.get(&rank)?;
            let mapping = obj
                .iter()
                .flat_map(|(cid, entry)| {
                    entry
                        .get("artifacts")
                        .and_then(|x| x.as_array())
                        .map(|arts| {
                            arts.iter()
                                .filter_map(|a| {
                                    let url = a.get("url")?.as_str()?;
                                    let prefix = url.split_once('/')?.0;
                                    Some((prefix.to_string(), cid.to_string()))
                                })
                                .collect::<Vec<_>>()
                        })
                        .unwrap_or_default()
                })
                .fold(FxHashMap::default(), |mut acc, (prefix, cid)| {
                    acc.entry(prefix).or_insert(cid);
                    acc
                });
            Some((rank, mapping))
        })
        .collect();

    // Build collective ops mapping
    let collective_by_graph: FxHashMap<(u32, String), Vec<String>> = collective_schedules
        .iter()
        .filter_map(|cs| {
            let m = dir_to_compile_id_per_rank.get(&cs.rank)?;
            let compile_id = m
                .get(&cs.graph)
                .cloned()
                .unwrap_or_else(|| cs.graph.clone());
            Some(((cs.rank, compile_id), cs.ops.clone()))
        })
        .fold(FxHashMap::default(), |mut acc, (key, ops)| {
            acc.entry(key).or_default().extend(ops);
            acc
        });

    // Build cache status mapping
    let cache_status: FxHashMap<(u32, String), String> = rank_nums
        .iter()
        .flat_map(|&rank| {
            cd_by_rank
                .get(&rank)
                .and_then(|obj| {
                    dir_to_compile_id_per_rank
                        .get(&rank)
                        .map(|dir2cid| (obj, dir2cid))
                })
                .map(|(obj, dir2cid)| {
                    let status_by_dir = obj
                        .values()
                        .filter_map(|entry| entry.get("artifacts").and_then(|x| x.as_array()))
                        .flat_map(|arts| arts.iter())
                        .filter_map(|a| {
                            let url = a.get("url")?.as_str()?;
                            let prefix = url.split_once('/')?.0.to_string();
                            let name = a.get("name")?.as_str()?;
                            let status = match () {
                                _ if name.contains("cache_miss") => ("miss", 3),
                                _ if name.contains("cache_hit") => ("hit", 2),
                                _ if name.contains("cache_bypass") => ("bypass", 1),
                                _ => return None,
                            };
                            Some((prefix, status))
                        })
                        .fold(
                            FxHashMap::default(),
                            |mut acc, (prefix, (status, priority))| {
                                acc.entry(prefix)
                                    .and_modify(|e: &mut (&str, u8)| {
                                        if priority > e.1 {
                                            *e = (status, priority);
                                        }
                                    })
                                    .or_insert((status, priority));
                                acc
                            },
                        );

                    status_by_dir
                        .into_iter()
                        .filter_map(|(dir, (st, _))| {
                            let cid = dir2cid.get(&dir)?;
                            Some(((rank, cid.clone()), st.to_string()))
                        })
                        .collect::<Vec<_>>()
                })
                .unwrap_or_default()
        })
        .collect();

    // Analyze and create summary
    let report = analyze_execution_order(&exec_orders, &collective_by_graph, &cache_status);

    let order_differs = report.by_index.iter().any(|row| {
        let uniq: HashSet<_> = row.by_rank.values().map(String::as_str).collect();
        uniq.len() > 1
    });

    let (sched_set, cache_set) = report.by_index.iter().fold(
        (HashSet::new(), HashSet::new()),
        |(mut sched, mut cache), row| {
            if row.issues.contains(&ExecOrderIssue::ScheduleMismatch) {
                sched.extend(row.by_rank.keys());
            }
            if row.issues.contains(&ExecOrderIssue::CacheMismatch) {
                cache.extend(row.by_rank.keys());
            }
            (sched, cache)
        },
    );

    let mut ranks_schedule: Vec<u32> = sched_set.into_iter().collect();
    let mut ranks_cache: Vec<u32> = cache_set.into_iter().collect();
    ranks_schedule.sort_unstable();
    ranks_cache.sort_unstable();

    let format_ranks = |ranks: &[u32]| {
        if ranks.is_empty() {
            String::new()
        } else {
            ranks
                .iter()
                .map(|r| format!("Rank {r}"))
                .collect::<Vec<_>>()
                .join(", ")
        }
    };

    Some(ExecOrderSummary {
        order_differs,
        has_schedule_mismatch: !ranks_schedule.is_empty(),
        has_cache_mismatch: !ranks_cache.is_empty(),
        ranks_schedule_str: format_ranks(&ranks_schedule),
        ranks_cache_str: format_ranks(&ranks_cache),
        ranks_schedule,
        ranks_cache,
    })
}

fn prepare_and_validate_graphs(
    runtime_estimations: &[GraphRuntime],
) -> Option<(
    std::collections::HashMap<u32, Vec<(&str, f64)>>,
    Vec<u32>,
    usize,
)> {
    use std::collections::HashMap;

    let rank_graphs: HashMap<u32, Vec<(&str, f64)>> = runtime_estimations
        .iter()
        .map(|gr| {
            (
                gr.rank,
                &gr.graph,
                gr.ops.iter().map(|op| op.estimated_runtime_ns).sum::<f64>(),
            )
        })
        .fold(HashMap::new(), |mut acc, (rank, graph, runtime)| {
            acc.entry(rank).or_default().push((graph, runtime));
            acc
        });

    let max_graphs = rank_graphs.values().map(|graphs| graphs.len()).max()?;
    let min_graphs = rank_graphs.values().map(|graphs| graphs.len()).min()?;

    if max_graphs != min_graphs {
        return None; // Different number of graphs across ranks
    }

    let mut ranks: Vec<_> = rank_graphs.keys().copied().collect();
    ranks.sort_unstable();

    Some((rank_graphs, ranks, max_graphs))
}

fn compare_graph_runtimes(
    rank_graphs: std::collections::HashMap<u32, Vec<(&str, f64)>>,
    ranks: Vec<u32>,
    max_graphs: usize,
) -> Vec<GraphAnalysis> {
    (0..max_graphs)
        .filter_map(|index| {
            let runtimes: Vec<_> = ranks
                .iter()
                .map(|&rank| {
                    rank_graphs
                        .get(&rank)
                        .and_then(|g| g.get(index))
                        .map(|(graph_id, runtime)| (rank, *graph_id, *runtime))
                })
                .collect::<Option<Vec<_>>>()?;

            let (min_runtime, max_runtime, fastest_rank, slowest_rank) = runtimes.iter().fold(
                (f64::INFINITY, f64::NEG_INFINITY, 0_u32, 0_u32),
                |(min_rt, max_rt, fast_rank, slow_rank), &(rank, _, rt)| {
                    let (new_min_rt, new_fast) = if rt <= min_rt {
                        (rt, rank)
                    } else {
                        (min_rt, fast_rank)
                    };
                    let (new_max_rt, new_slow) = if rt >= max_rt {
                        (rt, rank)
                    } else {
                        (max_rt, slow_rank)
                    };
                    (new_min_rt, new_max_rt, new_fast, new_slow)
                },
            );

            let delta_ns = max_runtime - min_runtime;

            Some(GraphAnalysis {
                graph_index: index,
                graph_id: runtimes[0].1.to_string(),
                delta_ms: (delta_ns / 1e6 * 1000.0).round() / 1000.0,
                rank_details: vec![
                    RuntimeRankDetail {
                        rank: fastest_rank,
                        runtime_ms: (min_runtime / 1e6 * 1000.0).round() / 1000.0,
                    },
                    RuntimeRankDetail {
                        rank: slowest_rank,
                        runtime_ms: (max_runtime / 1e6 * 1000.0).round() / 1000.0,
                    },
                ],
            })
        })
        .collect()
}

pub fn analyze_graph_runtime_deltas(
    runtime_estimations: &[GraphRuntime],
) -> Option<RuntimeAnalysis> {
    let Some((rank_graphs, ranks, max_graphs)) = prepare_and_validate_graphs(runtime_estimations)
    else {
        return Some(RuntimeAnalysis {
            graphs: vec![],
            has_mismatched_graph_counts: true,
        });
    };

    let mut graphs = compare_graph_runtimes(rank_graphs, ranks, max_graphs);
    graphs.sort_by(|a, b| a.graph_id.cmp(&b.graph_id));

    Some(RuntimeAnalysis {
        graphs,
        has_mismatched_graph_counts: false,
    })
}

/// Converts node-based mappings to line number-based mappings for visualization.
///
/// This function processes node mappings and converts them to line number mappings
/// that can be used to highlight corresponding lines across different views.
/// It handles pre-grad graph, post-grad graph, and generated code files.
fn convert_node_mappings_to_line_numbers(
    node_mappings_content: &str,
    pre_grad_graph_content: &str,
    post_grad_graph_content: &str,
    output_code_content: &str,
    aot_code_content: &str,
) -> serde_json::Value {
    // Parse the node mappings JSON
    let node_mappings: serde_json::Value = match serde_json::from_str(node_mappings_content) {
        Ok(mappings) => mappings,
        Err(_) => return serde_json::json!({}),
    };

    let version = node_mappings
        .get("version")
        .and_then(|v| v.as_f64())
        .unwrap_or(1.0) as i64;

    // Helper function to check if a line is valid (not empty and doesn't start with comment)
    fn valid_line(line: &str, symbol: &str) -> bool {
        let stripped = line.trim();
        !stripped.is_empty() && !stripped.starts_with(symbol)
    }

    // Helper function to extract node name from a line
    fn extract_node_name(line: &str) -> Option<String> {
        let trimmed = line.trim();
        if valid_line(trimmed, "#") {
            // Split on '=' and take everything before it
            let before_equals = trimmed.split('=').next()?;
            // Split on ':' and take everything before it
            let node_name = before_equals.split(':').next()?.trim();
            if !node_name.is_empty() {
                return Some(node_name.to_string());
            }
        }
        None
    }

    // Helper function to build node-to-line lookup map from graph content
    fn build_node_to_lines_map(content: &str) -> std::collections::HashMap<String, usize> {
        let mut node_to_lines = std::collections::HashMap::new();
        for (i, line) in content.lines().enumerate() {
            if let Some(node_name) = extract_node_name(line) {
                node_to_lines.insert(node_name, i + 1); // 1-based line numbers
            }
        }
        node_to_lines
    }

    // Helper function to build Python kernel-to-lines lookup map
    fn build_python_kernel_to_lines_map(
        content: &str,
        kernel_names: &[&str],
        _version: i64,
    ) -> std::collections::HashMap<String, Vec<usize>> {
        let content = content
            .lines()
            .skip_while(|line| line.is_empty())
            .collect::<Vec<&str>>()
            .join("\n");
        let mut kernel_to_lines = std::collections::HashMap::new();

        // Find the line number of "def call(args)" - allowing for whitespace between tokens
        let run_impl_line = content
            .lines()
            .position(|line| {
                line.contains("def") && line.contains("call") && line.contains("(args)")
            })
            .unwrap_or(0);
        let first_line_number = content
            .lines()
            .position(|line| line.contains("# AOT ID:"))
            .unwrap_or(0);

        // For each kernel name (e.g. triton_poi_fused_mul_1:2):
        // - Extract pure_kernel_name (triton_poi_fused_mul_1) before the ':'
        // - If kernel name found: map to next line containing pure_kernel_name
        // - If kernel_name not found: map to all lines with pure_kernel_name
        for kernel_name in kernel_names {
            // Get pure kernel name before ':' if it exists
            let pure_kernel_name = if let Some(idx) = kernel_name.find(':') {
                &kernel_name[..idx]
            } else {
                kernel_name
            };

            let mut found = false;
            // If kernel_name contains a debug handle and we found it, we can stop after first match
            if kernel_name.contains(':') {
                for (i, line) in content.lines().enumerate().skip(run_impl_line) {
                    if line.contains(kernel_name) {
                        // Found kernel name, look for next line with pure_kernel_name
                        for (j, next_line) in content.lines().enumerate().skip(i + 1) {
                            if next_line.contains(pure_kernel_name) {
                                kernel_to_lines
                                    .entry(kernel_name.to_string())
                                    .or_insert_with(Vec::new)
                                    .push(j + 1 - first_line_number);
                                found = true;
                                break;
                            }
                        }
                        break;
                    }
                }
            }

            // If exact kernel name not found, map all lines with pure kernel name
            if !found {
                for (i, line) in content.lines().enumerate().skip(run_impl_line) {
                    if line.contains(pure_kernel_name) {
                        kernel_to_lines
                            .entry(kernel_name.to_string())
                            .or_insert_with(Vec::new)
                            .push(i + 1 - first_line_number);
                    }
                }
            }
        }
        kernel_to_lines
    }

    // Helper function to build C++ kernel-to-lines lookup map
    // We only consider lines after "::run_impl(" and skip the empty lines at the beginning when computing line numbers
    fn build_cpp_kernel_to_lines_map(
        content: &str,
        kernel_names: &[&str],
        _version: i64,
    ) -> std::collections::HashMap<String, Vec<usize>> {
        // remove empty lines at the beginning and end of the content
        // We need to do this because empty lines are ignored in html <pre> tags
        let content = content
            .lines()
            .skip_while(|line| line.is_empty())
            .collect::<Vec<&str>>()
            .join("\n");
        let mut kernel_to_lines = std::collections::HashMap::new();

        // Find the line number of "::run_impl("
        let run_impl_line = content
            .lines()
            .position(|line| line.contains("::run_impl("))
            .unwrap_or(0);

        // For each kernel name (e.g. triton_poi_fused_mul_1:2):
        // - Extract pure_kernel_name (triton_poi_fused_mul_1) before the ':'
        // - If kernel name found: map to next line containing pure_kernel_name
        // - If kernel_name not found: map to all lines with pure_kernel_name
        for kernel_name in kernel_names {
            // Get pure kernel name before ':' if it exists
            let pure_kernel_name = if let Some(idx) = kernel_name.rfind(':') {
                &kernel_name[..idx]
            } else {
                kernel_name
            };

            let mut found = false;
            if kernel_name.contains(':') {
                for (i, line) in content.lines().enumerate().skip(run_impl_line) {
                    if valid_line(line, "def")
                        && valid_line(line, "static inline void")
                        && line.contains(kernel_name)
                    {
                        // Found exact kernel name - map to next matching line
                        let next_line = content
                            .lines()
                            .skip(i + 1)
                            // Filter out variable declarations like "int64_t kernel_xnumel_1 = value;" but keep function calls
                            .position(|l| {
                                l.contains(pure_kernel_name)
                                    && !l.contains("_xnumel = ")
                                    && !Regex::new(r"^\s*\w+\s+.*_xnumel(?:_\d+)?\s*=")
                                        .unwrap()
                                        .is_match(l)
                            })
                            .map(|pos| i + pos + 2);

                        if let Some(line_num) = next_line {
                            kernel_to_lines
                                .entry(kernel_name.to_string())
                                .or_insert_with(Vec::new)
                                .push(line_num);
                            found = true;
                            break;
                        }
                    }
                }
            }
            if !found {
                for (i, line) in content.lines().enumerate().skip(run_impl_line) {
                    if line.contains(pure_kernel_name) {
                        kernel_to_lines
                            .entry(kernel_name.to_string())
                            .or_insert_with(Vec::new)
                            .push(i + 1);
                    }
                }
            }
        }
        kernel_to_lines
    }

    // Helper function to process mappings from source to target
    fn process_mappings<F>(
        source_mappings: &serde_json::Map<String, serde_json::Value>,
        source_lookup: &std::collections::HashMap<String, usize>,
        _target_lookup: &std::collections::HashMap<String, usize>,
        target_line_processor: F,
    ) -> std::collections::HashMap<usize, Vec<usize>>
    where
        F: Fn(&str) -> Option<usize>,
    {
        let mut result = std::collections::HashMap::new();

        for (source_node, target_nodes) in source_mappings {
            if let Some(source_line) = source_lookup.get(source_node) {
                let mut target_lines = Vec::new();
                if let Some(target_nodes_array) = target_nodes.as_array() {
                    for target_node in target_nodes_array {
                        if let Some(target_node_str) = target_node.as_str() {
                            if let Some(target_line) = target_line_processor(target_node_str) {
                                target_lines.push(target_line);
                            }
                        }
                    }
                }
                if !target_lines.is_empty() {
                    result.insert(*source_line, target_lines);
                }
            }
        }
        result
    }

    // Helper function to process kernel-to-post mappings
    fn process_kernel_to_post_mappings(
        kernel_mappings: &serde_json::Map<String, serde_json::Value>,
        kernel_lookup: &std::collections::HashMap<String, Vec<usize>>,
        post_lookup: &std::collections::HashMap<String, usize>,
    ) -> std::collections::HashMap<usize, Vec<usize>> {
        let mut result = std::collections::HashMap::new();

        for (kernel_name, post_nodes) in kernel_mappings {
            if let Some(kernel_lines) = kernel_lookup.get(kernel_name) {
                for kernel_line in kernel_lines {
                    let mut target_lines = Vec::new();
                    if let Some(post_nodes_array) = post_nodes.as_array() {
                        for post_node in post_nodes_array {
                            if let Some(post_node_str) = post_node.as_str() {
                                if let Some(post_line) = post_lookup.get(post_node_str) {
                                    target_lines.push(*post_line);
                                }
                            }
                        }
                    }
                    if !target_lines.is_empty() {
                        result.insert(*kernel_line, target_lines);
                    }
                }
            }
        }
        result
    }

    // Helper function to process post-to-kernel mappings
    fn process_post_to_kernel_mappings(
        post_mappings: &serde_json::Map<String, serde_json::Value>,
        post_lookup: &std::collections::HashMap<String, usize>,
        kernel_lookup: &std::collections::HashMap<String, Vec<usize>>,
    ) -> std::collections::HashMap<usize, Vec<usize>> {
        let mut result = std::collections::HashMap::new();

        for (post_node, kernel_names) in post_mappings {
            if let Some(post_line) = post_lookup.get(post_node) {
                let mut target_lines = Vec::new();
                if let Some(kernel_names_array) = kernel_names.as_array() {
                    for kernel_name in kernel_names_array {
                        if let Some(kernel_name_str) = kernel_name.as_str() {
                            if let Some(kernel_lines) = kernel_lookup.get(kernel_name_str) {
                                target_lines.extend(kernel_lines);
                            }
                        }
                    }
                }
                if !target_lines.is_empty() {
                    result.insert(*post_line, target_lines);
                }
            }
        }
        result
    }

    // Helper function to convert HashMap to JSON Map
    fn hashmap_to_json_map(
        map: std::collections::HashMap<usize, Vec<usize>>,
    ) -> serde_json::Map<String, serde_json::Value> {
        map.into_iter()
            .map(|(k, v)| (k.to_string(), serde_json::json!(v)))
            .collect()
    }

    let kernel_names: Vec<&str> = node_mappings
        .get("cppCodeToPost")
        .and_then(|v| v.as_object())
        .map(|obj| obj.keys().map(|k| k.as_str()).collect())
        .unwrap_or_default();

    // Build lookup maps
    let pre_grad_node_to_lines = build_node_to_lines_map(pre_grad_graph_content);
    let post_grad_node_to_lines = build_node_to_lines_map(post_grad_graph_content);
    let py_kernel_to_lines =
        build_python_kernel_to_lines_map(output_code_content, &kernel_names, version);
    let cpp_code_to_lines = build_cpp_kernel_to_lines_map(aot_code_content, &kernel_names, version);

    // Process all mappings using helper functions
    let line_pre_to_post =
        if let Some(pre_to_post) = node_mappings.get("preToPost").and_then(|v| v.as_object()) {
            process_mappings(
                pre_to_post,
                &pre_grad_node_to_lines,
                &post_grad_node_to_lines,
                |node_name| post_grad_node_to_lines.get(node_name).copied(),
            )
        } else {
            std::collections::HashMap::new()
        };

    let line_post_to_pre =
        if let Some(post_to_pre) = node_mappings.get("postToPre").and_then(|v| v.as_object()) {
            process_mappings(
                post_to_pre,
                &post_grad_node_to_lines,
                &pre_grad_node_to_lines,
                |node_name| pre_grad_node_to_lines.get(node_name).copied(),
            )
        } else {
            std::collections::HashMap::new()
        };

    let line_cpp_code_to_post = if let Some(cpp_code_to_post) = node_mappings
        .get("cppCodeToPost")
        .and_then(|v| v.as_object())
    {
        process_kernel_to_post_mappings(
            cpp_code_to_post,
            &cpp_code_to_lines,
            &post_grad_node_to_lines,
        )
    } else {
        std::collections::HashMap::new()
    };

    let line_post_to_cpp_code = if let Some(post_to_cpp_code) = node_mappings
        .get("postToCppCode")
        .and_then(|v| v.as_object())
    {
        process_post_to_kernel_mappings(
            post_to_cpp_code,
            &post_grad_node_to_lines,
            &cpp_code_to_lines,
        )
    } else {
        std::collections::HashMap::new()
    };

    let line_py_code_to_post = if let Some(cpp_code_to_post) = node_mappings
        .get("cppCodeToPost")
        .and_then(|v| v.as_object())
    {
        process_kernel_to_post_mappings(
            cpp_code_to_post,
            &py_kernel_to_lines,
            &post_grad_node_to_lines,
        )
    } else {
        std::collections::HashMap::new()
    };

    let line_post_to_py_code = if let Some(post_to_cpp_code) = node_mappings
        .get("postToCppCode")
        .and_then(|v| v.as_object())
    {
        process_post_to_kernel_mappings(
            post_to_cpp_code,
            &post_grad_node_to_lines,
            &py_kernel_to_lines,
        )
    } else {
        std::collections::HashMap::new()
    };

    // Convert all HashMaps to JSON objects
    serde_json::json!({
        "preToPost": hashmap_to_json_map(line_pre_to_post),
        "postToPre": hashmap_to_json_map(line_post_to_pre),
        "pyCodeToPost": hashmap_to_json_map(line_py_code_to_post),
        "postToPyCode": hashmap_to_json_map(line_post_to_py_code),
        "cppCodeToPost": hashmap_to_json_map(line_cpp_code_to_post),
        "postToCppCode": hashmap_to_json_map(line_post_to_cpp_code)
    })
}

pub mod execution_order {
    use fxhash::FxHashMap;

    /// Issue types detected at a given execution index across ranks
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub enum ExecOrderIssue {
        ScheduleMismatch,
        CacheMismatch,
    }

    /// One row in the execution-order report
    #[derive(Debug, Clone)]
    pub struct ExecOrderIndexRow {
        /// Zero-based index into per-rank execution orders
        pub index: usize,
        /// Mapping: rank -> compile_id (compile directory name)
        pub by_rank: FxHashMap<u32, String>,
        /// Issues found for this index
        pub issues: Vec<ExecOrderIssue>,
    }

    /// Final report for execution-order diagnostics
    #[derive(Debug, Clone, Default)]
    pub struct ExecOrderReport {
        pub by_index: Vec<ExecOrderIndexRow>,
    }

    /// Analyze per-rank execution orders, aligning entries by index and flagging issues
    /// using provided per-graph properties.
    pub fn analyze_execution_order(
        exec_orders: &FxHashMap<u32, Vec<String>>,
        collective_schedule_by_graph: &FxHashMap<(u32, String), Vec<String>>,
        cache_status: &FxHashMap<(u32, String), String>,
    ) -> ExecOrderReport {
        // Determine max length across ranks (N)
        let max_len = exec_orders.values().map(|v| v.len()).max().unwrap_or(0);

        if max_len == 0 || exec_orders.is_empty() {
            return ExecOrderReport::default();
        }

        // Memoize property lookups per (rank, compile_id)
        let mut sched_memo: FxHashMap<(u32, String), Option<Vec<String>>> = FxHashMap::default();
        let mut cache_memo: FxHashMap<(u32, String), Option<String>> = FxHashMap::default();

        let mut rows: Vec<ExecOrderIndexRow> = Vec::with_capacity(max_len);

        for idx in 0..max_len {
            // Gather present ranks and their compile_ids at this index
            let by_rank: FxHashMap<u32, String> = exec_orders
                .iter()
                .filter_map(|(&rank, order)| order.get(idx).cloned().map(|cid| (rank, cid)))
                .collect();

            if by_rank.is_empty() {
                continue;
            }

            // Evaluate issues among present ranks
            let mut issues: Vec<ExecOrderIssue> = Vec::new();

            // Schedule mismatch: compare collective schedules regardless of compile_id
            {
                let schedules: Vec<Vec<String>> = by_rank
                    .iter()
                    .filter_map(|(&rank, cid)| {
                        let key = (rank, cid.clone());
                        let entry = sched_memo
                            .entry((rank, cid.clone()))
                            .or_insert_with(|| collective_schedule_by_graph.get(&key).cloned());
                        entry.clone()
                    })
                    .collect();
                if schedules.len() >= 2 && schedules[1..].iter().any(|s| s != &schedules[0]) {
                    issues.push(ExecOrderIssue::ScheduleMismatch);
                }
            }

            // Cache mismatch: compare cache statuses regardless of compile_id
            {
                let statuses: Vec<String> = by_rank
                    .iter()
                    .filter_map(|(&rank, cid)| {
                        let key = (rank, cid.clone());
                        let entry = cache_memo
                            .entry((rank, cid.clone()))
                            .or_insert_with(|| cache_status.get(&key).cloned());
                        entry.clone().filter(|s| !s.is_empty())
                    })
                    .collect();
                if statuses.len() >= 2 && statuses[1..].iter().any(|s| s != &statuses[0]) {
                    issues.push(ExecOrderIssue::CacheMismatch);
                }
            }

            rows.push(ExecOrderIndexRow {
                index: idx,
                by_rank,
                issues,
            });
        }

        ExecOrderReport { by_index: rows }
    }

    pub fn parse_graph_execution_order(payload: &str) -> anyhow::Result<Vec<String>> {
        let value: serde_json::Value = serde_json::from_str(payload)?;
        let arr = value
            .get("graph_execution_order")
            .and_then(|v| v.as_array())
            .ok_or_else(|| anyhow::anyhow!("missing graph_execution_order array"))?;

        let mut out = Vec::with_capacity(arr.len());
        for item in arr {
            match item {
                serde_json::Value::String(s) => out.push(s.clone()),
                serde_json::Value::Object(map) => {
                    if let Some(s) = map.get("compile_id").and_then(|v| v.as_str()) {
                        out.push(s.to_string());
                    }
                }
                _ => {}
            }
        }
        Ok(out)
    }
}