ferro-hgvs 1.0.0

HGVS variant normalizer - part of the ferro bioinformatics toolkit
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
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
//! cdot JSON parsing for transcript alignments.
//!
//! This module handles loading and parsing cdot JSON files which contain
//! transcript-to-genome alignments used for coordinate mapping.
//!
//! Supports both the real cdot format (with nested genome_builds) and
//! a simplified flat format for testing.
//!
//! # Coordinate Systems
//!
//! **IMPORTANT**: cdot uses MIXED coordinate systems!
//!
//! | Field | Basis | Format |
//! |-------|-------|--------|
//! | Genomic coordinates (`genome_start`, `genome_end`) | HGVS-value-based | Half-open `[start, end)` where `start` equals the numeric HGVS g. position of the first exonic base |
//! | Transcript coordinates (`tx_start`, `tx_end`) | 0-based | Half-open `[start, end)` |
//! | CDS coordinates (`cds_start`, `cds_end`) | 0-based | Half-open `[start, end)` |
//!
//! **Note on genomic coordinates**: `genome_start` stores the numeric value of the first HGVS
//! g. position in the exon (e.g., an exon starting at g.1000 has `genome_start = 1000`).
//! `genome_end` is one past the last HGVS g. position (exclusive). This differs from a
//! strict 0-based system: an exon at g.1000–g.1008 has `genome_start = 1000, genome_end = 1009`.
//!
//! For type-safe coordinate handling, see [`crate::coords`].

use crate::error::FerroError;
use crate::hgvs::location::CdsPos;
use crate::liftover::aliases::ContigAliases;
use crate::reference::transcript::GenomeBuild;
use crate::reference::Strand;
use bincode::Options;
use once_cell::sync::OnceCell;
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufReader, Read, Write};
use std::path::{Path, PathBuf};
use superintervals::IntervalMap;

/// rkyv-archivable mirror of the cdot cache. Kept fully separate from the
/// domain types (`CdotTranscript`, `Strand`, `CigarOp`) so the rkyv derives —
/// and the choice of an `i8` strand / flattened cigar encoding — stay contained
/// to the cache layer. `from_rkyv_file`/`to_rkyv_file` convert at the boundary.
mod rkyv_cache {
    use super::{CdotMapper, CdotTranscript, CigarOp};
    use crate::error::FerroError;
    use crate::reference::Strand;
    use rkyv::{Archive, Deserialize, Serialize};
    use rustc_hash::FxHashMap;
    use std::collections::HashMap;

    /// Bump whenever the layout below changes so a stale archive is rejected by
    /// the version check (in addition to rkyv's own structural validation) and
    /// regenerated rather than mis-read.
    // v2 (#742): exon coordinates are now stored in the HGVS convention
    // (genome 1-based, tx 0-based half-open); a v1 cache holds the old raw
    // cdot convention and must be regenerated.
    // v3 (#972): `RkyvTx` gained `cds_start_incomplete`; a v2 cache has no such
    // field and would silently rehydrate every transcript as "complete".
    pub(super) const RKYV_FORMAT_VERSION: u32 = 3;

    #[derive(Archive, Serialize, Deserialize)]
    pub(super) struct RkyvCigar {
        /// 0 = Match, 1 = Insertion, 2 = Deletion.
        op: u8,
        len: u64,
    }

    #[derive(Archive, Serialize, Deserialize)]
    pub(super) struct RkyvTx {
        gene_name: Option<String>,
        contig: String,
        /// 1 = Plus, -1 = Minus, 0 = Unknown.
        strand: i8,
        exons: Vec<[u64; 4]>,
        cds_start: Option<u64>,
        cds_end: Option<u64>,
        exon_cigars: Vec<Option<Vec<RkyvCigar>>>,
        gene_id: Option<String>,
        protein: Option<String>,
        cds_start_incomplete: bool,
    }

    #[derive(Archive, Serialize, Deserialize)]
    pub(super) struct RkyvSnapshot {
        /// Format version — first field so a mismatch is a clean signal.
        pub(super) format_version: u32,
        pub(super) transcripts: HashMap<String, RkyvTx>,
        pub(super) contig_index: HashMap<String, Vec<String>>,
        pub(super) contig_alias_to_canonical: HashMap<String, String>,
        pub(super) base_to_versioned: HashMap<String, String>,
        pub(super) lrg_to_refseq: HashMap<String, String>,
        pub(super) primary_build: Option<String>,
        pub(super) alt_build_transcripts: HashMap<String, HashMap<String, RkyvTx>>,
    }

    fn strand_to_i8(s: Strand) -> i8 {
        match s {
            Strand::Plus => 1,
            Strand::Minus => -1,
            Strand::Unknown => 0,
        }
    }
    /// Reject unknown tags rather than coercing them: a corrupt `.rkyv` whose
    /// strand byte is out of range must be regenerated, not silently read back
    /// as `Strand::Unknown`.
    fn strand_from_i8(v: i8) -> Result<Strand, FerroError> {
        match v {
            1 => Ok(Strand::Plus),
            -1 => Ok(Strand::Minus),
            0 => Ok(Strand::Unknown),
            other => Err(FerroError::Io {
                msg: format!("cdot rkyv archive has invalid strand tag {other}"),
            }),
        }
    }
    fn cigar_to_rkyv(c: &CigarOp) -> RkyvCigar {
        match *c {
            CigarOp::Match(n) => RkyvCigar { op: 0, len: n },
            CigarOp::Insertion(n) => RkyvCigar { op: 1, len: n },
            CigarOp::Deletion(n) => RkyvCigar { op: 2, len: n },
        }
    }

    pub(super) fn tx_to_rkyv(t: &CdotTranscript) -> RkyvTx {
        RkyvTx {
            gene_name: t.gene_name.clone(),
            contig: t.contig.clone(),
            strand: strand_to_i8(t.strand),
            exons: t.exons.clone(),
            cds_start: t.cds_start,
            cds_end: t.cds_end,
            exon_cigars: t
                .exon_cigars
                .iter()
                .map(|opt| opt.as_ref().map(|v| v.iter().map(cigar_to_rkyv).collect()))
                .collect(),
            gene_id: t.gene_id.clone(),
            protein: t.protein.clone(),
            cds_start_incomplete: t.cds_start_incomplete,
        }
    }

    /// Reject unknown op tags rather than coercing them to `Match`, for the same
    /// reason as [`strand_from_i8`].
    fn cigar_from_archived(a: &ArchivedRkyvCigar) -> Result<CigarOp, FerroError> {
        let len = a.len.to_native();
        match a.op {
            0 => Ok(CigarOp::Match(len)),
            1 => Ok(CigarOp::Insertion(len)),
            2 => Ok(CigarOp::Deletion(len)),
            other => Err(FerroError::Io {
                msg: format!("cdot rkyv archive has invalid cigar op tag {other}"),
            }),
        }
    }

    /// Build a `CdotTranscript` directly from the archived form — a single pass,
    /// avoiding an intermediate owned `RkyvTx`. Returns an error if any archived
    /// enum tag (strand, cigar op) is out of range, so a corrupt archive is
    /// rejected and regenerated rather than materialized with wrong data.
    fn tx_from_archived(a: &ArchivedRkyvTx) -> Result<CdotTranscript, FerroError> {
        Ok(CdotTranscript {
            gene_name: a.gene_name.as_ref().map(|s| s.as_str().to_string()),
            contig: a.contig.as_str().to_string(),
            strand: strand_from_i8(a.strand)?,
            exons: a
                .exons
                .iter()
                .map(|e| {
                    [
                        e[0].to_native(),
                        e[1].to_native(),
                        e[2].to_native(),
                        e[3].to_native(),
                    ]
                })
                .collect(),
            cds_start: a.cds_start.as_ref().map(|v| v.to_native()),
            cds_end: a.cds_end.as_ref().map(|v| v.to_native()),
            exon_cigars: a
                .exon_cigars
                .iter()
                .map(|opt| {
                    opt.as_ref()
                        .map(|v| {
                            v.iter()
                                .map(cigar_from_archived)
                                .collect::<Result<Vec<_>, _>>()
                        })
                        .transpose()
                })
                .collect::<Result<Vec<_>, _>>()?,
            gene_id: a.gene_id.as_ref().map(|s| s.as_str().to_string()),
            protein: a.protein.as_ref().map(|s| s.as_str().to_string()),
            // Plain `bool` in the archived form — no `.to_native()` needed.
            cds_start_incomplete: a.cds_start_incomplete,
        })
    }

    /// Owned cdot maps materialized directly from an archive (one pass).
    pub(super) struct CdotMaps {
        pub transcripts: FxHashMap<String, CdotTranscript>,
        pub contig_index: FxHashMap<String, Vec<String>>,
        pub contig_alias_to_canonical: FxHashMap<String, String>,
        pub base_to_versioned: FxHashMap<String, String>,
        pub lrg_to_refseq: FxHashMap<String, String>,
        pub primary_build: Option<String>,
        pub alt_build_transcripts: FxHashMap<String, FxHashMap<String, CdotTranscript>>,
    }

    pub(super) fn version_of(a: &ArchivedRkyvSnapshot) -> u32 {
        a.format_version.to_native()
    }

    /// Materialize owned cdot maps from a validated archive in a single pass.
    /// Returns an error if any transcript carries an out-of-range enum tag.
    pub(super) fn maps_from_archived(a: &ArchivedRkyvSnapshot) -> Result<CdotMaps, FerroError> {
        // Pre-size each runtime map to the archive's known entry count. The
        // `ArchivedHashMap` iterators do not report an exact `size_hint`, so a
        // plain `collect()` under-reserves and rehashes repeatedly while
        // rebuilding millions of entries; reserving up front removes that.
        let txs = |m: &rkyv::collections::swiss_table::ArchivedHashMap<
            rkyv::string::ArchivedString,
            ArchivedRkyvTx,
        >|
         -> Result<FxHashMap<String, CdotTranscript>, FerroError> {
            let mut out = FxHashMap::with_capacity_and_hasher(m.len(), Default::default());
            for (k, v) in m.iter() {
                out.insert(k.as_str().to_string(), tx_from_archived(v)?);
            }
            Ok(out)
        };
        let str_map = |m: &rkyv::collections::swiss_table::ArchivedHashMap<
            rkyv::string::ArchivedString,
            rkyv::string::ArchivedString,
        >|
         -> FxHashMap<String, String> {
            let mut out = FxHashMap::with_capacity_and_hasher(m.len(), Default::default());
            for (k, v) in m.iter() {
                out.insert(k.as_str().to_string(), v.as_str().to_string());
            }
            out
        };
        let mut contig_index =
            FxHashMap::with_capacity_and_hasher(a.contig_index.len(), Default::default());
        for (k, v) in a.contig_index.iter() {
            contig_index.insert(
                k.as_str().to_string(),
                v.iter().map(|s| s.as_str().to_string()).collect(),
            );
        }
        let mut alt_build_transcripts =
            FxHashMap::with_capacity_and_hasher(a.alt_build_transcripts.len(), Default::default());
        for (b, m) in a.alt_build_transcripts.iter() {
            alt_build_transcripts.insert(b.as_str().to_string(), txs(m)?);
        }
        Ok(CdotMaps {
            transcripts: txs(&a.transcripts)?,
            contig_index,
            contig_alias_to_canonical: str_map(&a.contig_alias_to_canonical),
            base_to_versioned: str_map(&a.base_to_versioned),
            lrg_to_refseq: str_map(&a.lrg_to_refseq),
            primary_build: a.primary_build.as_ref().map(|s| s.as_str().to_string()),
            alt_build_transcripts,
        })
    }

    /// Build the rkyv snapshot mirror from a populated mapper (serialize side).
    pub(super) fn snapshot_from_mapper(m: &CdotMapper) -> RkyvSnapshot {
        let map = |src: &FxHashMap<String, CdotTranscript>| -> HashMap<String, RkyvTx> {
            src.iter()
                .map(|(k, v)| (k.clone(), tx_to_rkyv(v)))
                .collect()
        };
        RkyvSnapshot {
            format_version: RKYV_FORMAT_VERSION,
            transcripts: map(&m.transcripts),
            // Re-collect the runtime `FxHashMap`s into plain `HashMap`s so the
            // archived (on-disk) layout is unchanged by the runtime hasher swap.
            contig_index: m
                .contig_index
                .iter()
                .map(|(k, v)| (k.clone(), v.clone()))
                .collect(),
            contig_alias_to_canonical: m
                .contig_alias_to_canonical
                .iter()
                .map(|(k, v)| (k.clone(), v.clone()))
                .collect(),
            base_to_versioned: m
                .base_to_versioned
                .iter()
                .map(|(k, v)| (k.clone(), v.clone()))
                .collect(),
            lrg_to_refseq: m
                .lrg_to_refseq
                .iter()
                .map(|(k, v)| (k.clone(), v.clone()))
                .collect(),
            primary_build: m.primary_build.clone(),
            alt_build_transcripts: m
                .alt_build_transcripts
                .iter()
                .map(|(b, txs)| (b.clone(), map(txs)))
                .collect(),
        }
    }

    /// Serialize a current-version archive carrying a single transcript whose
    /// `strand` / `cigar op` bytes are forced to the given (possibly invalid)
    /// raw tags. Lets tests exercise the archive-tag rejection path without
    /// going through `strand_to_i8` / `cigar_to_rkyv`, whose construction can
    /// only ever produce valid tags. The archive passes structural and version
    /// validation, so any rejection comes purely from tag checking.
    #[cfg(test)]
    pub(super) fn archive_bytes_with_tags(strand: i8, cigar_op: u8) -> Vec<u8> {
        let tx = RkyvTx {
            gene_name: None,
            contig: "NC_000017.11".to_string(),
            strand,
            exons: vec![[50184096, 50184169, 0, 73]],
            cds_start: Some(10),
            cds_end: Some(60),
            exon_cigars: vec![Some(vec![RkyvCigar {
                op: cigar_op,
                len: 73,
            }])],
            gene_id: None,
            protein: None,
            cds_start_incomplete: false,
        };
        let mut transcripts = HashMap::new();
        transcripts.insert("NM_000088.3".to_string(), tx);
        let snapshot = RkyvSnapshot {
            format_version: RKYV_FORMAT_VERSION,
            transcripts,
            contig_index: HashMap::new(),
            contig_alias_to_canonical: HashMap::new(),
            base_to_versioned: HashMap::new(),
            lrg_to_refseq: HashMap::new(),
            primary_build: None,
            alt_build_transcripts: HashMap::new(),
        };
        rkyv::to_bytes::<rkyv::rancor::Error>(&snapshot)
            .expect("serialize test archive")
            .to_vec()
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use crate::reference::Strand as DomainStrand;

        /// #972 round-trip: `cds_start_incomplete = true` must survive
        /// `tx_to_rkyv` -> (serialize/archive) -> `tx_from_archived`. Without
        /// this the field is silently dropped by the rkyv cache and every
        /// transcript rehydrates as "complete" regardless of the source JSON.
        #[test]
        fn cds_start_incomplete_round_trips_through_rkyv() {
            let cdot_tx = CdotTranscript {
                gene_name: Some("TEST".to_string()),
                contig: "NC_000001.11".to_string(),
                strand: DomainStrand::Plus,
                exons: vec![[1, 100, 0, 99]],
                cds_start: Some(0),
                cds_end: Some(99),
                exon_cigars: vec![None],
                gene_id: None,
                protein: None,
                cds_start_incomplete: true,
            };

            let rkyv_tx = tx_to_rkyv(&cdot_tx);
            let bytes = rkyv::to_bytes::<rkyv::rancor::Error>(&rkyv_tx).expect("serialize RkyvTx");
            let archived = rkyv::access::<ArchivedRkyvTx, rkyv::rancor::Error>(&bytes)
                .expect("access archived RkyvTx");

            let round_tripped = tx_from_archived(archived).expect("deserialize RkyvTx");
            assert!(round_tripped.cds_start_incomplete);
        }
    }
}

/// Magic bytes prefixing a cdot bincode cache file, followed by a `u32`
/// schema version. The version MUST be bumped whenever the serialized layout
/// of [`CdotMapperSnapshot`] changes (a field added/removed/reordered, or a
/// nested type's layout changes), so a cache written by an older build is
/// detected as stale and refreshed rather than silently mis-deserialized.
///
/// Without this guard a layout change makes `bincode` read past the end of the
/// file (`failed to fill whole buffer`) only *after* a partial read, and the
/// loader falls back to parsing the multi-hundred-MB JSON on every run — ~10x
/// slower — with no indication anything is wrong.
const CDOT_BINCODE_MAGIC: [u8; 4] = *b"FCDT";
// v2 (#742): exon coordinates now stored in the HGVS convention (genome
// 1-based, tx 0-based half-open); a v1 cache holds the old raw cdot convention.
// v3 (#972): `CdotTranscriptSnapshot` gained `cds_start_incomplete`; a v2
// cache has no such field and bincode's positional layout would otherwise
// misread the following bytes.
const CDOT_BINCODE_VERSION: u32 = 3;

/// Parse the integer version suffix of an accession (`"NM_003002.4"` -> `Some(4)`),
/// or `None` when there is no trailing numeric `.<n>`. Used to pick the highest
/// version deterministically when resolving a base accession to a specific one.
fn accession_version(accession: &str) -> Option<u32> {
    accession
        .split('.')
        .nth(1)
        .and_then(|v| v.parse::<u32>().ok())
}

/// cdot transcript alignment data (normalized internal representation).
///
/// # Coordinate Systems
/// - Genomic: HGVS-value-based half-open `[start, end)` (see module-level docs)
/// - Transcript (tx_start/tx_end in exons): 0-based half-open `[start, end)`
/// - CDS: 0-based half-open `[start, end)` in transcript space
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CdotTranscript {
    /// Gene name/symbol (e.g., "BRCA1").
    #[serde(default)]
    pub gene_name: Option<String>,

    /// Genomic contig/chromosome (e.g., "NC_000017.11").
    #[serde(alias = "contig", alias = "chr")]
    pub contig: String,

    /// Strand (+ or -).
    #[serde(deserialize_with = "deserialize_strand")]
    pub strand: Strand,

    /// Exon alignments: [genome_start(HGVS-val), genome_end(HGVS-val excl), tx_start(0-based), tx_end(0-based excl)].
    pub exons: Vec<[u64; 4]>,

    /// Start of CDS in transcript coordinates (0-based, inclusive).
    #[serde(default)]
    pub cds_start: Option<u64>,

    /// End of CDS in transcript coordinates (0-based, exclusive).
    #[serde(default)]
    pub cds_end: Option<u64>,

    /// Per-exon CIGAR alignment data from cdot gap info (GFF3 Gap format).
    /// Indexed in the same order as `exons` (sorted by tx position).
    #[serde(skip)]
    pub exon_cigars: Vec<Option<Vec<CigarOp>>>,

    /// Gene ID (e.g., "HGNC:1100").
    #[serde(default)]
    pub gene_id: Option<String>,

    /// Protein accession (e.g., "NP_000079.2").
    #[serde(default)]
    pub protein: Option<String>,

    /// True when the transcript's 5′ CDS is annotated incomplete (Ensembl
    /// `cds_start_NF`): the ATG start codon is not present, so `c.1`/`p.1` are
    /// undefined and the coding axis must not be described (HGVS #972).
    #[serde(default)]
    pub cds_start_incomplete: bool,
}

/// Raw cdot transcript entry as it appears in the JSON file.
/// The real cdot format nests genome-specific data under genome_builds.
#[derive(Debug, Clone, Deserialize)]
#[allow(dead_code)] // Fields used for serde deserialization
struct RawCdotTranscript {
    #[serde(default)]
    gene_name: Option<String>,
    #[serde(default)]
    gene_version: Option<String>,
    #[serde(default)]
    biotype: Option<Vec<String>>,
    /// Protein accession for the transcript's CDS (e.g. `NP_000068.1`). cdot
    /// records this per-transcript; plumbing it through lets the projector
    /// emit the correct `p.` accession. When it is absent the projector falls
    /// back to the transcript id itself, never the (frequently wrong) `NM_*` →
    /// `NP_*` number-preserving inference, which was removed in #808 because
    /// RefSeq does not guarantee the NM and NP numbers match.
    #[serde(default)]
    protein: Option<String>,
    #[serde(default)]
    genome_builds: Option<HashMap<String, RawGenomeBuild>>,
    /// CDS start in transcript coordinates (0-indexed)
    #[serde(default)]
    start_codon: Option<u64>,
    /// CDS end in transcript coordinates (0-indexed, exclusive)
    #[serde(default)]
    stop_codon: Option<u64>,
    // Flat format fields (for backwards compatibility)
    #[serde(default)]
    contig: Option<String>,
    #[serde(default)]
    strand: Option<String>,
    #[serde(default)]
    exons: Option<Vec<Vec<serde_json::Value>>>,
    #[serde(default)]
    cds_start: Option<u64>,
    #[serde(default)]
    cds_end: Option<u64>,
}

/// Genome build specific data in cdot format.
#[derive(Debug, Clone, Deserialize)]
struct RawGenomeBuild {
    contig: String,
    #[serde(default)]
    strand: Option<String>,
    /// Exons in cdot format: [genomic_start, genomic_end, exon_num, tx_start, tx_end, gap_info]
    exons: Vec<Vec<serde_json::Value>>,
    /// CDS start in raw cdot genomic coordinates (0-based, inclusive — same space
    /// as the raw exon `alt_start`). The genomic-CDS fallback in `from_genome_build`
    /// must `+ 1` this to match the 1-based exon table before mapping it to tx.
    #[serde(default)]
    cds_start: Option<u64>,
    /// CDS end in raw cdot genomic coordinates (0-based, **exclusive** — same
    /// space as the raw exon `alt_end`).
    ///
    /// A 0-based exclusive end and a 1-based inclusive one are the same number,
    /// so this value already *is* the 1-based coordinate of the last coding
    /// base. The genomic-CDS fallback in `from_genome_build` therefore maps it
    /// as-is — unlike `cds_start`, it takes no `+ 1`. That asymmetry is the
    /// whole content of this comment; see the fallback for the measurement that
    /// settles it.
    #[serde(default)]
    cds_end: Option<u64>,
    /// GENCODE/Ensembl completeness + status tags (e.g. `cds_start_NF`,
    /// `mRNA_start_NF`, `MANE_Select`), comma-joined in cdot. Absent for RefSeq.
    #[serde(default)]
    tag: Option<String>,
}

impl RawCdotTranscript {
    /// Convert raw transcript to internal format for a specific genome build.
    fn to_transcript(&self, genome_build: &str) -> Option<CdotTranscript> {
        // Try genome_builds first (real cdot format)
        if let Some(builds) = &self.genome_builds {
            if let Some(build) = builds.get(genome_build) {
                return self.from_genome_build(build);
            }
        }

        // Fall back to flat format
        self.from_flat_format()
    }

    /// Convert from nested genome_builds format.
    #[allow(clippy::wrong_self_convention)]
    fn from_genome_build(&self, build: &RawGenomeBuild) -> Option<CdotTranscript> {
        let strand = parse_strand(build.strand.as_deref().unwrap_or("+"))?;

        // Ensembl marks a transcript whose 5′ CDS lacks a confirmed ATG start
        // (no start codon in the annotation) with the `cds_start_NF` tag,
        // comma-joined alongside other status tags (e.g. `mRNA_start_NF`,
        // `MANE_Select`). Detection is tag-only — never key off `start_codon
        // == 0`/`None`, which also holds for legitimately-complete transcripts
        // (e.g. MANE Select) and would false-positive (#972).
        let cds_start_incomplete = build
            .tag
            .as_deref()
            .is_some_and(crate::reference::transcript::tags_mark_cds_start_nf);

        // Parse exons: [genomic_start, genomic_end, exon_num, tx_start, tx_end, gap_info]
        //
        // A row that cannot yield all four placement coordinates — because it is
        // truncated (fewer than the five leading fields) or carries a non-numeric
        // value where a coordinate belongs — is *malformed input*, and the whole
        // transcript is refused rather than the row silently dropped. Dropping it
        // (the prior `filter_map` behaviour) removes an exon from the table, which
        // opens a gap and displaces the derived CDS bounds *forward* — a
        // well-formed, in-bounds-looking, silently-wrong coordinate — instead of
        // surfacing the corruption (#1924; the drop was documented at
        // `reference/validate.rs`). Refusal is checkable; a displaced coordinate
        // is not. Every one of the 12,207,712 exon rows across 1,254,949
        // builds — the three shipped cdot-0.2.32 files (RefSeq and Ensembl
        // GRCh38, plus GRCh37) — carries all six fields, so a shorter or
        // non-numeric row is malformed input, not a supported shape.
        //
        // The `gap_info` field (index 5) is deliberately *not* required: a valid
        // exon may legitimately omit it (no CIGAR), and a malformed CIGAR string
        // in a present sixth field is handled locally (warn + no CIGAR) rather
        // than refusing the transcript.
        let mut exon_pairs: Vec<([u64; 4], Option<Vec<CigarOp>>)> =
            Vec::with_capacity(build.exons.len());
        for e in &build.exons {
            // cdot stores genomic bounds 0-based half-open (`alt_start`
            // 0-based inclusive, `alt_end` 0-based exclusive) and cDNA
            // bounds 1-based **inclusive** (`cds_start_i`/`cds_end_i`).
            // `Exon` + every mapping primitive (and the fixtures) use the
            // *HGVS* convention: genome 1-based (`genome_start` inclusive,
            // `genome_end` exclusive) and tx 0-based half-open. Convert
            // here so the in-memory layout matches that contract — leaving
            // it raw made the two off-by-ones cancel only for exon-interior
            // positions, mis-mapping the last cDNA base of each exon and
            // dropping the first base of the next (#742).
            let coords = (
                e.first().and_then(serde_json::Value::as_u64),
                e.get(1).and_then(serde_json::Value::as_u64),
                e.get(3).and_then(serde_json::Value::as_u64),
                e.get(4).and_then(serde_json::Value::as_u64),
            );
            let (
                Some(genome_start_0based),
                Some(genome_end_0based),
                Some(tx_start_1based),
                Some(tx_end),
            ) = coords
            else {
                log::warn!(
                    "Refusing malformed transcript (gene {:?}, contig {}): cdot exon \
                     row {:?} lacks the required genomic/transcript coordinates",
                    self.gene_name,
                    build.contig,
                    e
                );
                return None;
            };
            let exon = [
                genome_start_0based + 1, // genome_start: 0-based incl → 1-based incl
                genome_end_0based + 1,   // genome_end: 0-based excl → 1-based excl
                tx_start_1based.saturating_sub(1), // tx_start: 1-based incl → 0-based incl
                tx_end,                  // tx_end: 1-based incl → 0-based excl (same value)
            ];
            // Parse CIGAR gap info from index 5 if present
            let cigar =
                e.get(5)
                    .and_then(serde_json::Value::as_str)
                    .and_then(|s| match parse_cigar(s) {
                        Ok(ops) => Some(ops),
                        Err(err) => {
                            log::warn!("Malformed CIGAR string '{}': {}", s, err);
                            None
                        }
                    });
            exon_pairs.push((exon, cigar));
        }

        // Sort exons by transcript position, keeping CIGARs in sync
        exon_pairs.sort_by_key(|(e, _)| e[2]);
        let (exons, exon_cigars): (Vec<[u64; 4]>, Vec<Option<Vec<CigarOp>>>) =
            exon_pairs.into_iter().unzip();

        // Use transcript-level CDS coordinates (start_codon/stop_codon) if available
        // These are 0-indexed and more reliable than converting from genomic coords
        let (cds_start, cds_end) = if self.start_codon.is_some() || self.stop_codon.is_some() {
            // Use transcript-level coordinates directly (0-indexed)
            (self.start_codon, self.stop_codon)
        } else {
            // Fall back to converting genomic CDS coordinates to transcript coordinates
            match (build.cds_start, build.cds_end) {
                (Some(g_start), Some(g_end)) => {
                    // `build.cds_start`/`cds_end` are raw cdot genomic bounds,
                    // 0-based half-open, in the same space as the raw exon
                    // `alt_start`/`alt_end`. `exons` was converted to the HGVS
                    // 1-based convention above (`e[0] + 1` / `e[1] + 1`), so both
                    // endpoints must be restated 1-based before being scanned
                    // against that table (#742).
                    //
                    // `genomic_to_tx_pos` maps a genomic *position*, never a
                    // half-open bound, so each endpoint must name a base that is
                    // actually coding. Only ONE of the two takes a `+ 1`:
                    //
                    //   - first coding base, 1-based = `g_start + 1`
                    //     (0-based inclusive -> 1-based inclusive), and
                    //   - last coding base, 1-based = `g_end`
                    //     (0-based exclusive and 1-based inclusive are the same
                    //     number, so the restatement is the identity).
                    //
                    // Mapping `g_end + 1` walks one base past the CDS, and the
                    // `+ 1` below then makes the served CDS one base too long on
                    // every transcript — on the plus strand `cds_end` lands a base
                    // past the stop codon, on the minus strand `cds_start` lands a
                    // base before the ATG. Measured over cdot-0.2.32 GRCh38 by
                    // replaying this arithmetic over every build: with `g_end + 1`
                    // the mapped CDS length is not a whole number of codons for
                    // 354,187 of 355,590 RefSeq coding builds and 253,433 of
                    // 266,774 Ensembl ones; with `g_end` it is whole for 355,450
                    // and agrees with the record's own `start_codon`/`stop_codon`
                    // for all 266,774 Ensembl builds.
                    //
                    // Read the RefSeq denominator precisely, because two nearby
                    // ones differ by exactly one and both are correct for their
                    // own population: **355,591** GRCh38 builds carry a genomic
                    // CDS (both `cds_start` and `cds_end`), and **355,590** of
                    // those belong to a record that also carries both codon
                    // fields — which is the population the comparison column
                    // above is over. The single difference is `NM_001077693.2`,
                    // the one GRCh38 record carrying `stop_codon` but no
                    // `start_codon`. (Ensembl GRCh38 has no such record, which is
                    // why its 266,774 is the same number in both readings.)
                    let tx_cds_start = genomic_to_tx_pos(&exons, g_start + 1, strand);
                    let tx_cds_end = genomic_to_tx_pos(&exons, g_end, strand);

                    match (tx_cds_start, tx_cds_end) {
                        (Some(s), Some(e)) => {
                            // Both endpoints now name a coding base. Which is the
                            // last one in transcript order depends on the strand,
                            // so order them and make the upper bound exclusive.
                            // Use saturating_add to prevent overflow at u64::MAX
                            let (start, end) = if s < e {
                                (s, e.saturating_add(1))
                            } else {
                                (e, s.saturating_add(1))
                            };
                            (Some(start), Some(end))
                        }
                        _ => (None, None),
                    }
                }
                _ => (None, None),
            }
        };

        Some(CdotTranscript {
            gene_name: self.gene_name.clone(),
            contig: build.contig.clone(),
            strand,
            exons,
            exon_cigars,
            cds_start,
            cds_end,
            gene_id: None,
            protein: self.protein.clone(),
            cds_start_incomplete,
        })
    }

    /// Convert from flat format (for backwards compatibility).
    #[allow(clippy::wrong_self_convention)]
    fn from_flat_format(&self) -> Option<CdotTranscript> {
        let contig = self.contig.as_ref()?.clone();
        let strand = parse_strand(self.strand.as_deref().unwrap_or("+"))?;

        let exons: Vec<[u64; 4]> = self
            .exons
            .as_ref()?
            .iter()
            .filter_map(|e| {
                if e.len() >= 4 {
                    Some([
                        e[0].as_u64()?,
                        e[1].as_u64()?,
                        e[2].as_u64()?,
                        e[3].as_u64()?,
                    ])
                } else {
                    None
                }
            })
            .collect();

        Some(CdotTranscript {
            gene_name: self.gene_name.clone(),
            contig,
            strand,
            exon_cigars: Vec::new(),
            exons,
            cds_start: self.cds_start,
            cds_end: self.cds_end,
            gene_id: None,
            protein: self.protein.clone(),
            // Flat test format predates this field; Task 2 covers real ingestion.
            cds_start_incomplete: false,
        })
    }
}

/// Parse strand string to Strand enum.
fn parse_strand(s: &str) -> Option<Strand> {
    match s {
        "+" | "1" | "plus" => Some(Strand::Plus),
        "-" | "-1" | "minus" => Some(Strand::Minus),
        _ => None,
    }
}

/// Convert genomic position to transcript position using exon data.
fn genomic_to_tx_pos(exons: &[[u64; 4]], genomic_pos: u64, strand: Strand) -> Option<u64> {
    for e in exons {
        let (g_start, g_end, tx_start, _tx_end) = (e[0], e[1], e[2], e[3]);
        if genomic_pos >= g_start && genomic_pos < g_end {
            let offset = match strand {
                Strand::Plus => genomic_pos - g_start,
                Strand::Minus => g_end - 1 - genomic_pos,
                Strand::Unknown => return None,
            };
            return Some(tx_start + offset);
        }
    }
    // Position not in an exon - find closest exon boundary
    // This handles CDS boundaries that might be at intron edges
    for e in exons {
        let (g_start, g_end, tx_start, tx_end) = (e[0], e[1], e[2], e[3]);
        if genomic_pos == g_end {
            return Some(tx_end);
        }
        if genomic_pos == g_start.saturating_sub(1) {
            return Some(tx_start.saturating_sub(1));
        }
    }
    None
}

/// Deserialize strand from string.
fn deserialize_strand<'de, D>(deserializer: D) -> Result<Strand, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let s = String::deserialize(deserializer)?;
    match s.as_str() {
        "+" | "1" | "plus" => Ok(Strand::Plus),
        "-" | "-1" | "minus" => Ok(Strand::Minus),
        _ => Err(serde::de::Error::custom(format!("Invalid strand: {}", s))),
    }
}

/// Parsed exon with named fields for clarity.
///
/// # Coordinate Systems
/// - Genomic coordinates: HGVS-value-based half-open `[genome_start, genome_end)` where
///   `genome_start` equals the numeric value of the first HGVS g. position in the exon
///   and `genome_end` is one past the last (exclusive). For example, an exon spanning
///   g.1000–g.1008 has `genome_start = 1000`, `genome_end = 1009`.
/// - Transcript coordinates: 0-based half-open `[tx_start, tx_end)` where `tx_start = 0`
///   for the first base of the transcript. `contains_tx_pos` uses `pos >= tx_start && pos < tx_end`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Exon {
    /// Exon number (1-based).
    pub number: u32,
    /// Start position in genomic coordinates (HGVS-value-based, inclusive).
    /// Equals the numeric value of the first HGVS g. position in the exon.
    pub genome_start: u64,
    /// End position in genomic coordinates (HGVS-value-based, exclusive).
    /// Equals genome_start + exon_length.
    pub genome_end: u64,
    /// Start position in transcript coordinates (0-based, inclusive).
    pub tx_start: u64,
    /// End position in transcript coordinates (0-based, exclusive).
    pub tx_end: u64,
}

impl Exon {
    /// Create an exon from cdot array format.
    pub fn from_array(number: u32, arr: [u64; 4]) -> Self {
        Self {
            number,
            genome_start: arr[0],
            genome_end: arr[1],
            tx_start: arr[2],
            tx_end: arr[3],
        }
    }

    /// Get the length of this exon.
    pub fn len(&self) -> u64 {
        self.genome_end - self.genome_start
    }

    /// Check if the exon is empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Check if a genomic position is within this exon.
    pub fn contains_genome_pos(&self, pos: u64) -> bool {
        pos >= self.genome_start && pos < self.genome_end
    }

    /// Check if a transcript position is within this exon.
    pub fn contains_tx_pos(&self, pos: u64) -> bool {
        pos >= self.tx_start && pos < self.tx_end
    }
}

impl CdotTranscript {
    /// Get exons as structured objects.
    pub fn get_exons(&self) -> Vec<Exon> {
        self.exons
            .iter()
            .enumerate()
            .map(|(i, arr)| Exon::from_array((i + 1) as u32, *arr))
            .collect()
    }

    /// Get total transcript length (sum of exon lengths).
    pub fn transcript_length(&self) -> u64 {
        self.exons.iter().map(|e| e[3] - e[2]).sum()
    }

    /// Get CDS length if CDS is defined.
    pub fn cds_length(&self) -> Option<u64> {
        match (self.cds_start, self.cds_end) {
            (Some(start), Some(end)) => Some(end - start),
            _ => None,
        }
    }

    /// Find exon containing a transcript position.
    pub fn exon_for_tx_pos(&self, tx_pos: u64) -> Option<Exon> {
        for (i, arr) in self.exons.iter().enumerate() {
            if tx_pos >= arr[2] && tx_pos < arr[3] {
                return Some(Exon::from_array((i + 1) as u32, *arr));
            }
        }
        None
    }

    /// Find exon containing a genomic position.
    ///
    /// Exons in `self.exons` are sorted by `tx_start` (see
    /// `RawCdotTranscript::from_genome_build`). On a plus-strand transcript
    /// that means `genome_start` is monotonically increasing; on a
    /// minus-strand transcript it's monotonically *decreasing* (the
    /// 5'→3' transcript order runs against genomic coordinates). Use that
    /// to early-terminate the scan once we've passed `genome_pos` — for
    /// intronic / off-transcript positions, the previous unconditional
    /// linear walk consulted every exon even though the answer was already
    /// determined a few iterations in.
    pub fn exon_for_genome_pos(&self, genome_pos: u64) -> Option<Exon> {
        for (i, arr) in self.exons.iter().enumerate() {
            if genome_pos >= arr[0] && genome_pos < arr[1] {
                return Some(Exon::from_array((i + 1) as u32, *arr));
            }
            // Early-terminate based on the sort invariant.
            match self.strand {
                Strand::Plus if genome_pos < arr[0] => return None,
                Strand::Minus if genome_pos >= arr[1] => return None,
                _ => {}
            }
        }
        None
    }

    /// Convert transcript position to genomic position.
    pub fn tx_to_genome(&self, tx_pos: u64) -> Option<u64> {
        let exon = self.exon_for_tx_pos(tx_pos)?;
        let offset = tx_pos - exon.tx_start;

        match self.strand {
            Strand::Plus => Some(exon.genome_start + offset),
            Strand::Minus => Some(exon.genome_end - 1 - offset),
            Strand::Unknown => None,
        }
    }

    /// Like [`Self::tx_to_genome`], but additionally maps a transcript position
    /// that falls **past the 3'-terminal exon** (the transcript's poly-A region)
    /// to the contiguous downstream genome coordinate.
    ///
    /// Some derived transcript structures (#790) strip the post-transcriptional
    /// poly-A tail from their exon→genome map, so a `c.*` 3'UTR position landing
    /// in that tail has no exon and [`Self::tx_to_genome`] returns `None`.
    /// mutalyzer maps such positions by a base-agnostic coordinate walk into
    /// contiguous downstream genome using the transcript's own 3'-terminal exon
    /// anchor (#797). This reproduces that walk:
    /// - plus:  `genome_end + (tx_pos - tx_end)` (exon `genome_end` is exclusive,
    ///   so it is already the first downstream base);
    /// - minus: `genome_start - 1 - (tx_pos - tx_end)`.
    ///
    /// An in-exon `tx_pos` delegates to [`Self::tx_to_genome`] unchanged. Only a
    /// `tx_pos` past the **3'-terminal** exon extends: exons are stored
    /// contiguously in transcript order, so a `tx_pos` past a non-terminal exon's
    /// end is inside the next exon and is served by the in-exon path. Returns
    /// `None` for an unknown strand, an exon-less transcript, or a minus-strand
    /// walk that would underflow to an invalid (`< 1`, genome is 1-based)
    /// coordinate — never a wrong coordinate.
    ///
    /// This primitive is geometry-only: it does **not** bound the walk to the
    /// real poly-A tail length (the stripped tail length is not recoverable from
    /// the exon map alone). Callers that know the transcript's true length must
    /// gate the call to `tx_pos < true_tx_length` so the walk cannot run past the
    /// transcript end into genomic sequence that is not part of the transcript.
    pub fn tx_to_genome_extending_polya(&self, tx_pos: u64) -> Option<u64> {
        if let Some(g) = self.tx_to_genome(tx_pos) {
            return Some(g);
        }
        // No containing exon. Only extend past the 3'-terminal exon (the last in
        // transcript order); anything else is intronic/off-transcript.
        let last = self.exons.last()?;
        let (genome_start, genome_end, tx_end) = (last[0], last[1], last[3]);
        if tx_pos < tx_end {
            // Falls before the terminal exon's end but had no exon — a gap/hole,
            // not the poly-A region. Decline rather than guess.
            return None;
        }
        let delta = tx_pos - tx_end;
        match self.strand {
            Strand::Plus => genome_end.checked_add(delta),
            Strand::Minus => {
                // genome_start - 1 - delta, declining on 1-based underflow.
                let base = genome_start.checked_sub(1)?;
                let pos = base.checked_sub(delta)?;
                if pos < 1 {
                    None
                } else {
                    Some(pos)
                }
            }
            Strand::Unknown => None,
        }
    }

    /// Convert genomic position to transcript position.
    pub fn genome_to_tx(&self, genome_pos: u64) -> Option<u64> {
        let exon = self.exon_for_genome_pos(genome_pos)?;

        match self.strand {
            Strand::Plus => {
                let offset = genome_pos - exon.genome_start;
                Some(exon.tx_start + offset)
            }
            Strand::Minus => {
                let offset = exon.genome_end - 1 - genome_pos;
                Some(exon.tx_start + offset)
            }
            Strand::Unknown => None,
        }
    }

    /// Locate `genome_pos` against this transcript's exons in a single scan,
    /// returning the containing exon and the corresponding transcript-space
    /// position.
    ///
    /// Existing callers chained `genome_to_tx` (which internally scans the
    /// exon list) with a second `exon_for_genome_pos` call (another scan).
    /// This helper does both in one pass — relevant in
    /// [`CoordinateMapper::genome_pos_to_cds_pos`] which is invoked twice per
    /// projection and is the dominant per-variant cost on the SNP fixture
    /// after c11.
    pub fn locate_genome_pos(&self, genome_pos: u64) -> Option<(u64, Exon)> {
        for (i, arr) in self.exons.iter().enumerate() {
            if genome_pos >= arr[0] && genome_pos < arr[1] {
                let exon = Exon::from_array((i + 1) as u32, *arr);
                let tx_pos = match self.strand {
                    Strand::Plus => exon.tx_start + (genome_pos - exon.genome_start),
                    Strand::Minus => exon.tx_start + (exon.genome_end - 1 - genome_pos),
                    Strand::Unknown => return None,
                };
                return Some((tx_pos, exon));
            }
            // Same early-termination as in `exon_for_genome_pos`. Exons are
            // sorted by `tx_start`, which is monotone in `genome_start` on
            // plus-strand (increasing) and in `genome_end` on minus-strand
            // (decreasing).
            match self.strand {
                Strand::Plus if genome_pos < arr[0] => return None,
                Strand::Minus if genome_pos >= arr[1] => return None,
                _ => {}
            }
        }
        None
    }

    /// Determine whether `genome_pos` falls strictly inside a transcript-genome
    /// CIGAR `Deletion` gap (a genome base with no transcript counterpart) for
    /// the exon at index `exon_idx` in [`Self::exons`] / [`Self::exon_cigars`].
    ///
    /// The CIGAR ops describe the alignment within the exon, walked from the
    /// exon's transcript-5' end. A `Deletion(n)` consumes `n` genome bases and
    /// `0` transcript bases — so any genome position landing inside the
    /// deletion's genome span has no well-defined transcript coordinate. Plain
    /// offset arithmetic (as in [`Self::locate_genome_pos`]) would silently map
    /// such a position to a wrong coordinate; this lets the mapping site refuse
    /// it instead.
    ///
    /// Returns `Some(CigarGap)` describing the deletion when `genome_pos` is
    /// strictly inside one, and `None` when the position is matched, when the
    /// exon has no CIGAR data, or when the position is outside the exon.
    ///
    /// `genome_pos` must lie within the exon's genome span; callers pass the
    /// exon already located by [`Self::locate_genome_pos`].
    pub(crate) fn cigar_deletion_gap_at_genome_pos(
        &self,
        exon_idx: usize,
        genome_pos: u64,
    ) -> Option<CigarGap> {
        let exon = self.exons.get(exon_idx)?;
        let (genome_start, genome_end) = (exon[0], exon[1]);
        if genome_pos < genome_start || genome_pos >= genome_end {
            return None;
        }
        let ops = match self.exon_cigars.get(exon_idx) {
            Some(Some(ops)) if !ops.is_empty() => ops,
            _ => return None,
        };

        // Genome offset along the CIGAR, measured from the exon's tx-5' end
        // (the same orientation the CIGAR is written in). On the plus strand
        // this counts up from `genome_start`; on the minus strand it counts
        // down from `genome_end - 1`. This mirrors the offset
        // `locate_genome_pos` uses to derive the (CIGAR-unaware) tx position.
        let target_genome_offset = match self.strand {
            Strand::Plus => genome_pos - genome_start,
            Strand::Minus => genome_end - 1 - genome_pos,
            Strand::Unknown => return None,
        };

        let mut genome_consumed: u64 = 0;
        for op in ops {
            match op {
                CigarOp::Match(len) => {
                    genome_consumed += len;
                }
                CigarOp::Deletion(len) => {
                    // The deletion covers genome offsets
                    // [genome_consumed, genome_consumed + len). A position
                    // landing there is strictly inside the gap.
                    if target_genome_offset >= genome_consumed
                        && target_genome_offset < genome_consumed + len
                    {
                        return Some(CigarGap {
                            kind: CigarGapKind::Deletion,
                            length: *len,
                            offset_in_gap: target_genome_offset - genome_consumed,
                        });
                    }
                    genome_consumed += len;
                }
                CigarOp::Insertion(_) => {
                    // Insertions consume transcript bases only, not genome.
                }
            }
            if genome_consumed > target_genome_offset {
                break;
            }
        }
        None
    }

    /// Determine whether transcript position `tx_pos` falls strictly inside a
    /// transcript-genome CIGAR `Insertion` gap (a transcript base with no
    /// genome counterpart) for the exon at index `exon_idx`.
    ///
    /// The mirror of [`Self::cigar_deletion_gap_at_genome_pos`] on the
    /// transcript axis: an `Insertion(n)` consumes `n` transcript bases and `0`
    /// genome bases, so a transcript position inside the insertion's span has
    /// no well-defined genome coordinate. Returns `Some(CigarGap)` with
    /// `kind = Insertion` when `tx_pos` is strictly inside such a gap.
    ///
    /// `tx_pos` is the 0-based transcript position; callers pass an exon whose
    /// `[tx_start, tx_end)` span contains it.
    pub(crate) fn cigar_insertion_gap_at_tx_pos(
        &self,
        exon_idx: usize,
        tx_pos: u64,
    ) -> Option<CigarGap> {
        let exon = self.exons.get(exon_idx)?;
        let (tx_start, tx_end) = (exon[2], exon[3]);
        if tx_pos < tx_start || tx_pos >= tx_end {
            return None;
        }
        let ops = match self.exon_cigars.get(exon_idx) {
            Some(Some(ops)) if !ops.is_empty() => ops,
            _ => return None,
        };

        // Transcript offset along the CIGAR, measured from the exon's tx-5'
        // end (the order the CIGAR is written in, on both strands).
        let target_tx_offset = tx_pos - tx_start;

        let mut tx_consumed: u64 = 0;
        for op in ops {
            match op {
                CigarOp::Match(len) => {
                    tx_consumed += len;
                }
                CigarOp::Insertion(len) => {
                    if target_tx_offset >= tx_consumed && target_tx_offset < tx_consumed + len {
                        return Some(CigarGap {
                            kind: CigarGapKind::Insertion,
                            length: *len,
                            offset_in_gap: target_tx_offset - tx_consumed,
                        });
                    }
                    tx_consumed += len;
                }
                CigarOp::Deletion(_) => {
                    // Deletions consume genome bases only, not transcript.
                }
            }
            if tx_consumed > target_tx_offset {
                break;
            }
        }
        None
    }

    /// Convert CDS position (1-based) to transcript position (0-based).
    pub fn cds_to_tx(&self, cds_pos: i64) -> Option<u64> {
        let cds_start = self.cds_start?;

        if cds_pos > 0 {
            // Normal CDS position
            Some(cds_start + (cds_pos as u64 - 1))
        } else if cds_pos < 0 {
            // 5' UTR position (e.g., c.-100)
            let offset = (-cds_pos) as u64;
            if offset <= cds_start {
                Some(cds_start - offset)
            } else {
                None // Beyond transcript start
            }
        } else {
            None // Position 0 is not valid
        }
    }

    /// Convert transcript position (0-based) to CDS position (1-based).
    pub fn tx_to_cds(&self, tx_pos: u64) -> Option<CdsPosition> {
        let cds_start = self.cds_start?;
        let cds_end = self.cds_end?;

        if tx_pos < cds_start {
            // 5' UTR
            let offset = cds_start - tx_pos;
            Some(CdsPosition::FivePrimeUtr(offset as i64))
        } else if tx_pos < cds_end {
            // CDS
            let cds_pos = tx_pos - cds_start + 1;
            Some(CdsPosition::Cds(cds_pos as i64))
        } else {
            // 3' UTR
            let offset = tx_pos - cds_end + 1;
            Some(CdsPosition::ThreePrimeUtr(offset as i64))
        }
    }

    /// Convert a 0-based transcript position to a full [`CdsPos`], resolving the
    /// CDS / 5'UTR / 3'UTR region exactly as the genome→cds mapping does.
    ///
    /// This is the exonic (non-intronic) `CdsPosition` → `CdsPos` mapping shared
    /// by [`crate::data::mapping::CoordinateMapper::genome_pos_to_cds_pos`] and
    /// the sequence-aware exon-indel correction in the projector (issue #644).
    /// Returning a ready-to-use `CdsPos` keeps the two call sites from
    /// duplicating the region-to-coordinate translation (and drifting apart).
    ///
    /// Returns `None` when the transcript has no CDS bounds or `tx_pos` is not a
    /// resolvable transcript position.
    pub fn cds_pos_from_tx_pos(&self, tx_pos: u64) -> Option<CdsPos> {
        // Only resolve exonic transcript positions. `tx_to_cds` treats any
        // `tx_pos >= cds_end` as 3' UTR with no upper bound, so without this
        // guard a position past the last exon would be misreported as 3' UTR.
        self.exon_for_tx_pos(tx_pos)?;
        Some(Self::cds_pos_from_region(self.tx_to_cds(tx_pos)?))
    }

    /// Translate an already-resolved exonic [`CdsPosition`] into a [`CdsPos`].
    ///
    /// This is the pure region→coordinate step shared by
    /// [`Self::cds_pos_from_tx_pos`] and the genome→cds mapping. It performs no
    /// exon-bounds check, so callers that derive `tx_pos` from CIGAR-unaware
    /// offset arithmetic (e.g.
    /// [`crate::data::mapping::CoordinateMapper::genome_pos_to_cds_pos`], where a
    /// matched base after a CIGAR deletion yields a `tx_pos` past the exon's
    /// transcript span) can translate without being rejected. Callers that need
    /// the past-last-exon guard go through [`Self::cds_pos_from_tx_pos`].
    pub(crate) fn cds_pos_from_region(region: CdsPosition) -> CdsPos {
        match region {
            CdsPosition::FivePrimeUtr(offset) => CdsPos {
                base: -offset,
                offset: None,
                utr3: false,
                special: None,
            },
            CdsPosition::Cds(pos) => CdsPos {
                base: pos,
                offset: None,
                utr3: false,
                special: None,
            },
            // The `*N` distance is the `base` of a 3' UTR `CdsPos` (canonical
            // `CdsPos::utr3`), with no `offset` — keeping it round-trippable
            // through `cds_to_tx` and consistent with the genome→cds path.
            CdsPosition::ThreePrimeUtr(offset) => CdsPos {
                base: offset,
                offset: None,
                utr3: true,
                special: None,
            },
        }
    }

    /// Get the intron number for a genomic position.
    /// Returns None if the position is within an exon.
    pub fn intron_for_genome_pos(&self, genome_pos: u64) -> Option<(u32, i64)> {
        let exons = self.get_exons();

        for i in 0..exons.len().saturating_sub(1) {
            let current = &exons[i];
            let next = &exons[i + 1];

            let (intron_start, intron_end) = match self.strand {
                Strand::Plus => (current.genome_end, next.genome_start),
                Strand::Minus => (next.genome_end, current.genome_start),
                Strand::Unknown => return None,
            };

            if genome_pos >= intron_start && genome_pos < intron_end {
                let intron_num = (i + 1) as u32;
                let offset = match self.strand {
                    Strand::Plus => (genome_pos as i64) - (current.genome_end as i64),
                    Strand::Minus => (current.genome_start as i64) - (genome_pos as i64),
                    Strand::Unknown => return None,
                };
                // Adjust for 0-based to intronic offset convention
                let intronic_offset = if offset >= 0 { offset + 1 } else { offset };
                return Some((intron_num, intronic_offset));
            }
        }

        None
    }
}

/// CDS position type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CdsPosition {
    /// Position in 5' UTR (e.g., c.-100 would be FivePrimeUtr(100)).
    FivePrimeUtr(i64),
    /// Normal CDS position (1-based).
    Cds(i64),
    /// Position in 3' UTR (e.g., c.*100 would be ThreePrimeUtr(100)).
    ThreePrimeUtr(i64),
}

/// A single CIGAR operation from a GFF3 Gap attribute string.
///
/// cdot uses GFF3 Gap format (letter-first, space-separated), e.g. `M185 I3 M250`,
/// which differs from SAM CIGAR format (`185M3I250M`).
///
/// - `M` (Match): alignment match — bases align between transcript and genome.
/// - `I` (Insertion): bases present in the transcript but not the genome.
/// - `D` (Deletion): bases present in the genome but not the transcript.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CigarOp {
    /// Alignment match of `n` bases.
    Match(u64),
    /// Insertion of `n` bases in the transcript (not in genome).
    Insertion(u64),
    /// Deletion of `n` bases from the transcript (present in genome).
    Deletion(u64),
}

/// Which side of a transcript-genome CIGAR alignment a gap lives on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CigarGapKind {
    /// A genome base with no transcript counterpart (CIGAR `Deletion`).
    Deletion,
    /// A transcript base with no genome counterpart (CIGAR `Insertion`).
    Insertion,
}

/// Describes a transcript-genome CIGAR indel gap that a queried position falls
/// strictly inside. Produced by the gap-detection helpers on
/// [`CdotTranscript`] so the mapping site can build an informative error.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CigarGap {
    /// Whether the gap is a `Deletion` (genome-only) or `Insertion` (tx-only).
    pub kind: CigarGapKind,
    /// Length of the gap op in bases.
    pub length: u64,
    /// Offset of the queried position from the start of the gap (0-based).
    pub offset_in_gap: u64,
}

/// Parse a GFF3 Gap attribute string into a sequence of CIGAR operations.
///
/// The format is space-separated tokens, each starting with an operation letter
/// (`M`, `I`, or `D`) followed by a length, e.g. `"M185 I3 M250"`.
///
/// Returns an empty vector for empty or whitespace-only input.
///
/// # Errors
///
/// Returns an error if a token has an unrecognized operation letter or a non-numeric length.
pub fn parse_cigar(cigar_str: &str) -> Result<Vec<CigarOp>, FerroError> {
    let trimmed = cigar_str.trim();
    if trimmed.is_empty() {
        return Ok(Vec::new());
    }

    trimmed
        .split_whitespace()
        .map(|token| {
            if token.len() < 2 {
                return Err(FerroError::parse(
                    0,
                    format!("Invalid CIGAR token (too short): \'{token}\'"),
                ));
            }
            let (op_char, len_str) = token.split_at(1);
            let length: u64 = len_str.parse().map_err(|_| {
                FerroError::parse(0, format!("Invalid CIGAR length in token: \'{token}\'"))
            })?;
            match op_char {
                "M" => Ok(CigarOp::Match(length)),
                "I" => Ok(CigarOp::Insertion(length)),
                "D" => Ok(CigarOp::Deletion(length)),
                _ => Err(FerroError::parse(
                    0,
                    format!("Unknown CIGAR operation \'{op_char}\' in token: \'{token}\'"),
                )),
            }
        })
        .collect()
}

/// Raw cdot JSON file structure (as it appears on disk).
#[derive(Debug, Clone, Deserialize)]
#[allow(dead_code)] // Fields used for serde deserialization
struct RawCdotFile {
    /// Transcripts indexed by accession (raw format).
    transcripts: HashMap<String, RawCdotTranscript>,

    /// Genome builds available (list, e.g., ["GRCh38"])
    #[serde(default)]
    genome_builds: Option<Vec<String>>,

    /// cdot version
    #[serde(default)]
    cdot_version: Option<String>,

    /// Gene information (we ignore this for now)
    #[serde(default)]
    genes: Option<serde_json::Value>,

    /// Metadata (we ignore this for now)
    #[serde(default)]
    metadata: Option<serde_json::Value>,
}

/// cdot JSON file structure (normalized for internal use).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CdotFile {
    /// Transcripts indexed by accession.
    pub transcripts: HashMap<String, CdotTranscript>,

    /// Genome builds information (optional).
    #[serde(default)]
    pub genome_builds: Option<HashMap<String, serde_json::Value>>,
}

/// Bincode-friendly snapshot of CdotMapper data, without custom JSON deserializers.
/// Used for deserialization only; serialization uses [`CdotMapperSnapshotRef`].
///
/// **Format note (#389 follow-up).** `primary_build` was added after the
/// initial snapshot layout. bincode (1.x) is positional and does not honor
/// `#[serde(default)]` for trailing fields, so snapshots produced by older
/// builds will fail to deserialize against this struct. That failure is
/// non-fatal: [`CdotMapper::load`] catches it and falls back to JSON, which
/// regenerates the `.bin` with the new layout. Callers that pass a `.bin`
/// path directly (no JSON fallback available) must regenerate via
/// `ferro prepare`.
#[derive(Deserialize)]
struct CdotMapperSnapshot {
    transcripts: HashMap<String, CdotTranscriptSnapshot>,
    contig_index: HashMap<String, Vec<String>>,
    contig_alias_to_canonical: HashMap<String, String>,
    base_to_versioned: HashMap<String, String>,
    lrg_to_refseq: HashMap<String, String>,
    /// Genome build the snapshot was produced under, or `None` if the
    /// snapshot pre-dates the build-tracking format (only reachable via a
    /// hand-rolled deserializer skipping this field — bincode itself will
    /// error on a truncated stream and the loader falls back to JSON).
    primary_build: Option<String>,
    /// Per-build transcript maps for non-primary builds (e.g. GRCh37 when the
    /// primary is GRCh38). Required for NG/NC-parent-aware resolution (#332);
    /// omitting it from the cache silently degraded that path on every fast
    /// load. Part of the v1 layout — a cache missing it fails the version/EOF
    /// guard and is regenerated.
    alt_build_transcripts: HashMap<String, HashMap<String, CdotTranscriptSnapshot>>,
}

/// Borrowed view of CdotMapper for zero-copy serialization to bincode.
#[derive(Serialize)]
struct CdotMapperSnapshotRef<'a> {
    // These borrow the runtime `FxHashMap` fields. serde/bincode serialize a map
    // as length + entries regardless of the hasher, so the on-disk byte layout is
    // identical to the previous `HashMap`-backed snapshot.
    transcripts: HashMap<&'a String, CdotTranscriptSnapshotRef<'a>>,
    contig_index: &'a FxHashMap<String, Vec<String>>,
    contig_alias_to_canonical: &'a FxHashMap<String, String>,
    base_to_versioned: &'a FxHashMap<String, String>,
    lrg_to_refseq: &'a FxHashMap<String, String>,
    primary_build: Option<&'a str>,
    alt_build_transcripts: HashMap<&'a String, HashMap<&'a String, CdotTranscriptSnapshotRef<'a>>>,
}

/// Bincode-friendly snapshot of CdotTranscript, using standard Strand serde.
/// Used for deserialization only; serialization uses [`CdotTranscriptSnapshotRef`].
#[derive(Deserialize)]
struct CdotTranscriptSnapshot {
    gene_name: Option<String>,
    contig: String,
    strand: Strand,
    exons: Vec<[u64; 4]>,
    cds_start: Option<u64>,
    cds_end: Option<u64>,
    exon_cigars: Vec<Option<Vec<CigarOp>>>,
    gene_id: Option<String>,
    protein: Option<String>,
    /// Added in v3 (#972); trailing field so bincode's positional layout
    /// keeps all pre-existing fields at their original offsets.
    cds_start_incomplete: bool,
}

/// Borrowed view of CdotTranscript for zero-copy serialization to bincode.
#[derive(Serialize)]
struct CdotTranscriptSnapshotRef<'a> {
    gene_name: &'a Option<String>,
    contig: &'a str,
    strand: Strand,
    exons: &'a Vec<[u64; 4]>,
    cds_start: Option<u64>,
    cds_end: Option<u64>,
    exon_cigars: &'a Vec<Option<Vec<CigarOp>>>,
    gene_id: &'a Option<String>,
    protein: &'a Option<String>,
    /// Added in v3 (#972); mirrors `CdotTranscriptSnapshot::cds_start_incomplete`.
    cds_start_incomplete: bool,
}

impl<'a> From<&'a CdotTranscript> for CdotTranscriptSnapshotRef<'a> {
    fn from(tx: &'a CdotTranscript) -> Self {
        Self {
            gene_name: &tx.gene_name,
            contig: &tx.contig,
            strand: tx.strand,
            exons: &tx.exons,
            cds_start: tx.cds_start,
            cds_end: tx.cds_end,
            exon_cigars: &tx.exon_cigars,
            gene_id: &tx.gene_id,
            protein: &tx.protein,
            cds_start_incomplete: tx.cds_start_incomplete,
        }
    }
}

impl From<CdotTranscriptSnapshot> for CdotTranscript {
    fn from(snap: CdotTranscriptSnapshot) -> Self {
        Self {
            gene_name: snap.gene_name,
            contig: snap.contig,
            strand: snap.strand,
            exons: snap.exons,
            cds_start: snap.cds_start,
            cds_end: snap.cds_end,
            exon_cigars: snap.exon_cigars,
            gene_id: snap.gene_id,
            protein: snap.protein,
            cds_start_incomplete: snap.cds_start_incomplete,
        }
    }
}

/// Which path [`CdotMapper::load_with_source`] took to produce the mapper.
///
/// Makes a silent fast-path → slow-path fallback impossible to ignore at the
/// API level (the root cause of the #585 regression, where a broken binary
/// cache silently re-parsed 512 MB of JSON on every run). A binary cache
/// (`.rkyv` or legacy `.bin`) is the fast `Archive` path; an actual JSON parse
/// is `JsonFallback`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CdotLoadSource {
    /// Loaded from a fast binary archive (`.rkyv`, or legacy `.bin`).
    Archive,
    /// Fell back to parsing the source JSON (slow path).
    JsonFallback,
}

/// Coordinate mapper using cdot data.
#[derive(Debug, Clone)]
pub struct CdotMapper {
    /// Transcripts indexed by accession. Entries are populated from whatever
    /// genome build was passed at load time (the "primary build"). Use
    /// [`get_transcript_on_build`](Self::get_transcript_on_build) to fetch a
    /// non-primary build's view of a transcript.
    transcripts: FxHashMap<String, CdotTranscript>,
    /// Index from contig to transcript IDs that overlap.
    contig_index: FxHashMap<String, Vec<String>>,
    /// Alias-to-canonical contig name mapping (e.g., "chr7" -> "NC_000007.14").
    /// Allows lookups by UCSC-style names when `contig_index` keys are RefSeq accessions.
    contig_alias_to_canonical: FxHashMap<String, String>,
    /// Index from base accession (without version) to versioned accession.
    base_to_versioned: FxHashMap<String, String>,
    /// LRG transcript to RefSeq transcript mapping (e.g., "LRG_1t1" -> "NM_000088.3").
    lrg_to_refseq: FxHashMap<String, String>,
    /// Per-transcript data on builds OTHER than the primary load build.
    /// Outer key is the genome-build name (e.g. "GRCh37"); inner key is the
    /// transcript accession. Populated when the source cdot JSON nests
    /// per-build data under `genome_builds`. Empty for mappers built without
    /// a multi-build source (bincode snapshots, `from_transcripts`, manual
    /// `add_transcript`).
    ///
    /// The primary build's data lives in [`Self::transcripts`] only; it is
    /// NOT duplicated here. [`get_transcript_on_build`](Self::get_transcript_on_build)
    /// dispatches between the two maps.
    alt_build_transcripts: FxHashMap<String, FxHashMap<String, CdotTranscript>>,
    /// The genome-build name corresponding to entries in [`Self::transcripts`],
    /// or `None` if the build is unknown (e.g. a bincode snapshot produced
    /// by an older build that did not persist this field). Used by
    /// [`get_transcript_on_build`](Self::get_transcript_on_build) to
    /// short-circuit when the caller asks for the primary build, and by
    /// [`primary_build`](Self::primary_build) so downstream callers can
    /// honor uncertainty rather than assume a default (#389 follow-up).
    primary_build: Option<String>,
    /// Lazily-built per-contig SuperIntervals index for stabbing queries.
    ///
    /// Built on the first call to `transcripts_at_position` from the contents of
    /// `contig_index` + `transcripts`. Replaces a linear scan that re-folded
    /// every transcript's exon table on every query. The `u32` payload is the
    /// index into `contig_index[contig]` so the original accession can be
    /// recovered for the caller.
    ///
    /// Built eagerly here because every "real" caller (`from_json_file`,
    /// `load`, `from_transcripts`) populates `contig_index` once and then only
    /// queries; `add_transcript` followed by a query in tests still works
    /// because the cell is initialised on first access. If a caller adds
    /// transcripts AFTER a query has populated the cell the new transcripts
    /// will be missing from the index — `add_transcript` clears the cell to
    /// guard against that.
    contig_query_index: OnceCell<FxHashMap<String, IntervalMap<u32>>>,
    /// Lazily-built per-contig stab-query index for the NON-primary builds.
    ///
    /// Mirrors [`Self::contig_query_index`] but covers the contigs that only
    /// appear in [`Self::alt_build_transcripts`] (e.g. the GRCh37 `NC_*.11`
    /// accessions when the primary build is GRCh38). GRCh37 and GRCh38 contig
    /// accessions are distinct, so a contig is owned by exactly one build and
    /// `transcripts_at_position` can route to the owning build purely from the
    /// contig name.
    ///
    /// Derived entirely from `alt_build_transcripts`, so it is rebuilt lazily
    /// rather than persisted — this keeps the rkyv/bincode snapshot schema
    /// unchanged (snapshots already carry `alt_build_transcripts`, so a
    /// reloaded mapper rebuilds this index on first query). Cleared alongside
    /// `contig_query_index` whenever the transcript maps change.
    ///
    /// The inner `Vec<String>` is the accession list for the contig in the
    /// owning build's map; the `IntervalMap` payload is an index into it.
    alt_build_query_index: OnceCell<FxHashMap<String, AltBuildContigStab>>,
    /// Lazily-built per-transcript `(min_genome_start, max_genome_end)`
    /// cache so `VariantProjector::project_single_inner` doesn't re-fold the
    /// exon table on every projection. Sharing the same `OnceCell` build
    /// trigger as `contig_query_index` keeps the two views in sync.
    transcript_genome_spans: OnceCell<FxHashMap<String, (u64, u64)>>,
    /// Deferred secondary builds: build name -> source cdot path. Set by
    /// `MultiFastaProvider::from_manifest` so a declared secondary (e.g. the
    /// GRCh37 cdot) is not loaded until a lookup for that build needs it. NOT
    /// part of any rkyv/bincode snapshot — purely a runtime handle.
    deferred_alt_sources: HashMap<String, PathBuf>,
    /// Lazily-loaded secondary-build mappers, keyed by build name. `get_or_init`
    /// loads `deferred_alt_sources[build]` on first use; the inner `Option` is
    /// `None` when the source is missing/unreadable (best-effort, never retried).
    lazy_alt_mappers: HashMap<String, OnceCell<Option<Box<CdotMapper>>>>,
    /// Deferred Ensembl cdot source (#964): the `ensembl_cdot_json` path recorded
    /// by `MultiFastaProvider::from_manifest` so the ~198k Ensembl (`ENST`/`ENSG`/
    /// `ENSP`) transcripts are NOT merged into the primary build at construction.
    /// Unlike `deferred_alt_sources` (build-keyed), this is *source*-keyed: the
    /// Ensembl transcripts share the primary genome build, so the deferred mapper
    /// is consulted from the primary *accession-lookup* paths rather than an alt
    /// build. Genomic overlap enumeration stays RefSeq-scoped and does NOT consult
    /// it. `None` when the manifest carries no Ensembl cdot. NOT serialized —
    /// a purely runtime handle.
    deferred_ensembl_source: Option<PathBuf>,
    /// Lazily-loaded Ensembl mapper (#964). `get_or_init` loads
    /// `deferred_ensembl_source` on the first `ENS*`-accession lookup; the inner
    /// `Option` is `None` when the source is missing/unreadable (best-effort,
    /// never retried). A pure-RefSeq workload never touches it (genomic
    /// enumeration is RefSeq-scoped and does not consult it), so RefSeq startup
    /// pays nothing for Ensembl.
    lazy_ensembl_mapper: OnceCell<Option<Box<CdotMapper>>>,
}

/// Per-contig stab-query index entry for a non-primary build, used by
/// [`CdotMapper::transcripts_at_position`] to route alt-build contig queries.
///
/// Holds the owning build name, the accession list for the contig in that
/// build's [`CdotMapper::alt_build_transcripts`] map, and a SuperIntervals
/// index whose `u32` payload indexes into `accessions`.
#[derive(Debug, Clone)]
struct AltBuildContigStab {
    /// Genome build that owns this contig (key into `alt_build_transcripts`).
    build: String,
    /// Accessions on this contig, in the order the `IntervalMap` payloads index.
    accessions: Vec<String>,
    /// Stab-query index; payload is an index into `accessions`.
    index: IntervalMap<u32>,
}

impl CdotMapper {
    /// Create a new empty mapper (primary build defaults to GRCh38).
    pub fn new() -> Self {
        Self {
            transcripts: FxHashMap::default(),
            contig_index: FxHashMap::default(),
            contig_alias_to_canonical: FxHashMap::default(),
            base_to_versioned: FxHashMap::default(),
            lrg_to_refseq: FxHashMap::default(),
            alt_build_transcripts: FxHashMap::default(),
            primary_build: Some("GRCh38".to_string()),
            contig_query_index: OnceCell::new(),
            alt_build_query_index: OnceCell::new(),
            transcript_genome_spans: OnceCell::new(),
            deferred_alt_sources: HashMap::new(),
            lazy_alt_mappers: HashMap::new(),
            deferred_ensembl_source: None,
            lazy_ensembl_mapper: OnceCell::new(),
        }
    }

    /// Build a `CdotMapper` from in-memory `Transcript` records (typically loaded into a
    /// `MockProvider`). Converts the 1-based `Transcript` coordinates into the form expected
    /// by `CdotTranscript`.
    ///
    /// # Coordinate conversions
    ///
    /// `Transcript.Exon` fields are documented as 1-based inclusive (see
    /// `src/reference/transcript.rs`). `CdotTranscript` exon arrays use:
    /// - `exons[][0]` (genome_start): HGVS-value-based — the numeric value of the first
    ///   HGVS g. position in the exon. Conversion: `genome_start = Exon.genomic_start` (no change).
    /// - `exons[][1]` (genome_end): exclusive, equals `Exon.genomic_end + 1`.
    /// - `exons[][2]` (tx_start): 0-based. Conversion: `tx_start = Exon.start - 1`.
    /// - `exons[][3]` (tx_end): 0-based exclusive. Same numeric value as `Exon.end` (1-based
    ///   inclusive end equals 0-based exclusive end).
    /// - `cds_start`: 0-based. Conversion: `cds_start = Transcript.cds_start - 1`.
    /// - `cds_end`: 0-based exclusive. Same numeric value as `Transcript.cds_end`.
    /// - `cds_start_incomplete`: propagated verbatim from
    ///   `Transcript.cds_start_incomplete` (the Ensembl `cds_start_NF` flag, #972). Not a
    ///   coordinate, but listed here because the projector's decline gate reads the *cdot*
    ///   record in preference to the source `Transcript`, so dropping it on this edge
    ///   silently re-enables the `c.`/`p.`/`r.` axes for such a transcript.
    ///
    /// Defaults to GRCh38 for contig alias resolution (so `chr17` ↔ `NC_000017.11`
    /// works after construction). Use [`from_transcripts_with_build`] to specify a
    /// different genome build.
    pub fn from_transcripts<'a, I>(transcripts: I) -> Self
    where
        I: IntoIterator<Item = &'a crate::reference::transcript::Transcript>,
    {
        Self::from_transcripts_with_build(transcripts, "GRCh38")
    }

    /// Like [`from_transcripts`], but uses `genome_build` (e.g. "GRCh37" or
    /// "GRCh38") for contig alias resolution.
    ///
    /// Transcripts with missing or inconsistent coordinates are skipped with a
    /// `log::warn!`, rather than silently coerced to bogus intervals. A transcript
    /// must have a chromosome and, for every exon, all of: `genomic_start`,
    /// `genomic_end >= genomic_start`, `start >= 1` (1-based), `end >= start`.
    pub fn from_transcripts_with_build<'a, I>(transcripts: I, genome_build: &str) -> Self
    where
        I: IntoIterator<Item = &'a crate::reference::transcript::Transcript>,
    {
        let mut mapper = Self::new();
        mapper.primary_build = Some(genome_build.to_string());
        for tx in transcripts {
            let Some(contig) = tx.chromosome.clone() else {
                log::warn!("Skipping transcript {}: missing chromosome", tx.id);
                continue;
            };
            let mut exons: Vec<[u64; 4]> = Vec::with_capacity(tx.exons.len());
            let mut valid = true;
            for e in &tx.exons {
                // Require both genomic bounds and a non-empty, well-ordered interval
                // on both the transcript and genomic axes; 1-based `start == 0` is
                // invalid input and we refuse to silently turn it into `tx_start = 0`.
                let (Some(g_start), Some(g_end_inclusive)) = (e.genomic_start, e.genomic_end)
                else {
                    valid = false;
                    break;
                };
                let Some(t_start) = e.start.checked_sub(1) else {
                    valid = false;
                    break;
                };
                if e.end < e.start || g_end_inclusive < g_start {
                    valid = false;
                    break;
                }
                // genome_end: 1-based inclusive → exclusive (add 1).
                // tx_end: 1-based inclusive end equals 0-based exclusive end numerically.
                exons.push([g_start, g_end_inclusive + 1, t_start, e.end]);
            }
            if !valid || exons.is_empty() {
                log::warn!(
                    "Skipping transcript {}: incomplete or inconsistent exon coordinates",
                    tx.id
                );
                continue;
            }
            let cdot_tx = CdotTranscript {
                gene_name: tx.gene_symbol.clone(),
                contig,
                strand: tx.strand,
                exons,
                // cds_start: 1-based tx → 0-based. Use `checked_sub` so a stray `Some(0)`
                // becomes `None` rather than wrapping to a giant `u64`.
                cds_start: tx.cds_start.and_then(|c| c.checked_sub(1)),
                // cds_end: 1-based tx inclusive → 0-based exclusive (same value)
                cds_end: tx.cds_end,
                gene_id: None,
                // Propagate the ferro reference's explicit protein accession so
                // c. → p. projection works for non-RefSeq transcript IDs without
                // needing a cdot JSON. See #310.
                protein: tx.protein_id.clone(),
                exon_cigars: Vec::new(),
                // #972: carry the `cds_start_NF` flag through this reverse
                // Transcript → CdotTranscript direction. The projector's
                // decline gate reads the cdot transcript in preference to the
                // source `Transcript`, so hardcoding `false` here shadowed a
                // correct `true` and re-enabled c./p./r. for such transcripts.
                cds_start_incomplete: tx.cds_start_incomplete,
            };
            mapper.add_transcript(tx.id.clone(), cdot_tx);
        }
        mapper.populate_contig_aliases(genome_build);
        mapper
    }

    /// Load from a cdot JSON file.
    pub fn from_json_file<P: AsRef<Path>>(path: P) -> Result<Self, FerroError> {
        let file = File::open(path.as_ref()).map_err(|e| FerroError::Io {
            msg: format!("Failed to open cdot file: {}", e),
        })?;
        let reader = BufReader::new(file);
        Self::from_reader(reader)
    }

    /// Load from a gzip-compressed cdot JSON file.
    pub fn from_json_gz<P: AsRef<Path>>(path: P) -> Result<Self, FerroError> {
        let file = File::open(path.as_ref()).map_err(|e| FerroError::Io {
            msg: format!("Failed to open cdot file: {}", e),
        })?;
        let reader = BufReader::new(file);
        let decoder = flate2::read::GzDecoder::new(reader);
        let reader = BufReader::new(decoder);
        Self::from_reader(reader)
    }

    /// Load from a pre-serialized bincode file (much faster than JSON).
    pub fn from_bincode_file<P: AsRef<Path>>(path: P) -> Result<Self, FerroError> {
        let file = File::open(path.as_ref()).map_err(|e| FerroError::Io {
            msg: format!("Failed to open cdot bincode file: {}", e),
        })?;
        let file_size = file.metadata().map(|m| m.len()).unwrap_or(0);
        let mut reader = BufReader::new(file);

        // Verify the magic + schema version before deserializing. A mismatch
        // (including a legacy headerless cache, or one written by a build with a
        // different snapshot layout) is reported cleanly so the caller can fall
        // back to JSON and refresh the cache, instead of mis-deserializing.
        let mut header = [0u8; 8];
        reader.read_exact(&mut header).map_err(|e| FerroError::Io {
            msg: format!("cdot bincode too short to contain a header: {}", e),
        })?;
        if header[..4] != CDOT_BINCODE_MAGIC {
            return Err(FerroError::Io {
                msg: "cdot bincode has no valid magic (legacy or non-cdot file)".to_string(),
            });
        }
        let version = u32::from_le_bytes([header[4], header[5], header[6], header[7]]);
        if version != CDOT_BINCODE_VERSION {
            return Err(FerroError::Io {
                msg: format!(
                    "cdot bincode schema version {} != expected {}",
                    version, CDOT_BINCODE_VERSION
                ),
            });
        }

        // Use a size limit to prevent OOM on corrupt files. Allow 20x the file size
        // (bincode is compact, but deserialized HashMap overhead can be significant).
        // Limit deserialization size to prevent OOM on corrupt files (20x file size or 1MB min).
        let size_limit = file_size.saturating_mul(20).max(1024 * 1024);
        let snapshot: CdotMapperSnapshot = bincode::options()
            .with_fixint_encoding()
            .allow_trailing_bytes()
            .with_limit(size_limit)
            .deserialize_from(reader)
            .map_err(|e| FerroError::Io {
                msg: format!("Failed to deserialize cdot bincode: {}", e),
            })?;
        Ok(Self {
            transcripts: snapshot
                .transcripts
                .into_iter()
                .map(|(k, v)| (k, v.into()))
                .collect(),
            // Re-collect the deserialized `HashMap`s into runtime `FxHashMap`s;
            // the on-disk bincode layout is unchanged (the snapshot type still
            // deserializes into plain `HashMap`s).
            contig_index: snapshot.contig_index.into_iter().collect(),
            contig_alias_to_canonical: snapshot.contig_alias_to_canonical.into_iter().collect(),
            base_to_versioned: snapshot.base_to_versioned.into_iter().collect(),
            lrg_to_refseq: snapshot.lrg_to_refseq.into_iter().collect(),
            // Alt-build maps are now part of the serialized format (v1), so
            // NG/NC-parent-aware resolution (#332) works on the fast path too.
            alt_build_transcripts: snapshot
                .alt_build_transcripts
                .into_iter()
                .map(|(build, txs)| (build, txs.into_iter().map(|(k, v)| (k, v.into())).collect()))
                .collect(),
            // Honor the snapshot's recorded primary build; older snapshots
            // that pre-date this field surface as `None` rather than
            // claiming a fabricated GRCh38 (#389 follow-up).
            primary_build: snapshot.primary_build,
            contig_query_index: OnceCell::new(),
            alt_build_query_index: OnceCell::new(),
            transcript_genome_spans: OnceCell::new(),
            deferred_alt_sources: HashMap::new(),
            lazy_alt_mappers: HashMap::new(),
            deferred_ensembl_source: None,
            lazy_ensembl_mapper: OnceCell::new(),
        })
    }

    /// Cheap check: does `path` begin with the current cdot bincode magic and
    /// schema version? Lets callers (e.g. `ferro prepare`) decide whether a
    /// cache needs regenerating without paying for a full deserialize.
    pub fn bincode_is_current<P: AsRef<Path>>(path: P) -> bool {
        let Ok(mut file) = File::open(path) else {
            return false;
        };
        let mut header = [0u8; 8];
        if file.read_exact(&mut header).is_err() {
            return false;
        }
        header[..4] == CDOT_BINCODE_MAGIC
            && u32::from_le_bytes([header[4], header[5], header[6], header[7]])
                == CDOT_BINCODE_VERSION
    }

    /// Write the mapper to a bincode file for fast subsequent loading.
    pub fn to_bincode_file<P: AsRef<Path>>(&self, path: P) -> Result<(), FerroError> {
        let snapshot = CdotMapperSnapshotRef {
            transcripts: self
                .transcripts
                .iter()
                .map(|(k, v)| (k, v.into()))
                .collect(),
            contig_index: &self.contig_index,
            contig_alias_to_canonical: &self.contig_alias_to_canonical,
            base_to_versioned: &self.base_to_versioned,
            lrg_to_refseq: &self.lrg_to_refseq,
            primary_build: self.primary_build.as_deref(),
            alt_build_transcripts: self
                .alt_build_transcripts
                .iter()
                .map(|(build, txs)| (build, txs.iter().map(|(k, v)| (k, v.into())).collect()))
                .collect(),
        };
        // Write to a unique temp sibling, then atomically rename, so a crash
        // mid-write or a concurrent reader never observes a half-written cache.
        // The temp name combines the pid (unique across live processes) with a
        // process-global counter (unique across concurrent writers within this
        // process), so two threads writing the same cache never collide.
        use std::sync::atomic::{AtomicU64, Ordering};
        static TMP_COUNTER: AtomicU64 = AtomicU64::new(0);
        let path = path.as_ref();
        let mut tmp = path.to_path_buf();
        let tmp_name = format!(
            "{}.tmp.{}.{}",
            path.file_name()
                .map(|n| n.to_string_lossy().into_owned())
                .unwrap_or_else(|| "cdot.bin".to_string()),
            std::process::id(),
            TMP_COUNTER.fetch_add(1, Ordering::Relaxed)
        );
        tmp.set_file_name(tmp_name);

        let file = File::create(&tmp).map_err(|e| FerroError::Io {
            msg: format!("Failed to create cdot bincode temp file: {}", e),
        })?;
        let mut writer = std::io::BufWriter::new(file);
        let write_result = (|| -> std::io::Result<()> {
            writer.write_all(&CDOT_BINCODE_MAGIC)?;
            writer.write_all(&CDOT_BINCODE_VERSION.to_le_bytes())?;
            bincode::options()
                .with_fixint_encoding()
                .serialize_into(&mut writer, &snapshot)
                .map_err(std::io::Error::other)?;
            writer.flush()
        })();
        if let Err(e) = write_result {
            let _ = std::fs::remove_file(&tmp);
            return Err(FerroError::Io {
                msg: format!("Failed to serialize cdot bincode: {}", e),
            });
        }
        std::fs::rename(&tmp, path).map_err(|e| {
            let _ = std::fs::remove_file(&tmp);
            FerroError::Io {
                msg: format!("Failed to finalize cdot bincode file: {}", e),
            }
        })
    }

    /// `mmap`-backed load from a pre-serialized rkyv archive.
    ///
    /// Maps the archive file into memory (one `unsafe` `memmap2::Mmap::map`
    /// call) then validates and deserializes it in a single pass, rejects stale
    /// or corrupt archives so [`load`](Self::load) can regenerate them, and is
    /// ~3-4x faster than the bincode path because rkyv's layout skips the
    /// byte-stream decode.
    pub fn from_rkyv_file<P: AsRef<Path>>(path: P) -> Result<Self, FerroError> {
        use rkyv::rancor::Error as RkyvError;

        let file = std::fs::File::open(path.as_ref()).map_err(|e| FerroError::Io {
            msg: format!("Failed to open cdot rkyv file: {}", e),
        })?;
        // mmap (page-aligned, satisfies rkyv's alignment) so the 260MB+ archive
        // isn't read+copied up front — pages fault in lazily as `deserialize`
        // touches them. The mapping is dropped once we own the data below.
        // SAFETY: concurrent writers use `rename` (new inode) so an active
        // mapping is never invalidated by a parallel cache refresh; external
        // truncation of the file is not guarded against.
        let mmap = unsafe {
            memmap2::Mmap::map(&file).map_err(|e| FerroError::Io {
                msg: format!("Failed to mmap cdot rkyv file: {}", e),
            })?
        };

        let archived = rkyv::access::<rkyv_cache::ArchivedRkyvSnapshot, RkyvError>(&mmap[..])
            .map_err(|e| FerroError::Io {
                msg: format!("cdot rkyv archive failed validation: {}", e),
            })?;
        let version = rkyv_cache::version_of(archived);
        if version != rkyv_cache::RKYV_FORMAT_VERSION {
            return Err(FerroError::Io {
                msg: format!(
                    "cdot rkyv schema version {} != expected {}",
                    version,
                    rkyv_cache::RKYV_FORMAT_VERSION
                ),
            });
        }

        // Materialize owned cdot maps directly from the archive (single pass).
        // Rejects (rather than coerces) any out-of-range enum tag, so a corrupt
        // archive surfaces as an error and is regenerated by the caller.
        let maps = rkyv_cache::maps_from_archived(archived)?;
        Ok(Self {
            transcripts: maps.transcripts,
            contig_index: maps.contig_index,
            contig_alias_to_canonical: maps.contig_alias_to_canonical,
            base_to_versioned: maps.base_to_versioned,
            lrg_to_refseq: maps.lrg_to_refseq,
            alt_build_transcripts: maps.alt_build_transcripts,
            primary_build: maps.primary_build,
            contig_query_index: OnceCell::new(),
            alt_build_query_index: OnceCell::new(),
            transcript_genome_spans: OnceCell::new(),
            deferred_alt_sources: HashMap::new(),
            lazy_alt_mappers: HashMap::new(),
            deferred_ensembl_source: None,
            lazy_ensembl_mapper: OnceCell::new(),
        })
    }

    /// Cheap check: does `path` begin with a current, structurally valid rkyv
    /// archive? Reads and validates (the archive must be parsed to reach the
    /// version field), so it is not free — but far cheaper than a full load,
    /// and lets `prepare` decide whether to regenerate.
    pub fn rkyv_is_current<P: AsRef<Path>>(path: P) -> bool {
        let Ok(file) = std::fs::File::open(path.as_ref()) else {
            return false;
        };
        // SAFETY: concurrent writers use `rename` (new inode) so an active
        // mapping is never invalidated by a parallel cache refresh; external
        // truncation of the file is not guarded against.
        let Ok(mmap) = (unsafe { memmap2::Mmap::map(&file) }) else {
            return false;
        };
        match rkyv::access::<rkyv_cache::ArchivedRkyvSnapshot, rkyv::rancor::Error>(&mmap[..]) {
            Ok(a) => a.format_version.to_native() == rkyv_cache::RKYV_FORMAT_VERSION,
            Err(_) => false,
        }
    }

    /// Write the mapper to an rkyv archive (atomically), for fast loading.
    pub fn to_rkyv_file<P: AsRef<Path>>(&self, path: P) -> Result<(), FerroError> {
        let snapshot = rkyv_cache::snapshot_from_mapper(self);
        let bytes =
            rkyv::to_bytes::<rkyv::rancor::Error>(&snapshot).map_err(|e| FerroError::Io {
                msg: format!("Failed to serialize cdot rkyv: {}", e),
            })?;

        // Unique temp sibling (pid + process-global counter) so concurrent
        // writers in the same process never collide — see `to_bincode_file`.
        use std::sync::atomic::{AtomicU64, Ordering};
        static TMP_COUNTER: AtomicU64 = AtomicU64::new(0);
        let path = path.as_ref();
        let mut tmp = path.to_path_buf();
        let tmp_name = format!(
            "{}.tmp.{}.{}",
            path.file_name()
                .map(|n| n.to_string_lossy().into_owned())
                .unwrap_or_else(|| "cdot.rkyv".to_string()),
            std::process::id(),
            TMP_COUNTER.fetch_add(1, Ordering::Relaxed)
        );
        tmp.set_file_name(tmp_name);

        if let Err(e) = std::fs::write(&tmp, &bytes) {
            let _ = std::fs::remove_file(&tmp);
            return Err(FerroError::Io {
                msg: format!("Failed to write cdot rkyv temp file: {}", e),
            });
        }
        std::fs::rename(&tmp, path).map_err(|e| {
            let _ = std::fs::remove_file(&tmp);
            FerroError::Io {
                msg: format!("Failed to finalize cdot rkyv file: {}", e),
            }
        })
    }

    /// Load a cdot file using the fastest available cache format.
    ///
    /// Given a path to a `.json` or `.json.gz` file, checks for sibling cache
    /// files in order: `.rkyv` (fastest, preferred) then `.bin` (legacy
    /// bincode). If only `.bin` exists, loads from it and promotes it to
    /// `.rkyv` for future runs. Falls back to JSON if no cache is present or
    /// usable, then writes a fresh `.rkyv` cache. Also accepts direct `.rkyv`
    /// or `.bin` paths.
    pub fn load<P: AsRef<Path>>(path: P) -> Result<Self, FerroError> {
        Self::load_with_source(path).map(|(mapper, _)| mapper)
    }

    /// Like [`load`](Self::load), but also reports which path produced the
    /// mapper. This closes the API hole that let the #585 regression go silent:
    /// before this, a caller could not tell a fast archive load from a slow
    /// JSON re-parse, so a silently-broken cache (re-parsing 512 MB of JSON on
    /// every run) was invisible. The returned [`CdotLoadSource`] makes that
    /// distinction assertable in tests and observable via `ferro check`.
    ///
    /// A binary cache (`.rkyv` or legacy `.bin`) counts as
    /// [`CdotLoadSource::Archive`] — the "fast path". Only an actual JSON parse
    /// returns [`CdotLoadSource::JsonFallback`]. Note that the JSON-fallback arm
    /// still self-heals the sibling `.rkyv` as a side effect, so a *subsequent*
    /// `load_with_source` on the same path reports `Archive`.
    pub fn load_with_source<P: AsRef<Path>>(path: P) -> Result<(Self, CdotLoadSource), FerroError> {
        let path = path.as_ref();
        let path_str = path.to_string_lossy();

        // Direct archive paths — no JSON fallback available.
        if path_str.ends_with(".rkyv") {
            return Self::from_rkyv_file(path).map(|m| (m, CdotLoadSource::Archive));
        }
        if path_str.ends_with(".bin") {
            return Self::from_bincode_file(path).map(|m| (m, CdotLoadSource::Archive));
        }

        // Sibling cache paths next to the JSON. Replace the *single* trailing
        // extension (`.json`, or `.json` after stripping `.gz`); the accession
        // stem itself contains dots (e.g. `cdot-0.2.32.refseq.GRCh38`) so we
        // must not over-strip.
        let (rkyv_path, bin_path) = if path_str.ends_with(".json.gz") {
            let stem = path.with_extension(""); // foo.json.gz -> foo.json
            (stem.with_extension("rkyv"), stem.with_extension("bin"))
        } else {
            (path.with_extension("rkyv"), path.with_extension("bin"))
        };

        // A sibling cache is only usable if it is at least as new as the source
        // JSON. cdot files are normally version-stamped in the filename, but a
        // re-`prepare` that rewrites the JSON under the same name would
        // otherwise be masked by a stale archive. Mirrors the freshness check
        // the GFF/GTF loader applies via `TranscriptDb::cache_is_fresh`. An
        // unreadable mtime (cache or source) is treated as "not fresh" so we
        // fall through to JSON rather than serve a stale cache.
        let cache_is_fresh = |cache: &Path| -> bool {
            let Ok(cache_mtime) = std::fs::metadata(cache).and_then(|m| m.modified()) else {
                return false;
            };
            let Ok(source_mtime) = std::fs::metadata(path).and_then(|m| m.modified()) else {
                return false;
            };
            cache_mtime >= source_mtime
        };

        // 1. Prefer the rkyv archive (fastest, validated).
        if rkyv_path.exists() && cache_is_fresh(&rkyv_path) {
            match Self::from_rkyv_file(&rkyv_path) {
                Ok(mapper) => return Ok((mapper, CdotLoadSource::Archive)),
                Err(e) => eprintln!(
                    "warning: cdot rkyv cache {} is unusable ({}); trying other formats",
                    rkyv_path.display(),
                    e
                ),
            }
        }

        // 2. Legacy bincode cache — usable, but upgrade to rkyv for next time.
        //    Only promote a *fresh* bincode cache to rkyv; a stale one is
        //    skipped here and the JSON below refreshes both.
        if bin_path.exists() && cache_is_fresh(&bin_path) {
            match Self::from_bincode_file(&bin_path) {
                Ok(mapper) => {
                    if let Err(e) = mapper.to_rkyv_file(&rkyv_path) {
                        eprintln!(
                            "note: could not write cdot rkyv cache {}: {} (continuing)",
                            rkyv_path.display(),
                            e
                        );
                    }
                    return Ok((mapper, CdotLoadSource::Archive));
                }
                Err(e) => eprintln!(
                    "warning: cdot bincode cache {} is unusable ({}); \
                     parsing JSON (much slower) and refreshing the cache",
                    bin_path.display(),
                    e
                ),
            }
        }

        // 3. Fall back to JSON.
        let mapper = if path_str.ends_with(".gz") {
            Self::from_json_gz(path)?
        } else {
            Self::from_json_file(path)?
        };

        // Self-heal: best-effort refresh of the sibling rkyv cache so the next
        // load takes the fast path. Failures (e.g. a read-only mount) are
        // non-fatal — we already have a usable mapper.
        if let Err(e) = mapper.to_rkyv_file(&rkyv_path) {
            eprintln!(
                "note: could not refresh cdot rkyv cache {}: {} (continuing)",
                rkyv_path.display(),
                e
            );
        }

        Ok((mapper, CdotLoadSource::JsonFallback))
    }

    /// Load from any reader, defaulting to GRCh38 genome build.
    pub fn from_reader<R: Read>(reader: R) -> Result<Self, FerroError> {
        Self::from_reader_with_build(reader, "GRCh38")
    }

    /// Load from any reader with a specific genome build.
    pub fn from_reader_with_build<R: Read>(
        reader: R,
        genome_build: &str,
    ) -> Result<Self, FerroError> {
        let raw_file: RawCdotFile = serde_json::from_reader(reader)?;
        Ok(Self::from_raw_cdot_file(raw_file, genome_build))
    }

    /// Load a second cdot file as a NON-primary build, layering its
    /// transcripts onto this mapper without disturbing the primary build.
    ///
    /// The real reference manifest ships GRCh37 and GRCh38 cdot files
    /// separately (single-build each), so after loading the primary (GRCh38)
    /// cdot we layer the GRCh37 file here. The loaded transcripts go into
    /// [`Self::alt_build_transcripts`]`[build_name]` — they are NOT merged into
    /// the primary [`Self::transcripts`] map, because the same accession exists
    /// on both builds with different coordinates and a merge would corrupt the
    /// primary build (collision safety).
    ///
    /// Honors the same archive/JSON path handling as [`Self::load`] (`.rkyv`,
    /// `.bin`, `.json`, `.json.gz`). Returns the number of transcripts loaded
    /// into the secondary build.
    pub fn load_secondary_build<P: AsRef<Path>>(
        &mut self,
        path: P,
        build_name: &str,
    ) -> Result<usize, FerroError> {
        // Reuse the full `load` path so caches and `.gz`/`.rkyv`/`.bin` are
        // handled identically to the primary load. The loaded mapper's
        // `transcripts` map holds the secondary build's data (its primary
        // build); we then absorb it as our alt build.
        let other = Self::load(path.as_ref())?;
        Ok(self.absorb_secondary_build(other, build_name))
    }

    /// Reader-based variant of [`Self::load_secondary_build`] for tests and
    /// in-memory callers. Parses a single-build cdot JSON from `reader` and
    /// layers it as `build_name`.
    pub fn load_secondary_build_from_reader<R: Read>(
        &mut self,
        reader: R,
        build_name: &str,
    ) -> Result<usize, FerroError> {
        let other = Self::from_reader_with_build(reader, build_name)?;
        Ok(self.absorb_secondary_build(other, build_name))
    }

    /// Absorb the transcripts of an independently-loaded `other` mapper as the
    /// non-primary build `build_name`. The `other` mapper's primary
    /// `transcripts` become this mapper's `alt_build_transcripts[build_name]`;
    /// any builds `other` itself nested under `genome_builds` are also merged
    /// in (so a multi-build secondary file still contributes its nested views).
    /// Clears the lazy overlap indexes so they rebuild with the new contigs.
    fn absorb_secondary_build(&mut self, other: Self, build_name: &str) -> usize {
        // Snapshot the build's transcript count so we can report how many this
        // secondary file *newly* contributes (the primary cdot may already have
        // populated some `build_name` views from its own `genome_builds`).
        let before = self
            .alt_build_transcripts
            .get(build_name)
            .map_or(0, |m| m.len());
        let CdotMapper {
            transcripts: other_transcripts,
            alt_build_transcripts: other_alt,
            lrg_to_refseq: other_lrg,
            contig_alias_to_canonical: other_aliases,
            ..
        } = other;

        // The requested build's transcripts can arrive two ways: as `other`'s
        // primary view (when the secondary file's primary build *is*
        // `build_name`), or nested under `other.alt_build_transcripts[build_name]`
        // (when the file nests its data under `genome_builds`, which the real
        // RefSeq cdot files do — there the primary view selected by the default
        // load build is empty). Absorb both into our `build_name` slot.
        {
            let target = self
                .alt_build_transcripts
                .entry(build_name.to_string())
                .or_default();
            for (acc, tx) in other_transcripts {
                target.insert(acc, tx);
            }
        }
        // Fold in any builds the secondary file nested under `genome_builds`,
        // EXCEPT the primary build of this mapper (that data is authoritative
        // here and must not be overwritten by a secondary file's view).
        for (nested_build, txs) in other_alt {
            if Some(nested_build.as_str()) == self.primary_build.as_deref() {
                continue;
            }
            let dest = self.alt_build_transcripts.entry(nested_build).or_default();
            for (acc, tx) in txs {
                dest.insert(acc, tx);
            }
        }

        // Carry over the secondary build's contig aliases (e.g. chr17 ↔
        // NC_000017.10) so alt-build contig lookups can resolve UCSC/Ensembl
        // names too. Do not overwrite an existing primary-build alias.
        for (alias, canonical) in other_aliases {
            self.contig_alias_to_canonical
                .entry(alias)
                .or_insert(canonical);
        }
        // Merge LRG mappings the secondary file may carry; keep existing ones.
        for (lrg, refseq) in other_lrg {
            self.lrg_to_refseq.entry(lrg).or_insert(refseq);
        }

        // The new alt-build contigs invalidate the lazy overlap indexes.
        self.alt_build_query_index = OnceCell::new();
        // Report how many transcripts this secondary file newly contributed to
        // `build_name` (the net new entries). For real (`genome_builds`-nested)
        // cdot files the default-build primary view is empty, so the old count —
        // which only tallied `other.transcripts` — logged a misleading "0" even
        // though the build's transcripts were absorbed via the fold above.
        self.alt_build_transcripts
            .get(build_name)
            .map_or(0, |m| m.len())
            .saturating_sub(before)
    }

    /// Merge the transcripts of an independently-loaded cdot file into this
    /// mapper's **primary** build.
    ///
    /// Unlike [`Self::load_secondary_build`] — which layers the *same*
    /// transcripts on a *different* genome build into `alt_build_transcripts` —
    /// this absorbs *distinct* accessions that live on the *same* primary build
    /// (e.g. Ensembl `ENST`/`ENSG`/`ENSP` records from `cdot-*.ensembl.*.json`,
    /// alongside RefSeq `NM_`), so they resolve through the normal primary
    /// lookup path. Returns the number of transcripts merged.
    pub fn merge_primary_build<P: AsRef<Path>>(&mut self, path: P) -> Result<usize, FerroError> {
        let other = Self::load(path.as_ref())?;
        Ok(self.absorb_primary_build(other))
    }

    /// Reader-based variant of [`Self::merge_primary_build`] for tests and
    /// in-memory callers. Parses a single-build cdot JSON from `reader` using
    /// this mapper's primary build (defaulting to `GRCh38`).
    pub fn merge_primary_build_from_reader<R: Read>(
        &mut self,
        reader: R,
    ) -> Result<usize, FerroError> {
        let build = self
            .primary_build
            .clone()
            .unwrap_or_else(|| "GRCh38".to_string());
        let other = Self::from_reader_with_build(reader, &build)?;
        Ok(self.absorb_primary_build(other))
    }

    /// Absorb `other`'s primary-build transcripts into this mapper's primary
    /// build via [`Self::add_transcript`] (which maintains `contig_index` and
    /// the highest-version `base_to_versioned` fallback, and invalidates the
    /// lazy query indexes). Non-primary builds `other` nests under
    /// `genome_builds` are folded into the matching `alt_build_transcripts`
    /// slot so e.g. Ensembl GRCh37 views remain available. Returns the count of
    /// primary-build transcripts merged.
    fn absorb_primary_build(&mut self, other: Self) -> usize {
        let CdotMapper {
            transcripts: other_transcripts,
            alt_build_transcripts: other_alt,
            lrg_to_refseq: other_lrg,
            contig_alias_to_canonical: other_aliases,
            ..
        } = other;

        let mut merged = 0usize;
        for (accession, tx) in other_transcripts {
            self.add_transcript(accession, tx);
            merged += 1;
        }
        // Fold in any non-primary builds the merged file nested under
        // `genome_builds` (e.g. GRCh37 ENST views), without overwriting the
        // authoritative primary build.
        for (nested_build, txs) in other_alt {
            if Some(nested_build.as_str()) == self.primary_build.as_deref() {
                continue;
            }
            let dest = self.alt_build_transcripts.entry(nested_build).or_default();
            for (acc, tx) in txs {
                dest.insert(acc, tx);
            }
        }
        // Carry over contig aliases and LRG mappings without clobbering ours.
        for (alias, canonical) in other_aliases {
            self.contig_alias_to_canonical
                .entry(alias)
                .or_insert(canonical);
        }
        for (lrg, refseq) in other_lrg {
            self.lrg_to_refseq.entry(lrg).or_insert(refseq);
        }
        // The alt-build fold above mutated `alt_build_transcripts` directly, so
        // invalidate the lazy alt-build index (the primary index is already
        // cleared per-transcript by `add_transcript`).
        self.alt_build_query_index = OnceCell::new();
        merged
    }

    /// Create from a raw CdotFile, converting to internal format.
    ///
    /// Captures both the primary build's data (into [`Self::transcripts`])
    /// and any non-primary builds present in the source `genome_builds`
    /// (into [`Self::alt_build_transcripts`]), so callers can later request
    /// a non-default build via
    /// [`get_transcript_on_build`](Self::get_transcript_on_build). The
    /// non-primary capture is best-effort: transcripts that omit a given
    /// build are simply absent from that build's map.
    fn from_raw_cdot_file(raw_file: RawCdotFile, genome_build: &str) -> Self {
        let mut mapper = Self::new();
        mapper.primary_build = Some(genome_build.to_string());

        for (accession, raw_transcript) in raw_file.transcripts {
            // Stash any non-primary build views first so a missing primary-
            // build entry does not skip the alt builds.
            if let Some(builds) = &raw_transcript.genome_builds {
                for build_name in builds.keys() {
                    if build_name == genome_build {
                        continue;
                    }
                    if let Some(tx) = raw_transcript.to_transcript(build_name) {
                        mapper
                            .alt_build_transcripts
                            .entry(build_name.clone())
                            .or_default()
                            .insert(accession.clone(), tx);
                    }
                }
            }

            if let Some(transcript) = raw_transcript.to_transcript(genome_build) {
                mapper.add_transcript(accession, transcript);
            }
        }

        mapper.populate_contig_aliases(genome_build);

        mapper
    }

    /// Create from a parsed CdotFile (already normalized), defaulting to GRCh38 aliases.
    pub fn from_cdot_file(cdot_file: CdotFile) -> Self {
        Self::from_cdot_file_with_build(cdot_file, "GRCh38")
    }

    /// Create from a parsed CdotFile with a specific genome build for contig aliases.
    pub fn from_cdot_file_with_build(cdot_file: CdotFile, genome_build: &str) -> Self {
        let mut mapper = Self::new();
        mapper.primary_build = Some(genome_build.to_string());

        for (accession, transcript) in cdot_file.transcripts {
            mapper.add_transcript(accession, transcript);
        }

        mapper.populate_contig_aliases(genome_build);

        mapper
    }

    /// Add a transcript to the mapper.
    pub fn add_transcript(&mut self, accession: String, transcript: CdotTranscript) {
        // Update contig index
        self.contig_index
            .entry(transcript.contig.clone())
            .or_default()
            .push(accession.clone());

        // Update base to versioned index (e.g., "NM_000088" -> "NM_000088.4").
        //
        // The cdot file deserializes its transcripts into a `HashMap`, so the
        // order `add_transcript` is called in is non-deterministic across runs.
        // A plain last-writer-wins insert would therefore map a base accession
        // to a *random* one of its versions, which surfaces downstream as a
        // run-to-run flip in version-fallback resolution (e.g. requesting
        // `NM_003002.2` — absent from cdot — would resolve to `.3` or `.4`
        // arbitrarily, shifting CDS coordinates by the versions' length delta).
        // Pick the highest version deterministically so the fallback is stable.
        if let Some(base) = accession.split('.').next() {
            let replace = match self.base_to_versioned.get(base) {
                None => true,
                Some(existing) => {
                    (accession_version(&accession), accession.as_str())
                        > (accession_version(existing), existing.as_str())
                }
            };
            if replace {
                self.base_to_versioned
                    .insert(base.to_string(), accession.clone());
            }
        }

        self.transcripts.insert(accession, transcript);

        // Any previously-built query index is stale now. The next query will
        // rebuild it from the updated `contig_index` + `transcripts`. The
        // alt-build index is derived from `alt_build_transcripts`, which
        // `add_transcript` does not touch, but clear it too so any consumer
        // that mixes `add_transcript` with alt-build mutation stays consistent.
        self.contig_query_index = OnceCell::new();
        self.alt_build_query_index = OnceCell::new();
        self.transcript_genome_spans = OnceCell::new();
    }

    /// Build contig alias mappings from `ContigAliases` so that UCSC-style names
    /// (e.g., "chr7") resolve to the RefSeq accessions used as `contig_index` keys.
    fn populate_contig_aliases(&mut self, genome_build: &str) {
        let build = match genome_build {
            "GRCh37" => GenomeBuild::GRCh37,
            "GRCh38" => GenomeBuild::GRCh38,
            _ => {
                log::warn!(
                    "Unsupported genome build '{}'; contig alias resolution is disabled",
                    genome_build
                );
                return;
            }
        };

        let aliases = ContigAliases::default_human();
        for refseq_contig in self.contig_index.keys() {
            // Map UCSC alias (e.g., "chr7") -> RefSeq key (e.g., "NC_000007.14")
            if let Some(ucsc) = aliases.refseq_to_ucsc(refseq_contig) {
                self.contig_alias_to_canonical
                    .insert(ucsc.to_string(), refseq_contig.clone());
            }
            // Map Ensembl alias (e.g., "7") -> RefSeq key
            if let Some(ensembl) = aliases.refseq_to_ensembl(refseq_contig) {
                self.contig_alias_to_canonical
                    .insert(ensembl.to_string(), refseq_contig.clone());
            }
            // Also allow lookup by the other build's RefSeq accession via resolve
            // (e.g., if someone passes "NC_000007.13" but data is GRCh38)
            // This is handled implicitly since we only index contigs present in the data.
        }

        // Also map any non-RefSeq contig_index keys back through to_refseq
        // in case the cdot data itself uses UCSC names.
        let ucsc_keys: Vec<String> = self
            .contig_index
            .keys()
            .filter(|k| k.starts_with("chr"))
            .cloned()
            .collect();
        for ucsc_key in ucsc_keys {
            if let Some(refseq) = aliases.resolve_to_refseq(&ucsc_key, build) {
                self.contig_alias_to_canonical
                    .insert(refseq.to_string(), ucsc_key.clone());
            }
        }
    }

    /// Resolve a contig name through aliases, returning the canonical key used in `contig_index`.
    fn resolve_contig<'a>(&'a self, contig: &'a str) -> &'a str {
        if self.contig_index.contains_key(contig) {
            contig
        } else {
            self.contig_alias_to_canonical
                .get(contig)
                .map(|s| s.as_str())
                .unwrap_or(contig)
        }
    }

    /// Load LRG to RefSeq transcript mapping from a file.
    ///
    /// The file format is tab-separated with columns:
    /// LRG, HGNC_SYMBOL, REFSEQ_GENOMIC, LRG_TRANSCRIPT, REFSEQ_TRANSCRIPT, ENSEMBL_TRANSCRIPT, CCDS
    ///
    /// This creates mappings like "LRG_1t1" -> "NM_000088.3".
    pub fn load_lrg_mapping<P: AsRef<Path>>(&mut self, path: P) -> Result<usize, FerroError> {
        use std::io::BufRead;

        let file = File::open(path.as_ref()).map_err(|e| FerroError::Io {
            msg: format!("Failed to open LRG mapping file: {}", e),
        })?;
        let reader = std::io::BufReader::new(file);

        let mut count = 0;
        for line in reader.lines() {
            let line = line.map_err(|e| FerroError::Io {
                msg: format!("Failed to read LRG mapping line: {}", e),
            })?;

            // Skip comments and empty lines
            if line.starts_with('#') || line.trim().is_empty() {
                continue;
            }

            let fields: Vec<&str> = line.split('\t').collect();
            if fields.len() < 5 {
                continue;
            }

            // Fields: LRG, HGNC_SYMBOL, REFSEQ_GENOMIC, LRG_TRANSCRIPT, REFSEQ_TRANSCRIPT
            let lrg_id = fields[0]; // e.g., "LRG_1"
            let lrg_transcript = fields[3]; // e.g., "t1"
            let refseq_transcript = fields[4]; // e.g., "NM_000088.3"

            // Skip if RefSeq transcript is empty or "-"
            if refseq_transcript.is_empty() || refseq_transcript == "-" {
                continue;
            }

            // Create full LRG transcript ID: "LRG_1t1"
            let lrg_full = format!("{}{}", lrg_id, lrg_transcript);
            self.lrg_to_refseq
                .insert(lrg_full, refseq_transcript.to_string());
            count += 1;
        }

        Ok(count)
    }

    /// Get the RefSeq transcript ID for an LRG transcript.
    pub fn get_refseq_for_lrg(&self, lrg_accession: &str) -> Option<&str> {
        self.lrg_to_refseq.get(lrg_accession).map(|s| s.as_str())
    }

    /// Reverse of [`Self::get_refseq_for_lrg`], scoped to one LRG parent: return
    /// the `LRG_<n>t<k>` hosted by `lrg_parent` (e.g. `"LRG_24"`) whose mapped
    /// RefSeq transcript base-matches `nm` (version-stripped on both sides — the
    /// LRG mapping table pins one NM version while cdot / the projection fan-out
    /// may serve another). Scoping to `lrg_parent` avoids a cross-LRG collision
    /// were some NM base ever hosted by two LRGs. Returns `None` when no hosted
    /// transcript matches (#860).
    pub fn lrg_transcript_for_parent(&self, lrg_parent: &str, nm: &str) -> Option<String> {
        let nm_base = nm.rsplit_once('.').map_or(nm, |(b, _)| b);
        let prefix = format!("{lrg_parent}t");
        self.lrg_to_refseq.iter().find_map(|(lrg_t, refseq)| {
            let refseq_base = refseq.rsplit_once('.').map_or(refseq.as_str(), |(b, _)| b);
            (lrg_t.starts_with(&prefix) && refseq_base == nm_base).then(|| lrg_t.clone())
        })
    }

    /// Test-only: insert an `LRG_<n>t<k>` → versioned `NM_x.v` mapping. The
    /// `lrg_to_refseq` field is private, so tests in other modules (e.g. the
    /// projector's #860 LRG-namespace tests) use this to populate the reverse map.
    #[cfg(test)]
    pub(crate) fn insert_lrg_mapping(&mut self, lrg: String, refseq: String) {
        self.lrg_to_refseq.insert(lrg, refseq);
    }

    /// Get a transcript by accession.
    ///
    /// For LRG transcripts (e.g., "LRG_1t1"), this will look up the equivalent
    /// Whether the mapper has a transcript at exactly the requested accession
    /// (no version-strip or LRG fallback). Used by callers that need to
    /// distinguish "we have your exact version" from "we resolved to a
    /// sibling version" — e.g. the cdot-driven base synthesis path in
    /// `MultiFastaProvider::get_transcript` (closes #331).
    pub fn has_transcript_exact(&self, accession: &str) -> bool {
        // Mirror `get_transcript_exact`'s deferred-Ensembl consult (#964): an
        // exact `ENS*.version` present only in the lazily-loaded Ensembl mapper
        // must probe `true`, or this presence check would return a false negative
        // that disagrees with the resolving lookup. Exact (no version fallback);
        // ENS*-gated so a RefSeq probe never materializes the Ensembl mapper.
        self.transcripts.contains_key(accession)
            || (accession.starts_with("ENS")
                && self
                    .deferred_ensembl_mapper()
                    .is_some_and(|ens| ens.has_transcript_exact(accession)))
    }

    /// Name of the genome build whose data populates [`Self::transcripts`],
    /// or `None` if the build is unknown.
    ///
    /// This is the "primary" build set at load time
    /// (e.g. via [`from_transcripts_with_build`](Self::from_transcripts_with_build)
    /// or [`from_cdot_file_with_build`](Self::from_cdot_file_with_build));
    /// any other builds live in [`Self::alt_build_transcripts`] and are
    /// reachable only through [`get_transcript_on_build`](Self::get_transcript_on_build).
    ///
    /// Returns `None` when the mapper was loaded from a bincode snapshot
    /// produced before the build field was persisted — downstream callers
    /// must surface that uncertainty rather than substituting a default
    /// (#389 follow-up).
    pub fn primary_build(&self) -> Option<&str> {
        self.primary_build.as_deref()
    }

    /// RefSeq transcript if an LRG mapping has been loaded.
    ///
    /// Supports version fallback: if "NM_000088.2" is not found but "NM_000088.3"
    /// exists, the latter will be returned.
    pub fn get_transcript(&self, accession: &str) -> Option<&CdotTranscript> {
        // First try direct lookup
        if let Some(tx) = self.transcripts.get(accession) {
            return Some(tx);
        }

        // Try version fallback (e.g., NM_000088.2 -> NM_000088.3)
        if let Some(base) = accession.split('.').next() {
            if let Some(versioned) = self.base_to_versioned.get(base) {
                if let Some(tx) = self.transcripts.get(versioned) {
                    return Some(tx);
                }
            }
        }

        // For LRG transcripts, try to find via RefSeq mapping
        if accession.starts_with("LRG_") {
            if let Some(refseq) = self.lrg_to_refseq.get(accession) {
                // Try direct lookup of RefSeq
                if let Some(tx) = self.transcripts.get(refseq) {
                    return Some(tx);
                }
                // Try version fallback for RefSeq too
                if let Some(base) = refseq.split('.').next() {
                    if let Some(versioned) = self.base_to_versioned.get(base) {
                        if let Some(tx) = self.transcripts.get(versioned) {
                            return Some(tx);
                        }
                    }
                }
            }
        }

        // Deferred Ensembl (#964): an `ENS*` accession absent from the primary
        // (RefSeq) map resolves via the lazily-loaded Ensembl mapper, including
        // that mapper's own version fallback. RefSeq accessions never reach here
        // for Ensembl, so a pure-RefSeq workload never materializes it.
        self.ensembl_fallback(accession, |ens| ens.get_transcript(accession))
    }

    /// Version-**exact** transcript lookup: like [`get_transcript`](Self::get_transcript)
    /// but **without** the version-fallback that substitutes a sibling version
    /// (`NM_000088.2 → NM_000088.3`).
    ///
    /// Use this where the caller has already committed to a specific version's
    /// *sequence* and must not pair it with a *different* version's CDS/exon
    /// frame. Per HGVS, a `c.`/`r.` description is defined only against its
    /// named `accession.version` — `c.1` is the `A` of that version's start
    /// codon (`background/numbering.md`), and a versioned identifier is required
    /// precisely because versions differ in length/CDS offset
    /// (`background/refseq.md`). Substituting a sibling version's frame onto
    /// another version's sequence yields a spec-invalid description whose stated
    /// reference and coordinate frame disagree (#714).
    ///
    /// The LRG → RefSeq mapping is honored exactly (it is an alias to a specific
    /// `accession.version`, not a version fuzz).
    pub fn get_transcript_exact(&self, accession: &str) -> Option<&CdotTranscript> {
        if let Some(tx) = self.transcripts.get(accession) {
            return Some(tx);
        }
        if accession.starts_with("LRG_") {
            if let Some(refseq) = self.lrg_to_refseq.get(accession) {
                return self.transcripts.get(refseq);
            }
        }
        // Deferred Ensembl (#964): version-exact ENS* lookup via the lazy mapper.
        // The build-aware `*_on_build_exact` / `*_exact_any_build` variants reach
        // GRCh38 Ensembl through their delegation to this method on the primary
        // build, so wiring here covers them too.
        self.ensembl_fallback(accession, |ens| ens.get_transcript_exact(accession))
    }

    /// Build-aware version-**exact** lookup: the
    /// [`get_transcript_on_build`](Self::get_transcript_on_build) analogue of
    /// [`get_transcript_exact`](Self::get_transcript_exact). Consults the
    /// primary build, eagerly-captured alt views, and any deferred secondary
    /// build, but **never** falls back to a different version of the same base
    /// accession (#714).
    pub fn get_transcript_on_build_exact(
        &self,
        accession: &str,
        build: &str,
    ) -> Option<&CdotTranscript> {
        let primary_matches = match self.primary_build.as_deref() {
            Some(pb) => pb == build,
            None => true,
        };
        if primary_matches {
            return self.get_transcript_exact(accession);
        }
        let resolved: &str = if accession.starts_with("LRG_") {
            self.lrg_to_refseq
                .get(accession)
                .map(String::as_str)
                .unwrap_or(accession)
        } else {
            accession
        };
        if let Some(alt) = self.alt_build_transcripts.get(build) {
            if let Some(tx) = alt.get(resolved) {
                return Some(tx);
            }
            // NO version fallback here (exact only) — unlike
            // `get_transcript_on_build`.
        }
        self.deferred_alt_mapper(build)?
            .get_transcript_on_build_exact(accession, build)
    }

    /// Version-**exact** lookup across **all** loaded builds: the primary build,
    /// eagerly-captured alt views, and deferred secondary builds (e.g. a
    /// manifest's GRCh37 cdot).
    ///
    /// CDS bounds in *transcript* coordinates are genome-build-independent, so a
    /// transcript present only in a secondary build still yields the correct
    /// `c.` reading frame for normalization (#718) — the right answer when the
    /// requested version is absent from the active build's cdot but present in
    /// another. Like the other `*_exact` lookups, it **never** substitutes a
    /// different version of the same base.
    ///
    /// CAUTION: genomic/exon **alignment** coordinates ARE build-specific.
    /// Callers must use only the returned CDS (transcript-space) when the hit
    /// comes from a non-primary build, never its genomic placement.
    pub fn get_transcript_exact_any_build(&self, accession: &str) -> Option<&CdotTranscript> {
        if let Some(tx) = self.get_transcript_exact(accession) {
            return Some(tx);
        }
        let resolved: &str = if accession.starts_with("LRG_") {
            self.lrg_to_refseq
                .get(accession)
                .map(String::as_str)
                .unwrap_or(accession)
        } else {
            accession
        };
        // Eagerly-captured alt-build views (exact only — no sibling fallback).
        for alt in self.alt_build_transcripts.values() {
            if let Some(tx) = alt.get(resolved) {
                return Some(tx);
            }
        }
        // Deferred secondary builds, loaded lazily on first access. The deferred
        // mapper is loaded with its own (default) primary build, so the build's
        // transcripts may live in its alt view — query it build-aware-exact,
        // mirroring `get_transcript_on_build`'s deferred path.
        for build in self.deferred_alt_sources.keys() {
            if let Some(tx) = self
                .deferred_alt_mapper(build)
                .and_then(|m| m.get_transcript_on_build_exact(accession, build))
            {
                return Some(tx);
            }
        }
        None
    }

    /// Get a transcript by accession, restricted to a specific genome build.
    ///
    /// When `build` matches the mapper's primary load build, delegates to
    /// [`get_transcript`](Self::get_transcript). Otherwise consults the
    /// alt-build cache (populated from the source cdot JSON's `genome_builds`
    /// section). If the transcript is not found in the eagerly-captured alt
    /// views, falls back to a lazily-loaded deferred secondary build registered
    /// via [`defer_secondary_build`](Self::defer_secondary_build), if any.
    /// Returns `None` if the transcript is absent from the requested build (or
    /// if neither the alt-build cache nor any deferred secondary covers it,
    /// e.g. for bincode-loaded mappers or `from_transcripts`-built mappers).
    ///
    /// This is the lookup used by NG/NC-parent-aware transcript resolution
    /// (issue #332): when the input is `NG_*(NM_*):c.…` or
    /// `NC_*(NM_*):c.…`, the caller infers a build hint from the parent and
    /// asks for that build's view of the NM, so the resulting transcript
    /// carries the correct chromosome alignment.
    pub fn get_transcript_on_build(&self, accession: &str, build: &str) -> Option<&CdotTranscript> {
        // Treat unknown primary build (bincode snapshots without the field)
        // as a match: `alt_build_transcripts` is empty for those mappers so
        // the only data available lives in `transcripts`, and probing that
        // map is strictly better than returning `None` (#389 follow-up).
        let primary_matches = match self.primary_build.as_deref() {
            Some(pb) => pb == build,
            None => true,
        };
        if primary_matches {
            return self.get_transcript(accession);
        }
        // Alt-build path: resolve LRG → RefSeq before consulting the alt
        // map so build-specific lookups honor the same LRG fallback as
        // [`get_transcript`] (#389 follow-up). Without this, a non-primary
        // LRG lookup would return `None` even when the mapped RefSeq
        // transcript exists in the alt build.
        let resolved: &str = if accession.starts_with("LRG_") {
            self.lrg_to_refseq
                .get(accession)
                .map(String::as_str)
                .unwrap_or(accession)
        } else {
            accession
        };
        // Eagerly-captured alt views for this build, if any. Absent when the
        // build is deferred (consulted below).
        if let Some(alt) = self.alt_build_transcripts.get(build) {
            if let Some(tx) = alt.get(resolved) {
                return Some(tx);
            }
            // Version fallback within the alt-build map. Deterministically pick
            // the highest numeric version among siblings sharing the base, rather
            // than the first HashMap iteration hit — alt-build maps occasionally
            // hold more than one version of the same base accession, and
            // returning whichever the hasher landed on first was nondeterministic
            // across runs (#389 follow-up).
            if let Some(base) = resolved.split('.').next() {
                let mut best: Option<(u32, &CdotTranscript)> = None;
                for (k, v) in alt {
                    if !(k.starts_with(base) && k[base.len()..].starts_with('.')) {
                        continue;
                    }
                    let ver = k[base.len() + 1..]
                        .split('.')
                        .next()
                        .and_then(|s| s.parse::<u32>().ok())
                        .unwrap_or(0);
                    if best.is_none_or(|(cur, _)| ver > cur) {
                        best = Some((ver, v));
                    }
                }
                if let Some((_, tx)) = best {
                    return Some(tx);
                }
            }
        }
        // Not in the eagerly-captured alt views — consult a deferred secondary
        // build (e.g. a manifest's GRCh37 cdot) loaded lazily on first use.
        self.deferred_alt_mapper(build)?
            .get_transcript_on_build(accession, build)
    }

    /// Record a secondary build to load lazily on first use, instead of folding
    /// it in eagerly. `path` is any cdot source `load()` accepts (`.json`,
    /// `.json.gz`, `.rkyv`, `.bin`). The build's transcripts are not read until
    /// `deferred_alt_mapper(build)` is first called.
    ///
    /// Calling this again after the `OnceCell` for `build` has already been
    /// initialized updates the recorded path but has no effect on the
    /// already-loaded mapper — `OnceCell` is init-once and the existing value
    /// is returned on all subsequent calls.
    pub fn defer_secondary_build(&mut self, build: &str, path: PathBuf) {
        self.deferred_alt_sources.insert(build.to_string(), path);
        self.lazy_alt_mappers.entry(build.to_string()).or_default();
        // A newly-deferred build adds alt-build contigs; invalidate the lazy
        // overlap index so a previously force-built index doesn't omit them
        // (mirrors the eager `load_secondary_build` reset).
        self.alt_build_query_index = OnceCell::new();
    }

    /// Return the lazily-loaded secondary mapper for `build`, loading it from its
    /// deferred source on first call. `None` if `build` was never deferred or its
    /// source could not be loaded (best-effort; resolved once and not retried).
    fn deferred_alt_mapper(&self, build: &str) -> Option<&CdotMapper> {
        let cell = self.lazy_alt_mappers.get(build)?;
        cell.get_or_init(|| {
            let path = self.deferred_alt_sources.get(build)?;
            match Self::load(path) {
                Ok(m) => {
                    let n = m.alt_build_transcripts.get(build).map_or(0, |t| t.len());
                    eprintln!("Loaded {n} {build} transcripts (deferred secondary build)");
                    Some(Box::new(m))
                }
                Err(e) => {
                    eprintln!(
                        "warning: failed to load deferred {build} cdot {}: {e}",
                        path.display()
                    );
                    None
                }
            }
        })
        .as_deref()
    }

    /// Test probe: has the deferred-load attempt for `build` completed (whether it loaded or failed)?
    #[cfg(test)]
    pub(crate) fn deferred_alt_loaded(&self, build: &str) -> bool {
        self.lazy_alt_mappers
            .get(build)
            .is_some_and(|c| c.get().is_some())
    }

    /// Record the Ensembl cdot to merge lazily on first use, instead of folding
    /// its ~198k `ENST`/`ENSG`/`ENSP` transcripts into the primary build eagerly
    /// (#964). `path` is any cdot source [`load`](Self::load) accepts. The
    /// transcripts are not read until [`deferred_ensembl_mapper`](Self::deferred_ensembl_mapper)
    /// is first called — from the primary-lookup miss path for an `ENS*`
    /// accession (`get_transcript` / `get_transcript_exact`). Genomic-overlap
    /// enumeration is RefSeq-scoped (#933) and does NOT consult it, so a
    /// pure-RefSeq workload never triggers it and RefSeq startup pays nothing for
    /// Ensembl.
    ///
    /// Ensembl transcripts share the *primary* genome build (they are a different
    /// source, not a different build), so they are held in the deferred mapper's
    /// own primary build and consulted alongside — not as an alt build.
    pub fn defer_ensembl_primary_merge(&mut self, path: PathBuf) {
        // Honor init-once/no-retry: only (re)declare the source and reset the
        // once-cell BEFORE the first materialization. After a lookup has already
        // loaded the Ensembl mapper, leave it in place rather than silently
        // swapping the transcript data out from under prior results.
        if self.lazy_ensembl_mapper.get().is_none() {
            self.deferred_ensembl_source = Some(path);
            self.lazy_ensembl_mapper = OnceCell::new();
        }
    }

    /// Return the lazily-loaded Ensembl mapper, loading it from its deferred
    /// source on first call (#964). `None` if no Ensembl source was deferred or
    /// it could not be loaded (best-effort; resolved once and not retried).
    fn deferred_ensembl_mapper(&self) -> Option<&CdotMapper> {
        self.lazy_ensembl_mapper
            .get_or_init(|| {
                let path = self.deferred_ensembl_source.as_ref()?;
                match Self::load(path) {
                    Ok(m) => {
                        eprintln!(
                            "Loaded {} Ensembl transcripts (deferred primary merge)",
                            m.transcripts.len()
                        );
                        Some(Box::new(m))
                    }
                    Err(e) => {
                        eprintln!(
                            "warning: failed to load deferred Ensembl cdot {}: {e}",
                            path.display()
                        );
                        None
                    }
                }
            })
            .as_deref()
    }

    /// Consult the lazily-loaded Ensembl mapper for an `ENS*` accession (#964)
    /// via `lookup` (an exact / fallback lookup on that mapper). Returns `None`
    /// for non-Ensembl accessions and when no Ensembl cdot was deferred, so a
    /// pure-RefSeq lookup never materializes the Ensembl mapper. Centralizes the
    /// `ENS*` guard so every primary-map `-> Option<&CdotTranscript>` accessor
    /// delegates to the *same* method on the Ensembl mapper (exact→exact, etc.),
    /// preserving each accessor's version-fallback semantics.
    fn ensembl_fallback<'a>(
        &'a self,
        accession: &str,
        lookup: impl FnOnce(&'a CdotMapper) -> Option<&'a CdotTranscript>,
    ) -> Option<&'a CdotTranscript> {
        if accession.starts_with("ENS") {
            self.deferred_ensembl_mapper().and_then(lookup)
        } else {
            None
        }
    }

    /// Test probe: has the deferred Ensembl load been triggered yet (#964)?
    #[cfg(test)]
    pub(crate) fn deferred_ensembl_loaded(&self) -> bool {
        self.lazy_ensembl_mapper.get().is_some()
    }

    /// List every genome build that has data for the given transcript.
    ///
    /// Includes the primary build if the transcript is present there. The
    /// returned list is unordered; callers that want a deterministic probe
    /// order (e.g. GRCh38-then-GRCh37) should sort externally.
    ///
    /// Side effect: this can force-load a deferred secondary build on first
    /// use (via `deferred_alt_mapper`), which may read a large cdot source
    /// (~198k transcripts) from disk. Callers on a hot path should be aware
    /// this is not a cheap metadata-only query.
    pub fn available_builds_for(&self, accession: &str) -> Vec<String> {
        let mut builds = Vec::new();
        // Only claim the primary build when we actually know what it is —
        // a bincode snapshot loaded without a recorded build returns
        // `None` here and we omit it rather than fabricate one
        // (#389 follow-up).
        if let Some(primary) = self.primary_build.clone() {
            if self.get_transcript(accession).is_some() {
                builds.push(primary);
            }
        }
        for (build, alt) in &self.alt_build_transcripts {
            // Direct hit, or versioned-base fallback.
            let hit = alt.contains_key(accession)
                || accession.split('.').next().is_some_and(|base| {
                    alt.keys()
                        .any(|k| k.starts_with(base) && k[base.len()..].starts_with('.'))
                });
            if hit {
                builds.push(build.clone());
            }
        }
        // Also consider deferred secondary builds (loaded on demand). Only report
        // a deferred build when it actually has the transcript, mirroring the
        // eager check above.
        let deferred: Vec<String> = self.lazy_alt_mappers.keys().cloned().collect();
        for build in deferred {
            if builds.iter().any(|b| b == &build) {
                continue;
            }
            // `get_transcript_on_build` applies its own version-fallback, so we
            // don't repeat the eager loop's inline fallback here.
            if let Some(sub) = self.deferred_alt_mapper(&build) {
                if sub.get_transcript_on_build(accession, &build).is_some() {
                    builds.push(build);
                }
            }
        }
        builds
    }

    /// Get all transcripts on a contig. Resolves aliases (e.g., "chr7" -> "NC_000007.14").
    pub fn transcripts_on_contig(&self, contig: &str) -> Vec<&str> {
        self.contig_index
            .get(self.resolve_contig(contig))
            .map(|ids| ids.iter().map(|s| s.as_str()).collect())
            .unwrap_or_default()
    }

    /// Find transcripts overlapping a genomic position. Resolves contig aliases.
    ///
    /// Backed by a per-contig SuperIntervals stab-query index that is built
    /// lazily on first call and cached for the lifetime of the `CdotMapper`
    /// (invalidated by `add_transcript`). Replaces the previous linear scan
    /// that re-folded every transcript's exon table on every query.
    pub fn transcripts_at_position(&self, contig: &str, pos: u64) -> Vec<(&str, &CdotTranscript)> {
        let canonical = self.resolve_contig(contig);
        // i32 fits every chromosome in any current build (max ~250M < 2.1B).
        // Positions outside i32 cannot overlap a real transcript span anyway.
        let Ok(p) = i32::try_from(pos) else {
            return Vec::new();
        };

        // NOTE (#964): genomic-overlap enumeration deliberately does NOT consult
        // the deferred Ensembl mapper. Enumeration serves genomic inputs, which
        // #933 source-scoping always classifies as RefSeq, so any Ensembl overlap
        // would be dropped downstream regardless. Ensembl inputs (`ENST`/`ENSG`/
        // `ENSP`) resolve by *accession* via `get_transcript`/`get_transcript_exact`
        // (which do consult the deferred mapper), never by genomic enumeration —
        // so a genomic RefSeq projection never needs to materialize the Ensembl
        // cdot here. If Ensembl-scoped genomic enumeration is ever needed, gate it
        // on the requested source (which this low-level query does not know).

        // Primary build: the contig lives in `contig_index` / `transcripts`.
        let by_contig = self
            .contig_query_index
            .get_or_init(|| self.build_query_index());
        if let (Some(im), Some(accessions)) =
            (by_contig.get(canonical), self.contig_index.get(canonical))
        {
            let mut hits: Vec<u32> = Vec::with_capacity(16);
            im.search_stabbed(p, &mut hits);
            return hits
                .into_iter()
                .filter_map(|idx| {
                    let acc = accessions.get(idx as usize)?;
                    let tx = self.transcripts.get(acc)?;
                    Some((acc.as_str(), tx))
                })
                .collect();
        }

        // Non-primary build: GRCh37/GRCh38 contig accessions are distinct, so
        // the contig itself names the owning build. Route the query into that
        // build's `alt_build_transcripts` map.
        //
        // The index is built lazily and includes contigs from both eagerly-loaded
        // secondary builds (`alt_build_transcripts`) and deferred secondary builds
        // (force-loaded from `lazy_alt_mappers` at index-build time). Transcripts
        // for a given build may be split across both stores (the primary cdot's
        // eager alt-build view and the deferred secondary file), so each hit
        // accession is resolved from both stores before being dropped as missing.
        let alt_by_contig = self
            .alt_build_query_index
            .get_or_init(|| self.build_alt_build_query_index());
        let Some(stab) = alt_by_contig.get(canonical) else {
            return Vec::new();
        };
        let eager_alt = self.alt_build_transcripts.get(&stab.build);
        // Resolve the deferred sub-mapper now (force-loading if needed) so we
        // can check both stores per accession below. If neither store has data
        // for this build the whole query returns empty.
        let deferred_alt = self
            .deferred_alt_mapper(&stab.build)
            .and_then(|sub| sub.alt_build_transcripts.get(&stab.build));
        if eager_alt.is_none() && deferred_alt.is_none() {
            return Vec::new();
        }
        let mut hits: Vec<u32> = Vec::with_capacity(16);
        stab.index.search_stabbed(p, &mut hits);
        hits.into_iter()
            .filter_map(|idx| {
                let acc = stab.accessions.get(idx as usize)?;
                // Check the eager store first; fall back to the deferred store.
                // A transcript can only live in one of the two stores.
                let tx = eager_alt
                    .and_then(|m| m.get(acc))
                    .or_else(|| deferred_alt.and_then(|m| m.get(acc)))?;
                Some((acc.as_str(), tx))
            })
            .collect()
    }

    /// Genomic extent `(min_exon_start, max_exon_end)` of a transcript on
    /// the mapper's primary build, taken from a cached side-table that's
    /// built lazily on first call alongside the contig stab-query index.
    ///
    /// Used by `VariantProjector::project_single_inner` instead of folding
    /// `tx.exons.iter().map(|e| e[0]).min()/max()` per call — the inputs are
    /// stable for the life of the `CdotMapper`, so re-computing every time
    /// (~4.4M folds across the SNP fixture) is pure waste.
    pub fn transcript_genome_span(&self, transcript_id: &str) -> Option<(u64, u64)> {
        let spans = self
            .transcript_genome_spans
            .get_or_init(|| self.build_transcript_genome_spans());
        if let Some(span) = spans.get(transcript_id).copied() {
            return Some(span);
        }
        // Ensembl transcripts live in the deferred Ensembl sub-mapper's own
        // primary build (not `self.transcripts`), so they are absent from the
        // side-table built above. Mirror `ensembl_fallback`/`get_transcript`
        // with a DIRECT lookup on the Ensembl mapper's own span table (this is
        // not the RefSeq-scoped genomic *enumeration* of #933). Without this,
        // genome-pivot projection onto any `ENS*` transcript fails with
        // `ReferenceNotFound`.
        if transcript_id.starts_with("ENS") {
            return self
                .deferred_ensembl_mapper()?
                .transcript_genome_span(transcript_id);
        }
        None
    }

    /// Build-aware variant of [`transcript_genome_span`]: when `build`
    /// matches the primary build the cached side-table is used; otherwise
    /// the span is computed on demand from the alt-build view returned by
    /// [`get_transcript_on_build`]. Returns `None` if cdot has no
    /// alignment for the requested build (or the alignment has no exons).
    ///
    /// The alt-build branch folds the exon table on every call rather
    /// than caching like the primary side-table. This is an acceptable
    /// trade-off until profiling shows otherwise; for callers that
    /// routinely project alt-build inputs against a multi-build cdot it
    /// becomes a per-call O(exons) cost worth caching parallel to
    /// [`Self::transcript_genome_spans`].
    pub fn transcript_genome_span_on_build(
        &self,
        transcript_id: &str,
        build: &str,
    ) -> Option<(u64, u64)> {
        // Mirror the primary-vs-alt routing in `get_transcript_on_build`:
        // unknown primary build (bincode snapshot without the field) means
        // we only have `transcripts` to work with, so use the cached
        // primary-side span (#389 follow-up).
        let primary_matches = match self.primary_build.as_deref() {
            Some(pb) => pb == build,
            None => true,
        };
        if primary_matches {
            return self.transcript_genome_span(transcript_id);
        }
        let tx = self.get_transcript_on_build(transcript_id, build)?;
        let min = tx.exons.iter().map(|e| e[0]).min()?;
        let max = tx.exons.iter().map(|e| e[1]).max()?;
        Some((min, max))
    }

    /// Build the per-transcript span side-table. Same single-pass shape as
    /// `build_query_index` so the two views can't disagree about what
    /// "transcript span" means.
    fn build_transcript_genome_spans(&self) -> FxHashMap<String, (u64, u64)> {
        let mut out =
            FxHashMap::with_capacity_and_hasher(self.transcripts.len(), Default::default());
        for (acc, tx) in &self.transcripts {
            if tx.exons.is_empty() {
                continue;
            }
            let min = tx.exons.iter().map(|e| e[0]).min().unwrap();
            let max = tx.exons.iter().map(|e| e[1]).max().unwrap();
            out.insert(acc.clone(), (min, max));
        }
        out
    }

    /// Construct the per-contig stab-query index. Called at most once per
    /// `CdotMapper` lifetime (until `add_transcript` invalidates the cache).
    ///
    /// SuperIntervals' intervals are end-inclusive (`[start, end]`). To
    /// preserve the old half-open `pos >= min && pos < max` semantics we
    /// insert `[min, max - 1]` and probe with `search_stabbed(pos)`.
    fn build_query_index(&self) -> FxHashMap<String, IntervalMap<u32>> {
        let mut by_contig: FxHashMap<String, IntervalMap<u32>> =
            FxHashMap::with_capacity_and_hasher(self.contig_index.len(), Default::default());
        for (contig, accessions) in &self.contig_index {
            let mut im: IntervalMap<u32> = IntervalMap::new();
            for (idx, acc) in accessions.iter().enumerate() {
                let Some(tx) = self.transcripts.get(acc) else {
                    continue;
                };
                if tx.exons.is_empty() {
                    continue;
                }
                let min = tx.exons.iter().map(|e| e[0]).min().unwrap();
                let max = tx.exons.iter().map(|e| e[1]).max().unwrap();
                if max <= min {
                    continue;
                }
                let (Ok(s), Ok(e)) = (i32::try_from(min), i32::try_from(max - 1)) else {
                    continue;
                };
                im.add(s, e, idx as u32);
            }
            im.build();
            by_contig.insert(contig.clone(), im);
        }
        by_contig
    }

    /// Construct the per-contig stab-query index for the non-primary builds,
    /// derived from [`Self::alt_build_transcripts`] and any deferred secondary
    /// builds registered via [`Self::defer_secondary_build`] (which are
    /// force-loaded here). Mirrors [`Self::build_query_index`] but groups by
    /// `(build, contig)` so a query on an alt-build contig can recover both the
    /// owning build and the accession.
    ///
    /// Because GRCh37 and GRCh38 contig accessions are distinct, no contig is
    /// claimed by two builds; the per-contig map is therefore unambiguous.
    ///
    /// **Merge semantics**: a single build (e.g. "GRCh37") can have transcripts
    /// in *both* the eager store (`self.alt_build_transcripts`) and in a deferred
    /// secondary mapper, potentially on the *same* contig.  The old two-pass
    /// approach (call `index_one_build` once for eager, once for deferred) used
    /// `HashMap::insert` which silently replaced the eager contig stab with the
    /// deferred one, discarding all eagerly-indexed accessions.  The fix below
    /// gathers all `(build, accession)` pairs across **both** stores first, then
    /// builds exactly one `AltBuildContigStab` per contig from the combined,
    /// sorted accession list.
    fn build_alt_build_query_index(&self) -> FxHashMap<String, AltBuildContigStab> {
        // Step 1 — collect (build, Vec<accession>) per contig from every source.
        // A contig maps to exactly one build — NC_*.10 = GRCh37, NC_*.11 =
        // GRCh38 — so first-seen wins; the debug_assert guards the invariant
        // in test builds.
        let mut contig_build: FxHashMap<String, String> = FxHashMap::default();
        let mut contig_accs: FxHashMap<String, Vec<String>> = FxHashMap::default();

        let mut add_transcripts = |build: &str, txs: &FxHashMap<String, CdotTranscript>| {
            for (acc, tx) in txs {
                let contig = &tx.contig;
                let existing = contig_build
                    .entry(contig.clone())
                    .or_insert_with(|| build.to_string());
                debug_assert_eq!(
                    existing.as_str(),
                    build,
                    "contig {contig} claimed by two builds"
                );
                contig_accs
                    .entry(contig.clone())
                    .or_default()
                    .push(acc.clone());
            }
        };

        // Eager store.
        for (build, transcripts) in &self.alt_build_transcripts {
            add_transcripts(build, transcripts);
        }

        // Deferred secondary builds. Collect the keys first to avoid holding a
        // borrow on `self.lazy_alt_mappers` while calling `deferred_alt_mapper`
        // (which also borrows `self`).
        let deferred: Vec<String> = self.lazy_alt_mappers.keys().cloned().collect();
        for build in &deferred {
            if let Some(sub) = self.deferred_alt_mapper(build) {
                if let Some(transcripts) = sub.alt_build_transcripts.get(build.as_str()) {
                    add_transcripts(build, transcripts);
                }
            }
        }

        // Step 2 — for every contig, sort the combined accession list and build
        // one IntervalMap.  To resolve a transcript's exons we need to look the
        // accession up in a transcript map.  A given accession may live in either
        // the eager store or the deferred sub-mapper; try both.
        let mut by_contig: FxHashMap<String, AltBuildContigStab> =
            FxHashMap::with_capacity_and_hasher(contig_accs.len(), Default::default());
        for (contig, mut accessions) in contig_accs {
            // Deterministic payload→accession mapping (HashMap iteration order
            // is random across runs; sort to stabilise the u32 index).
            accessions.sort();
            // An accession present in BOTH the eager alt-build view and the deferred sub-mapper
            // would appear twice in the combined list; dedup keeps the IntervalMap
            // payload->accession mapping 1:1.
            accessions.dedup();

            let build = contig_build
                .get(&contig)
                .expect("contig_build populated in same loop")
                .as_str();

            let eager_map = self.alt_build_transcripts.get(build);
            // Resolve the deferred sub-mapper (force-loading if needed).
            let deferred_map = self
                .deferred_alt_mapper(build)
                .and_then(|sub| sub.alt_build_transcripts.get(build));

            let mut im: IntervalMap<u32> = IntervalMap::new();
            for (idx, acc) in accessions.iter().enumerate() {
                // Look up the transcript in the eager store first, then deferred.
                let tx = eager_map
                    .and_then(|m| m.get(acc))
                    .or_else(|| deferred_map.and_then(|m| m.get(acc)));
                let Some(tx) = tx else {
                    continue;
                };
                if tx.exons.is_empty() {
                    continue;
                }
                let min = tx.exons.iter().map(|e| e[0]).min().unwrap();
                let max = tx.exons.iter().map(|e| e[1]).max().unwrap();
                if max <= min {
                    continue;
                }
                let (Ok(s), Ok(e)) = (i32::try_from(min), i32::try_from(max - 1)) else {
                    continue;
                };
                im.add(s, e, idx as u32);
            }
            im.build();
            by_contig.insert(
                contig,
                AltBuildContigStab {
                    build: build.to_string(),
                    accessions,
                    index: im,
                },
            );
        }
        by_contig
    }

    /// Get the number of transcripts loaded.
    pub fn transcript_count(&self) -> usize {
        self.transcripts.len()
    }

    /// Get all transcript accessions.
    pub fn transcript_ids(&self) -> impl Iterator<Item = &str> {
        self.transcripts.keys().map(|s| s.as_str())
    }

    /// All transcript `accession.version` keys known to this mapper, across the
    /// primary build **and** every layered non-primary build (e.g. GRCh37 in
    /// [`Self::alt_build_transcripts`]).
    ///
    /// Unlike [`Self::transcript_ids`] — which returns only the primary build's
    /// accessions — this also yields versions that exist only on a secondary
    /// build. That matters for callers keyed on "is this exact version known to
    /// cdot at all" rather than "is it placed on the primary build": a version
    /// present only on GRCh37 (e.g. `NM_002001.2`, which GRCh38 cdot superseded
    /// with `.3`/`.4`) still has a deposited mRNA sequence to fetch, so the
    /// version-aware backfill (#842/#802) treats it as in-cdot. The same
    /// accession may appear on multiple builds; callers that need uniqueness
    /// should dedup (the backfill collects into a `HashSet`).
    pub fn all_build_transcript_ids(&self) -> impl Iterator<Item = &str> {
        self.transcripts.keys().map(|s| s.as_str()).chain(
            self.alt_build_transcripts
                .values()
                .flat_map(|by_acc| by_acc.keys().map(|s| s.as_str())),
        )
    }
}

impl Default for CdotMapper {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn lrg_transcript_for_parent_base_insensitive_and_scoped() {
        let mut cdot = CdotMapper::new();
        // LRG file carries .1; cdot/fan-out query .3 — must still match on base.
        cdot.insert_lrg_mapping("LRG_24t1".to_string(), "NM_001114101.1".to_string());
        cdot.insert_lrg_mapping("LRG_24t2".to_string(), "NM_172369.2".to_string());
        cdot.insert_lrg_mapping("LRG_1t1".to_string(), "NM_000079.3".to_string());

        // Version-insensitive base match, scoped to the parent:
        assert_eq!(
            cdot.lrg_transcript_for_parent("LRG_24", "NM_001114101.3")
                .as_deref(),
            Some("LRG_24t1")
        );
        assert_eq!(
            cdot.lrg_transcript_for_parent("LRG_24", "NM_172369.5")
                .as_deref(),
            Some("LRG_24t2")
        );
        // A transcript not hosted by LRG_24 → miss (graceful):
        assert_eq!(
            cdot.lrg_transcript_for_parent("LRG_24", "NM_001347619.2"),
            None
        );
        // Scoping: LRG_1's transcript is not returned under parent LRG_24:
        assert_eq!(
            cdot.lrg_transcript_for_parent("LRG_24", "NM_000079.3"),
            None
        );
    }

    /// #742 regression: a 2-exon minus-strand transcript loaded from raw cdot
    /// JSON (genome 0-based, cdna 1-based — the real cdot convention) maps the
    /// exon-interior, exon-last, and next-exon-first coding bases to the correct
    /// 1-based genomic coordinates. Pre-fix, the last cdna base of an exon
    /// mis-mapped (off by one) and the first base of the next exon declined.
    ///
    /// NM_012459.2 (TIMM8B, GRCh38, NC_000011.10, minus): start_codon=30, exon B
    /// (5') cdna 1..159 = genome 0-based [112086639,112086798), exon A (3') cdna
    /// 160..822 = genome 0-based [112084799,112085462). c.N → tx (cdna) → genome.
    #[test]
    fn cdot_exon_junction_maps_to_correct_genomic_coords_issue_742() {
        use crate::data::mapping::CoordinateMapper;
        let json = r#"
        {
            "transcripts": {
                "NM_012459.2": {
                    "gene_name": "TIMM8B",
                    "genome_builds": {
                        "GRCh38": {
                            "contig": "NC_000011.10",
                            "strand": "-",
                            "exons": [
                                [112084799, 112085462, 1, 160, 822, "M663"],
                                [112086639, 112086798, 0, 1, 159, "M159"]
                            ]
                        }
                    },
                    "start_codon": 30,
                    "stop_codon": 327
                }
            }
        }
        "#;
        let cdot = CdotMapper::from_reader_with_build(json.as_bytes(), "GRCh38").unwrap();
        let tx = cdot.get_transcript("NM_012459.2").unwrap();
        assert_eq!(tx.cds_start, Some(30), "cds_start must survive loading");
        // Exons load in the HGVS convention: genome 1-based, tx 0-based half-open.
        assert_eq!(tx.exons[0], [112086640, 112086799, 0, 159]); // exon B (sorted first)
        assert_eq!(tx.exons[1], [112084800, 112085463, 159, 822]); // exon A

        let mapper = CoordinateMapper::new(cdot);
        let g = |base: i64| {
            mapper
                .cds_to_genome(
                    "NM_012459.2",
                    &CdsPos {
                        base,
                        offset: None,
                        utr3: false,
                        special: None,
                    },
                )
                .unwrap()
                .variant
                .base
        };
        assert_eq!(g(5), 112086764, "c.5 (interior)"); // unchanged by the fix
        assert_eq!(g(127), 112086642, "c.127 (interior)");
        assert_eq!(g(128), 112086641, "c.128 (interior)");
        assert_eq!(g(129), 112086640, "c.129 (last cdna base of exon B)"); // was off-by-one
        assert_eq!(g(130), 112085462, "c.130 (first cdna base of exon A)"); // was a decline
    }

    /// A real cdot-0.2.32 GRCh38 record, plus strand, two contiguous exons.
    ///
    /// `NM_000015.3` (NAT2, MANE Select). Raw genomic CDS `[18400003, 18400876)`;
    /// the record's own `start_codon`/`stop_codon` are 70 and 943.
    const NAT2_PLUS_STRAND_CDOT: &str = r#"{
        "transcripts": {
            "NM_000015.3": {
                "gene_name": "NAT2",
                "protein": "NP_000006.2",
                "genome_builds": {
                    "GRCh38": {
                        "contig": "NC_000008.11",
                        "strand": "+",
                        "cds_start": 18400003,
                        "cds_end": 18400876,
                        "exons": [
                            [18391281, 18391345, 0, 1, 64, null],
                            [18399997, 18401218, 1, 65, 1285, null]
                        ]
                    }
                }
            }
        }
    }"#;

    /// A real cdot-0.2.32 GRCh38 record, minus strand, two contiguous exons.
    ///
    /// `NM_000025.3` (ADRB3, MANE Select). Raw genomic CDS `[37964217, 37966469)`;
    /// the record's own `start_codon`/`stop_codon` are 130 and 1357.
    const ADRB3_MINUS_STRAND_CDOT: &str = r#"{
        "transcripts": {
            "NM_000025.3": {
                "gene_name": "ADRB3",
                "protein": "NP_000016.1",
                "genome_builds": {
                    "GRCh38": {
                        "contig": "NC_000008.11",
                        "strand": "-",
                        "cds_start": 37964217,
                        "cds_end": 37966469,
                        "exons": [
                            [37962989, 37964239, 1, 1336, 2585, null],
                            [37965264, 37966599, 0, 1, 1335, null]
                        ]
                    }
                }
            }
        }
    }"#;

    /// cdot's raw genomic `cds_end` is 0-based **exclusive**, so the genomic-CDS
    /// fallback maps it as-is rather than `+ 1`.
    ///
    /// `RawGenomeBuild::cds_end`'s doc comment said "exclusive" while the
    /// arithmetic beneath it mapped `g_end + 1` and then added a further `+ 1` —
    /// which is only correct if the raw value is inclusive. Real cdot settles it
    /// for the doc comment; this test pins that answer so the contradiction
    /// cannot re-open.
    ///
    /// **The evidence, from cdot-0.2.32 GRCh38 and the prepared reference's
    /// transcript FASTA.** Slicing the real transcript sequence with each
    /// reading, on the two records above:
    ///
    /// | record | reading | CDS slice | length | %3 | first | last |
    /// |---|---|---|---|---|---|---|
    /// | `NM_000015.3` (+) | `g_end + 1` | `[70, 944)` | 874 | 1 | `ATG` | `AGA` |
    /// | `NM_000015.3` (+) | `g_end`     | `[70, 943)` | 873 | 0 | `ATG` | `TAG` |
    /// | `NM_000025.3` (-) | `g_end + 1` | `[129, 1357)` | 1228 | 1 | `GAT` | `TAG` |
    /// | `NM_000025.3` (-) | `g_end`     | `[130, 1357)` | 1227 | 0 | `ATG` | `TAG` |
    ///
    /// Only the `g_end` reading yields a whole number of codons opening on `ATG`
    /// and closing on a stop, and its lengths are the ones the proteins require
    /// (`NP_000006.2` is 290 aa = 873/3 - 1; `NP_000016.1` is 408 aa
    /// = 1227/3 - 1). The defect is strand-symmetric rather than confined to
    /// `cds_end`: the endpoint mapped one base too far is whichever comes later
    /// in transcript order, so on the plus strand `cds_end` overshoots the stop
    /// codon and on the minus strand `cds_start` undershoots the ATG. Either way
    /// the CDS is one base too long, which is why `% 3` is the sharpest census.
    ///
    /// Replayed over every GRCh38 build: with `g_end + 1` the mapped CDS length
    /// is not divisible by three for 354,187 of 355,590 RefSeq coding builds and
    /// 253,433 of 266,774 Ensembl ones; with `g_end` it agrees with the record's
    /// own `start_codon`/`stop_codon` for 354,504 RefSeq and all 266,774 Ensembl
    /// builds. (The RefSeq residue is `genomic_to_tx_pos` not being CIGAR-aware,
    /// which is a separate question and untouched here.)
    #[test]
    fn genomic_cds_fallback_reads_raw_cds_end_as_exclusive() {
        for (accession, json, expected) in [
            ("NM_000015.3", NAT2_PLUS_STRAND_CDOT, (70u64, 943u64)),
            ("NM_000025.3", ADRB3_MINUS_STRAND_CDOT, (130, 1357)),
        ] {
            let label = accession;
            let cdot = CdotMapper::from_reader_with_build(json.as_bytes(), "GRCh38")
                .unwrap_or_else(|e| panic!("{label} fixture should parse: {e}"));
            let tx = cdot
                .get_transcript(accession)
                .unwrap_or_else(|| panic!("{label} should load"));

            assert_eq!(
                (tx.cds_start, tx.cds_end),
                (Some(expected.0), Some(expected.1)),
                "{label}: the genomic-CDS fallback must reproduce the record's own \
                 start_codon/stop_codon. Reading the raw cds_end as inclusive \
                 (mapping `g_end + 1`) yields a CDS one base too long."
            );

            let cds_length = tx.cds_length().expect("CDS is defined");
            assert_eq!(
                cds_length % 3,
                0,
                "{label}: a coding CDS must be a whole number of codons, got {cds_length}"
            );
        }
    }

    /// The genomic-CDS fallback and the `start_codon`/`stop_codon` branch must
    /// agree on a record that could take either.
    ///
    /// `from_genome_build` prefers the codon fields and reaches the genomic CDS
    /// only when a record carries neither — which no build in cdot-0.2.32
    /// GRCh38 does (0 of 482,519 RefSeq and 0 of 574,584 Ensembl), so the
    /// fallback is currently unreachable on real data and nothing else in the
    /// suite covers it. Deleting the codon fields from a real record is what
    /// makes it reachable while keeping a known-correct answer to check against:
    /// the deleted values themselves.
    #[test]
    fn genomic_cds_fallback_agrees_with_the_start_stop_codon_branch() {
        for (accession, json, codons) in [
            ("NM_000015.3", NAT2_PLUS_STRAND_CDOT, (70u64, 943u64)),
            ("NM_000025.3", ADRB3_MINUS_STRAND_CDOT, (130, 1357)),
        ] {
            let label = accession;
            // Re-attach the codon fields the fixtures deliberately omit, so the
            // same record loads down the *other* branch.
            let with_codons = json.replacen(
                "\"genome_builds\"",
                &format!(
                    "\"start_codon\": {}, \"stop_codon\": {}, \"genome_builds\"",
                    codons.0, codons.1
                ),
                1,
            );

            let load = |src: &str| {
                let cdot = CdotMapper::from_reader_with_build(src.as_bytes(), "GRCh38")
                    .unwrap_or_else(|e| panic!("{label} fixture should parse: {e}"));
                let tx = cdot.get_transcript(accession).expect("transcript loads");
                (tx.cds_start, tx.cds_end)
            };

            assert_eq!(
                load(json),
                load(&with_codons),
                "{label}: the genomic-CDS fallback must agree with the \
                 start_codon/stop_codon branch on the same record"
            );
        }
    }

    /// Builds a minimal `RawGenomeBuild` carrying the given cdot `tag` string
    /// (or none), with no exons — sufficient to exercise
    /// `from_genome_build`'s tag parsing without needing real alignment data.
    fn raw_genome_build_with_tag(tag: Option<&str>) -> RawGenomeBuild {
        RawGenomeBuild {
            contig: "NC_000001.11".to_string(),
            strand: Some("+".to_string()),
            exons: Vec::new(),
            cds_start: None,
            cds_end: None,
            tag: tag.map(str::to_string),
        }
    }

    /// Minimal `RawCdotTranscript` with no transcript-level start/stop codon,
    /// so `from_genome_build` never touches `start_codon`/`stop_codon` and the
    /// only thing under test is `RawGenomeBuild::tag` -> `cds_start_incomplete`.
    fn raw_cdot_transcript_for_tag_test() -> RawCdotTranscript {
        RawCdotTranscript {
            gene_name: None,
            gene_version: None,
            biotype: None,
            protein: None,
            genome_builds: None,
            start_codon: None,
            stop_codon: None,
            contig: None,
            strand: None,
            exons: None,
            cds_start: None,
            cds_end: None,
        }
    }

    #[test]
    fn cds_start_nf_tag_sets_flag_true() {
        let build = raw_genome_build_with_tag(Some("cds_start_NF,mRNA_start_NF"));
        let raw = raw_cdot_transcript_for_tag_test();
        let tx = raw.from_genome_build(&build).expect("builds transcript");
        assert!(tx.cds_start_incomplete);
    }

    #[test]
    fn cds_start_nf_tag_absent_leaves_flag_false() {
        let build = raw_genome_build_with_tag(None);
        let raw = raw_cdot_transcript_for_tag_test();
        let tx = raw.from_genome_build(&build).expect("builds transcript");
        assert!(!tx.cds_start_incomplete);
    }

    #[test]
    fn cds_start_nf_tag_other_value_leaves_flag_false() {
        let build = raw_genome_build_with_tag(Some("MANE_Select"));
        let raw = raw_cdot_transcript_for_tag_test();
        let tx = raw.from_genome_build(&build).expect("builds transcript");
        assert!(!tx.cds_start_incomplete);
    }

    /// Builds a plus-strand `RawGenomeBuild` with three contiguous exons whose
    /// middle row (`101..200`, exon 1) is replaced by `middle_row`, and a genomic
    /// CDS spanning the outer exons. Used to exercise the malformed-row refusal in
    /// `from_genome_build` (#1924): with the intact six-field middle row the whole
    /// well-formed table loads, and any malformed substitute must refuse the
    /// transcript rather than drop the row and serve a two-exon table.
    fn raw_genome_build_with_middle_row(middle_row: Vec<serde_json::Value>) -> RawGenomeBuild {
        use serde_json::json;
        RawGenomeBuild {
            contig: "NC_000001.11".to_string(),
            strand: Some("+".to_string()),
            exons: vec![
                vec![
                    json!(1000),
                    json!(1100),
                    json!(0),
                    json!(1),
                    json!(100),
                    json!(null),
                ],
                middle_row,
                vec![
                    json!(1200),
                    json!(1300),
                    json!(2),
                    json!(201),
                    json!(300),
                    json!(null),
                ],
            ],
            cds_start: Some(1010),
            cds_end: Some(1250),
            tag: None,
        }
    }

    /// The well-formed three-exon table loads with all three exons and a CDS
    /// derived from the genomic fallback. This is the control the two refusal
    /// cases below are measured against — it must stay green so the refusal is
    /// shown to be specific to malformed rows, not a blanket rejection (#1924).
    #[test]
    fn well_formed_exon_table_loads_with_every_exon() {
        use serde_json::json;
        let build = raw_genome_build_with_middle_row(vec![
            json!(1100),
            json!(1200),
            json!(1),
            json!(101),
            json!(200),
            json!(null),
        ]);
        let raw = raw_cdot_transcript_for_tag_test();
        let tx = raw
            .from_genome_build(&build)
            .expect("a well-formed cdot exon table must load");
        assert_eq!(tx.exons.len(), 3, "every exon row must be kept");
        assert_eq!((tx.cds_start, tx.cds_end), (Some(10), Some(250)));
    }

    /// A row that legitimately omits only the optional `gap_info` field (five
    /// fields, not six) is still well-formed and must load — the refusal keys on
    /// the *placement* coordinates, not on a full six-field count, so a missing
    /// CIGAR slot is not malformed (#1924).
    #[test]
    fn exon_row_without_gap_info_field_still_loads() {
        use serde_json::json;
        let build = raw_genome_build_with_middle_row(vec![
            json!(1100),
            json!(1200),
            json!(1),
            json!(101),
            json!(200),
        ]);
        let raw = raw_cdot_transcript_for_tag_test();
        let tx = raw
            .from_genome_build(&build)
            .expect("a five-field row (no gap_info) is well-formed and must load");
        assert_eq!(tx.exons.len(), 3);
        assert_eq!((tx.cds_start, tx.cds_end), (Some(10), Some(250)));
    }

    /// A truncated exon row (fewer than the five leading placement fields) must
    /// refuse the whole transcript. Before #1924 it was silently dropped, leaving
    /// a two-exon table with a synthetic gap and a displaced-looking CDS derived
    /// from the partial table — corruption that looks well-formed and in-bounds.
    #[test]
    fn truncated_exon_row_refuses_the_transcript() {
        use serde_json::json;
        let build = raw_genome_build_with_middle_row(vec![json!(1100), json!(1200), json!(1)]);
        let raw = raw_cdot_transcript_for_tag_test();
        assert!(
            raw.from_genome_build(&build).is_none(),
            "a truncated exon row must refuse the transcript, not drop the row"
        );
    }

    /// The same refusal covers an *inconsistent* row: a full six-field row whose
    /// placement coordinate is non-numeric cannot be parsed into an exon and used
    /// to be silently dropped by the `?`-in-`filter_map`, opening the same gap as
    /// a truncated row. It must refuse the transcript too (#1924).
    #[test]
    fn non_numeric_exon_coordinate_refuses_the_transcript() {
        use serde_json::json;
        let build = raw_genome_build_with_middle_row(vec![
            json!(1100),
            json!(1200),
            json!(1),
            json!("not-a-number"),
            json!(200),
            json!(null),
        ]);
        let raw = raw_cdot_transcript_for_tag_test();
        assert!(
            raw.from_genome_build(&build).is_none(),
            "a non-numeric exon coordinate must refuse the transcript, not drop the row"
        );
    }

    fn sample_transcript() -> CdotTranscript {
        // Simple transcript with 3 exons on + strand
        // Exons: [genome_start, genome_end, tx_start, tx_end]
        CdotTranscript {
            cds_start_incomplete: false,
            gene_name: Some("TEST".to_string()),
            contig: "NC_000001.11".to_string(),
            strand: Strand::Plus,
            exons: vec![
                [1000, 1100, 0, 100],   // Exon 1: 100bp
                [2000, 2200, 100, 300], // Exon 2: 200bp
                [3000, 3150, 300, 450], // Exon 3: 150bp
            ],
            cds_start: Some(50), // CDS starts 50bp into transcript
            cds_end: Some(400),  // CDS ends 400bp into transcript
            exon_cigars: Vec::new(),
            gene_id: None,
            protein: None,
        }
    }

    fn minus_strand_transcript() -> CdotTranscript {
        // Transcript on - strand
        CdotTranscript {
            cds_start_incomplete: false,
            gene_name: Some("MINUS".to_string()),
            contig: "NC_000001.11".to_string(),
            strand: Strand::Minus,
            exons: vec![
                [3000, 3150, 0, 150],   // Exon 1 (most 3' on genome)
                [2000, 2200, 150, 350], // Exon 2
                [1000, 1100, 350, 450], // Exon 3 (most 5' on genome)
            ],
            cds_start: Some(50),
            cds_end: Some(400),
            exon_cigars: Vec::new(),
            gene_id: None,
            protein: None,
        }
    }

    // CdotTranscript tests
    #[test]
    fn test_transcript_length() {
        let tx = sample_transcript();
        assert_eq!(tx.transcript_length(), 450);
    }

    #[test]
    fn test_cds_length() {
        let tx = sample_transcript();
        assert_eq!(tx.cds_length(), Some(350));
    }

    #[test]
    fn test_exon_for_tx_pos() {
        let tx = sample_transcript();

        // Position in first exon
        let exon = tx.exon_for_tx_pos(50).unwrap();
        assert_eq!(exon.number, 1);

        // Position in second exon
        let exon = tx.exon_for_tx_pos(150).unwrap();
        assert_eq!(exon.number, 2);

        // Position in third exon
        let exon = tx.exon_for_tx_pos(350).unwrap();
        assert_eq!(exon.number, 3);

        // Position beyond transcript
        assert!(tx.exon_for_tx_pos(500).is_none());
    }

    #[test]
    fn test_exon_for_genome_pos() {
        let tx = sample_transcript();

        // Position in first exon
        let exon = tx.exon_for_genome_pos(1050).unwrap();
        assert_eq!(exon.number, 1);

        // Position in second exon
        let exon = tx.exon_for_genome_pos(2100).unwrap();
        assert_eq!(exon.number, 2);

        // Position in intron
        assert!(tx.exon_for_genome_pos(1500).is_none());
    }

    #[test]
    fn test_tx_to_genome_plus_strand() {
        let tx = sample_transcript();

        // First exon
        assert_eq!(tx.tx_to_genome(0), Some(1000));
        assert_eq!(tx.tx_to_genome(50), Some(1050));
        assert_eq!(tx.tx_to_genome(99), Some(1099));

        // Second exon
        assert_eq!(tx.tx_to_genome(100), Some(2000));
        assert_eq!(tx.tx_to_genome(200), Some(2100));

        // Third exon
        assert_eq!(tx.tx_to_genome(300), Some(3000));
    }

    #[test]
    fn test_tx_to_genome_minus_strand() {
        let tx = minus_strand_transcript();

        // First exon (3' on genome)
        assert_eq!(tx.tx_to_genome(0), Some(3149));
        assert_eq!(tx.tx_to_genome(50), Some(3099));
        assert_eq!(tx.tx_to_genome(149), Some(3000));

        // Second exon
        assert_eq!(tx.tx_to_genome(150), Some(2199));
    }

    #[test]
    fn test_tx_to_genome_extending_polya_plus_strand() {
        let tx = sample_transcript(); // last exon [3000, 3150, 300, 450]

        // In-exon positions delegate to the unchanged `tx_to_genome`.
        assert_eq!(tx.tx_to_genome_extending_polya(300), Some(3000));
        assert_eq!(tx.tx_to_genome_extending_polya(449), Some(3149));

        // Poly-A region (past the 3'-terminal exon end): contiguous downstream
        // genome walk. `genome_end` (3150) is exclusive, so it is already the
        // first downstream base.
        assert_eq!(tx.tx_to_genome_extending_polya(450), Some(3150));
        assert_eq!(tx.tx_to_genome_extending_polya(460), Some(3160));
    }

    #[test]
    fn test_tx_to_genome_extending_polya_minus_strand() {
        let tx = minus_strand_transcript(); // last exon [1000, 1100, 350, 450]

        // In-exon positions delegate to `tx_to_genome` (genome_end-1-offset).
        assert_eq!(tx.tx_to_genome_extending_polya(350), Some(1099));
        assert_eq!(tx.tx_to_genome_extending_polya(449), Some(1000));

        // Poly-A region: walk *down* in genome from genome_start - 1.
        assert_eq!(tx.tx_to_genome_extending_polya(450), Some(999));
        assert_eq!(tx.tx_to_genome_extending_polya(460), Some(989));
    }

    #[test]
    fn test_tx_to_genome_extending_polya_minus_underflow_declines() {
        // A minus-strand transcript whose 3'-terminal exon abuts genome
        // position 1 — extending into the poly-A region would underflow below
        // the 1-based genome origin, so it must decline rather than emit g.0.
        let tx = CdotTranscript {
            cds_start_incomplete: false,
            gene_name: Some("EDGE".to_string()),
            contig: "NC_000001.11".to_string(),
            strand: Strand::Minus,
            exons: vec![[1, 6, 0, 5]], // genome_start = 1, tx_end = 5
            cds_start: Some(0),
            cds_end: Some(3),
            exon_cigars: Vec::new(),
            gene_id: None,
            protein: None,
        };
        // tx 5 → genome_start - 1 - 0 = 0 → invalid (1-based) → None.
        assert_eq!(tx.tx_to_genome_extending_polya(5), None);
        // tx 6 would be even further below → None.
        assert_eq!(tx.tx_to_genome_extending_polya(6), None);
        // In-exon position still maps fine.
        assert_eq!(tx.tx_to_genome_extending_polya(0), Some(5));
    }

    #[test]
    fn test_tx_to_genome_extending_polya_plus_overflow_declines() {
        // A plus-strand transcript whose 3'-terminal exon abuts the very top of
        // the u64 coordinate range — extending into the poly-A region would
        // overflow `genome_end + delta`, so it must decline (via `checked_add`)
        // rather than wrap/panic before the caller's contig-bound check.
        let tx = CdotTranscript {
            cds_start_incomplete: false,
            gene_name: Some("EDGE".to_string()),
            contig: "NC_000001.11".to_string(),
            strand: Strand::Plus,
            // genome_end == u64::MAX, tx_end == 5.
            exons: vec![[u64::MAX - 5, u64::MAX, 0, 5]],
            cds_start: Some(0),
            cds_end: Some(3),
            exon_cigars: Vec::new(),
            gene_id: None,
            protein: None,
        };
        // tx 5 → genome_end + 0 == u64::MAX (no overflow): still a coordinate.
        assert_eq!(tx.tx_to_genome_extending_polya(5), Some(u64::MAX));
        // tx 6 → genome_end + 1 overflows → None (declines, no panic/wrap).
        assert_eq!(tx.tx_to_genome_extending_polya(6), None);
        // In-exon position still maps fine.
        assert_eq!(tx.tx_to_genome_extending_polya(0), Some(u64::MAX - 5));
    }

    #[test]
    fn test_tx_to_genome_extending_polya_intronic_hole_declines() {
        // A `tx_pos` that has no exon but is BEFORE the terminal exon's end is a
        // gap/hole, not the poly-A region — must not be extended. Construct a tx
        // with a transcript-coordinate gap between exons (non-contiguous tx),
        // which never occurs in real cdot but guards the branch.
        let tx = CdotTranscript {
            cds_start_incomplete: false,
            gene_name: Some("GAP".to_string()),
            contig: "NC_000001.11".to_string(),
            strand: Strand::Plus,
            exons: vec![
                [1000, 1100, 0, 100],
                // tx gap: 100..200 has no exon; next exon starts at tx 200.
                [2000, 2100, 200, 300],
            ],
            cds_start: Some(10),
            cds_end: Some(250),
            exon_cigars: Vec::new(),
            gene_id: None,
            protein: None,
        };
        // tx 150 falls in the tx-coordinate hole (< terminal tx_end 300) → None.
        assert_eq!(tx.tx_to_genome_extending_polya(150), None);
        // tx 300 is past the terminal exon end → poly-A extension applies.
        assert_eq!(tx.tx_to_genome_extending_polya(300), Some(2100));
    }

    #[test]
    fn test_genome_to_tx_plus_strand() {
        let tx = sample_transcript();

        // First exon
        assert_eq!(tx.genome_to_tx(1000), Some(0));
        assert_eq!(tx.genome_to_tx(1050), Some(50));

        // Second exon
        assert_eq!(tx.genome_to_tx(2000), Some(100));

        // Intron
        assert!(tx.genome_to_tx(1500).is_none());
    }

    #[test]
    fn test_genome_to_tx_minus_strand() {
        let tx = minus_strand_transcript();

        // First exon (3' on genome)
        assert_eq!(tx.genome_to_tx(3149), Some(0));
        assert_eq!(tx.genome_to_tx(3000), Some(149));

        // Second exon
        assert_eq!(tx.genome_to_tx(2199), Some(150));
    }

    /// c15 early-termination relies on the cdot sort invariant — exons are
    /// in `tx_start`-ascending order, which means `genome_start` is
    /// monotonically increasing on plus-strand and decreasing on
    /// minus-strand. These tests pin both the off-transcript None return and
    /// the in-transcript Some return so a future change to either the sort
    /// invariant or the early-break condition is caught.
    #[test]
    fn test_exon_for_genome_pos_plus_strand_early_term() {
        let tx = sample_transcript(); // exons at [1000,1100), [2000,2200), [3000,3150)
                                      // Below all exons → None.
        assert!(tx.exon_for_genome_pos(500).is_none());
        // Between exon 0 and 1 (intronic) → None.
        assert!(tx.exon_for_genome_pos(1500).is_none());
        // Above all exons → None.
        assert!(tx.exon_for_genome_pos(5000).is_none());
        // Inside each exon → Some(...).
        assert!(tx.exon_for_genome_pos(1050).is_some());
        assert!(tx.exon_for_genome_pos(2100).is_some());
        assert!(tx.exon_for_genome_pos(3100).is_some());
    }

    #[test]
    fn test_exon_for_genome_pos_minus_strand_early_term() {
        let tx = minus_strand_transcript();
        // The minus-strand fixture has exons (in tx-order, i.e. high→low
        // genome): [3000,3150), [2000,2200), [1000,1100).
        assert!(tx.exon_for_genome_pos(5000).is_none()); // above all
        assert!(tx.exon_for_genome_pos(2500).is_none()); // intronic between 3000 and 2200
        assert!(tx.exon_for_genome_pos(500).is_none()); // below all
        assert!(tx.exon_for_genome_pos(3050).is_some()); // first exon (highest)
        assert!(tx.exon_for_genome_pos(2100).is_some()); // middle exon
        assert!(tx.exon_for_genome_pos(1050).is_some()); // last exon (lowest)
    }

    #[test]
    fn test_locate_genome_pos_matches_exon_lookup() {
        // `locate_genome_pos` must agree with `exon_for_genome_pos` +
        // `genome_to_tx` on which exon (and what tx position) a query maps
        // to. Sweep a representative range of positions and require either
        // both succeed with the same exon number or both return None.
        for tx in [sample_transcript(), minus_strand_transcript()] {
            for pos in (500..5500).step_by(37) {
                let combined = tx.locate_genome_pos(pos);
                let separate = match (tx.genome_to_tx(pos), tx.exon_for_genome_pos(pos)) {
                    (Some(tp), Some(ex)) => Some((tp, ex)),
                    _ => None,
                };
                assert_eq!(
                    combined.map(|(tp, ex)| (tp, ex.number)),
                    separate.map(|(tp, ex)| (tp, ex.number)),
                    "disagreement at pos {pos} for {:?}-strand",
                    tx.strand
                );
            }
        }
    }

    #[test]
    fn test_cds_to_tx() {
        let tx = sample_transcript();

        // Normal CDS position
        assert_eq!(tx.cds_to_tx(1), Some(50)); // c.1 -> tx pos 50
        assert_eq!(tx.cds_to_tx(100), Some(149)); // c.100 -> tx pos 149

        // 5' UTR
        assert_eq!(tx.cds_to_tx(-1), Some(49)); // c.-1 -> tx pos 49
        assert_eq!(tx.cds_to_tx(-50), Some(0)); // c.-50 -> tx pos 0

        // Position 0 invalid
        assert!(tx.cds_to_tx(0).is_none());
    }

    #[test]
    fn test_tx_to_cds() {
        let tx = sample_transcript();

        // 5' UTR
        assert_eq!(tx.tx_to_cds(0), Some(CdsPosition::FivePrimeUtr(50)));
        assert_eq!(tx.tx_to_cds(49), Some(CdsPosition::FivePrimeUtr(1)));

        // CDS
        assert_eq!(tx.tx_to_cds(50), Some(CdsPosition::Cds(1)));
        assert_eq!(tx.tx_to_cds(149), Some(CdsPosition::Cds(100)));
        assert_eq!(tx.tx_to_cds(399), Some(CdsPosition::Cds(350)));

        // 3' UTR
        assert_eq!(tx.tx_to_cds(400), Some(CdsPosition::ThreePrimeUtr(1)));
        assert_eq!(tx.tx_to_cds(449), Some(CdsPosition::ThreePrimeUtr(50)));
    }

    // Exon tests
    #[test]
    fn test_exon_len() {
        let exon = Exon::from_array(1, [1000, 1100, 0, 100]);
        assert_eq!(exon.len(), 100);
        assert!(!exon.is_empty());
    }

    #[test]
    fn test_exon_contains() {
        let exon = Exon::from_array(1, [1000, 1100, 0, 100]);

        assert!(exon.contains_genome_pos(1000));
        assert!(exon.contains_genome_pos(1099));
        assert!(!exon.contains_genome_pos(1100));

        assert!(exon.contains_tx_pos(0));
        assert!(exon.contains_tx_pos(99));
        assert!(!exon.contains_tx_pos(100));
    }

    // CdotMapper tests
    #[test]
    fn test_mapper_new() {
        let mapper = CdotMapper::new();
        assert_eq!(mapper.transcript_count(), 0);
    }

    #[test]
    fn test_mapper_add_transcript() {
        let mut mapper = CdotMapper::new();
        mapper.add_transcript("NM_000088.3".to_string(), sample_transcript());

        assert_eq!(mapper.transcript_count(), 1);
        assert!(mapper.get_transcript("NM_000088.3").is_some());
        // Version fallback: NM_000088.4 falls back to NM_000088.3
        assert!(mapper.get_transcript("NM_000088.4").is_some());
        // Completely different accession should return None
        assert!(mapper.get_transcript("NM_999999.1").is_none());
    }

    #[test]
    fn test_mapper_contig_index() {
        let mut mapper = CdotMapper::new();
        mapper.add_transcript("NM_000088.3".to_string(), sample_transcript());
        mapper.add_transcript("NM_000088.4".to_string(), sample_transcript());

        let tx_ids = mapper.transcripts_on_contig("NC_000001.11");
        assert_eq!(tx_ids.len(), 2);
        assert!(tx_ids.contains(&"NM_000088.3"));
        assert!(tx_ids.contains(&"NM_000088.4"));

        let tx_ids = mapper.transcripts_on_contig("NC_000002.12");
        assert!(tx_ids.is_empty());
    }

    #[test]
    fn test_contig_alias_lookup_grch38() {
        // Transcripts indexed by RefSeq accession should also be found by UCSC name.
        let json = r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "contig": "NC_000017.11",
                    "strand": "+",
                    "exons": [[50184096, 50184169, 0, 73]],
                    "cds_start": 10,
                    "cds_end": 60
                }
            }
        }
        "#;
        let mapper = CdotMapper::from_reader(json.as_bytes()).unwrap();

        // Lookup by RefSeq accession (canonical key)
        assert_eq!(mapper.transcripts_on_contig("NC_000017.11").len(), 1);
        // Lookup by UCSC alias
        assert_eq!(mapper.transcripts_on_contig("chr17").len(), 1);
        // Lookup by Ensembl alias
        assert_eq!(mapper.transcripts_on_contig("17").len(), 1);
        // Non-existent contig
        assert!(mapper.transcripts_on_contig("chr99").is_empty());
    }

    #[test]
    fn test_contig_alias_lookup_grch37() {
        let json = r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "genome_builds": {
                        "GRCh37": {
                            "contig": "NC_000017.10",
                            "strand": "+",
                            "exons": [[48263025, 48263098, 1, 0, 73, "M73"]]
                        }
                    },
                    "start_codon": 10,
                    "stop_codon": 60
                }
            }
        }
        "#;
        let mapper = CdotMapper::from_reader_with_build(json.as_bytes(), "GRCh37").unwrap();

        assert_eq!(mapper.transcripts_on_contig("NC_000017.10").len(), 1);
        assert_eq!(mapper.transcripts_on_contig("chr17").len(), 1);
        assert_eq!(mapper.transcripts_on_contig("17").len(), 1);

        // Verify the transcript was fully parsed (not dropped due to bad exon format)
        let tx = mapper.get_transcript("NM_000088.3").unwrap();
        assert_eq!(tx.exons.len(), 1);
        // #742: exons are stored in the HGVS convention (genome 1-based), so the
        // raw cdot 0-based `alt_start`/`alt_end` (48263025, 48263098) load as
        // 1-based `genome_start`/`genome_end` (+1 each).
        assert_eq!(tx.exons[0][0], 48263026); // genome_start (1-based incl)
        assert_eq!(tx.exons[0][1], 48263099); // genome_end (1-based excl)
    }

    #[test]
    fn test_merge_primary_build_adds_ensembl_alongside_refseq() {
        // A RefSeq cdot mapper (NM_) ...
        let refseq = r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "contig": "NC_000017.11",
                    "strand": "+",
                    "exons": [[50184096, 50184169, 0, 73]],
                    "cds_start": 10,
                    "cds_end": 60
                }
            }
        }
        "#;
        let mut mapper = CdotMapper::from_reader(refseq.as_bytes()).unwrap();
        assert!(mapper.get_transcript("NM_000088.3").is_some());
        assert!(mapper.get_transcript("ENST00000375549.8").is_none());

        // ... merged with an Ensembl cdot file (ENST, distinct accession on the
        // same primary build) resolves BOTH through the primary lookup path.
        let ensembl = r#"
        {
            "transcripts": {
                "ENST00000375549.8": {
                    "gene_name": "EDN1",
                    "contig": "NC_000006.12",
                    "strand": "+",
                    "exons": [[12290360, 12290460, 0, 100]],
                    "cds_start": 5,
                    "cds_end": 95
                }
            }
        }
        "#;
        let merged = mapper
            .merge_primary_build_from_reader(ensembl.as_bytes())
            .unwrap();
        assert_eq!(merged, 1, "one Ensembl transcript merged");

        // RefSeq still resolves; Ensembl now resolves too.
        assert!(mapper.get_transcript("NM_000088.3").is_some());
        let enst = mapper
            .get_transcript("ENST00000375549.8")
            .expect("merged ENST resolves");
        assert_eq!(enst.gene_name.as_deref(), Some("EDN1"));

        // Version-fallback (base -> highest version) works for the merged ENST.
        assert!(mapper.get_transcript("ENST00000375549").is_some());
        // The Ensembl contig was indexed alongside the RefSeq one.
        assert_eq!(mapper.transcripts_on_contig("NC_000006.12").len(), 1);
        assert_eq!(mapper.transcripts_on_contig("NC_000017.11").len(), 1);
    }

    #[test]
    fn test_from_transcripts_populates_contig_aliases_grch38() {
        use crate::reference::transcript::{Exon, ManeStatus, Transcript};
        use crate::reference::Strand as TxStrand;
        use std::sync::OnceLock;

        let tx = Transcript {
            cds_start_incomplete: false,
            id: "NM_000088.3".to_string(),
            gene_symbol: Some("COL1A1".to_string()),
            strand: TxStrand::Plus,
            sequence: None,
            cds_start: Some(11),
            cds_end: Some(60),
            exons: vec![Exon::with_genomic(1, 1, 73, 50184096, 50184168)],
            chromosome: Some("NC_000017.11".to_string()),
            genomic_start: Some(50184096),
            genomic_end: Some(50184168),
            genome_build: GenomeBuild::GRCh38,
            mane_status: ManeStatus::default(),
            refseq_match: None,
            ensembl_match: None,
            protein_id: None,
            exon_cigars: Vec::new(),
            cached_introns: OnceLock::new(),
        };

        let mapper = CdotMapper::from_transcripts(std::iter::once(&tx));

        // Canonical RefSeq lookup works.
        assert_eq!(mapper.transcripts_on_contig("NC_000017.11").len(), 1);
        // UCSC alias resolution (default GRCh38).
        assert_eq!(mapper.transcripts_on_contig("chr17").len(), 1);
        // Ensembl alias resolution.
        assert_eq!(mapper.transcripts_on_contig("17").len(), 1);
    }

    #[test]
    fn test_from_transcripts_with_build_grch37_aliases() {
        use crate::reference::transcript::{Exon, ManeStatus, Transcript};
        use crate::reference::Strand as TxStrand;
        use std::sync::OnceLock;

        let tx = Transcript {
            cds_start_incomplete: false,
            id: "NM_000088.3".to_string(),
            gene_symbol: Some("COL1A1".to_string()),
            strand: TxStrand::Plus,
            sequence: None,
            cds_start: Some(11),
            cds_end: Some(60),
            exons: vec![Exon::with_genomic(1, 1, 73, 48263025, 48263097)],
            chromosome: Some("NC_000017.10".to_string()),
            genomic_start: Some(48263025),
            genomic_end: Some(48263097),
            genome_build: GenomeBuild::GRCh37,
            mane_status: ManeStatus::default(),
            refseq_match: None,
            ensembl_match: None,
            protein_id: None,
            exon_cigars: Vec::new(),
            cached_introns: OnceLock::new(),
        };

        let mapper = CdotMapper::from_transcripts_with_build(std::iter::once(&tx), "GRCh37");

        assert_eq!(mapper.transcripts_on_contig("NC_000017.10").len(), 1);
        assert_eq!(mapper.transcripts_on_contig("chr17").len(), 1);
        assert_eq!(mapper.transcripts_on_contig("17").len(), 1);
    }

    #[test]
    fn test_from_transcripts_skips_missing_chromosome() {
        use crate::reference::transcript::{Exon, ManeStatus, Transcript};
        use crate::reference::Strand as TxStrand;
        use std::sync::OnceLock;

        let tx = Transcript {
            cds_start_incomplete: false,
            id: "NM_NOCHR.1".to_string(),
            gene_symbol: Some("X".to_string()),
            strand: TxStrand::Plus,
            sequence: None,
            cds_start: Some(1),
            cds_end: Some(9),
            exons: vec![Exon::with_genomic(1, 1, 9, 1000, 1008)],
            chromosome: None, // ← missing chromosome
            genomic_start: None,
            genomic_end: None,
            genome_build: GenomeBuild::GRCh38,
            mane_status: ManeStatus::default(),
            refseq_match: None,
            ensembl_match: None,
            protein_id: None,
            exon_cigars: Vec::new(),
            cached_introns: OnceLock::new(),
        };

        let mapper = CdotMapper::from_transcripts(std::iter::once(&tx));
        assert_eq!(
            mapper.transcript_count(),
            0,
            "transcript with no chromosome must be skipped, not silently coerced"
        );
    }

    #[test]
    fn test_from_transcripts_skips_exon_missing_genomic_coords() {
        use crate::reference::transcript::{Exon, ManeStatus, Transcript};
        use crate::reference::Strand as TxStrand;
        use std::sync::OnceLock;

        // Exon::new(...) leaves genomic_start/genomic_end as None.
        let tx = Transcript {
            cds_start_incomplete: false,
            id: "NM_NOGENOMIC.1".to_string(),
            gene_symbol: Some("X".to_string()),
            strand: TxStrand::Plus,
            sequence: None,
            cds_start: Some(1),
            cds_end: Some(9),
            exons: vec![Exon::new(1, 1, 9)],
            chromosome: Some("chr1".to_string()),
            genomic_start: None,
            genomic_end: None,
            genome_build: GenomeBuild::GRCh38,
            mane_status: ManeStatus::default(),
            refseq_match: None,
            ensembl_match: None,
            protein_id: None,
            exon_cigars: Vec::new(),
            cached_introns: OnceLock::new(),
        };

        let mapper = CdotMapper::from_transcripts(std::iter::once(&tx));
        assert_eq!(
            mapper.transcript_count(),
            0,
            "transcript with exon missing genomic coords must be skipped"
        );
    }

    #[test]
    fn test_from_transcripts_skips_exon_with_zero_start() {
        use crate::reference::transcript::{Exon, ManeStatus, Transcript};
        use crate::reference::Strand as TxStrand;
        use std::sync::OnceLock;

        // Exon.start is documented as 1-based; 0 is invalid. We must NOT
        // silently coerce it to tx_start = 0 (it would collide with a real
        // first exon and break downstream coordinate math).
        let tx = Transcript {
            cds_start_incomplete: false,
            id: "NM_ZEROSTART.1".to_string(),
            gene_symbol: Some("X".to_string()),
            strand: TxStrand::Plus,
            sequence: None,
            cds_start: Some(1),
            cds_end: Some(9),
            exons: vec![Exon::with_genomic(1, 0, 9, 1000, 1008)],
            chromosome: Some("chr1".to_string()),
            genomic_start: Some(1000),
            genomic_end: Some(1008),
            genome_build: GenomeBuild::GRCh38,
            mane_status: ManeStatus::default(),
            refseq_match: None,
            ensembl_match: None,
            protein_id: None,
            exon_cigars: Vec::new(),
            cached_introns: OnceLock::new(),
        };

        let mapper = CdotMapper::from_transcripts(std::iter::once(&tx));
        assert_eq!(
            mapper.transcript_count(),
            0,
            "transcript with 1-based start=0 must be skipped"
        );
    }

    #[test]
    fn test_from_transcripts_skips_inverted_exon() {
        use crate::reference::transcript::{Exon, ManeStatus, Transcript};
        use crate::reference::Strand as TxStrand;
        use std::sync::OnceLock;

        // end < start on either axis is invalid (empty or inverted interval).
        let tx = Transcript {
            cds_start_incomplete: false,
            id: "NM_INVERTED.1".to_string(),
            gene_symbol: Some("X".to_string()),
            strand: TxStrand::Plus,
            sequence: None,
            cds_start: Some(1),
            cds_end: Some(9),
            // Genomic end (1000) < genomic start (1008).
            exons: vec![Exon::with_genomic(1, 1, 9, 1008, 1000)],
            chromosome: Some("chr1".to_string()),
            genomic_start: Some(1000),
            genomic_end: Some(1008),
            genome_build: GenomeBuild::GRCh38,
            mane_status: ManeStatus::default(),
            refseq_match: None,
            ensembl_match: None,
            protein_id: None,
            exon_cigars: Vec::new(),
            cached_introns: OnceLock::new(),
        };

        let mapper = CdotMapper::from_transcripts(std::iter::once(&tx));
        assert_eq!(
            mapper.transcript_count(),
            0,
            "transcript with inverted exon genomic interval must be skipped"
        );
    }

    #[test]
    fn test_from_transcripts_cds_start_zero_yields_none() {
        use crate::reference::transcript::{Exon, ManeStatus, Transcript};
        use crate::reference::Strand as TxStrand;
        use std::sync::OnceLock;

        // tx.cds_start is documented as 1-based; if upstream feeds Some(0)
        // we should yield None instead of wrapping to u64::MAX via saturating_sub.
        let tx = Transcript {
            cds_start_incomplete: false,
            id: "NM_CDSZERO.1".to_string(),
            gene_symbol: Some("X".to_string()),
            strand: TxStrand::Plus,
            sequence: None,
            cds_start: Some(0),
            cds_end: Some(9),
            exons: vec![Exon::with_genomic(1, 1, 9, 1000, 1008)],
            chromosome: Some("chr1".to_string()),
            genomic_start: Some(1000),
            genomic_end: Some(1008),
            genome_build: GenomeBuild::GRCh38,
            mane_status: ManeStatus::default(),
            refseq_match: None,
            ensembl_match: None,
            protein_id: None,
            exon_cigars: Vec::new(),
            cached_introns: OnceLock::new(),
        };

        let mapper = CdotMapper::from_transcripts(std::iter::once(&tx));
        let stored = mapper
            .get_transcript("NM_CDSZERO.1")
            .expect("transcript should be present (exon coords are valid)");
        assert_eq!(
            stored.cds_start, None,
            "cds_start=Some(0) must become None, not a wrapped u64"
        );
    }

    /// #972: `cds_start_incomplete` must survive the reverse
    /// `Transcript` → `CdotTranscript` construction. The projector's decline
    /// gate reads the *cdot* transcript first (`projector.rs`
    /// `terminus_multiaxis_projection`), so a dropped flag here silently
    /// shadows a correct `true` on the source `Transcript` and re-enables the
    /// `c.`/`p.`/`r.` axes for a `cds_start_NF` transcript.
    #[test]
    fn test_from_transcripts_propagates_cds_start_incomplete() {
        use crate::reference::transcript::{Exon, ManeStatus, Transcript};
        use crate::reference::Strand as TxStrand;
        use std::sync::OnceLock;

        let make_tx = |incomplete: bool| Transcript {
            cds_start_incomplete: incomplete,
            id: "NM_CDSNF.1".to_string(),
            gene_symbol: Some("X".to_string()),
            strand: TxStrand::Plus,
            sequence: None,
            cds_start: Some(1),
            cds_end: Some(9),
            exons: vec![Exon::with_genomic(1, 1, 9, 1000, 1008)],
            chromosome: Some("chr1".to_string()),
            genomic_start: Some(1000),
            genomic_end: Some(1008),
            genome_build: GenomeBuild::GRCh38,
            mane_status: ManeStatus::default(),
            refseq_match: None,
            ensembl_match: None,
            protein_id: None,
            exon_cigars: Vec::new(),
            cached_introns: OnceLock::new(),
        };

        // `from_transcripts` (defaults to GRCh38) must carry the flag through.
        let incomplete = make_tx(true);
        let mapper = CdotMapper::from_transcripts(std::iter::once(&incomplete));
        assert!(
            mapper
                .get_transcript("NM_CDSNF.1")
                .expect("transcript should be present (exon coords are valid)")
                .cds_start_incomplete,
            "cds_start_incomplete=true must survive Transcript -> CdotTranscript"
        );

        // `from_transcripts_with_build` is the underlying constructor; pin it
        // directly so a future refactor of the `from_transcripts` wrapper
        // cannot quietly reintroduce the drop on the build-specific path.
        let mapper =
            CdotMapper::from_transcripts_with_build(std::iter::once(&incomplete), "GRCh37");
        assert!(
            mapper
                .get_transcript("NM_CDSNF.1")
                .expect("transcript should be present (exon coords are valid)")
                .cds_start_incomplete,
            "cds_start_incomplete=true must survive from_transcripts_with_build too"
        );

        // Guardrail: the flag is propagated, not hardcoded the other way. Cover
        // both constructors here too, so a hardcode in the opposite direction on
        // the build-specific path is caught from either side.
        let complete = make_tx(false);
        let mapper = CdotMapper::from_transcripts(std::iter::once(&complete));
        assert!(
            !mapper
                .get_transcript("NM_CDSNF.1")
                .expect("transcript should be present (exon coords are valid)")
                .cds_start_incomplete,
            "cds_start_incomplete=false must stay false (propagated, not forced true)"
        );
        let mapper = CdotMapper::from_transcripts_with_build(std::iter::once(&complete), "GRCh37");
        assert!(
            !mapper
                .get_transcript("NM_CDSNF.1")
                .expect("transcript should be present (exon coords are valid)")
                .cds_start_incomplete,
            "cds_start_incomplete=false must stay false on from_transcripts_with_build too"
        );
    }

    #[test]
    fn test_contig_alias_transcripts_at_position() {
        let json = r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "contig": "NC_000017.11",
                    "strand": "+",
                    "exons": [[50184096, 50184169, 0, 73]],
                    "cds_start": 10,
                    "cds_end": 60
                }
            }
        }
        "#;
        let mapper = CdotMapper::from_reader(json.as_bytes()).unwrap();

        // Position within transcript, looked up by UCSC alias
        let results = mapper.transcripts_at_position("chr17", 50184100);
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].0, "NM_000088.3");

        // Position outside transcript
        let results = mapper.transcripts_at_position("chr17", 99999999);
        assert!(results.is_empty());
    }

    #[test]
    fn test_contig_alias_chrm() {
        let json = r#"
        {
            "transcripts": {
                "NM_MITO.1": {
                    "gene_name": "MT_TEST",
                    "contig": "NC_012920.1",
                    "strand": "+",
                    "exons": [[100, 200, 0, 100]],
                    "cds_start": 10,
                    "cds_end": 90
                }
            }
        }
        "#;
        let mapper = CdotMapper::from_reader(json.as_bytes()).unwrap();

        assert_eq!(mapper.transcripts_on_contig("NC_012920.1").len(), 1);
        assert_eq!(mapper.transcripts_on_contig("chrM").len(), 1);
        assert_eq!(mapper.transcripts_on_contig("MT").len(), 1);
    }

    #[test]
    fn test_mapper_transcripts_at_position() {
        let mut mapper = CdotMapper::new();
        mapper.add_transcript("NM_000088.3".to_string(), sample_transcript());

        // Position within transcript
        let results = mapper.transcripts_at_position("NC_000001.11", 2050);
        assert_eq!(results.len(), 1);

        // Position outside transcript
        let results = mapper.transcripts_at_position("NC_000001.11", 5000);
        assert!(results.is_empty());
    }

    #[test]
    fn test_mapper_from_json() {
        let json = r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "contig": "NC_000017.11",
                    "strand": "+",
                    "exons": [
                        [50184096, 50184169, 0, 73],
                        [50185022, 50185148, 73, 199]
                    ],
                    "cds_start": 149,
                    "cds_end": 4544
                }
            }
        }
        "#;

        let mapper = CdotMapper::from_reader(json.as_bytes()).unwrap();
        assert_eq!(mapper.transcript_count(), 1);

        let tx = mapper.get_transcript("NM_000088.3").unwrap();
        assert_eq!(tx.gene_name.as_deref(), Some("COL1A1"));
        assert_eq!(tx.strand, Strand::Plus);
        assert_eq!(tx.exons.len(), 2);
    }

    // =========================================================================
    // Bincode serialization tests
    // =========================================================================

    #[test]
    fn test_bincode_roundtrip() {
        let json = r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "contig": "NC_000017.11",
                    "strand": "+",
                    "exons": [
                        [50184096, 50184169, 0, 73],
                        [50185022, 50185148, 73, 199]
                    ],
                    "cds_start": 149,
                    "cds_end": 4544
                },
                "NM_000059.4": {
                    "gene_name": "BRCA2",
                    "contig": "NC_000013.11",
                    "strand": "+",
                    "exons": [[32315474, 32315667, 0, 193]],
                    "cds_start": 40,
                    "cds_end": 150
                }
            }
        }
        "#;
        let original = CdotMapper::from_reader(json.as_bytes()).unwrap();
        assert_eq!(original.transcript_count(), 2);

        // Roundtrip through bincode file
        let temp_dir = tempfile::TempDir::new().unwrap();
        let bin_path = temp_dir.path().join("roundtrip.bin");
        original.to_bincode_file(&bin_path).unwrap();
        let decoded = CdotMapper::from_bincode_file(&bin_path).unwrap();

        assert_eq!(decoded.transcript_count(), 2);
        let tx = decoded.get_transcript("NM_000088.3").unwrap();
        assert_eq!(tx.gene_name.as_deref(), Some("COL1A1"));
        assert_eq!(tx.contig, "NC_000017.11");
        assert_eq!(tx.strand, Strand::Plus);
        assert_eq!(tx.exons.len(), 2);

        let tx2 = decoded.get_transcript("NM_000059.4").unwrap();
        assert_eq!(tx2.gene_name.as_deref(), Some("BRCA2"));

        // Contig index should be preserved
        assert_eq!(decoded.transcripts_on_contig("NC_000017.11").len(), 1);
        assert_eq!(decoded.transcripts_on_contig("NC_000013.11").len(), 1);

        // Base-to-versioned index should be preserved
        assert!(decoded.get_transcript("NM_000088.4").is_some()); // falls back to .3
    }

    #[test]
    fn test_bincode_file_roundtrip() {
        let json = r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "contig": "NC_000017.11",
                    "strand": "+",
                    "exons": [[50184096, 50184169, 0, 73]],
                    "cds_start": 10,
                    "cds_end": 60
                }
            }
        }
        "#;
        let original = CdotMapper::from_reader(json.as_bytes()).unwrap();

        let temp_dir = tempfile::TempDir::new().unwrap();
        let bin_path = temp_dir.path().join("test.bin");

        original.to_bincode_file(&bin_path).unwrap();
        assert!(bin_path.exists());

        let loaded = CdotMapper::from_bincode_file(&bin_path).unwrap();
        assert_eq!(loaded.transcript_count(), 1);
        assert!(loaded.get_transcript("NM_000088.3").is_some());
    }

    #[test]
    fn test_concurrent_to_bincode_file_same_path() {
        // Multiple threads writing the same cache path concurrently must not
        // collide on their temp siblings or leave a half-written file: the
        // final cache must always be loadable and complete.
        let json = r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "contig": "NC_000017.11",
                    "strand": "+",
                    "exons": [[50184096, 50184169, 0, 73]],
                    "cds_start": 10,
                    "cds_end": 60
                }
            }
        }
        "#;
        let original = std::sync::Arc::new(CdotMapper::from_reader(json.as_bytes()).unwrap());

        let temp_dir = tempfile::TempDir::new().unwrap();
        let bin_path = std::sync::Arc::new(temp_dir.path().join("concurrent.bin"));

        let handles: Vec<_> = (0..8)
            .map(|_| {
                let original = std::sync::Arc::clone(&original);
                let bin_path = std::sync::Arc::clone(&bin_path);
                std::thread::spawn(move || original.to_bincode_file(bin_path.as_path()))
            })
            .collect();
        for handle in handles {
            handle
                .join()
                .unwrap()
                .expect("concurrent write should succeed");
        }

        // The final cache is complete and loadable, and no temp siblings leaked.
        let loaded = CdotMapper::from_bincode_file(bin_path.as_path()).unwrap();
        assert_eq!(loaded.transcript_count(), 1);
        assert!(loaded.get_transcript("NM_000088.3").is_some());

        let leftover_tmp: Vec<_> = std::fs::read_dir(temp_dir.path())
            .unwrap()
            .filter_map(|e| e.ok())
            .filter(|e| e.file_name().to_string_lossy().contains(".tmp."))
            .collect();
        assert!(
            leftover_tmp.is_empty(),
            "temp siblings leaked: {:?}",
            leftover_tmp
        );
    }

    #[test]
    fn test_concurrent_to_rkyv_file_same_path() {
        // Multiple threads writing the same rkyv cache path concurrently must
        // not collide on their temp siblings or leave a half-written archive:
        // the final cache must always be loadable and complete.  Mirrors the
        // bincode variant above; `to_rkyv_file` uses the same pid-counter-rename
        // pattern.
        let json = r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "contig": "NC_000017.11",
                    "strand": "+",
                    "exons": [[50184096, 50184169, 0, 73]],
                    "cds_start": 10,
                    "cds_end": 60
                }
            }
        }
        "#;
        let original = std::sync::Arc::new(CdotMapper::from_reader(json.as_bytes()).unwrap());

        let temp_dir = tempfile::TempDir::new().unwrap();
        let rkyv_path = std::sync::Arc::new(temp_dir.path().join("concurrent.rkyv"));

        let handles: Vec<_> = (0..8)
            .map(|_| {
                let original = std::sync::Arc::clone(&original);
                let rkyv_path = std::sync::Arc::clone(&rkyv_path);
                std::thread::spawn(move || original.to_rkyv_file(rkyv_path.as_path()))
            })
            .collect();
        for handle in handles {
            handle
                .join()
                .unwrap()
                .expect("concurrent rkyv write should succeed");
        }

        // The final archive is complete and loadable, and no temp siblings leaked.
        assert!(
            CdotMapper::rkyv_is_current(rkyv_path.as_path()),
            "rkyv cache must be current after concurrent writes"
        );
        let loaded = CdotMapper::from_rkyv_file(rkyv_path.as_path()).unwrap();
        assert_eq!(loaded.transcript_count(), 1);
        assert!(loaded.get_transcript("NM_000088.3").is_some());

        let leftover_tmp: Vec<_> = std::fs::read_dir(temp_dir.path())
            .unwrap()
            .filter_map(|e| e.ok())
            .filter(|e| e.file_name().to_string_lossy().contains(".tmp."))
            .collect();
        assert!(
            leftover_tmp.is_empty(),
            "temp siblings leaked: {:?}",
            leftover_tmp
        );
    }

    #[test]
    fn test_load_prefers_bincode() {
        let json = r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "contig": "NC_000017.11",
                    "strand": "+",
                    "exons": [[50184096, 50184169, 0, 73]],
                    "cds_start": 10,
                    "cds_end": 60
                }
            }
        }
        "#;
        let original = CdotMapper::from_reader(json.as_bytes()).unwrap();

        // Mutate the mapper so bincode content differs from JSON
        let mut from_bin = original.clone();
        from_bin
            .transcripts
            .get_mut("NM_000088.3")
            .unwrap()
            .gene_name = Some("FROM_BIN".to_string());

        let temp_dir = tempfile::TempDir::new().unwrap();
        let json_path = temp_dir.path().join("cdot.json");
        let bin_path = temp_dir.path().join("cdot.bin");

        // Write JSON file (gene_name = "COL1A1")
        std::fs::write(&json_path, json).unwrap();

        // Write bincode file (gene_name = "FROM_BIN")
        from_bin.to_bincode_file(&bin_path).unwrap();

        // load() given the JSON path should find and use the .bin sibling
        let loaded = CdotMapper::load(&json_path).unwrap();
        assert_eq!(loaded.transcript_count(), 1);
        assert_eq!(
            loaded
                .get_transcript("NM_000088.3")
                .unwrap()
                .gene_name
                .as_deref(),
            Some("FROM_BIN"),
            "load() should prefer bincode over JSON"
        );
    }

    #[test]
    fn test_load_prefers_rkyv_over_bincode() {
        // When both a .rkyv sibling and a .bin sibling exist, load() must pick
        // the .rkyv one. Each on-disk representation carries a unique sentinel in
        // gene_name so the returned value identifies which path was taken.
        let json = r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "contig": "NC_000017.11",
                    "strand": "+",
                    "exons": [[50184096, 50184169, 0, 73]],
                    "cds_start": 10,
                    "cds_end": 60
                }
            }
        }
        "#;
        let original = CdotMapper::from_reader(json.as_bytes()).unwrap();

        // Build distinct mappers for each on-disk format.
        let mut from_bin = original.clone();
        from_bin
            .transcripts
            .get_mut("NM_000088.3")
            .unwrap()
            .gene_name = Some("FROM_BIN".to_string());

        let mut from_rkyv = original.clone();
        from_rkyv
            .transcripts
            .get_mut("NM_000088.3")
            .unwrap()
            .gene_name = Some("FROM_RKYV".to_string());

        let temp_dir = tempfile::TempDir::new().unwrap();
        let json_path = temp_dir.path().join("cdot.json");
        let bin_path = temp_dir.path().join("cdot.bin");
        let rkyv_path = temp_dir.path().join("cdot.rkyv");

        std::fs::write(&json_path, json).unwrap();
        from_bin.to_bincode_file(&bin_path).unwrap();
        from_rkyv.to_rkyv_file(&rkyv_path).unwrap();

        // With all three siblings present, load() must prefer .rkyv.
        let loaded = CdotMapper::load(&json_path).unwrap();
        assert_eq!(
            loaded
                .get_transcript("NM_000088.3")
                .unwrap()
                .gene_name
                .as_deref(),
            Some("FROM_RKYV"),
            "load() should prefer .rkyv over .bin and JSON"
        );
    }

    #[test]
    fn test_load_skips_stale_rkyv_and_reparses_json() {
        // A sibling .rkyv OLDER than the source JSON must not be served: a
        // re-`prepare` that rewrites the JSON under the same name would
        // otherwise be masked by the stale archive. load() must skip it, reparse
        // the JSON, and refresh the cache.
        let json = r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "contig": "NC_000017.11",
                    "strand": "+",
                    "exons": [[50184096, 50184169, 0, 73]],
                    "cds_start": 10,
                    "cds_end": 60
                }
            }
        }
        "#;
        let original = CdotMapper::from_reader(json.as_bytes()).unwrap();

        // A stale rkyv carrying a sentinel gene_name distinct from the JSON.
        let mut stale = original.clone();
        stale.transcripts.get_mut("NM_000088.3").unwrap().gene_name =
            Some("FROM_STALE_RKYV".to_string());

        let temp_dir = tempfile::TempDir::new().unwrap();
        let json_path = temp_dir.path().join("cdot.json");
        let rkyv_path = temp_dir.path().join("cdot.rkyv");

        std::fs::write(&json_path, json).unwrap();
        stale.to_rkyv_file(&rkyv_path).unwrap();

        // Backdate the rkyv so it is strictly older than the JSON source.
        let backdated = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
        std::fs::File::options()
            .write(true)
            .open(&rkyv_path)
            .unwrap()
            .set_modified(backdated)
            .unwrap();

        // load() must ignore the stale rkyv and reparse the JSON (COL1A1).
        let loaded = CdotMapper::load(&json_path).unwrap();
        assert_eq!(
            loaded
                .get_transcript("NM_000088.3")
                .unwrap()
                .gene_name
                .as_deref(),
            Some("COL1A1"),
            "load() must skip an rkyv cache older than its source JSON"
        );

        // Self-heal: the stale archive should have been refreshed from JSON, so
        // reading the rkyv directly now yields the JSON's value, not the stale
        // sentinel.
        let refreshed = CdotMapper::from_rkyv_file(&rkyv_path).unwrap();
        assert_eq!(
            refreshed
                .get_transcript("NM_000088.3")
                .unwrap()
                .gene_name
                .as_deref(),
            Some("COL1A1"),
            "load() should refresh the stale rkyv after reparsing the JSON"
        );
    }

    // -------------------------------------------------------------------------
    // Load-source observability (the #585 perf-regression gate). These assert
    // the `CdotLoadSource` tag, not just the data — so a silent fast-path →
    // JSON-fallback regression fails the build deterministically, with no
    // reference data and no timing thresholds.
    // -------------------------------------------------------------------------

    /// A fresh sibling archive is taken AND reported as `Archive`, and the data
    /// round-trips through it. Guards "layout drifted but load still claims the
    /// fast path" (#585): a load that quietly fell back to JSON would report
    /// `JsonFallback` and fail this.
    #[test]
    fn load_with_source_reports_archive_for_fresh_rkyv() {
        let json = multi_build_cdot_json();
        let expected = CdotMapper::from_reader(json.as_bytes()).unwrap();

        let temp_dir = tempfile::TempDir::new().unwrap();
        let json_path = temp_dir.path().join("cdot.json");
        let rkyv_path = temp_dir.path().join("cdot.rkyv");

        // Write the JSON first, then the sibling archive — so the archive is at
        // least as new as the source and `load` prefers it.
        std::fs::write(&json_path, json).unwrap();
        expected.to_rkyv_file(&rkyv_path).unwrap();

        let (loaded, source) = CdotMapper::load_with_source(&json_path).unwrap();
        assert_eq!(
            source,
            CdotLoadSource::Archive,
            "a fresh sibling .rkyv must load via the fast archive path"
        );
        // Data round-trips through the archive.
        assert_eq!(loaded.transcript_count(), expected.transcript_count());
        assert_eq!(loaded.primary_build, expected.primary_build);
    }

    /// A stale archive is observably *not* served: the load falls back to JSON
    /// and reports `JsonFallback` (rather than silently re-parsing forever as in
    /// #585), and the side-effecting self-heal makes the *next* load report
    /// `Archive`.
    #[test]
    fn load_with_source_reports_json_fallback_then_self_heals() {
        let json = r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "contig": "NC_000017.11",
                    "strand": "+",
                    "exons": [[50184096, 50184169, 0, 73]],
                    "cds_start": 10,
                    "cds_end": 60
                }
            }
        }
        "#;
        let original = CdotMapper::from_reader(json.as_bytes()).unwrap();

        // A stale rkyv carrying a sentinel distinct from the JSON.
        let mut stale = original.clone();
        stale.transcripts.get_mut("NM_000088.3").unwrap().gene_name =
            Some("FROM_STALE_RKYV".to_string());

        let temp_dir = tempfile::TempDir::new().unwrap();
        let json_path = temp_dir.path().join("cdot.json");
        let rkyv_path = temp_dir.path().join("cdot.rkyv");

        std::fs::write(&json_path, json).unwrap();
        stale.to_rkyv_file(&rkyv_path).unwrap();

        // Backdate the rkyv so it is strictly older than the JSON source.
        let backdated = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
        std::fs::File::options()
            .write(true)
            .open(&rkyv_path)
            .unwrap()
            .set_modified(backdated)
            .unwrap();

        // First load: stale archive skipped → slow JSON path, observably tagged.
        let (first, first_source) = CdotMapper::load_with_source(&json_path).unwrap();
        assert_eq!(
            first_source,
            CdotLoadSource::JsonFallback,
            "a stale archive must surface as a JSON fallback, not be silently served"
        );
        assert_eq!(
            first
                .get_transcript("NM_000088.3")
                .unwrap()
                .gene_name
                .as_deref(),
            Some("COL1A1"),
            "the fallback must serve the real JSON data, not the stale sentinel"
        );

        // Second load: the self-heal refreshed the archive → fast path restored.
        let (_second, second_source) = CdotMapper::load_with_source(&json_path).unwrap();
        assert_eq!(
            second_source,
            CdotLoadSource::Archive,
            "after self-heal the next load must take the fast archive path \
             (not re-parse JSON forever, the #585 failure)"
        );
    }

    #[test]
    fn test_load_bin_upgrades_to_rkyv() {
        // When only a .bin sibling is present (no .rkyv), load() must load from
        // .bin and then write a .rkyv sibling for future runs.
        let json = r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "contig": "NC_000017.11",
                    "strand": "+",
                    "exons": [[50184096, 50184169, 0, 73]],
                    "cds_start": 10,
                    "cds_end": 60
                }
            }
        }
        "#;
        let original = CdotMapper::from_reader(json.as_bytes()).unwrap();

        let temp_dir = tempfile::TempDir::new().unwrap();
        let json_path = temp_dir.path().join("cdot.json");
        let bin_path = temp_dir.path().join("cdot.bin");
        let rkyv_path = temp_dir.path().join("cdot.rkyv");

        std::fs::write(&json_path, json).unwrap();
        original.to_bincode_file(&bin_path).unwrap();

        // No .rkyv exists yet.
        assert!(!rkyv_path.exists(), ".rkyv must not exist before load()");

        let loaded = CdotMapper::load(&json_path).unwrap();
        assert_eq!(loaded.transcript_count(), 1);
        assert!(loaded.get_transcript("NM_000088.3").is_some());

        // load() must have written the .rkyv promotion.
        assert!(
            CdotMapper::rkyv_is_current(&rkyv_path),
            "load() should promote .bin to a valid .rkyv sibling"
        );
    }

    #[test]
    fn test_load_falls_back_to_json() {
        let json = r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "contig": "NC_000017.11",
                    "strand": "+",
                    "exons": [[50184096, 50184169, 0, 73]],
                    "cds_start": 10,
                    "cds_end": 60
                }
            }
        }
        "#;
        let temp_dir = tempfile::TempDir::new().unwrap();
        let json_path = temp_dir.path().join("cdot.json");

        // Write only JSON, no bincode
        std::fs::write(&json_path, json).unwrap();

        let loaded = CdotMapper::load(&json_path).unwrap();
        assert_eq!(loaded.transcript_count(), 1);
    }

    #[test]
    fn test_load_falls_back_to_json_on_corrupt_bincode() {
        let json = r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "contig": "NC_000017.11",
                    "strand": "+",
                    "exons": [[50184096, 50184169, 0, 73]],
                    "cds_start": 10,
                    "cds_end": 60
                }
            }
        }
        "#;
        let temp_dir = tempfile::TempDir::new().unwrap();
        let json_path = temp_dir.path().join("cdot.json");
        let bin_path = temp_dir.path().join("cdot.bin");
        let rkyv_path = temp_dir.path().join("cdot.rkyv");

        // Write valid JSON and a corrupt bincode cache; no rkyv cache yet.
        std::fs::write(&json_path, json).unwrap();
        std::fs::write(&bin_path, b"not valid bincode data").unwrap();

        // load() should fall back to JSON despite the corrupt .bin.
        let loaded = CdotMapper::load(&json_path).unwrap();
        assert_eq!(loaded.transcript_count(), 1);
        assert!(loaded.get_transcript("NM_000088.3").is_some());

        // Self-heal now writes the fast rkyv cache, so a second load takes the
        // fast path.
        assert!(
            CdotMapper::rkyv_is_current(&rkyv_path),
            "an rkyv cache should be written after the JSON fallback"
        );
        let reloaded = CdotMapper::from_rkyv_file(&rkyv_path).unwrap();
        assert_eq!(reloaded.transcript_count(), 1);
        assert!(reloaded.get_transcript("NM_000088.3").is_some());
    }

    #[test]
    fn test_bincode_roundtrip_preserves_alt_build() {
        // A transcript with both GRCh37 and GRCh38 alignments. Primary build is
        // GRCh38, so GRCh37 lives in the alt-build map. The fast (bincode) path
        // must preserve it, or NG/NC-parent build resolution (#332) silently
        // breaks whenever the cache is used.
        let json = r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "genome_builds": {
                        "GRCh37": {
                            "contig": "NC_000017.10",
                            "strand": "+",
                            "exons": [[48263025, 48263098, 1, 0, 73, "M73"]]
                        },
                        "GRCh38": {
                            "contig": "NC_000017.11",
                            "strand": "+",
                            "exons": [[50184096, 50184169, 1, 0, 73, "M73"]]
                        }
                    },
                    "start_codon": 10,
                    "stop_codon": 60
                }
            }
        }
        "#;
        let from_json = CdotMapper::from_reader(json.as_bytes()).unwrap();
        let temp = tempfile::TempDir::new().unwrap();
        let p = temp.path().join("cdot.bin");
        from_json.to_bincode_file(&p).unwrap();
        let from_bin = CdotMapper::from_bincode_file(&p).unwrap();

        // GRCh37 (alt-build) resolution must be identical across both paths.
        let want = from_json
            .get_transcript_on_build("NM_000088.3", "GRCh37")
            .map(|t| (t.contig.clone(), t.cds_start));
        let got = from_bin
            .get_transcript_on_build("NM_000088.3", "GRCh37")
            .map(|t| (t.contig.clone(), t.cds_start));
        assert_eq!(
            want, got,
            "alt-build resolution must survive bincode roundtrip"
        );
        assert_eq!(got, Some(("NC_000017.10".to_string(), Some(10))));
    }

    #[test]
    fn test_rkyv_roundtrip_preserves_data() {
        // Same transcript as the bincode test, plus a per-exon CIGAR ("M73"),
        // so the rkyv path is verified to preserve exons, strand, CDS, the
        // per-exon cigar, AND the alt-build (GRCh37) map.
        let json = r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "genome_builds": {
                        "GRCh37": {
                            "contig": "NC_000017.10",
                            "strand": "-",
                            "exons": [[48263025, 48263098, 1, 0, 73, "M73"]]
                        },
                        "GRCh38": {
                            "contig": "NC_000017.11",
                            "strand": "-",
                            "exons": [[50184096, 50184169, 1, 0, 73, "M73"]]
                        }
                    },
                    "start_codon": 10,
                    "stop_codon": 60
                }
            }
        }
        "#;
        let from_json = CdotMapper::from_reader(json.as_bytes()).unwrap();
        let temp = tempfile::TempDir::new().unwrap();
        let p = temp.path().join("cdot.rkyv");
        from_json.to_rkyv_file(&p).unwrap();
        assert!(CdotMapper::rkyv_is_current(&p));
        let from_rkyv = CdotMapper::from_rkyv_file(&p).unwrap();

        // Primary-build transcript must be byte-identical across the roundtrip,
        // including strand, exons, CDS, and the per-exon cigars.
        let a = from_json.get_transcript("NM_000088.3").unwrap();
        let b = from_rkyv.get_transcript("NM_000088.3").unwrap();
        assert_eq!(a.contig, b.contig);
        assert_eq!(a.strand, b.strand);
        assert_eq!(a.exons, b.exons);
        assert_eq!((a.cds_start, a.cds_end), (b.cds_start, b.cds_end));
        assert_eq!(a.exon_cigars, b.exon_cigars);
        assert_eq!(a.gene_name, b.gene_name);

        // Alt-build (GRCh37) resolution must survive too.
        let want = from_json
            .get_transcript_on_build("NM_000088.3", "GRCh37")
            .map(|t| (t.contig.clone(), t.strand, t.cds_start));
        let got = from_rkyv
            .get_transcript_on_build("NM_000088.3", "GRCh37")
            .map(|t| (t.contig.clone(), t.strand, t.cds_start));
        assert_eq!(want, got, "alt-build must survive the rkyv roundtrip");
    }

    #[test]
    fn test_rkyv_rejects_invalid_strand_tag() {
        // A structurally valid, current-version archive whose strand byte is out
        // of range must be rejected (not coerced to Strand::Unknown), so a
        // corrupt cache is regenerated rather than materialized with wrong data.
        let temp = tempfile::TempDir::new().unwrap();
        let p = temp.path().join("cdot.rkyv");
        let bytes = rkyv_cache::archive_bytes_with_tags(7, 0);
        std::fs::write(&p, &bytes).unwrap();

        // The archive itself is current — rejection comes from the tag check.
        assert!(CdotMapper::rkyv_is_current(&p));
        let err = CdotMapper::from_rkyv_file(&p).unwrap_err();
        assert!(
            err.to_string().contains("invalid strand tag"),
            "expected invalid-strand rejection, got: {err}"
        );
    }

    #[test]
    fn test_rkyv_rejects_invalid_cigar_op_tag() {
        // Same as above, but for an out-of-range per-exon cigar op tag.
        let temp = tempfile::TempDir::new().unwrap();
        let p = temp.path().join("cdot.rkyv");
        let bytes = rkyv_cache::archive_bytes_with_tags(1, 9);
        std::fs::write(&p, &bytes).unwrap();

        assert!(CdotMapper::rkyv_is_current(&p));
        let err = CdotMapper::from_rkyv_file(&p).unwrap_err();
        assert!(
            err.to_string().contains("invalid cigar op tag"),
            "expected invalid-cigar-op rejection, got: {err}"
        );
    }

    #[test]
    fn test_bincode_header_roundtrip_and_staleness() {
        let temp = tempfile::TempDir::new().unwrap();
        let p = temp.path().join("cdot.bin");

        let mut m = CdotMapper::new();
        m.add_transcript("NM_000001.1".to_string(), sample_transcript());
        m.to_bincode_file(&p).unwrap();

        // A freshly written cache carries the current magic+version and loads.
        assert!(CdotMapper::bincode_is_current(&p));
        assert_eq!(
            CdotMapper::from_bincode_file(&p)
                .unwrap()
                .transcript_count(),
            1
        );

        // A legacy / headerless cache is detected as not-current and rejected
        // cleanly, rather than mis-deserialized.
        std::fs::write(&p, b"legacy-bincode-without-any-header-bytes").unwrap();
        assert!(!CdotMapper::bincode_is_current(&p));
        assert!(CdotMapper::from_bincode_file(&p).is_err());

        // Correct magic but a future schema version is also rejected.
        let mut wrong_version = Vec::new();
        wrong_version.extend_from_slice(&CDOT_BINCODE_MAGIC);
        wrong_version.extend_from_slice(&(CDOT_BINCODE_VERSION + 1).to_le_bytes());
        wrong_version.extend_from_slice(&[0u8; 16]);
        std::fs::write(&p, &wrong_version).unwrap();
        assert!(!CdotMapper::bincode_is_current(&p));
        assert!(CdotMapper::from_bincode_file(&p).is_err());
    }

    /// #972 round-trip: `cds_start_incomplete = true` must survive the legacy
    /// bincode snapshot (`CdotTranscriptSnapshotRef` write -> `CdotTranscriptSnapshot`
    /// read -> `From`). Without this the flag is silently dropped by the `.bin`
    /// cache and every transcript loaded from it rehydrates as "complete"
    /// regardless of the source JSON.
    #[test]
    fn test_bincode_cds_start_incomplete_round_trips() {
        let temp = tempfile::TempDir::new().unwrap();
        let p = temp.path().join("cdot.bin");

        let mut tx = sample_transcript();
        tx.cds_start_incomplete = true;

        let mut m = CdotMapper::new();
        m.add_transcript("NM_000001.1".to_string(), tx);
        m.to_bincode_file(&p).unwrap();

        let loaded = CdotMapper::from_bincode_file(&p).unwrap();
        let loaded_tx = loaded.get_transcript("NM_000001.1").unwrap();
        assert!(loaded_tx.cds_start_incomplete);
    }

    // =========================================================================
    // CIGAR parsing tests
    // =========================================================================

    #[test]
    fn test_parse_cigar_simple_match() {
        let ops = parse_cigar("M185").unwrap();
        assert_eq!(ops, vec![CigarOp::Match(185)]);
    }

    #[test]
    fn test_parse_cigar_with_insertion() {
        let ops = parse_cigar("M185 I3 M250").unwrap();
        assert_eq!(
            ops,
            vec![
                CigarOp::Match(185),
                CigarOp::Insertion(3),
                CigarOp::Match(250),
            ]
        );
    }

    #[test]
    fn test_parse_cigar_with_deletion() {
        let ops = parse_cigar("M504 D2 M123").unwrap();
        assert_eq!(
            ops,
            vec![
                CigarOp::Match(504),
                CigarOp::Deletion(2),
                CigarOp::Match(123),
            ]
        );
    }

    #[test]
    fn test_parse_cigar_complex() {
        let ops = parse_cigar("M6 D1 M4 I2 M3").unwrap();
        assert_eq!(
            ops,
            vec![
                CigarOp::Match(6),
                CigarOp::Deletion(1),
                CigarOp::Match(4),
                CigarOp::Insertion(2),
                CigarOp::Match(3),
            ]
        );
    }

    #[test]
    fn test_parse_cigar_empty() {
        let ops = parse_cigar("").unwrap();
        assert!(ops.is_empty());
    }

    #[test]
    fn test_parse_cigar_whitespace_only() {
        let ops = parse_cigar("   ").unwrap();
        assert!(ops.is_empty());
    }

    #[test]
    fn test_parse_cigar_invalid_operation() {
        let result = parse_cigar("X5");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_cigar_invalid_length() {
        let result = parse_cigar("Mabc");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_cigar_too_short_token() {
        let result = parse_cigar("M");
        assert!(result.is_err());
    }

    // -------------------------------------------------------------------------
    // Issue #332: multi-build retention. A cdot JSON with `genome_builds` for
    // both GRCh37 and GRCh38 must yield a mapper that can return the
    // transcript on either build via `get_transcript_on_build`.
    // -------------------------------------------------------------------------

    fn multi_build_cdot_json() -> &'static str {
        r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "genome_builds": {
                        "GRCh37": {
                            "contig": "NC_000017.10",
                            "strand": "+",
                            "exons": [[48263025, 48263098, 1, 0, 73, "M73"]]
                        },
                        "GRCh38": {
                            "contig": "NC_000017.11",
                            "strand": "+",
                            "exons": [[50184096, 50184169, 1, 0, 73, "M73"]]
                        }
                    },
                    "start_codon": 10,
                    "stop_codon": 60
                }
            }
        }
        "#
    }

    #[test]
    fn test_get_transcript_on_build_returns_correct_contig() {
        let json = multi_build_cdot_json();
        // Primary build = GRCh38.
        let mapper = CdotMapper::from_reader(json.as_bytes()).unwrap();

        let tx38 = mapper
            .get_transcript_on_build("NM_000088.3", "GRCh38")
            .expect("GRCh38 view must be present");
        assert_eq!(tx38.contig, "NC_000017.11");

        let tx37 = mapper
            .get_transcript_on_build("NM_000088.3", "GRCh37")
            .expect("GRCh37 view must be retained even when GRCh38 is primary");
        assert_eq!(tx37.contig, "NC_000017.10");
    }

    #[test]
    fn load_secondary_build_counts_genome_builds_nested_transcripts() {
        // Regression for the misleading "Loaded 0 GRCh37 transcripts" log. Real
        // cdot files nest their alignments under `genome_builds`, and the
        // path-based `load_secondary_build` loads via `load()` using the default
        // build — so a GRCh37-nested file's *primary* (default-build) view is
        // empty and the transcripts arrive through the alt-build fold. The
        // reported count must reflect what is actually queryable for the build,
        // not the empty primary view (which previously logged "0").
        let secondary_grch37_json = r#"
        {
            "transcripts": {
                "NM_000001.1": {
                    "gene_name": "GENE_A",
                    "genome_builds": {
                        "GRCh37": {
                            "contig": "NC_000001.10",
                            "strand": "+",
                            "exons": [[100, 200, 1, 0, 100, "M100"]]
                        }
                    }
                },
                "NM_000002.1": {
                    "gene_name": "GENE_B",
                    "genome_builds": {
                        "GRCh37": {
                            "contig": "NC_000001.10",
                            "strand": "+",
                            "exons": [[300, 400, 1, 0, 100, "M100"]]
                        }
                    }
                }
            }
        }
        "#;
        // Primary mapper on GRCh38; write the GRCh37 secondary to a temp file
        // (no sibling cache) so `load_secondary_build` parses the JSON via the
        // default-build `load()` path that exhibited the miscount.
        let mut mapper = CdotMapper::from_reader(multi_build_cdot_json().as_bytes()).unwrap();
        let temp_dir = tempfile::TempDir::new().unwrap();
        let path = temp_dir.path().join("grch37.json");
        std::fs::write(&path, secondary_grch37_json).unwrap();

        let count = mapper.load_secondary_build(&path, "GRCh37").unwrap();
        assert_eq!(
            count, 2,
            "secondary load must count the GRCh37-nested transcripts, not the empty primary view"
        );
        // And the data is genuinely queryable on GRCh37 (not just counted).
        assert!(
            mapper
                .get_transcript_on_build("NM_000002.1", "GRCh37")
                .is_some(),
            "GRCh37-nested transcript must be resolvable after secondary load"
        );
    }

    #[test]
    fn test_get_transcript_on_build_primary_build_grch37() {
        let json = multi_build_cdot_json();
        // Primary build = GRCh37.
        let mapper = CdotMapper::from_reader_with_build(json.as_bytes(), "GRCh37").unwrap();

        let tx37 = mapper
            .get_transcript_on_build("NM_000088.3", "GRCh37")
            .expect("primary build access via get_transcript_on_build");
        assert_eq!(tx37.contig, "NC_000017.10");

        let tx38 = mapper
            .get_transcript_on_build("NM_000088.3", "GRCh38")
            .expect("non-primary GRCh38 view must be retained");
        assert_eq!(tx38.contig, "NC_000017.11");
    }

    #[test]
    fn test_available_builds_for_multi_build_input() {
        let json = multi_build_cdot_json();
        let mapper = CdotMapper::from_reader(json.as_bytes()).unwrap();
        let mut builds = mapper.available_builds_for("NM_000088.3");
        builds.sort();
        assert_eq!(builds, vec!["GRCh37".to_string(), "GRCh38".to_string()]);
    }

    #[test]
    fn test_available_builds_for_unknown_accession() {
        let json = multi_build_cdot_json();
        let mapper = CdotMapper::from_reader(json.as_bytes()).unwrap();
        assert!(mapper.available_builds_for("NM_999999.1").is_empty());
    }

    #[test]
    fn test_available_builds_for_includes_deferred_build() {
        let secondary_grch37_json = r#"
        {
            "transcripts": {
                "NM_000001.1": {
                    "gene_name": "GENE_A",
                    "genome_builds": {
                        "GRCh37": { "contig": "NC_000001.10", "strand": "+", "exons": [[100, 200, 1, 0, 100, "M100"]] }
                    }
                }
            }
        }
        "#;
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("grch37.json");
        std::fs::write(&path, secondary_grch37_json).unwrap();

        let mut lazy = CdotMapper::from_reader(multi_build_cdot_json().as_bytes()).unwrap();
        lazy.defer_secondary_build("GRCh37", path);

        let mut builds = lazy.available_builds_for("NM_000001.1");
        builds.sort();
        assert_eq!(
            builds,
            vec!["GRCh37".to_string()],
            "deferred GRCh37 must be the sole available build"
        );
    }

    // ---- #964: deferred Ensembl primary merge -----------------------------

    /// Primary RefSeq mapper (NM_000088.3 on NC_000001.11, exon2 [2000,2200])
    /// with a deferred Ensembl cdot (ENST00000375549.8 on the same contig,
    /// overlapping exon [2000,2200]). Returns the mapper plus the `TempDir`
    /// backing the deferred file — kept alive so the deferred path stays valid.
    fn deferred_ensembl_fixture() -> (CdotMapper, tempfile::TempDir) {
        let ensembl_json = r#"
        {
            "transcripts": {
                "ENST00000375549.8": {
                    "gene_name": "SDHD",
                    "genome_builds": {
                        "GRCh38": { "contig": "NC_000001.11", "strand": "+", "exons": [[2000, 2200, 1, 0, 200, "M200"]] }
                    }
                }
            }
        }
        "#;
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("cdot-ensembl.GRCh38.json");
        std::fs::write(&path, ensembl_json).unwrap();

        let mut mapper = CdotMapper::new();
        mapper.add_transcript("NM_000088.3".to_string(), sample_transcript());
        mapper.defer_ensembl_primary_merge(path);
        (mapper, dir)
    }

    #[test]
    fn deferred_ensembl_resolves_lazily_and_refseq_never_triggers() {
        let (mapper, _dir) = deferred_ensembl_fixture();

        // Nothing materialized at construction.
        assert!(
            !mapper.deferred_ensembl_loaded(),
            "deferring must not load the Ensembl cdot up front"
        );

        // A RefSeq hit resolves without materializing the Ensembl mapper.
        assert!(mapper.get_transcript("NM_000088.3").is_some());
        assert!(
            !mapper.deferred_ensembl_loaded(),
            "a RefSeq lookup must not materialize the deferred Ensembl mapper"
        );

        // A RefSeq MISS (non-ENS*) also must not trigger it.
        assert!(mapper.get_transcript("NM_999999.9").is_none());
        assert!(
            !mapper.deferred_ensembl_loaded(),
            "a non-Ensembl miss must not materialize the deferred Ensembl mapper"
        );

        // The first ENS* lookup resolves via the deferred mapper, materializing
        // it exactly once.
        let enst = mapper.get_transcript("ENST00000375549.8");
        assert_eq!(
            enst.and_then(|t| t.gene_name.as_deref()),
            Some("SDHD"),
            "deferred Ensembl transcript must resolve on first ENS* use"
        );
        assert!(
            mapper.deferred_ensembl_loaded(),
            "first ENS* use materializes the deferred Ensembl mapper"
        );
    }

    #[test]
    fn deferred_ensembl_version_fallback() {
        let (mapper, _dir) = deferred_ensembl_fixture();
        // An unversioned Ensembl accession resolves via the deferred mapper's own
        // base->versioned fallback (ENST00000375549 -> .8).
        assert!(
            mapper.get_transcript("ENST00000375549").is_some(),
            "deferred Ensembl lookup must apply the mapper's version fallback"
        );
    }

    #[test]
    fn has_transcript_exact_consults_deferred_ensembl() {
        let (mapper, _dir) = deferred_ensembl_fixture();
        // The exact-presence probe must agree with `get_transcript_exact` for a
        // versioned Ensembl accession resolved via the deferred mapper (#964) —
        // otherwise a presence check false-negatives while the lookup succeeds.
        assert!(
            mapper.has_transcript_exact("ENST00000375549.8"),
            "has_transcript_exact must consult the deferred Ensembl mapper"
        );
        // Exact means exact: an unversioned ENST is not a hit (no version fallback).
        assert!(
            !mapper.has_transcript_exact("ENST00000375549"),
            "has_transcript_exact must not apply version fallback"
        );
        // A non-Ensembl exact probe is unaffected (and never materializes Ensembl).
        assert!(!mapper.has_transcript_exact("NM_999999.9"));
    }

    #[test]
    fn genomic_enumeration_does_not_consult_deferred_ensembl() {
        let (mapper, _dir) = deferred_ensembl_fixture();
        // Genomic-overlap enumeration is RefSeq-scoped (#933), so it must NOT
        // consult (or materialize) the deferred Ensembl mapper — even at a
        // position an Ensembl transcript overlaps. Only the primary RefSeq hit
        // is returned, and the Ensembl cdot stays unloaded.
        let hits = mapper.transcripts_at_position("NC_000001.11", 2050);
        let ids: Vec<&str> = hits.iter().map(|(id, _)| *id).collect();
        assert_eq!(
            ids,
            vec!["NM_000088.3"],
            "enumeration returns only the RefSeq overlap: {ids:?}"
        );
        assert!(
            !mapper.deferred_ensembl_loaded(),
            "genomic enumeration must not materialize the deferred Ensembl mapper"
        );
    }

    #[test]
    fn transcript_genome_span_resolves_deferred_ensembl() {
        let (mapper, _dir) = deferred_ensembl_fixture();
        // A DIRECT span lookup for a known Ensembl transcript must consult the
        // deferred Ensembl mapper, mirroring `get_transcript` (this is not the
        // RefSeq-scoped genomic *enumeration* of #933). Before the fix the span
        // side-table was built only from the primary RefSeq map, so every ENST
        // returned `None` — which made genome-pivot projection onto any Ensembl
        // transcript fail with `ReferenceNotFound`.
        // Value reflects ferro's stored 1-based exon coordinates (the raw 0-based
        // cdot `[2000, 2200]` is `+1`-converted on ingestion) — the SAME builder
        // and convention RefSeq spans use, so Ensembl is consistent with RefSeq.
        assert_eq!(
            mapper.transcript_genome_span("ENST00000375549.8"),
            Some((2001, 2201)),
            "Ensembl transcript genome span must resolve via the deferred mapper"
        );
        // The primary RefSeq span still resolves, and a non-Ensembl miss stays None.
        assert!(mapper.transcript_genome_span("NM_000088.3").is_some());
        assert_eq!(mapper.transcript_genome_span("NM_999999.9"), None);
        // The build-aware variant on the primary build agrees.
        assert_eq!(
            mapper.transcript_genome_span_on_build("ENST00000375549.8", "GRCh38"),
            Some((2001, 2201)),
        );
    }

    #[test]
    fn test_get_transcript_on_build_version_fallback_in_alt() {
        // NM_000088.4 falls back to NM_000088.3 inside the alt-build map too.
        let json = multi_build_cdot_json();
        let mapper = CdotMapper::from_reader(json.as_bytes()).unwrap();
        let tx37 = mapper
            .get_transcript_on_build("NM_000088.4", "GRCh37")
            .expect("version fallback inside alt-build map");
        assert_eq!(tx37.contig, "NC_000017.10");
    }

    #[test]
    fn test_get_transcript_on_build_alt_version_fallback_picks_highest() {
        // When the alt-build map holds multiple versions of the same base
        // (e.g. NM_000088.3 and NM_000088.4), the version fallback must
        // deterministically prefer the highest numeric version. Pre-fix this
        // iterated the HashMap and returned whichever versioned key the hasher
        // landed on first.
        let json = r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "genome_builds": {
                        "GRCh37": {
                            "contig": "NC_000017.10",
                            "strand": "+",
                            "exons": [[48263025, 48263098, 1, 0, 73, "M73"]]
                        },
                        "GRCh38": {
                            "contig": "NC_000017.11",
                            "strand": "+",
                            "exons": [[50184096, 50184169, 1, 0, 73, "M73"]]
                        }
                    },
                    "start_codon": 10,
                    "stop_codon": 60
                },
                "NM_000088.4": {
                    "gene_name": "COL1A1",
                    "genome_builds": {
                        "GRCh37": {
                            "contig": "NC_000017.10",
                            "strand": "+",
                            "exons": [[48263025, 48263198, 1, 0, 173, "M173"]]
                        },
                        "GRCh38": {
                            "contig": "NC_000017.11",
                            "strand": "+",
                            "exons": [[50184096, 50184269, 1, 0, 173, "M173"]]
                        }
                    },
                    "start_codon": 20,
                    "stop_codon": 160
                }
            }
        }
        "#;
        let mapper = CdotMapper::from_reader(json.as_bytes()).unwrap();
        // Primary build = GRCh38, so the GRCh37 alt map holds both .3 and .4.
        // Querying with .2 (absent) forces the version fallback.
        let tx = mapper
            .get_transcript_on_build("NM_000088.2", "GRCh37")
            .expect("version fallback must find a sibling");
        assert_eq!(
            tx.cds_start,
            Some(20),
            "alt-build fallback must deterministically pick the highest version (.4 over .3)"
        );
    }

    #[test]
    fn test_get_transcript_primary_version_fallback_picks_highest() {
        // Same determinism guarantee as the alt-build path, but for the primary
        // build's base->versioned fallback. The cdot file deserializes its
        // transcripts into a HashMap, so `add_transcript` runs in a
        // nondeterministic order; `base_to_versioned` must still map a base
        // accession to its highest version rather than whichever the hasher
        // inserted last. Pre-fix, requesting an absent version (.2) resolved to
        // .3 or .4 arbitrarily across runs, shifting CDS coordinates downstream.
        let json = r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "genome_builds": {
                        "GRCh38": {
                            "contig": "NC_000017.11",
                            "strand": "+",
                            "exons": [[50184096, 50184169, 1, 0, 73, "M73"]]
                        }
                    },
                    "start_codon": 10,
                    "stop_codon": 60
                },
                "NM_000088.4": {
                    "gene_name": "COL1A1",
                    "genome_builds": {
                        "GRCh38": {
                            "contig": "NC_000017.11",
                            "strand": "+",
                            "exons": [[50184096, 50184269, 1, 0, 173, "M173"]]
                        }
                    },
                    "start_codon": 20,
                    "stop_codon": 160
                }
            }
        }
        "#;
        let mapper = CdotMapper::from_reader(json.as_bytes()).unwrap();
        // .2 is absent, forcing the base->versioned fallback on the primary build.
        let tx = mapper
            .get_transcript("NM_000088.2")
            .expect("version fallback must find a sibling");
        assert_eq!(
            tx.cds_start,
            Some(20),
            "primary-build base->version fallback must deterministically pick \
             the highest version (.4 over .3)"
        );
    }

    /// JSON with only `NM_000088.3` and `.4` present (no `.2`), used to contrast
    /// fuzzy vs. exact resolution.
    fn version_skew_mapper() -> CdotMapper {
        let json = r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "genome_builds": { "GRCh38": {
                        "contig": "NC_000017.11", "strand": "+",
                        "exons": [[50184096, 50184169, 1, 0, 73, "M73"]]
                    }},
                    "start_codon": 10, "stop_codon": 60
                },
                "NM_000088.4": {
                    "gene_name": "COL1A1",
                    "genome_builds": { "GRCh38": {
                        "contig": "NC_000017.11", "strand": "+",
                        "exons": [[50184096, 50184269, 1, 0, 173, "M173"]]
                    }},
                    "start_codon": 20, "stop_codon": 160
                }
            }
        }
        "#;
        CdotMapper::from_reader(json.as_bytes()).unwrap()
    }

    // #714: `get_transcript_exact` must NOT substitute a sibling version. An
    // absent exact version returns `None`, where the fuzzy `get_transcript`
    // returns a different version — pairing that frame with the requested
    // version's sequence is what silently mis-normalizes `c.` variants.
    #[test]
    fn test_get_transcript_exact_does_not_version_fuzz() {
        let mapper = version_skew_mapper();
        // Absent exact version: fuzzy finds a sibling, exact returns None.
        assert!(
            mapper.get_transcript("NM_000088.2").is_some(),
            "fuzzy get_transcript still resolves an absent version to a sibling"
        );
        assert!(
            mapper.get_transcript_exact("NM_000088.2").is_none(),
            "exact lookup must NOT substitute a sibling version (#714)"
        );
        // Present exact versions resolve to their OWN frame.
        assert_eq!(
            mapper
                .get_transcript_exact("NM_000088.3")
                .map(|t| t.cds_start),
            Some(Some(10)),
            "exact .3 must return .3's own CDS frame"
        );
        assert_eq!(
            mapper
                .get_transcript_exact("NM_000088.4")
                .map(|t| t.cds_start),
            Some(Some(20)),
            "exact .4 must return .4's own CDS frame"
        );
    }

    // #714: the build-aware exact lookup is also version-exact on the primary
    // build (the path the normalize transcript resolution uses with no hint).
    #[test]
    fn test_get_transcript_on_build_exact_no_version_fuzz_primary() {
        let mapper = version_skew_mapper();
        assert!(
            mapper
                .get_transcript_on_build_exact("NM_000088.2", "GRCh38")
                .is_none(),
            "build-exact lookup must not substitute a sibling on the primary build (#714)"
        );
        assert_eq!(
            mapper
                .get_transcript_on_build_exact("NM_000088.4", "GRCh38")
                .map(|t| t.cds_start),
            Some(Some(20)),
            "build-exact lookup resolves the exact version when present"
        );
    }

    // #718: cross-build version-exact lookup finds a version present only in a
    // secondary build (its build-independent CDS frame), without fuzzing to a
    // sibling in the primary build.
    #[test]
    fn test_get_transcript_exact_any_build_finds_secondary_build_version() {
        // .3 is in the primary (GRCh38) build; .2 is ONLY in the alt (GRCh37)
        // build. .2 must be found with its OWN CDS (start_codon 5), never .3's.
        let json = r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "genome_builds": { "GRCh38": {
                        "contig": "NC_000017.11", "strand": "+",
                        "exons": [[50184096, 50184169, 1, 0, 73, "M73"]]
                    }},
                    "start_codon": 20, "stop_codon": 60
                },
                "NM_000088.2": {
                    "gene_name": "COL1A1",
                    "genome_builds": { "GRCh37": {
                        "contig": "NC_000017.10", "strand": "+",
                        "exons": [[48263025, 48263098, 1, 0, 73, "M73"]]
                    }},
                    "start_codon": 5, "stop_codon": 60
                }
            }
        }
        "#;
        let mapper = CdotMapper::from_reader(json.as_bytes()).unwrap();
        // Primary (GRCh38) exact lookup does not see .2 (it lives only in GRCh37).
        assert!(
            mapper.get_transcript_exact("NM_000088.2").is_none(),
            "primary-build exact lookup must not see a secondary-build-only version"
        );
        // Cross-build exact lookup finds .2's OWN frame (start_codon 5), not .3's (20).
        assert_eq!(
            mapper
                .get_transcript_exact_any_build("NM_000088.2")
                .map(|t| t.cds_start),
            Some(Some(5)),
            "must return .2's own CDS from the secondary build, never a sibling's (#718)"
        );
        // A version present in NO build is still not invented.
        assert!(
            mapper
                .get_transcript_exact_any_build("NM_000088.9")
                .is_none(),
            "must not resolve a version absent from every build"
        );
    }

    #[test]
    fn test_accession_version_parsing() {
        assert_eq!(accession_version("NM_003002.4"), Some(4));
        assert_eq!(accession_version("NM_003002.10"), Some(10));
        assert_eq!(accession_version("NM_003002"), None);
        assert_eq!(accession_version("LRG_1t1"), None);
        // Versionless accessions both yield `None`; the `>` tie-break comparison
        // in `base_to_versioned` insertion evaluates to `false`, so the existing
        // entry is kept — the fallback is stable for unversioned ids.
        assert_eq!(accession_version("LRG_1t2"), accession_version("LRG_1t1"));
    }

    #[test]
    fn test_protein_accession_parsed_from_cdot() {
        // cdot records the CDS protein accession per transcript. The loader
        // must surface it on `CdotTranscript.protein` so the projector emits
        // the correct `p.` accession (here NP_000068.1). Without it the
        // projector falls back to the transcript id (#310); it never infers
        // NP_000077.4 from NM_000077.4 by preserving the number, which is wrong
        // whenever the NP number differs from the NM number (#808).
        let json = r#"
        {
            "transcripts": {
                "NM_000077.4": {
                    "gene_name": "CDKN2A",
                    "protein": "NP_000068.1",
                    "genome_builds": {
                        "GRCh38": {
                            "contig": "NC_000009.12",
                            "strand": "+",
                            "exons": [[21967750, 21968240, 1, 0, 490, "M490"]]
                        }
                    },
                    "start_codon": 10,
                    "stop_codon": 60
                }
            }
        }
        "#;
        let mapper = CdotMapper::from_reader(json.as_bytes()).unwrap();
        let tx = mapper
            .get_transcript_on_build("NM_000077.4", "GRCh38")
            .expect("transcript present");
        assert_eq!(
            tx.protein.as_deref(),
            Some("NP_000068.1"),
            "cdot `protein` field must be plumbed onto CdotTranscript.protein"
        );
    }

    // -------------------------------------------------------------------------
    // #389 follow-up: primary_build() returns Option, and bincode loads that
    // pre-date the primary_build field must surface as None rather than
    // fabricating "GRCh38" (which mis-stamps GRCh37 snapshots).
    // -------------------------------------------------------------------------

    #[test]
    fn test_primary_build_known_after_explicit_build_load() {
        let mapper =
            CdotMapper::from_reader_with_build(multi_build_cdot_json().as_bytes(), "GRCh37")
                .unwrap();
        assert_eq!(mapper.primary_build(), Some("GRCh37"));
    }

    #[test]
    fn test_bincode_roundtrip_preserves_primary_build_grch37() {
        // Persist a GRCh37-primary mapper to bincode and read it back; the
        // build name must survive the round-trip so downstream callers
        // don't mis-stamp transcripts as GRCh38.
        let mapper =
            CdotMapper::from_reader_with_build(multi_build_cdot_json().as_bytes(), "GRCh37")
                .unwrap();
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("roundtrip.bin");
        mapper.to_bincode_file(&path).expect("write bincode");
        let reloaded = CdotMapper::from_bincode_file(&path).expect("read bincode");
        assert_eq!(
            reloaded.primary_build(),
            Some("GRCh37"),
            "primary_build must survive bincode round-trip; pre-fix this returned \"GRCh38\""
        );
    }

    #[test]
    fn test_bincode_roundtrip_preserves_primary_build_grch38() {
        // Symmetric to the GRCh37 case — verifies the field is persisted
        // (rather than constant-defaulted) by exercising the non-default
        // value above and the default value here.
        let mapper = CdotMapper::from_reader(multi_build_cdot_json().as_bytes()).unwrap();
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("roundtrip.bin");
        mapper.to_bincode_file(&path).expect("write bincode");
        let reloaded = CdotMapper::from_bincode_file(&path).expect("read bincode");
        assert_eq!(reloaded.primary_build(), Some("GRCh38"));
    }

    // -------------------------------------------------------------------------
    // #389 follow-up: build-specific lookups carry the LRG fallback.
    // Pre-fix, asking for an LRG transcript on a non-primary build returned
    // None even when the mapped RefSeq transcript existed in the alt-build
    // map; `get_transcript_on_build` short-circuited before LRG resolution.
    // -------------------------------------------------------------------------

    #[test]
    fn test_get_transcript_on_build_resolves_lrg_to_refseq_on_alt_build() {
        // Build a multi-build mapper and register an LRG → RefSeq mapping.
        let mut mapper =
            CdotMapper::from_reader_with_build(multi_build_cdot_json().as_bytes(), "GRCh38")
                .unwrap();
        mapper
            .lrg_to_refseq
            .insert("LRG_1t1".to_string(), "NM_000088.3".to_string());

        // Primary build: LRG lookup works via the get_transcript LRG path.
        let tx38 = mapper
            .get_transcript_on_build("LRG_1t1", "GRCh38")
            .expect("LRG → RefSeq on primary build");
        assert_eq!(tx38.contig, "NC_000017.11");

        // Alt build (the regression): LRG lookup must resolve to the
        // RefSeq accession before consulting alt_build_transcripts.
        let tx37 = mapper
            .get_transcript_on_build("LRG_1t1", "GRCh37")
            .expect("LRG → RefSeq must work on alt build too (pre-fix this returned None)");
        assert_eq!(tx37.contig, "NC_000017.10");
    }

    /// Single-exon transcript with a CIGAR `M3 D4 M3`: exon genome `[1000, 1010)`
    /// (10 genome bases), tx `[0, 6)` (6 tx bases). Genome offsets 3..=6 are the
    /// deletion gap; offsets 0..=2 and 7..=9 are matched.
    fn cigar_deletion_transcript(strand: Strand) -> CdotTranscript {
        CdotTranscript {
            cds_start_incomplete: false,
            gene_name: Some("GAP".to_string()),
            contig: "NC_000001.11".to_string(),
            strand,
            exons: vec![[1000, 1010, 0, 6]],
            cds_start: Some(0),
            cds_end: Some(6),
            exon_cigars: vec![Some(vec![
                CigarOp::Match(3),
                CigarOp::Deletion(4),
                CigarOp::Match(3),
            ])],
            gene_id: None,
            protein: None,
        }
    }

    #[test]
    fn cigar_deletion_gap_detects_inside_only_plus() {
        let tx = cigar_deletion_transcript(Strand::Plus);
        // Inside the deletion: genome positions 1003..=1006.
        for g in 1003..=1006 {
            let gap = tx
                .cigar_deletion_gap_at_genome_pos(0, g)
                .unwrap_or_else(|| panic!("genome {g} should be inside the deletion gap"));
            assert_eq!(gap.kind, CigarGapKind::Deletion);
            assert_eq!(gap.length, 4);
        }
        // Matched (outside the gap): 1000..=1002 and 1007..=1009.
        for g in [1000, 1001, 1002, 1007, 1008, 1009] {
            assert!(
                tx.cigar_deletion_gap_at_genome_pos(0, g).is_none(),
                "genome {g} is matched and must not report a gap"
            );
        }
    }

    #[test]
    fn cigar_deletion_gap_detects_inside_only_minus() {
        let tx = cigar_deletion_transcript(Strand::Minus);
        // On minus strand the CIGAR walks the genome from genome_end-1 down.
        // Deletion genome offsets 3..=6 → positions 1009-6..=1009-3 = 1003..=1006.
        for g in 1003..=1006 {
            let gap = tx
                .cigar_deletion_gap_at_genome_pos(0, g)
                .unwrap_or_else(|| panic!("minus genome {g} should be inside the gap"));
            assert_eq!(gap.kind, CigarGapKind::Deletion);
        }
        for g in [1000, 1001, 1002, 1007, 1008, 1009] {
            assert!(tx.cigar_deletion_gap_at_genome_pos(0, g).is_none());
        }
    }

    #[test]
    fn cigar_deletion_gap_none_without_cigar() {
        let tx = sample_transcript(); // no exon_cigars
        for g in [1000, 1050, 1099] {
            assert!(tx.cigar_deletion_gap_at_genome_pos(0, g).is_none());
        }
    }

    #[test]
    fn cigar_insertion_gap_detects_inside_only() {
        // CIGAR `M3 I2 M15`: exon genome `[1000, 1018)` (18 genome bases),
        // tx `[0, 20)` (20 tx bases). Tx offsets 3..=4 are the insertion gap
        // (transcript bases with no genome counterpart).
        let tx = CdotTranscript {
            cds_start_incomplete: false,
            gene_name: Some("INS".to_string()),
            contig: "NC_000001.11".to_string(),
            strand: Strand::Plus,
            exons: vec![[1000, 1018, 0, 20]],
            cds_start: Some(0),
            cds_end: Some(20),
            exon_cigars: vec![Some(vec![
                CigarOp::Match(3),
                CigarOp::Insertion(2),
                CigarOp::Match(15),
            ])],
            gene_id: None,
            protein: None,
        };
        // Inside the insertion: tx positions 3 and 4.
        for t in [3, 4] {
            let gap = tx
                .cigar_insertion_gap_at_tx_pos(0, t)
                .unwrap_or_else(|| panic!("tx {t} should be inside the insertion gap"));
            assert_eq!(gap.kind, CigarGapKind::Insertion);
            assert_eq!(gap.length, 2);
        }
        // Matched positions before (0..=2) and after (5..) the insertion.
        for t in [0, 1, 2, 5, 6, 19] {
            assert!(
                tx.cigar_insertion_gap_at_tx_pos(0, t).is_none(),
                "tx {t} is matched and must not report an insertion gap"
            );
        }
    }

    // -------------------------------------------------------------------------
    // Multi-build overlap discovery: `transcripts_at_position` must route by
    // contig to the build that owns it. GRCh37 and GRCh38 have distinct contig
    // accessions (NC_000017.10 vs .11), so the contig disambiguates the build.
    // Pre-fix, the stab index was built from the primary build's `contig_index`
    // only, so a GRCh37 contig query returned empty.
    // -------------------------------------------------------------------------

    #[test]
    fn test_transcripts_at_position_routes_to_owning_build_by_contig() {
        // Primary build = GRCh38; the same NM lives on GRCh37 in the alt map.
        let mapper = CdotMapper::from_reader(multi_build_cdot_json().as_bytes()).unwrap();

        // Primary (GRCh38) contig: a position inside the GRCh38 exon must hit.
        let hits38 = mapper.transcripts_at_position("NC_000017.11", 50184100);
        let ids38: Vec<&str> = hits38.iter().map(|(acc, _)| *acc).collect();
        assert_eq!(
            ids38,
            vec!["NM_000088.3"],
            "primary-build overlap must still resolve"
        );
        // The returned transcript carries the GRCh38 alignment.
        assert_eq!(hits38[0].1.contig, "NC_000017.11");

        // Alt (GRCh37) contig: a position inside the GRCh37 exon must hit, and
        // the returned transcript must carry the GRCh37 alignment.
        let hits37 = mapper.transcripts_at_position("NC_000017.10", 48263050);
        let ids37: Vec<&str> = hits37.iter().map(|(acc, _)| *acc).collect();
        assert_eq!(
            ids37,
            vec!["NM_000088.3"],
            "alt-build overlap must resolve via the contig (pre-fix returned empty)"
        );
        assert_eq!(hits37[0].1.contig, "NC_000017.10");

        // A contig owned by neither build resolves to empty.
        assert!(
            mapper
                .transcripts_at_position("NC_000099.9", 1000)
                .is_empty(),
            "unknown contig must return empty"
        );

        // A position outside the alt-build exon on a known alt contig is empty.
        assert!(
            mapper
                .transcripts_at_position("NC_000017.10", 1_000)
                .is_empty(),
            "position outside the alt-build exon must return empty"
        );
    }

    // -------------------------------------------------------------------------
    // Loading a second, single-build cdot file as a non-primary build. The
    // real manifest ships GRCh37 and GRCh38 cdot files separately (single-build
    // each, not nested `genome_builds`), so the loader must be able to layer a
    // second file onto an already-loaded primary mapper.
    // -------------------------------------------------------------------------

    fn single_build_grch38_json() -> &'static str {
        r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "contig": "NC_000017.11",
                    "strand": "+",
                    "exons": [[50184096, 50184169, 0, 73, "M73"]],
                    "start_codon": 10,
                    "stop_codon": 60
                }
            }
        }
        "#
    }

    fn single_build_grch37_json() -> &'static str {
        r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "contig": "NC_000017.10",
                    "strand": "+",
                    "exons": [[48263025, 48263098, 0, 73, "M73"]],
                    "start_codon": 10,
                    "stop_codon": 60
                }
            }
        }
        "#
    }

    #[test]
    fn test_load_secondary_build_layers_second_cdot_file() {
        // Primary build = GRCh38, loaded from a single-build file.
        let mut mapper = CdotMapper::from_reader(single_build_grch38_json().as_bytes()).unwrap();
        // Sanity: only GRCh38 known before layering.
        assert_eq!(
            mapper.available_builds_for("NM_000088.3"),
            vec!["GRCh38".to_string()]
        );

        // Layer GRCh37 on top.
        let count = mapper
            .load_secondary_build_from_reader(single_build_grch37_json().as_bytes(), "GRCh37")
            .unwrap();
        assert_eq!(count, 1, "one GRCh37 transcript loaded");

        // Both builds now available, and each returns its own contig.
        let mut builds = mapper.available_builds_for("NM_000088.3");
        builds.sort();
        assert_eq!(builds, vec!["GRCh37".to_string(), "GRCh38".to_string()]);

        assert_eq!(
            mapper
                .get_transcript_on_build("NM_000088.3", "GRCh38")
                .unwrap()
                .contig,
            "NC_000017.11"
        );
        assert_eq!(
            mapper
                .get_transcript_on_build("NM_000088.3", "GRCh37")
                .unwrap()
                .contig,
            "NC_000017.10"
        );

        // The primary `transcripts` map must NOT be clobbered: the GRCh38
        // record's contig is unchanged (collision safety).
        assert_eq!(
            mapper.get_transcript("NM_000088.3").unwrap().contig,
            "NC_000017.11"
        );

        // Overlap discovery routes by contig to the freshly-loaded GRCh37 build.
        let hits = mapper.transcripts_at_position("NC_000017.10", 48263050);
        let ids: Vec<&str> = hits.iter().map(|(acc, _)| *acc).collect();
        assert_eq!(ids, vec!["NM_000088.3"]);
        assert_eq!(hits[0].1.contig, "NC_000017.10");
    }

    #[test]
    fn all_build_transcript_ids_surfaces_alt_build_only_versions() {
        use std::collections::HashSet;
        // Reproduces the #802 reference shape: GRCh38 cdot carries only the
        // current version of an accession, while GRCh37 cdot retains an older
        // version GRCh38 superseded. (NM_002001.2 is GRCh37-only; GRCh38 has
        // .3/.4.) The version-aware backfill must treat that GRCh37-only version
        // as "in cdot" so its deposited mRNA is fetched rather than declined.
        let grch38_only_new = r#"
        {
            "transcripts": {
                "NM_002001.4": {
                    "gene_name": "FCER1A",
                    "contig": "NC_000001.11",
                    "strand": "+",
                    "exons": [[159283895, 159283897, 0, 2, "M2"]]
                }
            }
        }
        "#;
        let grch37_retains_old = r#"
        {
            "transcripts": {
                "NM_002001.2": {
                    "gene_name": "FCER1A",
                    "contig": "NC_000001.10",
                    "strand": "+",
                    "exons": [[159253685, 159253687, 0, 2, "M2"]]
                }
            }
        }
        "#;
        let mut mapper = CdotMapper::from_reader(grch38_only_new.as_bytes()).unwrap();
        mapper
            .load_secondary_build_from_reader(grch37_retains_old.as_bytes(), "GRCh37")
            .unwrap();

        // Primary-only `transcript_ids` sees just the GRCh38 version...
        let primary: HashSet<&str> = mapper.transcript_ids().collect();
        assert!(primary.contains("NM_002001.4"));
        assert!(
            !primary.contains("NM_002001.2"),
            "transcript_ids must not surface the GRCh37-only old version"
        );

        // ...while `all_build_transcript_ids` also surfaces the GRCh37-only
        // old version, the predicate the backfill keys on.
        let all: HashSet<&str> = mapper.all_build_transcript_ids().collect();
        assert!(all.contains("NM_002001.4"));
        assert!(
            all.contains("NM_002001.2"),
            "all_build_transcript_ids must surface the GRCh37-only old version (#802)"
        );
    }

    #[test]
    fn all_build_transcript_ids_surfaces_standalone_grch37_file_load() {
        use std::collections::HashSet;
        // Pins the exact path `load_cdot_versions` (#802 backfill) takes: it
        // loads the GRCh37 cdot file *standalone* via `CdotMapper::load`/
        // `from_reader`, which always uses GRCh38 as the primary build. A
        // single-build GRCh37 cdot file nests all its data under
        // `genome_builds["GRCh37"]`, so with a GRCh38 primary the primary
        // `transcripts` map is empty and every GRCh37 transcript lands in the
        // alt map. `transcript_ids` (primary only) therefore returns nothing;
        // `all_build_transcript_ids` is the predicate that actually sees the
        // GRCh37-only version.
        let grch37_only_nested = r#"
        {
            "transcripts": {
                "NM_002001.2": {
                    "gene_name": "FCER1A",
                    "genome_builds": {
                        "GRCh37": {
                            "contig": "NC_000001.10",
                            "strand": "+",
                            "exons": [[159253685, 159253687, 1, 0, 2, "M2"]]
                        }
                    }
                }
            }
        }
        "#;
        // `from_reader` == the default-GRCh38-primary standalone load.
        let mapper = CdotMapper::from_reader(grch37_only_nested.as_bytes()).unwrap();

        let primary: HashSet<&str> = mapper.transcript_ids().collect();
        assert!(
            primary.is_empty(),
            "a standalone GRCh37 file loaded with a GRCh38 primary has an empty primary map"
        );

        let all: HashSet<&str> = mapper.all_build_transcript_ids().collect();
        assert!(
            all.contains("NM_002001.2"),
            "all_build_transcript_ids must surface the GRCh37-only version from a standalone load (#802)"
        );
    }

    // -------------------------------------------------------------------------
    // Deferred secondary-build: lazy-load tests
    // -------------------------------------------------------------------------

    #[test]
    fn deferred_alt_mapper_loads_once_on_first_access() {
        let secondary_grch37_json = r#"
        {
            "transcripts": {
                "NM_000001.1": {
                    "gene_name": "GENE_A",
                    "genome_builds": {
                        "GRCh37": { "contig": "NC_000001.10", "strand": "+", "exons": [[100, 200, 1, 0, 100, "M100"]] }
                    }
                }
            }
        }
        "#;
        let mut mapper = CdotMapper::from_reader(multi_build_cdot_json().as_bytes()).unwrap();
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("grch37.json");
        std::fs::write(&path, secondary_grch37_json).unwrap();

        mapper.defer_secondary_build("GRCh37", path);
        assert!(
            !mapper.deferred_alt_loaded("GRCh37"),
            "deferral must not load eagerly"
        );

        let tx = mapper
            .deferred_alt_mapper("GRCh37")
            .and_then(|m| m.get_transcript_on_build("NM_000001.1", "GRCh37"));
        assert!(
            tx.is_some(),
            "deferred mapper must expose its GRCh37 transcript"
        );
        assert!(
            mapper.deferred_alt_loaded("GRCh37"),
            "first access must load it"
        );

        assert!(mapper.deferred_alt_mapper("GRCh37").is_some());
        assert!(mapper.deferred_alt_loaded("GRCh37"));
    }

    #[test]
    fn deferred_alt_mapper_missing_source_resolves_to_none() {
        let mut mapper = CdotMapper::from_reader(multi_build_cdot_json().as_bytes()).unwrap();
        mapper.defer_secondary_build("GRCh37", PathBuf::from("/no/such/cdot.json"));
        assert!(
            mapper.deferred_alt_mapper("GRCh37").is_none(),
            "missing source -> None, no panic"
        );
        assert!(mapper.deferred_alt_loaded("GRCh37"));
        assert!(mapper.deferred_alt_mapper("GRCh99").is_none());
    }

    #[test]
    fn get_transcript_on_build_deferred_matches_eager() {
        let secondary_grch37_json = r#"
        {
            "transcripts": {
                "NM_000001.1": {
                    "gene_name": "GENE_A",
                    "genome_builds": {
                        "GRCh37": { "contig": "NC_000001.10", "strand": "+", "exons": [[100, 200, 1, 0, 100, "M100"]] }
                    }
                }
            }
        }
        "#;
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("grch37.json");
        std::fs::write(&path, secondary_grch37_json).unwrap();

        let mut eager = CdotMapper::from_reader(multi_build_cdot_json().as_bytes()).unwrap();
        eager.load_secondary_build(&path, "GRCh37").unwrap();

        let mut lazy = CdotMapper::from_reader(multi_build_cdot_json().as_bytes()).unwrap();
        lazy.defer_secondary_build("GRCh37", path.clone());

        let e = eager
            .get_transcript_on_build("NM_000001.1", "GRCh37")
            .unwrap();
        let l = lazy
            .get_transcript_on_build("NM_000001.1", "GRCh37")
            .unwrap();
        assert_eq!(e.contig, l.contig);
        assert_eq!(e.contig, "NC_000001.10");
        assert_eq!(e.strand, l.strand);
        assert_eq!(e.exons, l.exons);

        let mut lazy2 = CdotMapper::from_reader(multi_build_cdot_json().as_bytes()).unwrap();
        lazy2.defer_secondary_build("GRCh37", path);
        // A GRCh37 lookup satisfied by the PRIMARY cdot's own eager GRCh37 alt view
        // must NOT spill into (load) the deferred secondary.
        let _ = lazy2
            .get_transcript_on_build("NM_000088.3", "GRCh37")
            .unwrap();
        assert!(
            !lazy2.deferred_alt_loaded("GRCh37"),
            "an eagerly-satisfiable GRCh37 lookup must not load the deferred secondary"
        );
    }

    #[test]
    fn test_overlap_index_includes_deferred_grch37_contigs() {
        let secondary_grch37_json = r#"
        {
            "transcripts": {
                "NM_000001.1": {
                    "gene_name": "GENE_A",
                    "genome_builds": {
                        "GRCh37": { "contig": "NC_000001.10", "strand": "+", "exons": [[100, 200, 1, 0, 100, "M100"]] }
                    }
                }
            }
        }
        "#;
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("grch37.json");
        std::fs::write(&path, secondary_grch37_json).unwrap();

        let mut eager = CdotMapper::from_reader(multi_build_cdot_json().as_bytes()).unwrap();
        eager.load_secondary_build(&path, "GRCh37").unwrap();
        let eager_hits = eager.transcripts_at_position("NC_000001.10", 150);

        let mut lazy = CdotMapper::from_reader(multi_build_cdot_json().as_bytes()).unwrap();
        lazy.defer_secondary_build("GRCh37", path);
        let lazy_hits = lazy.transcripts_at_position("NC_000001.10", 150);

        let mut e: Vec<&str> = eager_hits.iter().map(|(a, _)| *a).collect();
        let mut l: Vec<&str> = lazy_hits.iter().map(|(a, _)| *a).collect();
        e.sort();
        l.sort();
        assert_eq!(e, l, "deferred overlap must match eager overlap");
        assert!(
            lazy.deferred_alt_loaded("GRCh37"),
            "an overlap query must force-load the deferred secondary"
        );
        assert!(
            l.contains(&"NM_000001.1"),
            "overlap result must include NM_000001.1 at position 150"
        );
    }

    #[test]
    fn test_overlap_merges_eager_and_deferred_same_contig() {
        // The primary (multi_build) cdot puts NM_000088.3 on GRCh37 contig
        // NC_000017.10 (eager alt view). A deferred GRCh37 file adds another
        // transcript on the SAME contig. Both must appear in an overlap query —
        // the deferred index must MERGE with, not replace, the eager contig stab.
        //
        // Regression: the old `index_one_build`-based approach called
        // `HashMap::insert` per contig, so the deferred pass silently overwrote
        // the eager stab for NC_000017.10, discarding NM_000088.3.
        let secondary_grch37_json = r#"
        {
            "transcripts": {
                "NM_999999.1": {
                    "gene_name": "GENE_X",
                    "genome_builds": {
                        "GRCh37": { "contig": "NC_000017.10", "strand": "+", "exons": [[48263025, 48263098, 1, 0, 73, "M73"]] }
                    }
                }
            }
        }
        "#;
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("grch37.json");
        std::fs::write(&path, secondary_grch37_json).unwrap();

        let mut lazy = CdotMapper::from_reader(multi_build_cdot_json().as_bytes()).unwrap();
        lazy.defer_secondary_build("GRCh37", path);

        // A position inside NM_000088.3's GRCh37 exon (NC_000017.10:48263025-48263098).
        // NM_999999.1 has an identical exon, so both transcripts overlap pos 48263050.
        let hits = lazy.transcripts_at_position("NC_000017.10", 48263050);
        let mut accs: Vec<&str> = hits.iter().map(|(a, _)| *a).collect();
        accs.sort();
        assert!(
            accs.contains(&"NM_000088.3"),
            "eager GRCh37 transcript must not be dropped by the deferred merge; got: {accs:?}"
        );
        assert!(
            accs.contains(&"NM_999999.1"),
            "deferred GRCh37 transcript must be present; got: {accs:?}"
        );
    }

    #[test]
    fn deferred_grch37_not_loaded_for_grch38_only_sequence() {
        let secondary_grch37_json = r#"
        {
            "transcripts": {
                "NM_000001.1": {
                    "gene_name": "GENE_A",
                    "genome_builds": {
                        "GRCh37": { "contig": "NC_000001.10", "strand": "+", "exons": [[100, 200, 1, 0, 100, "M100"]] }
                    }
                }
            }
        }
        "#;
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("grch37.json");
        std::fs::write(&path, secondary_grch37_json).unwrap();

        // A sequence of GRCh38 / primary-build-only lookups must NOT load the deferred GRCh37 mapper.
        let mut m = CdotMapper::from_reader(multi_build_cdot_json().as_bytes()).unwrap();
        m.defer_secondary_build("GRCh37", path);
        let _ = m.get_transcript("NM_000088.3");
        let _ = m.get_transcript_on_build("NM_000088.3", "GRCh38");
        assert!(
            !m.deferred_alt_loaded("GRCh37"),
            "GRCh38/primary lookups must not load the GRCh37 secondary"
        );
    }

    #[test]
    fn deferred_grch37_loads_once_under_concurrency() {
        use std::sync::Arc;
        let secondary_grch37_json = r#"
        {
            "transcripts": {
                "NM_000001.1": {
                    "gene_name": "GENE_A",
                    "genome_builds": {
                        "GRCh37": { "contig": "NC_000001.10", "strand": "+", "exons": [[100, 200, 1, 0, 100, "M100"]] }
                    }
                }
            }
        }
        "#;
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("grch37.json");
        std::fs::write(&path, secondary_grch37_json).unwrap();
        let mut mapper = CdotMapper::from_reader(multi_build_cdot_json().as_bytes()).unwrap();
        mapper.defer_secondary_build("GRCh37", path);
        let shared = Arc::new(mapper);

        let mut handles = Vec::new();
        for _ in 0..8 {
            let m = Arc::clone(&shared);
            handles.push(std::thread::spawn(move || {
                m.get_transcript_on_build("NM_000001.1", "GRCh37")
                    .map(|t| t.contig.clone())
            }));
        }
        for h in handles {
            assert_eq!(h.join().unwrap().as_deref(), Some("NC_000001.10"));
        }
        assert!(shared.deferred_alt_loaded("GRCh37"));
    }

    #[test]
    fn deferred_state_is_not_serialized() {
        // The deferred source is runtime-only: serializing and reloading drops it
        // (from_manifest re-establishes it). Round-trip must not panic and must yield
        // a mapper with no deferred state, while primary data survives.
        let mut mapper = CdotMapper::from_reader(multi_build_cdot_json().as_bytes()).unwrap();
        mapper.defer_secondary_build("GRCh37", PathBuf::from("/tmp/whatever.json"));

        let dir = tempfile::TempDir::new().unwrap();
        let rkyv_path = dir.path().join("m.rkyv");
        mapper.to_rkyv_file(&rkyv_path).unwrap();
        let reloaded = CdotMapper::from_rkyv_file(&rkyv_path).unwrap();

        // Deferred state did not survive serialization.
        assert!(
            !reloaded.deferred_alt_loaded("GRCh37"),
            "deferred state must not survive serialization"
        );
        assert!(
            reloaded.deferred_alt_mapper("GRCh37").is_none(),
            "no deferred source should be reconstructed from a snapshot"
        );
        // Primary data survives normally.
        assert!(reloaded.get_transcript("NM_000088.3").is_some());
    }

    /// #693: the genome-pivot n.→r. renumber relies on `cds_pos_from_tx_pos` to
    /// convert a 1-based transcript position to its CDS coordinate. With
    /// `cds_start = 50` (0-based), `n.51` (tx 0-based 50) is `c.1` and `n.50`
    /// (tx 0-based 49) is the 5'UTR `c.-1` — exactly the renumber a coding
    /// transcript must apply before mapping an `n.`/`r.` position to the genome.
    #[test]
    fn cds_pos_from_tx_pos_renumbers_transcript_to_cds() {
        let tx = sample_transcript();
        // First CDS base: tx 0-based 50 → c.1.
        let first = tx.cds_pos_from_tx_pos(50).expect("exonic");
        assert_eq!(first.base, 1);
        assert!(!first.utr3);
        // One base 5' of the CDS: tx 0-based 49 → c.-1.
        let utr5 = tx.cds_pos_from_tx_pos(49).expect("exonic");
        assert_eq!(utr5.base, -1);
        assert!(!utr5.utr3);
        // Worked example shape (NM_058195.3: n.204 → c.44): a base N into the
        // CDS renumbers to `N - cds_start` (1-based). tx 0-based 60 → c.11.
        let mid = tx.cds_pos_from_tx_pos(60).expect("exonic");
        assert_eq!(mid.base, 11);
    }
}