gtars-refget 0.11.0

Rust implementation of the refget standard for accessing reference sequences
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
//! ReadonlyRefgetStore struct definition and core methods.

use super::*;
use super::alias::AliasManager;
use super::lock::{LockOptions, StoreLock};

use std::collections::{HashMap, HashSet};
use std::fmt::{Display, Formatter};
use std::path::{Path, PathBuf};

use indexmap::IndexMap;

use anyhow::{anyhow, Context, Result};

use crate::collection::{read_rgsi_file, SequenceMetadataExt, SequenceRecordExt};
use crate::digest::lookup_alphabet;
use crate::digest::{
    SequenceCollectionMetadata, SequenceCollectionRecord, SequenceMetadata,
    SequenceRecord,
};
use crate::digest::{decode_string_from_bytes, decode_substring_from_bytes, encode_sequence, StreamingDecoder};
use crate::digest::{byte_range_for_bases, decode_substring_from_bytes_at_offset};
use crate::hashkeyable::{DigestKey, HashKeyable, key_to_digest_string};
use crate::seqcol::metadata_matches_attribute;

use std::fs::{self, create_dir_all, File};
use std::io::{BufReader, Read, Seek, SeekFrom};
use std::sync::{Arc, Mutex, RwLock};

/// Fallback capacity for the per-store open-file-descriptor cache, used when
/// the process's soft `RLIMIT_NOFILE` cannot be read at all (non-unix
/// targets, or the `getrlimit` syscall failing). Matches the old fixed cap
/// this replaces.
const SEQ_FD_CACHE_CAP_FLOOR: usize = 256;

/// Ceiling for the adaptive fd-cache capacity. Even under a very high or
/// unlimited `RLIMIT_NOFILE`, the cache stays bounded so its O(n) LRU eviction
/// scan (see `FdCache::insert`) stays cheap and a single store instance does
/// not gratuitously hold an unbounded number of fds open (a process may have
/// several stores open at once, plus its own stdio/sockets/other files).
const SEQ_FD_CACHE_CAP_CEILING: usize = 8192;

/// Headroom subtracted from the soft `RLIMIT_NOFILE` when sizing the fd
/// cache, reserved for the rest of the process (stdio, sockets, other open
/// files, other store instances).
const SEQ_FD_CACHE_HEADROOM: usize = 64;

/// Capacity of the per-store open-file-descriptor cache used by the
/// partial-read path, adapted to the process's soft `RLIMIT_NOFILE`.
///
/// The old fixed cap of 256 mirrored seqrepo's `fd_cache_size`, but a
/// genome-scale refget store has tens of thousands of segment `.seq` files
/// (e.g. ~52k for a human genome at typical segment sizes; a transcriptome
/// store can have ~122k sequences). A scattered/genome-wide batch of queries
/// touches far more than 256 distinct files, so the fixed cap thrashed:
/// nearly every region evicted and reopened its file, costing an extra
/// `openat`+`close` pair per region. Sizing the cache from the process's own
/// fd limit lets it hold far more open handles when the ulimit allows it,
/// while still leaving headroom and an upper bound so it can't exhaust fds or
/// let LRU eviction get expensive.
fn default_fd_cache_cap() -> usize {
    #[cfg(unix)]
    {
        let mut rlim = libc::rlimit {
            rlim_cur: 0,
            rlim_max: 0,
        };
        if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut rlim) } == 0 {
            let soft = rlim.rlim_cur;
            if soft == libc::RLIM_INFINITY {
                // No real ceiling to respect; use our own bound.
                return SEQ_FD_CACHE_CAP_CEILING;
            }
            let usable = (soft as usize).saturating_sub(SEQ_FD_CACHE_HEADROOM).max(1);
            // Never size the cache above what the rlimit (minus headroom)
            // actually allows, even when that is below the floor -- an
            // unusually small ulimit must be respected, not overridden by a
            // "typical minimum". Above the floor, cap at the ceiling.
            return usable.min(SEQ_FD_CACHE_CAP_CEILING);
        }
    }
    SEQ_FD_CACHE_CAP_FLOOR
}

/// True when `err` (as returned by [`ReadonlyRefgetStore::get_substring_from_disk`]
/// / [`ReadonlyRefgetStore::get_cached_seq_file`]) is ultimately caused by the
/// `.seq` file not existing, as opposed to some other failure (permission
/// denied, a bad range, a genuine I/O error). Used to fall through to the
/// remote fallback exactly on a missing file, replacing an upfront
/// `path.exists()` stat with inspecting the result of an attempted open --
/// the common case (file present) then costs no extra syscall at all, since
/// the fd cache would have to open it anyway.
fn is_missing_seq_file(err: &anyhow::Error) -> bool {
    err.chain()
        .any(|cause| matches!(cause.downcast_ref::<std::io::Error>(), Some(io_err) if io_err.kind() == std::io::ErrorKind::NotFound))
}

/// Batch size at which `get_substrings` against a *remote-only* sequence stops
/// issuing one HTTP byte-range request per range and instead downloads the whole
/// `.seq` once (cached locally, like `load_sequence`), then serves every range
/// from the local file. Each remote range is a separate round-trip, so for bulk
/// extraction (e.g. BED region sets) the per-request latency dominates and a
/// single cached download wins; below the threshold, fetching only the touched
/// bytes is cheaper than pulling a whole chromosome. Heuristic, count-based:
/// small/ad-hoc reads stay lean, bulk reads promote.
const REMOTE_BULK_FETCH_THRESHOLD: usize = 16;

/// Convert decoded sequence bytes into a `String` without re-validating UTF-8.
///
/// # Why this exists
/// gtars sequence bytes are *always* ASCII: the Encoded decoder emits only
/// bytes drawn from `alphabet.decoding_array` (A/C/G/T/N/IUPAC/protein), and Raw
/// mode stores one ASCII base per byte per the refget data model. So
/// `String::from_utf8`'s validation scan can never fail on this data — it is
/// pure overhead.
///
/// # Why it justifies a (single, audited) `unsafe`
/// Benchmarked (AMD Ryzen 7 3800X, release build): on the whole-sequence Encoded
/// decode path the `from_utf8` validation scan costs a steady ~6–10% of total
/// decode-and-convert time — roughly 10–20 ms per 250 Mbp chromosome. That is a
/// real, repeatable cost on the whole-genome read hot path, so we skip it here.
///
/// This is the crate's only `from_utf8_unchecked`. Remote data is validated in
/// `get_substring_from_remote` before it reaches this conversion.
///
/// The `debug_assert` re-validates the ASCII invariant in debug and test builds,
/// so any future break (a non-ASCII alphabet, an offset bug) fails loudly under
/// test while release builds stay fast.
#[inline]
fn decoded_sequence_to_string(bytes: Vec<u8>) -> String {
    debug_assert!(
        bytes.is_ascii(),
        "decoded sequence bytes must be ASCII (decoder invariant violated)"
    );
    // SAFETY: gtars sequence bytes are guaranteed ASCII (see doc above), hence
    // valid UTF-8, so skipping validation is sound.
    unsafe { String::from_utf8_unchecked(bytes) }
}

/// A tiny bounded LRU cache mapping a sequence digest to an open, shared
/// `.seq` file handle. `.seq` content for a digest is immutable, so a cached
/// handle never goes stale and needs no invalidation. When the cache is full,
/// inserting a new handle evicts (closes) the least-recently-used one.
///
/// Recency is tracked with a monotonically increasing counter stamped on each
/// access; eviction scans for the minimum stamp. With a small cap (default 256)
/// this O(n) eviction is negligible compared to the avoided `open`/`seek`
/// syscalls on the hot path.
#[derive(Debug)]
struct FdCache {
    cap: usize,
    tick: u64,
    /// digest key -> (shared file handle, last-use stamp)
    entries: HashMap<DigestKey, (Arc<File>, u64)>,
}

impl FdCache {
    fn new(cap: usize) -> Self {
        FdCache {
            cap: cap.max(1),
            tick: 0,
            entries: HashMap::with_capacity(cap.max(1)),
        }
    }

    /// Return a cloned handle on hit, bumping recency. `None` on miss.
    fn get(&mut self, key: &DigestKey) -> Option<Arc<File>> {
        self.tick += 1;
        let tick = self.tick;
        if let Some(slot) = self.entries.get_mut(key) {
            slot.1 = tick;
            Some(Arc::clone(&slot.0))
        } else {
            None
        }
    }

    /// Insert a freshly opened handle, evicting (closing) the LRU entry if full.
    fn insert(&mut self, key: DigestKey, file: Arc<File>) {
        self.tick += 1;
        let tick = self.tick;
        if !self.entries.contains_key(&key) && self.entries.len() >= self.cap {
            // Evict the least-recently-used entry. Dropping the Arc closes the
            // fd once no in-flight read still holds a clone.
            if let Some(lru_key) = self
                .entries
                .iter()
                .min_by_key(|(_, (_, stamp))| *stamp)
                .map(|(k, _)| *k)
            {
                self.entries.remove(&lru_key);
            }
        }
        self.entries.insert(key, (file, tick));
    }
}


/// A `Read` adapter that yields a byte range from a shared `Arc<Vec<u8>>`
/// buffer without cloning the backing data.
///
/// Used by `stream_sequence` when the target sequence is already resident
/// in memory as `SequenceRecord::Full`. The alternative of slicing+cloning
/// would allocate a second copy of the (possibly chromosome-sized) buffer
/// and defeat the O(1) memory guarantee of streaming.
pub(crate) struct ArcSliceReader {
    buf: Arc<Vec<u8>>,
    pos: usize,
    end: usize,
}

impl ArcSliceReader {
    pub(crate) fn new(buf: Arc<Vec<u8>>, start: usize, end: usize) -> Self {
        debug_assert!(start <= end);
        debug_assert!(end <= buf.len());
        Self { buf, pos: start, end }
    }
}

impl Read for ArcSliceReader {
    fn read(&mut self, out: &mut [u8]) -> std::io::Result<usize> {
        let remaining = self.end - self.pos;
        if remaining == 0 {
            return Ok(0);
        }
        let n = remaining.min(out.len());
        out[..n].copy_from_slice(&self.buf[self.pos..self.pos + n]);
        self.pos += n;
        Ok(n)
    }
}

/// Open a bounded HTTP byte range against a remote refget store and return
/// a `Read` yielding exactly `byte_end - byte_start` bytes.
#[cfg(feature = "http")]
fn open_remote_range(
    remote: &str,
    relpath: &Path,
    byte_start: u64,
    byte_end: u64,
) -> Result<Box<dyn Read + Send>> {
    let relpath_str = relpath
        .to_str()
        .ok_or_else(|| anyhow!("Non-UTF8 sequence path"))?;
    let url = if remote.ends_with('/') {
        format!("{}{}", remote, relpath_str)
    } else {
        format!("{}/{}", remote, relpath_str)
    };

    let byte_len = byte_end - byte_start;
    let last_byte = byte_end.saturating_sub(1);
    let agent: ureq::Agent = ureq::Agent::config_builder()
        .timeout_connect(Some(std::time::Duration::from_secs(30)))
        .timeout_recv_response(Some(std::time::Duration::from_secs(60)))
        .build()
        .into();
    let response = agent
        .get(&url)
        .header("Range", &format!("bytes={}-{}", byte_start, last_byte))
        .call()
        .map_err(|e| anyhow!("Failed to open remote byte range: {}", e))?;

    // Guard against servers that ignore the Range header and return the full
    // body with HTTP 200 instead of a 206 Partial Content slice. Wrapping the
    // full body here would silently produce wrong bases, so refuse outright.
    let status = response.status();
    if status.as_u16() != 206 {
        return Err(anyhow!(
            "Remote server did not honor Range header (got HTTP {}); \
             refusing to stream to avoid silent data corruption. URL: {}",
            status,
            url
        ));
    }

    Ok(Box::new(BufReader::with_capacity(
        64 * 1024,
        response.into_body().into_reader().take(byte_len),
    )))
}

#[cfg(not(feature = "http"))]
fn open_remote_range(
    _remote: &str,
    _relpath: &Path,
    _byte_start: u64,
    _byte_end: u64,
) -> Result<Box<dyn Read + Send>> {
    Err(anyhow!(
        "Remote streaming requires the 'http' feature to be enabled"
    ))
}

/// Core refget store with `&self` read methods, suitable for `Arc` sharing in servers.
///
/// Mutating methods are used during the setup/loading phase; once wrapped in `Arc`,
/// only `&self` reads are accessible, making concurrent access thread-safe.
///
/// Holds a global sequence_store with all sequences (across collections) deduplicated.
/// This allows lookup by sequence digest directly (bypassing collection information).
/// Also holds a collections hashmap, to provide lookup by collection+name.
#[derive(Debug)]
pub struct ReadonlyRefgetStore {
    /// SHA512t24u digest -> SequenceRecord (metadata + optional data)
    pub(crate) sequence_store: HashMap<DigestKey, SequenceRecord>,
    /// MD5 digest -> SHA512t24u digest lookup
    pub(crate) md5_lookup: HashMap<DigestKey, DigestKey>,

    /// Collection digest -> {name -> SHA512t24u digest} (IndexMap preserves FASTA insertion order)
    pub(crate) name_lookup: HashMap<DigestKey, IndexMap<String, DigestKey>>,
    /// Active sequence collections (now using SequenceCollectionRecord for Stub/Full pattern)
    pub(crate) collections: HashMap<DigestKey, SequenceCollectionRecord>,
    /// Storage strategy for sequences
    pub(crate) mode: StorageMode,
    /// Where the store lives on disk (local store or cache directory)
    pub(crate) local_path: Option<PathBuf>,
    /// Where to pull sequences from (if remote-backed)
    pub(crate) remote_source: Option<String>,
    /// Template for sequence file paths (e.g., "sequences/%s2/%s.seq")
    pub(crate) seqdata_path_template: Option<String>,
    /// Whether to persist sequences to disk (write-through caching)
    pub(crate) persist_to_disk: bool,
    /// Whether to suppress progress output
    pub(crate) quiet: bool,
    /// Whether to compute ancillary digests (nlp, snlp, sorted_sequences).
    /// Default: true for new stores.
    pub(crate) ancillary_digests: bool,
    /// Whether on-disk attribute reverse index is enabled.
    /// Default: false. Part 2 implements the indexed path.
    pub(crate) attribute_index: bool,
    /// Human-readable aliases for sequences and collections.
    pub(crate) aliases: AliasManager,
    /// FHR metadata for collections, keyed by collection digest.
    pub(crate) fhr_metadata: HashMap<DigestKey, super::fhr_metadata::FhrMetadata>,
    /// Available sequence alias namespaces (from manifest, for remote discovery).
    pub(crate) available_sequence_alias_namespaces: Vec<String>,
    /// Available collection alias namespaces (from manifest, for remote discovery).
    pub(crate) available_collection_alias_namespaces: Vec<String>,
    /// Bounded LRU cache of open `.seq` file handles for the partial-read path,
    /// behind a `Mutex` because `get_substring` takes `&self`. Avoids re-opening
    /// the same chromosome file on every per-region `get_substring` call.
    seq_fd_cache: Mutex<FdCache>,
    /// `&self` resident overlay: whole, on-disk-packed `.seq` byte arrays keyed by
    /// SHA512t24u digest. Populated via [`Self::load_resident`] to promote a
    /// `Stub` sequence to RAM-served without taking `&mut self` (the store is
    /// `Arc`-shared behind a readonly handle). Consulted in `get_substring` /
    /// `get_substrings` *before* the on-disk partial-read path: on a hit the
    /// covering span is decoded from these bytes exactly like the `Full` arm, so
    /// output is byte-identical to the disk path but every region query becomes an
    /// in-memory decode instead of a positioned read. The bytes are the raw file
    /// contents (2-bit packed in `Encoded` mode, one byte/base in `Raw`), so a hit
    /// is mode-agnostic and only the sliced span is ever decoded. `RwLock` so many
    /// readers proceed concurrently; the `Arc` is cloned out under a brief read
    /// lock and decoded after the lock is dropped, so decodes never serialize.
    resident: RwLock<HashMap<DigestKey, Arc<Vec<u8>>>>,
    /// Whether the sequence index (sequences.rgsi) has been loaded.
    /// For remote stores, this starts as `false` and is lazily loaded on first
    /// sequence access, avoiding the costly download when only browsing collections.
    pub(crate) sequence_index_loaded: bool,
    /// The relative path to the sequence index file (from rgstore.json),
    /// stored for deferred loading in remote stores.
    pub(crate) sequence_index_path: Option<String>,
    /// What this handle has actually changed since its last successful commit.
    /// See [`PendingChanges`]. Behind a `Mutex` because the commit path is
    /// `&self`.
    pub(crate) pending: Mutex<PendingChanges>,
    /// A store-directory write lock held across several mutations, set by
    /// [`Self::lock_for_batch`]. When present, individual commits skip acquiring
    /// their own lock — otherwise a batch guard would deadlock against the
    /// `write_index_files` each mutation triggers.
    pub(crate) commit_lock: Option<Arc<StoreLock>>,
    /// Timeout/staleness settings used when acquiring the store write lock.
    pub(crate) lock_options: LockOptions,
    /// Overwrite an alias already published on disk with a different target,
    /// instead of erroring on the conflict. Off by default: two writers binding
    /// one human-readable name to different content is a semantic conflict, not
    /// a merge detail.
    pub(crate) force_alias: bool,
}

/// What this handle has actually created, modified, or deleted since its last
/// successful commit.
///
/// A store handle's in-memory maps hold two different things mixed together:
/// rows it produced, and rows it merely LOADED so they could be read
/// (`open_local` loads a stub for every collection in `collections.rgci`, and
/// every row of `sequences.rgsi`). A commit that cannot tell those apart has to
/// write the whole pile back — and the pile is an open-time snapshot, which on a
/// long import is hours stale.
///
/// Recording changes explicitly is what makes a commit a DELTA: take the lock,
/// re-read the index from disk, apply exactly these sets, publish. A row this
/// handle never touched is never rewritten, so a concurrent writer's additions
/// cannot be clobbered and its deletions cannot be resurrected.
///
/// In-memory only, never written to disk: this describes an intent that is fully
/// discharged by the commit that applies it, and is cleared as soon as that
/// commit succeeds. A handle dropped without committing abandons its pending
/// changes — see [`ReadonlyRefgetStore::has_uncommitted_changes`].
#[derive(Debug, Default, Clone)]
pub struct PendingChanges {
    /// Collection digests to publish into `collections.rgci`.
    pub(crate) collections: HashSet<DigestKey>,
    /// Sequence digests to publish into `sequences.rgsi`.
    pub(crate) sequences: HashSet<DigestKey>,
    /// `(kind, namespace, alias)` triples to publish into the alias TSVs.
    pub(crate) aliases: HashSet<(AliasKind, String, String)>,
    /// Collection digests to drop from `collections.rgci`.
    pub(crate) removed_collections: HashSet<DigestKey>,
    /// Sequence digests to drop from `sequences.rgsi`.
    pub(crate) removed_sequences: HashSet<DigestKey>,
    /// `(kind, namespace, alias)` triples to drop from the alias TSVs.
    pub(crate) removed_aliases: HashSet<(AliasKind, String, String)>,
    /// `(kind, namespace)` pairs this handle explicitly emptied. Recorded so the
    /// commit visits the namespace at all; whether the TSV is actually deleted
    /// depends on the MERGED result being empty, not on this handle's intent.
    pub(crate) emptied_alias_namespaces: HashSet<(AliasKind, String)>,
    /// Subset of `aliases` the caller asked to force: on commit these overwrite
    /// a conflicting binding another writer already published, as if
    /// `force_alias` were set for that one entry.
    pub(crate) forced_aliases: HashSet<(AliasKind, String, String)>,
}

impl PendingChanges {
    pub(crate) fn is_empty(&self) -> bool {
        self.collections.is_empty()
            && self.sequences.is_empty()
            && self.aliases.is_empty()
            && self.removed_collections.is_empty()
            && self.removed_sequences.is_empty()
            && self.removed_aliases.is_empty()
            && self.emptied_alias_namespaces.is_empty()
    }

    /// Record a collection this handle added. An add supersedes a pending
    /// removal of the same digest (and vice versa), so the two sets stay
    /// disjoint and the commit never has to guess which wins.
    pub(crate) fn add_collection(&mut self, key: DigestKey) {
        self.removed_collections.remove(&key);
        self.collections.insert(key);
    }

    pub(crate) fn remove_collection(&mut self, key: DigestKey) {
        self.collections.remove(&key);
        self.removed_collections.insert(key);
    }

    pub(crate) fn add_sequence(&mut self, key: DigestKey) {
        self.removed_sequences.remove(&key);
        self.sequences.insert(key);
    }

    pub(crate) fn remove_sequence(&mut self, key: DigestKey) {
        self.sequences.remove(&key);
        self.removed_sequences.insert(key);
    }

    /// Drop sequences from the pending set WITHOUT recording a removal.
    ///
    /// For rows that were staged but never published — the failed-import
    /// cleanup path. Recording a removal instead would be wrong: it would delete
    /// an identical row another writer had legitimately published, since
    /// sequence rows are content-addressed and therefore shared.
    pub(crate) fn forget_sequences(&mut self, keys: &HashSet<DigestKey>) {
        self.sequences.retain(|k| !keys.contains(k));
    }

    pub(crate) fn add_alias(&mut self, kind: AliasKind, namespace: &str, alias: &str) {
        let entry = (kind, namespace.to_string(), alias.to_string());
        self.removed_aliases.remove(&entry);
        self.aliases.insert(entry);
    }

    pub(crate) fn add_forced_alias(&mut self, kind: AliasKind, namespace: &str, alias: &str) {
        self.add_alias(kind, namespace, alias);
        self.forced_aliases
            .insert((kind, namespace.to_string(), alias.to_string()));
    }

    pub(crate) fn is_forced(&self, kind: AliasKind, namespace: &str, alias: &str) -> bool {
        self.forced_aliases
            .contains(&(kind, namespace.to_string(), alias.to_string()))
    }

    pub(crate) fn remove_alias(&mut self, kind: AliasKind, namespace: &str, alias: &str) {
        let entry = (kind, namespace.to_string(), alias.to_string());
        self.aliases.remove(&entry);
        self.forced_aliases.remove(&entry);
        self.removed_aliases.insert(entry);
    }

    /// Namespaces of one kind this handle has touched — the only ones a commit
    /// needs to rewrite. Namespaces nobody changed are left alone on disk.
    pub(crate) fn touched_alias_namespaces(&self, kind: AliasKind) -> HashSet<String> {
        let mut out = HashSet::new();
        for (k, ns, _) in self.aliases.iter().chain(self.removed_aliases.iter()) {
            if *k == kind {
                out.insert(ns.clone());
            }
        }
        for (k, ns) in &self.emptied_alias_namespaces {
            if *k == kind {
                out.insert(ns.clone());
            }
        }
        out
    }

    /// Drop exactly the changes a completed commit applied.
    ///
    /// Set difference, not `clear()`: another thread may have recorded a change
    /// after the commit snapshotted, and that one still has to be applied.
    pub(crate) fn clear_matching(&mut self, applied: &PendingChanges) {
        self.collections.retain(|k| !applied.collections.contains(k));
        self.sequences.retain(|k| !applied.sequences.contains(k));
        self.aliases.retain(|k| !applied.aliases.contains(k));
        self.forced_aliases.retain(|k| !applied.aliases.contains(k));
        self.removed_collections
            .retain(|k| !applied.removed_collections.contains(k));
        self.removed_sequences
            .retain(|k| !applied.removed_sequences.contains(k));
        self.removed_aliases
            .retain(|k| !applied.removed_aliases.contains(k));
        self.emptied_alias_namespaces
            .retain(|k| !applied.emptied_alias_namespaces.contains(k));
    }

    /// Drop the alias changes for one namespace, after the cheap
    /// single-namespace commit path published it.
    pub(crate) fn clear_alias_namespace(&mut self, kind: AliasKind, namespace: &str) {
        self.aliases
            .retain(|(k, ns, _)| !(*k == kind && ns == namespace));
        self.forced_aliases
            .retain(|(k, ns, _)| !(*k == kind && ns == namespace));
        self.removed_aliases
            .retain(|(k, ns, _)| !(*k == kind && ns == namespace));
        self.emptied_alias_namespaces
            .retain(|(k, ns)| !(*k == kind && ns == namespace));
    }
}

impl ReadonlyRefgetStore {
    /// Generic constructor. Creates a new, empty `ReadonlyRefgetStore`.
    /// Internal only - users should go through RefgetStore.
    pub(crate) fn new(mode: StorageMode) -> Self {
        ReadonlyRefgetStore {
            sequence_store: HashMap::new(),
            md5_lookup: HashMap::new(),
            name_lookup: HashMap::new(),
            collections: HashMap::new(),
            mode,
            local_path: None,
            remote_source: None,
            seqdata_path_template: None,
            persist_to_disk: false,
            quiet: false,
            ancillary_digests: true,
            attribute_index: false,
            aliases: AliasManager::default(),
            fhr_metadata: HashMap::new(),
            available_sequence_alias_namespaces: Vec::new(),
            available_collection_alias_namespaces: Vec::new(),
            seq_fd_cache: Mutex::new(FdCache::new(default_fd_cache_cap())),
            resident: RwLock::new(HashMap::new()),
            sequence_index_loaded: true,
            sequence_index_path: None,
            pending: Mutex::new(PendingChanges::default()),
            commit_lock: None,
            lock_options: LockOptions::default(),
            force_alias: false,
        }
    }

    // =========================================================================
    // Write locking
    // =========================================================================

    /// Hold the store's exclusive writer lock across several mutations.
    ///
    /// Individual mutations already commit under the lock, so this is only needed
    /// when a sequence of them must be atomic with respect to other writers — the
    /// registry's alias step, for instance, which adds many aliases and expects
    /// them to appear together. The guard is dropped by
    /// [`Self::release_batch_lock`] or when the store is dropped.
    ///
    /// Nested commits are re-entrant: they see the held guard and skip acquiring.
    pub fn lock_for_batch(&mut self, operation: &str) -> Result<()> {
        if self.commit_lock.is_some() {
            return Ok(());
        }
        let local_path = self
            .local_path
            .as_ref()
            .context("lock_for_batch requires a disk-backed store")?;
        let lock = StoreLock::acquire(local_path, operation, self.lock_options.clone())?;
        self.commit_lock = Some(Arc::new(lock));
        Ok(())
    }

    /// Release a lock taken by [`Self::lock_for_batch`].
    pub fn release_batch_lock(&mut self) {
        self.commit_lock = None;
    }

    /// Whether this store currently holds a batch write lock.
    pub fn holds_batch_lock(&self) -> bool {
        self.commit_lock.is_some()
    }

    /// Whether this store has additions or removals that have not yet been
    /// committed to the shared index files.
    ///
    /// Pending changes live only in memory, so dropping a store without
    /// committing silently abandons them: added rows never reach
    /// `sequences.rgsi`/`collections.rgci`, and removed rows are still on disk.
    pub fn has_uncommitted_changes(&self) -> bool {
        !self.pending.lock().unwrap().is_empty()
    }

    /// Record a change this handle made, so the next commit applies it to the
    /// index it reads fresh from disk.
    pub(crate) fn record<F: FnOnce(&mut PendingChanges)>(&self, f: F) {
        f(&mut self.pending.lock().unwrap());
    }

    /// Override the timeout/staleness settings used when acquiring the write lock.
    pub fn set_lock_options(&mut self, options: LockOptions) {
        self.lock_options = options;
    }

    /// Allow a commit to overwrite an alias another writer already published
    /// under a different digest, instead of erroring on the conflict.
    pub fn set_force_alias(&mut self, force: bool) {
        self.force_alias = force;
    }

    /// Test-only: shrink the partial-read fd-cache to a tiny capacity so the
    /// eviction/reopen path is exercised deterministically. Only used by the
    /// filesystem-gated partial-read tests.
    #[cfg(all(test, feature = "filesystem"))]
    pub(crate) fn set_seq_fd_cache_cap_for_test(&self, cap: usize) {
        let mut cache = self.seq_fd_cache.lock().unwrap();
        *cache = FdCache::new(cap);
    }

    /// Set whether to suppress progress output.
    pub fn set_quiet(&mut self, quiet: bool) {
        self.quiet = quiet;
    }

    /// Returns whether the store is in quiet mode.
    pub fn is_quiet(&self) -> bool {
        self.quiet
    }

    /// Check whether a valid RefgetStore exists at the given path.
    pub fn store_exists<P: AsRef<Path>>(path: P) -> bool {
        path.as_ref().join("rgstore.json").exists()
    }

    /// Change the storage mode, re-encoding/decoding existing sequences as needed.
    pub fn set_encoding_mode(&mut self, new_mode: StorageMode) {
        if self.mode == new_mode {
            return;
        }

        for record in self.sequence_store.values_mut() {
            match record {
                SequenceRecord::Full { metadata, sequence } => {
                    match (self.mode, new_mode) {
                        (StorageMode::Raw, StorageMode::Encoded) => {
                            let alphabet = lookup_alphabet(&metadata.alphabet);
                            *sequence = std::sync::Arc::new(encode_sequence(&sequence[..], alphabet));
                        }
                        (StorageMode::Encoded, StorageMode::Raw) => {
                            let alphabet = lookup_alphabet(&metadata.alphabet);
                            *sequence = std::sync::Arc::new(decode_string_from_bytes(
                                &sequence[..],
                                metadata.length,
                                alphabet,
                            ));
                        }
                        // Zstd conversions: normalize through ASCII. The stored
                        // body for Zstd is the whole-record zstd frame.
                        (StorageMode::Raw, StorageMode::Zstd) => {
                            *sequence = std::sync::Arc::new(
                                zstd::encode_all(&sequence[..], super::ZSTD_STORAGE_LEVEL)
                                    .expect("zstd encode during mode switch"),
                            );
                        }
                        (StorageMode::Zstd, StorageMode::Raw) => {
                            *sequence = std::sync::Arc::new(
                                zstd::decode_all(&sequence[..])
                                    .expect("zstd decode during mode switch"),
                            );
                        }
                        (StorageMode::Encoded, StorageMode::Zstd) => {
                            let alphabet = lookup_alphabet(&metadata.alphabet);
                            let ascii = decode_string_from_bytes(
                                &sequence[..],
                                metadata.length,
                                alphabet,
                            );
                            *sequence = std::sync::Arc::new(
                                zstd::encode_all(&ascii[..], super::ZSTD_STORAGE_LEVEL)
                                    .expect("zstd encode during mode switch"),
                            );
                        }
                        (StorageMode::Zstd, StorageMode::Encoded) => {
                            let alphabet = lookup_alphabet(&metadata.alphabet);
                            let ascii = zstd::decode_all(&sequence[..])
                                .expect("zstd decode during mode switch");
                            *sequence =
                                std::sync::Arc::new(encode_sequence(&ascii[..], alphabet));
                        }
                        _ => {}
                    }
                }
                SequenceRecord::Stub(_) => {}
            }
        }

        self.mode = new_mode;
    }

    /// Enable 2-bit encoding for space efficiency.
    pub fn enable_encoding(&mut self) {
        self.set_encoding_mode(StorageMode::Encoded);
    }

    /// Disable encoding, use raw byte storage.
    pub fn disable_encoding(&mut self) {
        self.set_encoding_mode(StorageMode::Raw);
    }

    /// Enable disk persistence for this store.
    pub fn enable_persistence<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
        let path = path.as_ref();

        self.local_path = Some(path.to_path_buf());
        self.persist_to_disk = true;
        self.seqdata_path_template
            .get_or_insert_with(|| DEFAULT_SEQDATA_PATH_TEMPLATE.to_string());

        create_dir_all(path.join("sequences"))?;
        create_dir_all(path.join("collections"))?;

        // Materializing an in-memory store onto disk: EVERYTHING resident is a
        // change, because none of it came from this directory. This is the one
        // place where "write back the whole in-memory pile" is the correct
        // commit, and it is correct precisely because nothing here was loaded.
        {
            let mut pending = self.pending.lock().unwrap();
            for key in self.sequence_store.keys() {
                pending.add_sequence(*key);
            }
            for key in self.collections.keys() {
                pending.add_collection(*key);
            }
            for kind in [AliasKind::Sequence, AliasKind::Collection] {
                for ns in self.aliases.namespaces_for(kind) {
                    for alias in self.aliases.namespace_map(kind, &ns).keys() {
                        pending.add_alias(kind, &ns, alias);
                    }
                }
            }
        }

        let keys: Vec<DigestKey> = self.sequence_store.keys().cloned().collect();
        for key in keys {
            if let Some(SequenceRecord::Full { metadata, sequence }) = self.sequence_store.get(&key)
            {
                self.write_sequence_to_disk_single(metadata, sequence)?;
                let stub = SequenceRecord::Stub(metadata.clone());
                self.sequence_store.insert(key, stub);
            }
        }

        for record in self.collections.values() {
            self.write_collection_to_disk_single(record)?;
        }

        self.write_index_files()?;

        Ok(())
    }

    /// Disable disk persistence for this store.
    pub fn disable_persistence(&mut self) {
        self.persist_to_disk = false;
    }

    /// Check if persistence to disk is enabled.
    pub fn is_persisting(&self) -> bool {
        self.persist_to_disk
    }

    /// Adds a sequence to the Store
    pub fn add_sequence<T: Into<Option<DigestKey>>>(
        &mut self,
        sequence_record: SequenceRecord,
        collection_digest: T,
        force: bool,
    ) -> Result<()> {
        let collection_digest = collection_digest
            .into()
            .ok_or_else(|| anyhow::anyhow!("Collection digest is required"))?;
        self.collections.get(&collection_digest).ok_or_else(|| {
            anyhow::anyhow!("Collection not found for digest: {:?}", collection_digest)
        })?;

        let metadata = sequence_record.metadata();

        self.name_lookup
            .entry(collection_digest)
            .or_default()
            .insert(metadata.name.clone(), metadata.sha512t24u.to_key());

        self.add_sequence_record(sequence_record, force)?;

        Ok(())
    }

    /// Adds a collection, and all sequences in it, to the store.
    pub fn add_sequence_collection(
        &mut self,
        collection: crate::digest::SequenceCollection,
    ) -> Result<()> {
        self.add_sequence_collection_internal(collection, false)
    }

    /// Adds a collection, overwriting existing data.
    pub fn add_sequence_collection_force(
        &mut self,
        collection: crate::digest::SequenceCollection,
    ) -> Result<()> {
        self.add_sequence_collection_internal(collection, true)
    }

    /// Internal implementation for adding a sequence collection.
    pub(crate) fn add_sequence_collection_internal(
        &mut self,
        collection: crate::digest::SequenceCollection,
        force: bool,
    ) -> Result<()> {
        let coll_digest = collection.metadata.digest.to_key();

        if !force && self.collections.contains_key(&coll_digest) {
            return Ok(());
        }

        let crate::digest::SequenceCollection { metadata, sequences } = collection;

        let record = SequenceCollectionRecord::Full {
            metadata: metadata.clone(),
            sequences: sequences.iter().map(|s| SequenceRecord::Stub(s.metadata().clone())).collect(),
        };

        if self.persist_to_disk && self.local_path.is_some() {
            self.write_collection_to_disk_single(&record)?;
        }

        self.collections.insert(coll_digest, record);
        self.record(|p| p.add_collection(coll_digest));

        for sequence_record in sequences {
            self.add_sequence(sequence_record, coll_digest, force)?;
        }

        if self.persist_to_disk && self.local_path.is_some() {
            self.write_index_files()?;
        }

        Ok(())
    }

    /// Pack a raw ASCII record when the store uses encoded storage.
    ///
    /// Raw and packed forms are distinguished by their expected lengths, so a
    /// single-base sequence is ambiguous. Use [`ingest_sequence`](Self::ingest_sequence)
    /// when the input is known to be raw; it handles that case explicitly.
    fn pack_raw_ascii_for_encoded_mode(&self, sr: SequenceRecord) -> SequenceRecord {
        if self.mode != StorageMode::Encoded {
            return sr;
        }
        match sr {
            SequenceRecord::Full { metadata, sequence } => {
                let alphabet = lookup_alphabet(&metadata.alphabet);
                let bps = alphabet.bits_per_symbol;
                let expected_encoded = metadata.length.saturating_mul(bps).div_ceil(8);
                let looks_raw = sequence.len() == metadata.length
                    && sequence.len() != expected_encoded
                    && sequence.is_ascii();
                if looks_raw {
                    let packed = encode_sequence(&sequence[..], alphabet);
                    SequenceRecord::Full {
                        metadata,
                        sequence: std::sync::Arc::new(packed),
                    }
                } else {
                    SequenceRecord::Full { metadata, sequence }
                }
            }
            stub @ SequenceRecord::Stub(_) => stub,
        }
    }

    /// Digest and insert raw bytes using the store's native encoding.
    ///
    /// Because the input is known to be raw, this method also handles
    /// single-base sequences, whose raw and packed lengths are identical.
    /// Input is normalized in the same way as `digest_sequence`.
    pub fn ingest_sequence(&mut self, name: &str, bytes: &[u8]) -> Result<String> {
        let record = crate::digest::digest_sequence(name, bytes);
        let digest = record.metadata().sha512t24u.clone();

        let record = match record {
            SequenceRecord::Full { metadata, sequence } if self.mode == StorageMode::Encoded => {
                let alphabet = lookup_alphabet(&metadata.alphabet);
                let packed = encode_sequence(&sequence[..], alphabet);
                SequenceRecord::Full {
                    metadata,
                    sequence: std::sync::Arc::new(packed),
                }
            }
            other => other,
        };

        self.add_sequence_record(record, false)?;
        Ok(digest)
    }

    /// Adds a SequenceRecord directly to the store without collection association.
    ///
    /// Raw ASCII records are packed when the store uses encoded storage.
    /// Already-packed records are stored unchanged.
    pub fn add_sequence_record(&mut self, sr: SequenceRecord, force: bool) -> Result<()> {
        let sr = self.pack_raw_ascii_for_encoded_mode(sr);

        let metadata = sr.metadata();
        let key = metadata.sha512t24u.to_key();

        // Records must now match the store's native representation: ASCII in
        // Raw mode or the alphabet's packed size in Encoded mode.
        debug_assert!(
            match &sr {
                SequenceRecord::Full { metadata, sequence } => match self.mode {
                    StorageMode::Raw => sequence.is_ascii(),
                    StorageMode::Encoded => {
                        let bps = lookup_alphabet(&metadata.alphabet).bits_per_symbol;
                        sequence.len() == metadata.length.saturating_mul(bps).div_ceil(8)
                    }
                    StorageMode::Zstd => true, // zstd bytes have no simple invariant to check
                },
                SequenceRecord::Stub(_) => true,
            },
            "add_sequence_record: sequence bytes must be stored in the store's native encoding (ASCII in Raw mode, packed to the alphabet's encoded size in Encoded mode)"
        );

        // A dedup hit records NOTHING: the row is already in memory, which for a
        // disk-backed store means it is already in `sequences.rgsi`. Re-asserting
        // it would put a row this handle did not produce back into the delta.
        if !force && self.sequence_store.contains_key(&key) {
            return Ok(());
        }

        self.md5_lookup
            .insert(metadata.md5.to_key(), metadata.sha512t24u.to_key());
        self.record(|p| p.add_sequence(key));

        // In Zstd mode the caller passes the ASCII record body (per contract,
        // "do not 2-bit pre-pack, let zstd own the entropy"); the store owns the
        // whole-record zstd compression here so the on-disk / in-memory body is
        // the compressed frame. Reads decompress the whole frame and slice.
        let sr = self.compress_record_for_storage(sr)?;

        if self.persist_to_disk && self.local_path.is_some() {
            match &sr {
                SequenceRecord::Full { metadata, sequence } => {
                    self.write_sequence_to_disk_single(metadata, sequence)?;
                    let stub = SequenceRecord::Stub(metadata.clone());
                    self.sequence_store.insert(key, stub);
                    return Ok(());
                }
                SequenceRecord::Stub(_) => {}
            }
        }

        self.sequence_store.insert(key, sr);
        Ok(())
    }

    /// For a `Zstd`-mode store, compress a `Full` record's ASCII body into a zstd
    /// frame (the stored representation). A no-op for every other mode and for
    /// `Stub` records. `metadata.length` stays the logical (ASCII) base count.
    fn compress_record_for_storage(&self, sr: SequenceRecord) -> Result<SequenceRecord> {
        if self.mode != StorageMode::Zstd {
            return Ok(sr);
        }
        match sr {
            SequenceRecord::Full { metadata, sequence } => {
                let compressed = zstd::encode_all(&sequence[..], super::ZSTD_STORAGE_LEVEL)
                    .context("zstd compression of sequence record failed")?;
                Ok(SequenceRecord::Full {
                    metadata,
                    sequence: std::sync::Arc::new(compressed),
                })
            }
            other => Ok(other),
        }
    }

    /// Inserter-side half of [`add_sequence_record`](Self::add_sequence_record)
    /// for the parallel streaming import: do the FAST in-memory dedup decision
    /// and map/`md5_lookup` insert here (single inserter, so no race on the
    /// dedup truth), but DO NOT write the `.seq` to disk. Instead return the
    /// expanded full path + bytes so the caller can dispatch the (independent,
    /// per-digest) disk write to a bounded writer pool.
    ///
    /// Returns `Some((full_path, bytes))` when a `.seq` write must be performed
    /// (disk-backed store, `Full` record, and either a first occurrence or a
    /// forced overwrite), or `None` when nothing needs to be written to disk
    /// (in-memory mode, a `Stub`, or a dedup hit). The in-memory state is fully
    /// updated before returning, so dedup stays the single source of truth on
    /// the inserter thread.
    #[cfg_attr(not(feature = "filesystem"), allow(dead_code))]
    pub(crate) fn add_sequence_record_deferred_write(
        &mut self,
        sr: SequenceRecord,
        force: bool,
    ) -> Result<Option<(PathBuf, Vec<u8>)>> {
        let metadata = sr.metadata();
        let key = metadata.sha512t24u.to_key();

        // Dedup hit: nothing inserted, so nothing to record. See
        // [`Self::add_sequence_record`].
        if !force && self.sequence_store.contains_key(&key) {
            return Ok(None);
        }

        self.md5_lookup
            .insert(metadata.md5.to_key(), metadata.sha512t24u.to_key());
        self.record(|p| p.add_sequence(key));

        if self.persist_to_disk && self.local_path.is_some() {
            match sr {
                SequenceRecord::Full { metadata, sequence } => {
                    // Insert the stub into the map NOW (reserve), so the dedup
                    // decision is committed on the inserter thread. The actual
                    // byte write is dispatched to the writer pool by the caller.
                    let full_path = self
                        .sequence_file_path(&metadata.sha512t24u)
                        .context("seqdata_path_template/local_path not set")?;
                    let stub = SequenceRecord::Stub(metadata);
                    self.sequence_store.insert(key, stub);
                    // INVARIANT: strong_count == 1 here — the Arc was just
                    // constructed in the import pipeline (Arc::new in import.rs)
                    // and no other owner exists at the point of this call, so
                    // try_unwrap always succeeds and reclaims the buffer with zero
                    // copy. The clone fallback is dead code / future-proofing only.
                    debug_assert_eq!(
                        std::sync::Arc::strong_count(&sequence),
                        1,
                        "sequence Arc must be uniquely owned for zero-copy reclaim"
                    );
                    let bytes = std::sync::Arc::try_unwrap(sequence)
                        .unwrap_or_else(|arc| (*arc).clone());
                    // Zstd mode: the caller handed us the ASCII body; compress the
                    // whole record so the writer pool persists the zstd frame.
                    let bytes = if self.mode == StorageMode::Zstd {
                        zstd::encode_all(&bytes[..], super::ZSTD_STORAGE_LEVEL)
                            .context("zstd compression of sequence record failed")?
                    } else {
                        bytes
                    };
                    return Ok(Some((full_path, bytes)));
                }
                SequenceRecord::Stub(s) => {
                    self.sequence_store.insert(key, SequenceRecord::Stub(s));
                    return Ok(None);
                }
            }
        }

        // In-memory (non-disk-backed): keep the resident body in the store's
        // native form, so a Zstd store holds the compressed frame just like the
        // disk-backed path returns compressed bytes above.
        let sr = self.compress_record_for_storage(sr)?;
        self.sequence_store.insert(key, sr);
        Ok(None)
    }

    // =========================================================================
    // Sequence query methods
    // =========================================================================

    /// Returns an iterator over all sequence digests in the store
    pub fn sequence_digests(&self) -> impl Iterator<Item = DigestKey> + '_ {
        self.sequence_store.keys().cloned()
    }

    /// Returns an iterator over sequence metadata for all sequences in the store.
    pub fn sequence_metadata(&self) -> impl Iterator<Item = &SequenceMetadata> + '_ {
        self.sequence_store.values().map(|rec| rec.metadata())
    }

    /// Logical size in bytes of all sequence *payloads*, computed from metadata
    /// (length x storage mode). Cheap: O(n_sequences) arithmetic, no I/O, no walk,
    /// works on stubs. Does NOT include index files, sidecars, or rgstore.json.
    /// This is the value cached in the manifest at write time (see write path); for
    /// the exact full on-disk footprint use `actual_disk_usage()` (walks the dir).
    pub fn logical_sequence_bytes(&self) -> usize {
        self.sequence_store
            .values()
            .map(|rec| rec.metadata().disk_size(&self.mode))
            .sum()
    }

    /// Exact on-disk footprint of the store: recursively walks the store directory
    /// and sums every file's byte length (`.seq` data, `.rgsi`/`.rgci` indexes, FHR
    /// sidecars, alias data, `rgstore.json`). Accurate and complete, but does I/O on
    /// every call. Use this when an exact footprint is needed; for the cheap cached
    /// sequence-content size use `logical_sequence_bytes()`.
    pub fn actual_disk_usage(&self) -> usize {
        let Some(path) = &self.local_path else {
            return 0;
        };

        fn dir_size(path: &std::path::Path) -> usize {
            let mut total = 0;
            if let Ok(entries) = std::fs::read_dir(path) {
                for entry in entries.flatten() {
                    let path = entry.path();
                    if path.is_file() {
                        total += entry.metadata().map(|m| m.len() as usize).unwrap_or(0);
                    } else if path.is_dir() {
                        total += dir_size(&path);
                    }
                }
            }
            total
        }

        dir_size(path)
    }

    // =========================================================================
    // Collection API
    // =========================================================================

    /// List collections with pagination and optional attribute filtering.
    pub fn list_collections(
        &self,
        page: usize,
        page_size: usize,
        filters: &[(&str, &str)],
    ) -> Result<PagedResult<SequenceCollectionMetadata>> {
        let mut filtered: Vec<SequenceCollectionMetadata> = Vec::new();
        for record in self.collections.values() {
            let meta = record.metadata();
            let mut passes = true;
            for &(attr_name, attr_digest) in filters {
                if !metadata_matches_attribute(meta, attr_name, attr_digest)? {
                    passes = false;
                    break;
                }
            }
            if passes {
                filtered.push(meta.clone());
            }
        }

        filtered.sort_by(|a, b| a.digest.cmp(&b.digest));

        let total = filtered.len();
        let start = page * page_size;
        let results = if start < total {
            filtered.into_iter().skip(start).take(page_size).collect()
        } else {
            Vec::new()
        };

        Ok(PagedResult {
            results,
            pagination: Pagination {
                page,
                page_size,
                total,
            },
        })
    }

    /// Get metadata for a single collection by digest (no sequence data).
    pub fn get_collection_metadata<K: AsRef<[u8]>>(
        &self,
        collection_digest: K,
    ) -> Option<&SequenceCollectionMetadata> {
        let key = collection_digest.to_key();
        self.collections.get(&key).map(|record| record.metadata())
    }

    /// Per-collection sequence metadata (name, description, digest) in FASTA
    /// order. This is the source of truth for names/headers; the global
    /// `sequence_store` record only labels the shared bytes.
    pub(crate) fn collection_sequence_metadata(&self, key: &DigestKey) -> Result<&[SequenceRecord]> {
        match self.collections.get(key) {
            Some(SequenceCollectionRecord::Full { sequences, .. }) => Ok(sequences),
            Some(SequenceCollectionRecord::Stub(_)) => Err(anyhow!(
                "Collection {} not loaded. Call load_collection() first.",
                key_to_digest_string(key)
            )),
            None => Err(anyhow!("Collection not found: {}", key_to_digest_string(key))),
        }
    }

    /// Get a collection with all its sequences loaded.
    pub fn get_collection(&self, collection_digest: &str) -> Result<crate::digest::SequenceCollection> {
        let key = collection_digest.to_key();

        if !self.name_lookup.contains_key(&key) {
            return Err(anyhow!(
                "Collection not loaded: {}. Call load_collection() or load_all_collections() first.",
                collection_digest
            ));
        }

        let metadata = self
            .collections
            .get(&key)
            .ok_or_else(|| anyhow!("Collection not found: {}", collection_digest))?
            .metadata()
            .clone();

        // Iterate the collection's own per-sequence records so each result carries
        // the per-collection name AND description, not the first-imported global
        // label of a sequence shared across collections. Only the bytes (and `fai`,
        // if the collection record lacks it) come from the global store.
        let sequences: Vec<SequenceRecord> = self
            .collection_sequence_metadata(&key)?
            .iter()
            .map(|coll_record| {
                let mut meta = coll_record.metadata().clone();
                let seq_key = meta.sha512t24u.to_key();
                let global = self.sequence_store.get(&seq_key).ok_or_else(|| {
                    anyhow!(
                        "Sequence {} not found in store for collection {}",
                        key_to_digest_string(&seq_key),
                        collection_digest,
                    )
                })?;
                if meta.fai.is_none() {
                    meta.fai = global.metadata().fai.clone();
                }
                Ok(match global.sequence_arc() {
                    Some(seq) => SequenceRecord::Full {
                        metadata: meta,
                        sequence: seq,
                    },
                    None => SequenceRecord::Stub(meta),
                })
            })
            .collect::<Result<Vec<_>>>()?;

        Ok(crate::digest::SequenceCollection {
            metadata,
            sequences,
        })
    }

    /// Dry-run of [`Self::remove_collection`]'s orphan cleanup: the sequence
    /// digests that WOULD be deleted, without touching anything.
    ///
    /// Uses the same disk-derived live set as the real thing, so it fails with the
    /// same error if the store is not in a state where orphan GC is safe.
    ///
    /// # Advisory, by design
    ///
    /// This takes NO lock. It exists for confirmation prompts ("this will free
    /// 21 sequences, proceed?"), where blocking every concurrent writer for the
    /// length of a full-store scan to answer a question the user may say no to
    /// would be absurd. The authoritative scan runs again inside
    /// `remove_collection`, under the lock, and the two can legitimately differ:
    /// a collection committed in between makes some planned orphan live again,
    /// and the real removal will correctly spare it. Callers comparing the two
    /// should treat a shortfall as normal concurrency, not corruption.
    pub fn plan_orphan_removal(&self, digest: &str) -> Result<Vec<String>> {
        let key = digest.to_key();
        let candidates = self.orphan_candidates(digest)?;
        let live = self.live_sequence_set(&key)?;
        Ok(candidates
            .into_iter()
            .filter(|k| !live.contains(k))
            .map(|k| key_to_digest_string(&k))
            .collect())
    }

    /// Sequence digests belonging to the collection being removed.
    fn orphan_candidates(&self, digest: &str) -> Result<Vec<DigestKey>> {
        if self.local_path.is_some() {
            self.collection_sequence_digests(digest)
        } else {
            Ok(self
                .name_lookup
                .get(&digest.to_key())
                .map(|name_map| name_map.values().cloned().collect())
                .unwrap_or_default())
        }
    }

    /// Sequence digests still referenced by some OTHER collection.
    ///
    /// Disk-backed stores derive this from disk. Only a pure in-memory store
    /// (`local_path == None`) falls back to `name_lookup` — there, the in-memory
    /// maps are all there is, so they are authoritative rather than incidental.
    fn live_sequence_set(&self, exclude: &DigestKey) -> Result<HashSet<DigestKey>> {
        if self.local_path.is_some() {
            return self.live_sequence_digests_from_disk(exclude);
        }
        let mut live = HashSet::new();
        for (key, name_map) in &self.name_lookup {
            if key == exclude {
                continue;
            }
            live.extend(name_map.values().copied());
        }
        Ok(live)
    }

    /// Remove a collection from the store.
    ///
    /// When `remove_orphan_sequences` is true, the orphan-cleanup path is
    /// O(sequences + collections): `md5_lookup` is scanned exactly once, not
    /// once per orphan. Do not reintroduce a per-orphan scan here — on large
    /// stores that is quadratic and effectively unbounded.
    ///
    /// The live set is derived from DISK, not from `name_lookup` — see
    /// [`Self::live_sequence_digests_from_disk`] for why that distinction is the
    /// difference between a GC and a data-loss bug.
    ///
    /// # The lock is held across the orphan scan, deliberately
    ///
    /// The scan is the expensive part — on the plantref store (147 collections,
    /// ~1.5M sequence digests) it reads every `collections/*.rgsi` and takes
    /// roughly a minute. Everywhere else in this module the rule is "do the
    /// expensive work outside the lock"; here that rule is wrong. Computing the
    /// live set before taking the lock leaves a window in which another writer
    /// commits a collection referencing one of the digests the scan just
    /// classified as an orphan, and the unlink that follows deletes live data.
    /// Removals are rare and hand-run, so blocking concurrent builds for a
    /// minute is the cheap side of that trade.
    pub fn remove_collection(
        &mut self,
        digest: &str,
        remove_orphan_sequences: bool,
    ) -> Result<bool> {
        let key = digest.to_key();

        if !self.collections.contains_key(&key) {
            return Ok(false);
        }

        // Take the lock BEFORE the orphan scan and hold it through the scan, the
        // index commit, and the unlinks. All three have to see the same store: a
        // collection another writer adds in between would make an "orphan" live
        // again, and we would unlink it anyway. The nested `write_index_files`
        // sees the guard and does not re-acquire.
        let acquired = self.acquire_commit_lock("remove_collection")?;
        let restore = match acquired {
            Some(lock) => {
                let previous = self.commit_lock.replace(Arc::new(lock));
                Some(previous)
            }
            // Already inside a caller's `lock_for_batch`; leave it alone.
            None => None,
        };

        let result = self.remove_collection_locked(digest, key, remove_orphan_sequences);

        if let Some(previous) = restore {
            self.commit_lock = previous;
        }
        result
    }

    fn remove_collection_locked(
        &mut self,
        digest: &str,
        key: DigestKey,
        remove_orphan_sequences: bool,
    ) -> Result<bool> {
        // Compute both sets BEFORE mutating anything: the candidates come from
        // the collection's own `.rgsi`, which the cleanup below unlinks.
        let orphan_candidates: Vec<DigestKey> = if remove_orphan_sequences {
            self.orphan_candidates(digest)?
        } else {
            Vec::new()
        };
        let still_referenced: HashSet<DigestKey> = if remove_orphan_sequences {
            self.live_sequence_set(&key)?
        } else {
            HashSet::new()
        };

        self.collections.remove(&key);
        self.name_lookup.remove(&key);
        self.fhr_metadata.remove(&key);
        self.record(|p| p.remove_collection(key));

        // Remove collection aliases pointing to this digest. The in-memory
        // alias table is an open-time snapshot; an alias another process
        // published for this collection since then is only on disk, and
        // leaving it behind makes it resolve to nothing. Under the lock, also
        // scan the published TSVs for every entry targeting this digest.
        let mut alias_pairs = self.aliases.reverse_lookup_collection(digest);
        if self.persist_to_disk {
            if let Some(local_path) = &self.local_path {
                let dir = local_path.join("aliases").join(AliasKind::Collection.subdir());
                if let Ok(entries) = fs::read_dir(&dir) {
                    for entry in entries.filter_map(|e| e.ok()) {
                        let path = entry.path();
                        if path.extension().map_or(true, |e| e != "tsv") {
                            continue;
                        }
                        let Some(ns) = path.file_stem().and_then(|s| s.to_str()) else {
                            continue;
                        };
                        for (alias, target) in super::persistence::read_alias_tsv(&path)? {
                            if target == key {
                                alias_pairs.push((ns.to_string(), alias));
                            }
                        }
                    }
                }
            }
        }
        alias_pairs.sort();
        alias_pairs.dedup();
        let affected_namespaces: HashSet<String> = alias_pairs
            .iter()
            .map(|(ns, _)| ns.clone())
            .collect();
        for (ns, alias) in &alias_pairs {
            self.aliases.remove_collection(ns, alias);
            self.record_alias_removal(AliasKind::Collection, ns, alias);
        }
        for ns in &affected_namespaces {
            self.persist_alias_namespace(AliasKind::Collection, ns)?;
        }

        // Which sequences to unlink, decided under the lock from the live set
        // computed under the same lock.
        let orphans: Vec<DigestKey> = if remove_orphan_sequences {
            orphan_candidates
                .into_iter()
                .filter(|k| !still_referenced.contains(k))
                .collect()
        } else {
            Vec::new()
        };

        if !orphans.is_empty() {
            {
                let mut pending = self.pending.lock().unwrap();
                for orphan_key in &orphans {
                    pending.remove_sequence(*orphan_key);
                }
            }

            for orphan_key in &orphans {
                self.sequence_store.remove(orphan_key);
            }

            // Single pass over md5_lookup instead of one full scan per orphan.
            // md5_lookup maps md5 key -> sha512 key, so we filter on the VALUE.
            let orphan_set: std::collections::HashSet<DigestKey> =
                orphans.iter().copied().collect();
            self.md5_lookup.retain(|_, v| !orphan_set.contains(v));
        }

        // INDEX FIRST, FILES SECOND. Both orderings can be interrupted by a
        // crash; only one of the two resulting states is recoverable. Rows gone,
        // files present is garbage on disk that a later GC can reclaim. Rows
        // present, files gone is a store that lies: `get_substring` raises,
        // `get_collection` cannot open its sequences, and an alias resolves to a
        // collection that no longer exists. That second state is exactly what the
        // pre-delta implementation produced.
        if self.persist_to_disk {
            self.write_index_files()?;

            if let (Some(local_path), Some(template)) =
                (self.local_path.clone(), self.seqdata_path_template.clone())
            {
                // Collect parent shard dirs while unlinking, then rmdir them
                // ONCE at the end. Do NOT move the rmdir back into this loop:
                // `.seq` files are sharded over ~4096 two-char prefix dirs, so
                // a per-file rmdir issues N syscalls (nearly all failing with
                // ENOTEMPTY) to remove at most ~4096 dirs -- roughly doubling
                // syscall count in a loop that is filesystem-metadata bound.
                // The rmdir pass must run AFTER all unlinks, or dirs that only
                // become empty later would be skipped.
                let mut parent_dirs: std::collections::HashSet<PathBuf> =
                    std::collections::HashSet::new();
                for orphan_key in &orphans {
                    let orphan_digest = key_to_digest_string(orphan_key);
                    let seq_file_path = Self::expand_template(&orphan_digest, &template);
                    let full_path = local_path.join(&seq_file_path);
                    let _ = fs::remove_file(&full_path);
                    if let Some(parent) = full_path.parent() {
                        parent_dirs.insert(parent.to_path_buf());
                    }
                }
                for parent in &parent_dirs {
                    let _ = fs::remove_dir(parent); // ignore if non-empty
                }
            }

            if let Some(local_path) = &self.local_path {
                let rgsi_path = local_path.join(format!("collections/{}.rgsi", digest));
                let _ = fs::remove_file(&rgsi_path);
                let fhr_path = local_path.join(format!("fhr/{}.fhr.json", digest));
                let _ = fs::remove_file(&fhr_path);
            }
        }

        Ok(true)
    }

    /// Remove any sequence from `sequence_store` (and its `.seq` file on disk)
    /// that is not referenced by any entry in `self.collections`.
    ///
    /// Used as a best-effort cleanup after a failed import:
    /// [`add_sequence_collections_from_fastas`](Self::add_sequence_collections_from_fastas)
    /// may have inserted sequences for a partially-built collection that never
    /// received an `End` message (and was therefore never added to
    /// `self.collections`).  Those sequences are orphans — they have no
    /// owning collection — and this method removes them so the store stays
    /// internally consistent. The operation is O(sequences + collections):
    /// `md5_lookup` is scanned exactly once, not once per orphan.
    ///
    /// Sequences shared with a successfully-finalized collection are preserved.
    ///
    /// Only sequences THIS import staged (still pending, never committed) are
    /// candidates. Anything already in the on-disk index is out of bounds:
    /// `open_local` loads every global sequence stub but leaves `name_lookup`
    /// empty for stub collections, so "in `sequence_store` but not in
    /// `name_lookup`" describes the entire pre-existing store, not an orphan.
    /// Deriving candidates from that would unlink every published `.seq` file
    /// after one failed import into a reopened store.
    #[cfg_attr(not(feature = "filesystem"), allow(dead_code))]
    pub(crate) fn remove_orphan_seq_files(&mut self) {
        // Build the set of all sequence digest keys that are referenced by at
        // least one surviving (finalized) collection.
        let mut referenced: std::collections::HashSet<DigestKey> =
            std::collections::HashSet::new();
        for name_map in self.name_lookup.values() {
            for &seq_key in name_map.values() {
                referenced.insert(seq_key);
            }
        }

        // Candidates: staged by this handle and not yet published.
        let staged: Vec<DigestKey> = self
            .pending
            .lock()
            .unwrap()
            .sequences
            .iter()
            .copied()
            .collect();

        // Collect the orphan keys (staged but not referenced).
        let orphans: Vec<DigestKey> = staged
            .into_iter()
            .filter(|k| !referenced.contains(k))
            .collect();

        if orphans.is_empty() {
            return;
        }

        // Remove from in-memory structures.
        for key in &orphans {
            self.sequence_store.remove(key);
        }

        // Single pass over md5_lookup instead of one full scan per orphan.
        // md5_lookup maps md5 key -> sha512 key, so we filter on the VALUE.
        let orphan_set: std::collections::HashSet<DigestKey> = orphans.iter().copied().collect();
        self.md5_lookup.retain(|_, v| !orphan_set.contains(v));

        // FORGET these, do not tombstone them. They were staged by an import
        // that failed before its single commit, so no row of ours was ever
        // published; recording a removal would delete the identical row a
        // different writer legitimately published, since sequence rows are
        // content-addressed and therefore shared between collections.
        self.record(|p| p.forget_sequences(&orphan_set));

        // Best-effort remove on-disk `.seq` files.
        if self.persist_to_disk {
            if let (Some(local_path), Some(template)) =
                (&self.local_path, &self.seqdata_path_template)
            {
                // Collect parent shard dirs while unlinking, then rmdir them ONCE
                // at the end. Do NOT move the rmdir back into this loop: `.seq`
                // files are sharded over ~4096 two-char prefix dirs, so a per-file
                // rmdir issues N syscalls (nearly all failing with ENOTEMPTY) to
                // remove at most ~4096 dirs -- roughly doubling syscall count in a
                // loop that is filesystem-metadata bound. The rmdir pass must run
                // AFTER all unlinks, or dirs that only become empty later would be
                // skipped.
                let mut parent_dirs: std::collections::HashSet<PathBuf> =
                    std::collections::HashSet::new();
                for key in &orphans {
                    let digest_str = key_to_digest_string(key);
                    let rel = Self::expand_template(&digest_str, template);
                    let full = local_path.join(&rel);
                    let _ = fs::remove_file(&full);
                    if let Some(parent) = full.parent() {
                        parent_dirs.insert(parent.to_path_buf());
                    }
                }
                for parent in &parent_dirs {
                    let _ = fs::remove_dir(parent); // ignore if non-empty
                }
            }
        }
    }

    // =========================================================================
    // Import from another store
    // =========================================================================

    /// Import a single collection (with all its sequences, aliases, and FHR
    /// metadata) from another store into this store.
    ///
    /// Both stores must be disk-backed with matching storage modes.
    /// The source store must have the collection loaded (call
    /// `load_collection()` or `load_all_collections()` first).
    pub fn import_collection(&mut self, source: &ReadonlyRefgetStore, digest: &str) -> Result<()> {
        // Both stores must be disk-backed with same mode
        if source.local_path.is_none() || self.local_path.is_none() || !self.persist_to_disk {
            return Err(anyhow!("import_collection requires both stores to be disk-backed"));
        }
        if source.mode != self.mode {
            return Err(anyhow!(
                "import_collection requires matching storage modes (source={:?}, dest={:?})",
                source.mode,
                self.mode,
            ));
        }

        self.import_collection_file_copy(source, digest)?;

        // Copy sequence aliases for every sequence in the imported collection
        let coll_key = digest.to_key();
        if let Some(name_map) = source.name_lookup.get(&coll_key) {
            for seq_key in name_map.values() {
                let seq_digest = key_to_digest_string(seq_key);
                for (ns, alias) in source.aliases.reverse_lookup_sequence(&seq_digest) {
                    self.add_sequence_alias(&ns, &alias, &seq_digest)?;
                }
            }
        }

        // Copy collection aliases
        for (ns, alias) in source.aliases.reverse_lookup_collection(digest) {
            self.add_collection_alias(&ns, &alias, digest)?;
        }

        // Copy FHR metadata
        if let Some(fhr) = source.get_fhr_metadata(digest) {
            self.set_fhr_metadata(digest, fhr.clone())?;
        }

        Ok(())
    }

    /// File-copy based import: copies RGSI and .seq files directly from
    /// source to destination, then registers the collection in memory.
    fn import_collection_file_copy(
        &mut self,
        source: &ReadonlyRefgetStore,
        digest: &str,
    ) -> Result<()> {
        use crate::collection::read_rgsi_file;

        // 1. Read the source RGSI file to get collection metadata
        let src_rgsi_path = source
            .collection_file_path(digest)
            .ok_or_else(|| anyhow!("Source store has no local path for collection {}", digest))?;
        let collection = read_rgsi_file(&src_rgsi_path)
            .with_context(|| format!("Failed to read source RGSI file: {}", src_rgsi_path.display()))?;

        let mut metadata = collection.metadata.clone();

        // 2. Handle ancillary digests and copy/write the RGSI file
        let dst_rgsi_path = self
            .collection_file_path(digest)
            .ok_or_else(|| anyhow!("Dest store has no local path for collection {}", digest))?;
        if let Some(parent) = dst_rgsi_path.parent() {
            create_dir_all(parent)?;
        }

        let needs_ancillary_rewrite = self.ancillary_digests
            && metadata.name_length_pairs_digest.is_none();

        if needs_ancillary_rewrite {
            // Source lacks ancillary digests but destination wants them --
            // compute them and write a new RGSI file.
            metadata.compute_ancillary_digests(&collection.sequences);
            use crate::collection::SequenceCollectionRecordExt;
            let record = SequenceCollectionRecord::Full {
                metadata: metadata.clone(),
                sequences: collection.sequences.iter()
                    .map(|s| SequenceRecord::Stub(s.metadata().clone()))
                    .collect(),
            };
            record.write_collection_rgsi(&dst_rgsi_path)?;
        } else {
            // Byte-for-byte copy of the RGSI file
            fs::copy(&src_rgsi_path, &dst_rgsi_path)
                .with_context(|| format!(
                    "Failed to copy RGSI {} -> {}",
                    src_rgsi_path.display(),
                    dst_rgsi_path.display(),
                ))?;
        }

        // 3. Copy sequence data files
        for seq_record in &collection.sequences {
            let seq_meta = seq_record.metadata();
            let seq_digest = &seq_meta.sha512t24u;

            let src_seq_path = source
                .sequence_file_path(seq_digest)
                .ok_or_else(|| anyhow!("Source has no path for sequence {}", seq_digest))?;
            let dst_seq_path = self
                .sequence_file_path(seq_digest)
                .ok_or_else(|| anyhow!("Dest has no path for sequence {}", seq_digest))?;

            // Skip if destination already has this sequence (dedup across collections)
            if dst_seq_path.exists() {
                // Still need to register in memory below
            } else {
                if let Some(parent) = dst_seq_path.parent() {
                    create_dir_all(parent)?;
                }
                fs::copy(&src_seq_path, &dst_seq_path).with_context(|| {
                    format!(
                        "Failed to copy sequence {} -> {}",
                        src_seq_path.display(),
                        dst_seq_path.display(),
                    )
                })?;
            }
        }

        // 4. Register in memory
        let coll_key = digest.to_key();

        // Build the collection record with stub sequences
        let stub_sequences: Vec<SequenceRecord> = collection
            .sequences
            .iter()
            .map(|s| SequenceRecord::Stub(s.metadata().clone()))
            .collect();

        let record = SequenceCollectionRecord::Full {
            metadata: metadata.clone(),
            sequences: stub_sequences,
        };
        self.collections.insert(coll_key, record);
        self.record(|p| p.add_collection(coll_key));

        // Register sequences and populate name_lookup
        let mut name_map = IndexMap::new();
        for seq_record in &collection.sequences {
            let seq_meta = seq_record.metadata();
            let seq_key = seq_meta.sha512t24u.to_key();

            name_map.insert(seq_meta.name.clone(), seq_key);

            // Insert stub into sequence_store (skip if already present -- dedup)
            if !self.sequence_store.contains_key(&seq_key) {
                self.sequence_store
                    .insert(seq_key, SequenceRecord::Stub(seq_meta.clone()));
                self.md5_lookup
                    .insert(seq_meta.md5.to_key(), seq_key);
                self.record(|p| p.add_sequence(seq_key));
            }
        }
        self.name_lookup.insert(coll_key, name_map);

        // 5. Update index files
        self.write_index_files()?;

        Ok(())
    }

    // =========================================================================
    // Sequence API
    // =========================================================================

    /// List all sequences in the store (metadata only, no sequence data).
    pub fn list_sequences(&self) -> Vec<SequenceMetadata> {
        let mut result: Vec<_> = self
            .sequence_store
            .values()
            .map(|rec| rec.metadata().clone())
            .collect();
        result.sort_by(|a, b| a.sha512t24u.cmp(&b.sha512t24u));
        result
    }

    /// Get metadata for a single sequence by digest (no sequence data).
    pub fn get_sequence_metadata<K: AsRef<[u8]>>(
        &self,
        seq_digest: K,
    ) -> Option<&SequenceMetadata> {
        let key = seq_digest.to_key();
        self.sequence_store.get(&key).map(|rec| rec.metadata())
    }

    /// Get a sequence by its SHA512t24u digest.
    pub fn get_sequence<K: AsRef<[u8]>>(&self, seq_digest: K) -> Result<&SequenceRecord> {
        let digest_key = seq_digest.to_key();
        let actual_key = self
            .md5_lookup
            .get(&digest_key)
            .copied()
            .unwrap_or(digest_key);
        self.sequence_store.get(&actual_key).ok_or_else(|| {
            anyhow!(
                "Sequence not found: {}",
                String::from_utf8_lossy(seq_digest.as_ref())
            )
        })
    }

    /// Clear sequence data from the store to free memory.
    ///
    /// Removes all sequence records. Metadata is preserved:
    /// collections, name lookups, MD5 lookups, aliases, and FHR
    /// metadata remain intact.
    ///
    /// For on-disk stores, data on disk is unaffected.
    pub fn clear(&mut self) {
        self.sequence_store.clear();
        if let Ok(mut cache) = self.seq_fd_cache.lock() {
            cache.entries.clear();
        }
    }

    /// Check whether a sequence's record is loaded (Full) rather
    /// than a metadata-only Stub.
    pub fn is_sequence_loaded<K: AsRef<[u8]>>(&self, seq_digest: K) -> bool {
        let digest_key = seq_digest.to_key();
        let actual_key = self
            .md5_lookup
            .get(&digest_key)
            .copied()
            .unwrap_or(digest_key);
        match self.sequence_store.get(&actual_key) {
            Some(SequenceRecord::Stub(_)) | None => false,
            Some(SequenceRecord::Full { .. }) => true,
        }
    }

    /// Get a sequence by collection digest and name.
    ///
    /// The returned record carries THIS collection's name and description for
    /// the sequence, not the first-imported label of a sequence shared across
    /// collections. Bytes (and `fai`, if the collection record lacks it) come
    /// from the global store; the clone is an `Arc` bump, not a copy of the bases.
    pub fn get_sequence_by_name<K: AsRef<[u8]>>(
        &self,
        collection_digest: K,
        sequence_name: &str,
    ) -> Result<SequenceRecord> {
        let collection_key = collection_digest.to_key();

        if !self.name_lookup.contains_key(&collection_key) {
            return Err(anyhow!(
                "Collection not loaded. Call load_collection() or load_all_collections() first."
            ));
        }

        let digest_key = self.name_lookup.get(&collection_key)
            .and_then(|name_map| name_map.get(sequence_name).cloned())
            .ok_or_else(|| anyhow!("Sequence '{}' not found in collection", sequence_name))?;

        let coll_record = self
            .collection_sequence_metadata(&collection_key)?
            .iter()
            .find(|r| r.metadata().sha512t24u.to_key() == digest_key)
            .ok_or_else(|| anyhow!("Sequence '{}' not found in collection", sequence_name))?;

        let mut meta = coll_record.metadata().clone();
        let global = self.sequence_store.get(&digest_key).ok_or_else(|| {
            anyhow!("Sequence record not found for '{}'. Call load_sequence() first.", sequence_name)
        })?;
        if meta.fai.is_none() {
            meta.fai = global.metadata().fai.clone();
        }

        Ok(match global.sequence_arc() {
            Some(seq) => SequenceRecord::Full {
                metadata: meta,
                sequence: seq,
            },
            None => SequenceRecord::Stub(meta),
        })
    }

    // =========================================================================
    // Loading methods
    // =========================================================================

    /// Ensure the sequence index (sequences.rgsi) is loaded.
    /// For remote stores this is deferred until first sequence access.
    /// Returns Ok(()) immediately if already loaded.
    pub(crate) fn ensure_sequence_index_loaded(&mut self) -> Result<()> {
        if self.sequence_index_loaded {
            return Ok(());
        }

        let seq_index_path = self.sequence_index_path.clone()
            .ok_or_else(|| anyhow!("No sequence_index_path set for deferred loading"))?;

        if !self.quiet {
            eprintln!("Downloading sequence index {}...", seq_index_path);
        }

        let data = Self::fetch_file(
            &self.local_path,
            &self.remote_source,
            &seq_index_path,
            true,
            false,
        )?;
        let data_str = String::from_utf8(data)
            .context("sequence index contains invalid UTF-8")?;

        Self::load_sequences_from_reader(self, data_str.as_bytes())?;
        self.sequence_index_loaded = true;
        Ok(())
    }

    /// Explicitly load the sequence index. For servers that want to preload
    /// all data during startup before converting to `ReadonlyRefgetStore`.
    pub fn load_sequence_index(&mut self) -> Result<()> {
        self.ensure_sequence_index_loaded()
    }

    /// Eagerly load all Stub collections to Full.
    pub fn load_all_collections(&mut self) -> Result<()> {
        let keys: Vec<DigestKey> = self.collections.keys().cloned().collect();
        for key in keys {
            self.ensure_collection_loaded(&key)?;
        }
        Ok(())
    }

    /// Eagerly load all Stub sequences to Full.
    pub fn load_all_sequences(&mut self) -> Result<()> {
        let keys: Vec<DigestKey> = self.sequence_store.keys().cloned().collect();
        for key in keys {
            self.ensure_sequence_loaded(&key)?;
        }
        Ok(())
    }

    /// Load a single collection by digest.
    pub fn load_collection(&mut self, digest: &str) -> Result<()> {
        let key = digest.to_key();
        self.ensure_collection_loaded(&key)
    }

    /// Load a single sequence by digest.
    pub fn load_sequence(&mut self, digest: &str) -> Result<()> {
        let key = digest.to_key();
        self.ensure_sequence_loaded(&key)
    }

    // =========================================================================
    // Resident overlay (&self): promote whole `.seq` files to RAM without &mut
    // =========================================================================

    /// Promote a set of sequences to the `&self` resident overlay, reading each
    /// whole `.seq` file into RAM as its raw on-disk (packed) bytes.
    ///
    /// Unlike [`load_sequence`](Self::load_sequence) / [`load_all_sequences`](
    /// Self::load_all_sequences) — which take `&mut self` and are therefore
    /// unusable once the store is wrapped in an `Arc` — this takes `&self` and
    /// stores into an `RwLock`-guarded overlay consulted by `get_substring` /
    /// `get_substrings` before the on-disk partial-read path.
    ///
    /// The loads are made cheap and predictable: digests are deduped (md5 aliases
    /// resolved), any already `Full` or already resident are skipped, and the rest
    /// are **sorted by `.seq` path** so the reads walk the sequence directory in
    /// order rather than in `HashMap` hash order (the pathology of
    /// [`load_all_sequences`](Self::load_all_sequences)). Each file is one
    /// `File::open` + `read_to_end` (a few large sequential reads), not a scatter
    /// of positioned reads.
    ///
    /// Returns the number of bytes newly loaded into the overlay by this call
    /// (already-resident/`Full` skips contribute 0), for RAM-budget accounting.
    pub fn load_resident(&self, digests: &[String]) -> Result<u64> {
        let template = self.seqdata_path_template.as_ref().ok_or_else(|| {
            anyhow!("Resident load requires a sequence data path template")
        })?;

        // Plan: resolve to canonical keys, skip Full / already-resident, dedupe.
        let mut plan: Vec<(DigestKey, String, String)> = Vec::new();
        let mut seen: HashSet<DigestKey> = HashSet::new();
        {
            let resident = self
                .resident
                .read()
                .map_err(|_| anyhow!("resident overlay lock poisoned"))?;
            for d in digests {
                let dk = d.to_key();
                let key = self.md5_lookup.get(&dk).copied().unwrap_or(dk);
                if !seen.insert(key) {
                    continue; // duplicate in this request
                }
                if resident.contains_key(&key) {
                    continue; // already resident
                }
                match self.sequence_store.get(&key) {
                    Some(rec) if rec.is_loaded() => continue, // already Full in the store
                    Some(rec) => {
                        let digest_str = rec.metadata().sha512t24u.clone();
                        let relpath = Self::expand_template(&digest_str, template)
                            .to_string_lossy()
                            .into_owned();
                        plan.push((key, digest_str, relpath));
                    }
                    None => {
                        return Err(anyhow!(
                            "Cannot load resident: sequence not found: {}",
                            d
                        ));
                    }
                }
            }
        }

        // Ordered, coalesced whole-file reads: sort by on-disk path so the
        // directory is walked in order, not in hash order.
        plan.sort_by(|a, b| a.2.cmp(&b.2));

        let mut loaded: Vec<(DigestKey, Arc<Vec<u8>>)> = Vec::with_capacity(plan.len());
        let mut total: u64 = 0;
        for (key, _digest_str, relpath) in plan {
            // Prefer a direct local read (one open + sequential read_to_end);
            // fall back to the remote fetch only when the local file is absent.
            let data: Vec<u8> = if let Some(lp) = self.local_path.as_ref() {
                let full = lp.join(&relpath);
                match File::open(&full) {
                    Ok(f) => {
                        let mut buf = Vec::new();
                        BufReader::new(f).read_to_end(&mut buf).with_context(|| {
                            format!("Failed to read seq file {}", full.display())
                        })?;
                        buf
                    }
                    Err(e) if e.kind() == std::io::ErrorKind::NotFound
                        && self.remote_source.is_some() =>
                    {
                        Self::fetch_file(
                            &self.local_path,
                            &self.remote_source,
                            &relpath,
                            self.persist_to_disk,
                            false,
                        )?
                    }
                    Err(e) => {
                        return Err(anyhow!(
                            "Failed to open seq file {}: {}",
                            full.display(),
                            e
                        ));
                    }
                }
            } else {
                Self::fetch_file(
                    &self.local_path,
                    &self.remote_source,
                    &relpath,
                    self.persist_to_disk,
                    false,
                )?
            };
            total += data.len() as u64;
            loaded.push((key, Arc::new(data)));
        }

        // Publish into the overlay under a single write lock.
        {
            let mut resident = self
                .resident
                .write()
                .map_err(|_| anyhow!("resident overlay lock poisoned"))?;
            for (key, arc) in loaded {
                resident.insert(key, arc);
            }
        }

        Ok(total)
    }

    /// Drop the given digests from the resident overlay. Subsequent queries for
    /// them fall back to the on-disk partial-read path. Unknown / non-resident
    /// digests are ignored.
    pub fn evict_resident(&self, digests: &[String]) {
        if let Ok(mut resident) = self.resident.write() {
            for d in digests {
                let dk = d.to_key();
                let key = self.md5_lookup.get(&dk).copied().unwrap_or(dk);
                resident.remove(&key);
            }
        }
    }

    /// Drop the entire resident overlay.
    pub fn evict_all_resident(&self) {
        if let Ok(mut resident) = self.resident.write() {
            resident.clear();
        }
    }

    /// Total bytes currently held in the resident overlay (sum of the packed
    /// `.seq` byte arrays). Used for RAM-budget accounting.
    pub fn resident_bytes(&self) -> u64 {
        self.resident
            .read()
            .map(|r| r.values().map(|b| b.len() as u64).sum())
            .unwrap_or(0)
    }

    /// Number of sequences currently resident.
    pub fn resident_len(&self) -> usize {
        self.resident.read().map(|r| r.len()).unwrap_or(0)
    }

    /// Estimate, from in-memory metadata only (no I/O), the additional bytes
    /// [`load_resident`](Self::load_resident) would pull into RAM for `digests`.
    /// Already-`Full` or already-resident digests, and duplicates, contribute 0.
    /// Used for RAM-budget planning before committing to a load.
    pub fn resident_estimate_bytes(&self, digests: &[String]) -> u64 {
        let resident = self.resident.read().ok();
        let mut seen: HashSet<DigestKey> = HashSet::new();
        let mut total: u64 = 0;
        for d in digests {
            let dk = d.to_key();
            let key = self.md5_lookup.get(&dk).copied().unwrap_or(dk);
            if !seen.insert(key) {
                continue;
            }
            if let Some(r) = &resident {
                if r.contains_key(&key) {
                    continue;
                }
            }
            if let Some(rec) = self.sequence_store.get(&key) {
                if rec.is_loaded() {
                    continue;
                }
                let meta = rec.metadata();
                let bytes = match self.mode {
                    StorageMode::Encoded => {
                        let bps = lookup_alphabet(&meta.alphabet).bits_per_symbol as u64;
                        (meta.length as u64 * bps + 7) / 8
                    }
                    StorageMode::Raw => meta.length as u64,
                    // Zstd: compressed size varies; use uncompressed as upper bound
                    StorageMode::Zstd => meta.length as u64,
                };
                total += bytes;
            }
        }
        total
    }

    /// Clone the resident packed bytes for `key`, if present. The `Arc` is cloned
    /// out under a brief read lock so the lock is released before the caller
    /// decodes -- decodes therefore never serialize against each other.
    fn resident_lookup(&self, key: &DigestKey) -> Option<Arc<Vec<u8>>> {
        self.resident.read().ok().and_then(|r| r.get(key).cloned())
    }

    /// Decode `[start, end)` from a whole packed `.seq` byte buffer, applying the
    /// same bounds check and per-mode decode as the resident `Full` arm of
    /// [`get_substring`](Self::get_substring). Factored out so the resident-overlay
    /// hit produces output byte-identical to a `Full` record.
    fn decode_full_span(
        &self,
        metadata: &SequenceMetadata,
        sequence: &[u8],
        start: usize,
        end: usize,
    ) -> Result<Vec<u8>> {
        if start >= metadata.length || end > metadata.length || start >= end {
            return Err(anyhow!(
                "Invalid substring range: start={}, end={}, sequence length={}",
                start,
                end,
                metadata.length
            ));
        }
        match self.mode {
            StorageMode::Encoded => {
                let alphabet = lookup_alphabet(&metadata.alphabet);
                Ok(decode_substring_from_bytes(sequence, start, end, alphabet))
            }
            StorageMode::Raw => Ok(sequence[start..end].to_vec()),
            StorageMode::Zstd => {
                let ascii = zstd::decode_all(sequence)
                    .context("zstd decompression of sequence record failed")?;
                Ok(ascii[start..end].to_vec())
            }
        }
    }

    /// Iterate over all collections with their sequences loaded.
    pub fn iter_collections(&self) -> impl Iterator<Item = crate::digest::SequenceCollection> + '_ {
        let mut digests: Vec<String> = self
            .collections
            .values()
            .map(|rec| rec.metadata().digest.clone())
            .collect();
        digests.sort();

        digests.into_iter().filter_map(move |digest| {
            self.get_collection(&digest).ok()
        })
    }

    /// Iterate over all sequences with their data loaded.
    pub fn iter_sequences(&self) -> impl Iterator<Item = SequenceRecord> + '_ {
        let mut records: Vec<_> = self.sequence_store.values().cloned().collect();
        records.sort_by(|a, b| a.metadata().sha512t24u.cmp(&b.metadata().sha512t24u));
        records.into_iter()
    }

    /// Check if a collection is fully loaded.
    pub fn is_collection_loaded<K: AsRef<[u8]>>(&self, collection_digest: K) -> bool {
        let key = collection_digest.to_key();
        self.collections
            .get(&key)
            .map_or(false, |record| record.has_sequences())
    }

    /// Returns the local path where the store is located (if any)
    pub fn local_path(&self) -> Option<&PathBuf> {
        self.local_path.as_ref()
    }

    /// Returns the remote source URL (if any)
    pub fn remote_source(&self) -> Option<&str> {
        self.remote_source.as_deref()
    }

    /// Returns the storage mode used by this store
    pub fn storage_mode(&self) -> StorageMode {
        self.mode
    }

    // =========================================================================
    // Substring retrieval
    // =========================================================================

    /// Retrieves a substring from an encoded sequence by its SHA512t24u digest.
    ///
    /// Thin `String` wrapper over [`get_substring_bytes`](Self::get_substring_bytes);
    /// see it for the actual retrieval logic.
    pub fn get_substring<K: AsRef<[u8]>>(
        &self,
        sha512_digest: K,
        start: usize,
        end: usize,
    ) -> Result<String> {
        self.get_substring_bytes(sha512_digest, start, end)
            .map(decoded_sequence_to_string)
    }

    /// Retrieves a substring from an encoded sequence by its SHA512t24u digest,
    /// as raw bytes rather than a `String`.
    pub fn get_substring_bytes<K: AsRef<[u8]>>(
        &self,
        sha512_digest: K,
        start: usize,
        end: usize,
    ) -> Result<Vec<u8>> {
        let digest_key = sha512_digest.to_key();
        let actual_key = self
            .md5_lookup
            .get(&digest_key)
            .copied()
            .unwrap_or(digest_key);

        let record = self.sequence_store.get(&actual_key).ok_or_else(|| {
            anyhow!(
                "Sequence not found: {}",
                String::from_utf8_lossy(sha512_digest.as_ref())
            )
        })?;

        // Zero-length range: a request for `[start, start)` is a well-formed
        // empty interval, so return an empty result instead of erroring. This
        // is the natural substring semantics, matches the wasm/JS
        // `RemoteRefgetStore.getSubstring` contract, and is what bulk/region
        // callers expect for an empty interval. Handling it here, before record
        // resolution, means every downstream path (resident `Full`, on-disk
        // `Stub`, remote `Stub`) agrees without each needing its own guard.
        // Inverted ranges are rejected by the bounds checks below.
        if start == end {
            return Ok(Vec::new());
        }

        let (metadata, sequence): (&SequenceMetadata, &[u8]) = match record {
            // Not resident: for a disk-backed store, read only the bytes covering
            // [start, end) directly from the `.seq` file instead of loading the
            // whole sequence into RAM. This is the random-access extract path:
            // sparse region extraction touches a tiny fraction of each sequence,
            // so a per-query partial read avoids the cost of `load_sequence`
            // pulling entire chromosomes into memory.
            SequenceRecord::Stub(meta) => {
                // Resident overlay first: if the whole `.seq` has been promoted to
                // RAM (via `load_resident`), decode the covering span from those
                // packed bytes exactly like the `Full` arm -- byte-identical
                // output, no disk read. Consulted BEFORE the on-disk partial-read
                // path so a resident hit never touches the filesystem.
                if let Some(bytes) = self.resident_lookup(&actual_key) {
                    return self.decode_full_span(meta, &bytes, start, end);
                }
                // Partial-read resolution for a non-resident sequence:
                //   local `.seq` (if present) -> remote byte-range (if configured).
                // Attempt the disk read directly rather than `path.exists()`-ing
                // first: the fd cache already amortizes opens across queries, so
                // the pre-check was a pure-overhead `statx` on the overwhelmingly
                // common case (the file exists). A missing local file still
                // falls through to the remote fallback rather than erroring --
                // detected from the open failing with `NotFound`, not from a
                // stat beforehand.
                if self.local_path.is_some() && self.seqdata_path_template.is_some() {
                    match self.get_substring_from_disk(meta, start, end) {
                        Ok(s) => return Ok(s),
                        Err(e) if is_missing_seq_file(&e) => {} // fall through to remote below
                        Err(e) => return Err(e),
                    }
                }
                if self.remote_source.is_some() {
                    return self.get_substring_from_remote(meta, start, end);
                }
                return Err(anyhow!("Sequence data not loaded (stub only)"));
            }
            SequenceRecord::Full { metadata, sequence } => (metadata, sequence.as_slice()),
        };

        if start >= metadata.length || end > metadata.length || start >= end {
            return Err(anyhow!(
                "Invalid substring range: start={}, end={}, sequence length={}",
                start,
                end,
                metadata.length
            ));
        }

        match self.mode {
            StorageMode::Encoded => {
                let alphabet = lookup_alphabet(&metadata.alphabet);
                Ok(decode_substring_from_bytes(sequence, start, end, alphabet))
            }
StorageMode::Raw => Ok(sequence[start..end].to_vec()),
            StorageMode::Zstd => {
                // `sequence` is the whole-record zstd frame; decompress it, then
                // slice the ASCII. Record bodies are small (CDC chunks), so this
                // is microseconds.
                let ascii = zstd::decode_all(sequence)
                    .context("zstd decompression of sequence record failed")?;
                Ok(ascii[start..end].to_vec())
            }
        }
    }

    /// Batch substring retrieval for many ranges of ONE sequence.
    ///
    /// Resolves the record once and validates all ranges up front, then:
    /// - **Resident `Full`**: decode/slice each range from the resident bytes.
    /// - **Disk-backed `Stub`**: partial-read each range independently via the
    ///   fd-cached [`get_substring_from_disk`](Self::get_substring_from_disk)
    ///   path (reads only the bytes covering each range; reuses the open `.seq`
    ///   handle across ranges).
    ///
    /// The main benefit over a loop of [`get_substring`](Self::get_substring) is
    /// for FFI callers (e.g. the Python binding): resolving the record once and
    /// crossing the boundary once per sequence instead of once per range.
    ///
    /// A whole-sequence "decode once, slice all" strategy was tried for
    /// wide/overlapping range sets but measured *slower* on real chromosome-scale
    /// sequences (decoding a 250 Mbp chromosome into one buffer, plus the large
    /// allocation, outweighs the avoided re-decode of scattered spans), so the
    /// partial path is used uniformly. Callers wanting resident behavior should
    /// load the sequence (`load_sequence`) first; the `Full` arm then serves it.
    ///
    /// Output strings are byte-identical to a loop of
    /// [`get_substring`](Self::get_substring).
    ///
    /// Thin `String` wrapper over
    /// [`get_substrings_bytes`](Self::get_substrings_bytes); see it for the
    /// actual retrieval logic.
    pub fn get_substrings<K: AsRef<[u8]>>(
        &self,
        sha512_digest: K,
        ranges: &[(usize, usize)],
    ) -> Result<Vec<String>> {
        self.get_substrings_bytes(sha512_digest, ranges).map(|v| {
            v.into_iter().map(decoded_sequence_to_string).collect()
        })
    }

    /// Batch substring retrieval for many ranges of ONE sequence, as raw bytes
    /// rather than `String`s. See [`get_substrings`](Self::get_substrings) for
    /// the full behavior description.
    pub fn get_substrings_bytes<K: AsRef<[u8]>>(
        &self,
        sha512_digest: K,
        ranges: &[(usize, usize)],
    ) -> Result<Vec<Vec<u8>>> {
        let digest_key = sha512_digest.to_key();
        let actual_key = self
            .md5_lookup
            .get(&digest_key)
            .copied()
            .unwrap_or(digest_key);

        let record = self.sequence_store.get(&actual_key).ok_or_else(|| {
            anyhow!(
                "Sequence not found: {}",
                String::from_utf8_lossy(sha512_digest.as_ref())
            )
        })?;

        let metadata = record.metadata();
        let seq_length = metadata.length;

        // Validate every range up front (same rule as get_substring). A
        // zero-length range (`start == end`) is a valid empty interval that
        // yields "" (see get_substring); only an inverted range (`start > end`)
        // or an out-of-bounds end is rejected. `start == seq_length` is allowed
        // only when it is also an empty range (start == end == seq_length).
        for &(start, end) in ranges {
            let empty = start == end;
            if (!empty && start >= seq_length) || end > seq_length || start > end {
                return Err(anyhow!(
                    "Invalid substring range: start={}, end={}, sequence length={}",
                    start,
                    end,
                    seq_length
                ));
            }
        }

        match record {
            SequenceRecord::Full { metadata, sequence } => {
                let seq: &[u8] = sequence.as_slice();
                let mut out = Vec::with_capacity(ranges.len());
                match self.mode {
                    StorageMode::Encoded => {
                        let alphabet = lookup_alphabet(&metadata.alphabet);
                        for &(start, end) in ranges {
                            out.push(decode_substring_from_bytes(seq, start, end, alphabet));
                        }
                    }
                    StorageMode::Raw => {
                        for &(start, end) in ranges {
                            out.push(seq[start..end].to_vec());
                        }
                    }
                    StorageMode::Zstd => {
                        // Decompress the whole record once, slice every range.
                        let ascii = zstd::decode_all(seq)
                            .context("zstd decompression of sequence record failed")?;
                        for &(start, end) in ranges {
                            out.push(ascii[start..end].to_vec());
                        }
                    }
                }
                Ok(out)
            }
            SequenceRecord::Stub(meta) => {
                // Resident overlay first: if the whole `.seq` is RAM-resident
                // (via `load_resident`), decode every range from those packed
                // bytes exactly like the `Full` arm above -- byte-identical, no
                // disk read. Consulted BEFORE the on-disk partial-read path.
                if let Some(bytes) = self.resident_lookup(&actual_key) {
                    let seq: &[u8] = bytes.as_slice();
                    let mut out = Vec::with_capacity(ranges.len());
                    match self.mode {
                        StorageMode::Encoded => {
                            let alphabet = lookup_alphabet(&meta.alphabet);
                            for &(start, end) in ranges {
                                out.push(decode_substring_from_bytes(seq, start, end, alphabet));
                            }
                        }
                        StorageMode::Raw => {
                            for &(start, end) in ranges {
                                out.push(seq[start..end].to_vec());
                            }
                        }
                        StorageMode::Zstd => {
                            let ascii = zstd::decode_all(seq)
                                .context("zstd decompression of resident record failed")?;
                            for &(start, end) in ranges {
                                out.push(ascii[start..end].to_vec());
                            }
                        }
                    }
                    return Ok(out);
                }
                // Resolve once for the whole batch: local `.seq` (if present) ->
                // remote byte-range (if configured). Whether the local file
                // exists is determined lazily below from an actual open/read
                // attempt rather than a `path.exists()` stat here -- the fd
                // cache already amortizes opens, so pre-checking existence is
                // pure overhead on the common (file present) case. A missing
                // local file still falls through to the remote fallback rather
                // than erroring.
                let has_local_path = self.local_path.is_some() && self.seqdata_path_template.is_some();
                let has_remote = self.remote_source.is_some();
                if !has_local_path && !has_remote {
                    return Err(anyhow!("Sequence data not loaded (stub only)"));
                }

                // No remote fallback configured: there is nothing to branch on,
                // so read every range straight from disk without ever stat-ing
                // for existence -- an open failure has nowhere else to fall
                // back to anyway and simply propagates. This is the common path
                // for local (non-remote) batch extraction.
                if !has_remote {
                    let mut out = Vec::with_capacity(ranges.len());
                    for &(start, end) in ranges {
                        if start == end {
                            out.push(Vec::new());
                        } else {
                            out.push(self.get_substring_from_disk(meta, start, end)?);
                        }
                    }
                    return Ok(out);
                }

                // A remote fallback exists, so we do need to know up front
                // whether the file is already cached locally in order to pick
                // between the on-disk and (possibly bulk-downloaded) remote
                // path below. This stat is paid once per batch call for this
                // sequence, not once per range.
                let local_seq_exists = has_local_path
                    && self
                        .sequence_file_path(&meta.sha512t24u)
                        .map(|p| p.exists())
                        .unwrap_or(false);

                // Bulk remote extraction: one HTTP round-trip per range is slow
                // for large batches. Past REMOTE_BULK_FETCH_THRESHOLD, download and
                // cache the whole `.seq` once (needs a local cache dir + path
                // template to write into), then read every range from the local
                // file. Single / small-batch reads fall through to pure byte-range.
                if !local_seq_exists
                    && self.local_path.is_some()
                    && self.seqdata_path_template.is_some()
                    && ranges.len() >= REMOTE_BULK_FETCH_THRESHOLD
                {
                    let relpath = self.resolve_seq_file_relpath(&meta.sha512t24u)?;
                    let relpath_str = relpath
                        .to_str()
                        .ok_or_else(|| anyhow!("Non-UTF8 sequence path"))?;
                    // persist_to_disk=true caches the file for this and future
                    // reads; force_refresh=false reuses it if already present.
                    Self::fetch_file(&self.local_path, &self.remote_source, relpath_str, true, false)?;
                    let mut out = Vec::with_capacity(ranges.len());
                    for &(start, end) in ranges {
                        // Zero-length range -> "" (see get_substring). Short-circuit
                        // before the partial-read path, which rejects start == end.
                        if start == end {
                            out.push(Vec::new());
                        } else {
                            out.push(self.get_substring_from_disk(meta, start, end)?);
                        }
                    }
                    return Ok(out);
                }

                let mut out = Vec::with_capacity(ranges.len());
                for &(start, end) in ranges {
                    // Zero-length range -> "" (see get_substring). Short-circuit
                    // before the partial-read paths, which reject start == end.
                    if start == end {
                        out.push(Vec::new());
                    } else if local_seq_exists {
                        out.push(self.get_substring_from_disk(meta, start, end)?);
                    } else {
                        out.push(self.get_substring_from_remote(meta, start, end)?);
                    }
                }
                Ok(out)
            }
        }
    }

    /// Read a substring directly from the on-disk `.seq` file, fetching only the
    /// bytes that cover `[start, end)`.
    ///
    /// `.seq` files are headerless raw byte arrays (bit-packed in Encoded mode,
    /// one ASCII byte per base in Raw mode), so byte offsets map directly to base
    /// positions. We compute the covering byte range with [`byte_range_for_bases`],
    /// read just that window with a positioned read, and decode it with
    /// [`decode_substring_from_bytes_at_offset`]. This is the partial-read path
    /// that makes random-access extraction cheap: it never materializes the whole
    /// sequence in memory.
    fn get_substring_from_disk(
        &self,
        metadata: &SequenceMetadata,
        start: usize,
        end: usize,
    ) -> Result<Vec<u8>> {
        if start >= metadata.length || end > metadata.length || start >= end {
            return Err(anyhow!(
                "Invalid substring range: start={}, end={}, sequence length={}",
                start,
                end,
                metadata.length
            ));
        }

        // Fetch (or open + cache) the shared `.seq` file handle. The critical
        // section is kept tiny: lock -> get-or-open -> clone Arc -> unlock. The
        // actual positioned read happens OUTSIDE the lock, so concurrent reads
        // are never serialized by the cache.
        let file = self.get_cached_seq_file(&metadata.sha512t24u)?;

        // Zstd: there is no base->byte mapping into a compressed frame, so read
        // the whole `.seq` (a small CDC chunk), decompress once, and slice the
        // ASCII. Whole-frame decompress of a <=256 KiB chunk is microseconds.
        if self.mode == StorageMode::Zstd {
            let file_len = file
                .metadata()
                .context("failed to stat zstd seq file")?
                .len() as usize;
            let compressed = crate::posread::read_exact_window(&file, 0, file_len)?;
            let ascii = zstd::decode_all(&compressed[..])
                .context("zstd decompression of seq file failed")?;
            return Ok(ascii[start..end].to_vec());
        }

        // Compute the covering byte window, then read it with a positioned read.
        let (byte_start, byte_end) = match self.mode {
            StorageMode::Encoded => {
                let alphabet = lookup_alphabet(&metadata.alphabet);
                byte_range_for_bases(start, end, alphabet.bits_per_symbol)
            }
            StorageMode::Raw => (start, end),
            StorageMode::Zstd => unreachable!("handled above"),
        };
        let buf = crate::posread::read_exact_window(&file, byte_start, byte_end - byte_start)?;

        let decoded: Vec<u8> = match self.mode {
            StorageMode::Encoded => {
                let alphabet = lookup_alphabet(&metadata.alphabet);
                decode_substring_from_bytes_at_offset(&buf, byte_start, start, end, alphabet)
            }
            StorageMode::Raw => buf,
            StorageMode::Zstd => unreachable!("handled above"),
        };

        Ok(decoded)
    }

    /// Return a shared handle to the `.seq` file for `digest`, opening and
    /// caching it on a miss. Bounded LRU; the LRU handle is evicted (closed)
    /// when the cache is full.
    fn get_cached_seq_file(&self, digest: &str) -> Result<Arc<File>> {
        let key = digest.to_key();

        // Fast path: hit. Hold the lock only for the tiny map op.
        {
            let mut cache = self
                .seq_fd_cache
                .lock()
                .map_err(|_| anyhow!("seq fd cache mutex poisoned"))?;
            if let Some(f) = cache.get(&key) {
                return Ok(f);
            }
        }

        // Miss: build the path and open OUTSIDE the lock (the open syscall must
        // not serialize other readers).
        let local_path = self
            .local_path
            .as_ref()
            .ok_or_else(|| anyhow!("Partial read requires a local disk-backed store"))?;
        let template = self
            .seqdata_path_template
            .as_ref()
            .ok_or_else(|| anyhow!("No sequence data path template configured"))?;
        let full_path = local_path.join(Self::expand_template(digest, template));
        let file = Arc::new(
            File::open(&full_path)
                .with_context(|| format!("Failed to open seq file {}", full_path.display()))?,
        );

        // Insert under the lock. A concurrent miss may have inserted the same
        // digest meanwhile; that is harmless (both handles read the same
        // immutable file) -- prefer the already-cached one to avoid duplicating.
        let mut cache = self
            .seq_fd_cache
            .lock()
            .map_err(|_| anyhow!("seq fd cache mutex poisoned"))?;
        if let Some(existing) = cache.get(&key) {
            return Ok(existing);
        }
        cache.insert(key, Arc::clone(&file));
        Ok(file)
    }

    /// Read a substring from a remote `.seq` file via an HTTP byte-range
    /// request, fetching only the bytes that cover `[start, end)` and persisting
    /// nothing locally.
    ///
    /// This is the remote fallback for the partial-read path (flow 1): when a
    /// sequence is a remote-only `Stub` — no resident bytes and no cached local
    /// `.seq` — [`get_substring`](Self::get_substring) /
    /// [`get_substrings`](Self::get_substrings) fall through to here instead of
    /// erroring. It mirrors
    /// [`get_substring_from_disk`](Self::get_substring_from_disk) but fetches the
    /// covering byte window over HTTP `Range:` (reusing [`open_remote_range`], the
    /// same machinery as [`stream_sequence`](Self::stream_sequence)) rather than
    /// reading from a local file. Decoded with
    /// [`decode_substring_from_bytes_at_offset`].
    ///
    /// Kept `&self` so the `Arc`-shared readonly store stays usable; this path
    /// never mutates the store and never writes to disk (use `load_sequence`,
    /// flow 3, for caching).
    fn get_substring_from_remote(
        &self,
        metadata: &SequenceMetadata,
        start: usize,
        end: usize,
    ) -> Result<Vec<u8>> {
        if start >= metadata.length || end > metadata.length || start >= end {
            return Err(anyhow!(
                "Invalid substring range: start={}, end={}, sequence length={}",
                start,
                end,
                metadata.length
            ));
        }

        // Zstd records are whole-frame compressed with no base->byte mapping, so
        // a covering byte window cannot be computed for a remote range request.
        // The novel/unplaced store this mode serves is always local, so this
        // path is unreachable in practice; fail loudly rather than fetch garbage.
        if self.mode == StorageMode::Zstd {
            return Err(anyhow!(
                "remote partial read is not supported for Zstd-mode stores; \
                 fetch and cache the whole compressed record first"
            ));
        }

        let remote = self
            .remote_source
            .as_ref()
            .ok_or_else(|| anyhow!("Remote partial read requires a remote source"))?;

        let relpath = self.resolve_seq_file_relpath(&metadata.sha512t24u)?;

        // Compute the covering byte window. `.seq` files are headerless raw byte
        // arrays, so byte offsets map directly to base positions.
        let (byte_start, byte_end) = match self.mode {
            StorageMode::Encoded => {
                let alphabet = lookup_alphabet(&metadata.alphabet);
                byte_range_for_bases(start, end, alphabet.bits_per_symbol)
            }
            StorageMode::Raw => (start, end),
            StorageMode::Zstd => unreachable!("guarded above"),
        };

        let mut reader =
            open_remote_range(remote, &relpath, byte_start as u64, byte_end as u64)?;
        let mut buf = Vec::with_capacity(byte_end - byte_start);
        reader
            .read_to_end(&mut buf)
            .context("Failed to read remote byte range")?;

        let decoded: Vec<u8> = match self.mode {
            StorageMode::Encoded => {
                let alphabet = lookup_alphabet(&metadata.alphabet);
                decode_substring_from_bytes_at_offset(&buf, byte_start, start, end, alphabet)
            }
            StorageMode::Raw => buf,
            StorageMode::Zstd => unreachable!("guarded above"),
        };

        // The Encoded decoder emits only ASCII alphabet bytes and Raw stores
        // ASCII sequence bytes, so this validation always passes; we keep it
        // checked (rather than skipping straight to bytes) because this is the
        // untrusted-remote path — bytes come from an HTTP server we don't
        // control — and the validation cost is nil against the network fetch.
        // Reuse the validated String buffer when returning bytes.
        String::from_utf8(decoded)
            .map(String::into_bytes)
            .map_err(|e| anyhow!("decoded remote sequence was not valid UTF-8: {}", e))
    }

    // =========================================================================
    // Streaming retrieval
    // =========================================================================

    /// Resolve the relative on-disk/remote path for a sequence's encoded bytes.
    fn resolve_seq_file_relpath(&self, digest: &str) -> Result<PathBuf> {
        let template = self
            .seqdata_path_template
            .as_deref()
            .unwrap_or(DEFAULT_SEQDATA_PATH_TEMPLATE);
        let relpath = Self::expand_template(digest, template);
        let relpath_str = relpath
            .to_str()
            .ok_or_else(|| anyhow!("Non-UTF8 sequence path"))?;
        Self::sanitize_relative_path(relpath_str)?;
        Ok(relpath)
    }

    /// Stream a (sub)sequence as decoded ASCII bases without loading the full
    /// sequence into memory.
    ///
    /// Opens a bounded byte window on the backing store (local file via
    /// `seek`+`take`, or remote via HTTP `Range: bytes=`), and wraps it in a
    /// [`StreamingDecoder`] when the store is in `Encoded` mode. In `Raw`
    /// mode the bounded byte source is returned directly, since bytes and
    /// bases are 1:1.
    ///
    /// Memory use is O(1) in the sequence length.
    pub fn stream_sequence<K: AsRef<[u8]>>(
        &self,
        sha512_digest: K,
        start: Option<u64>,
        end: Option<u64>,
    ) -> Result<Box<dyn Read + Send>> {
        // 1. Resolve digest (MD5 -> SHA512t24u fallback).
        let digest_key = sha512_digest.to_key();
        let actual_key = self
            .md5_lookup
            .get(&digest_key)
            .copied()
            .unwrap_or(digest_key);

        // 2. Fetch metadata only (do not load bytes).
        let record = self.sequence_store.get(&actual_key).ok_or_else(|| {
            anyhow!(
                "Sequence not found: {}",
                String::from_utf8_lossy(sha512_digest.as_ref())
            )
        })?;
        let metadata = record.metadata();

        // 3. Resolve bounds.
        let length = metadata.length as u64;
        let start = start.unwrap_or(0);
        let end = end.unwrap_or(length);
        if start > end || end > length {
            return Err(anyhow!(
                "Invalid stream range: start={}, end={}, length={}",
                start,
                end,
                length
            ));
        }

        // 3b. Zstd: no base->byte mapping into a compressed frame, so the byte-
        // window streaming machinery below does not apply. Decompress the whole
        // record (small CDC chunk) once and stream the requested ASCII slice.
        if self.mode == StorageMode::Zstd {
            let (s, e) = (start as usize, end as usize);
            let ascii: Vec<u8> = match record {
                SequenceRecord::Full { sequence, .. } => zstd::decode_all(&sequence[..])
                    .context("zstd decompression of resident record failed")?,
                SequenceRecord::Stub(meta) => {
                    let relpath = self.resolve_seq_file_relpath(&meta.sha512t24u)?;
                    let local = self.local_path.as_ref().ok_or_else(|| {
                        anyhow!("streaming a Zstd stub requires a local disk-backed store")
                    })?;
                    let full = local.join(&relpath);
                    let compressed = std::fs::read(&full)
                        .with_context(|| format!("failed to read zstd seq file: {}", full.display()))?;
                    zstd::decode_all(&compressed[..])
                        .context("zstd decompression of seq file failed")?
                }
            };
            return Ok(Box::new(std::io::Cursor::new(ascii[s..e].to_vec())));
        }

        // 4. Look up alphabet and compute bits-per-base.
        let alphabet = crate::digest::lookup_alphabet(&metadata.alphabet);
        let bps = match self.mode {
            StorageMode::Encoded => alphabet.bits_per_symbol as u64,
            StorageMode::Raw => 8,
            StorageMode::Zstd => unreachable!("handled above"),
        };

        // 5. Compute byte range + leading-skip bits.
        let start_bit = start * bps;
        let end_bit = end * bps;
        let byte_start = start_bit / 8;
        let byte_end = end_bit.div_ceil(8);
        let leading_skip_bits = (start_bit - byte_start * 8) as u8;
        let bases_to_emit = end - start;
        let byte_len = byte_end - byte_start;

        // Fast path for empty range.
        if bases_to_emit == 0 {
            return Ok(Box::new(std::io::empty()));
        }

        let sha = metadata.sha512t24u.clone();

        // 6. Build the source reader. In-memory Full records are streamed
        // directly from their encoded byte buffer. Otherwise try the
        // on-disk path (local_path / remote_source).
        if let SequenceRecord::Full { sequence, .. } = record {
            // Share ownership of the already-resident buffer instead of
            // cloning the byte range. This keeps peak allocation O(1) in
            // the sequence size.
            let shared = Arc::clone(sequence);
            let source: Box<dyn Read + Send> = Box::new(ArcSliceReader::new(
                shared,
                byte_start as usize,
                byte_end as usize,
            ));
            return match self.mode {
                StorageMode::Encoded => Ok(Box::new(StreamingDecoder::new(
                    source,
                    alphabet,
                    leading_skip_bits,
                    bases_to_emit,
                ))),
                StorageMode::Raw => {
                    debug_assert_eq!(leading_skip_bits, 0);
                    Ok(source)
                }
                StorageMode::Zstd => unreachable!("handled above"),
            };
        }

        let relpath = self.resolve_seq_file_relpath(&sha)?;

        let source: Box<dyn Read + Send> = if let Some(local) = self.local_path.as_ref() {
            let full = local.join(&relpath);
            if full.exists() {
                let mut file = File::open(&full)
                    .with_context(|| format!("Failed to open local seq file: {}", full.display()))?;
                file.seek(SeekFrom::Start(byte_start))
                    .context("Failed to seek in local seq file")?;
                let file_len = file.metadata()
                    .with_context(|| format!("Failed to stat local seq file: {}", full.display()))?.len();
                if file_len < byte_start + byte_len {
                    return Err(anyhow!(
                        "Local seq file is too short to satisfy the requested byte range \
                         [{}..{}) (file has {} bytes): {}",
                        byte_start, byte_start + byte_len,
                        file_len,
                        full.display()
                    ));
                }
                Box::new(BufReader::new(file).take(byte_len))
            } else if let Some(remote) = self.remote_source.as_ref() {
                open_remote_range(remote, &relpath, byte_start, byte_end)?
            } else {
                return Err(anyhow!(
                    "Sequence file missing locally and no remote source: {}",
                    full.display()
                ));
            }
        } else if let Some(remote) = self.remote_source.as_ref() {
            open_remote_range(remote, &relpath, byte_start, byte_end)?
        } else {
            return Err(anyhow!("No backing source configured for sequence {}", sha));
        };

        // 7. Dispatch on mode.
        match self.mode {
            StorageMode::Encoded => Ok(Box::new(StreamingDecoder::new(
                source,
                alphabet,
                leading_skip_bits,
                bases_to_emit,
            ))),
            StorageMode::Raw => {
                debug_assert_eq!(leading_skip_bits, 0);
                Ok(source)
            }
            StorageMode::Zstd => unreachable!("handled above"),
        }
    }

    // =========================================================================
    // Internal helpers
    // =========================================================================

    /// Expand a path template by substituting digest-based placeholders.
    pub(crate) fn expand_template(digest_str: &str, template: &str) -> PathBuf {
        debug_assert!(
            digest_str.len() >= 4,
            "Digest string must be at least 4 characters for template expansion, got {} chars",
            digest_str.len()
        );
        let path_str = template
            .replace("%s2", digest_str.get(0..2).unwrap_or(digest_str))
            .replace("%s4", digest_str.get(0..4).unwrap_or(digest_str))
            .replace("%s", digest_str);
        PathBuf::from(path_str)
    }

    /// Return the full filesystem path to a sequence `.seq` file for the given digest.
    ///
    /// Returns `None` if the store has no local path or no seqdata path template.
    pub fn sequence_file_path(&self, seq_digest: &str) -> Option<PathBuf> {
        let local_path = self.local_path.as_ref()?;
        let template = self.seqdata_path_template.as_ref()?;
        Some(local_path.join(Self::expand_template(seq_digest, template)))
    }

    /// Return the full filesystem path to a collection RGSI file for the given digest.
    ///
    /// Returns `None` if the store has no local path.
    pub fn collection_file_path(&self, coll_digest: &str) -> Option<PathBuf> {
        let local_path = self.local_path.as_ref()?;
        Some(local_path.join(format!("collections/{}.rgsi", coll_digest)))
    }

    /// Validate a relative path to prevent directory traversal attacks.
    pub(crate) fn sanitize_relative_path(path: &str) -> Result<()> {
        if path.starts_with('/') || path.starts_with('\\') {
            return Err(anyhow!("Absolute paths not allowed: {}", path));
        }
        if path.contains("..") {
            return Err(anyhow!("Directory traversal not allowed: {}", path));
        }
        if path.contains('\0') {
            return Err(anyhow!("Null bytes not allowed in path"));
        }
        Ok(())
    }

    /// Helper function to fetch a file from local path or remote source
    pub(crate) fn fetch_file(
        local_path: &Option<PathBuf>,
        remote_source: &Option<String>,
        relative_path: &str,
        persist_to_disk: bool,
        force_refresh: bool,
    ) -> Result<Vec<u8>> {
        Self::sanitize_relative_path(relative_path)?;

        if persist_to_disk && !force_refresh {
            if let Some(local_path) = local_path {
                let full_local_path = local_path.join(relative_path);
                if full_local_path.exists() {
                    return fs::read(&full_local_path).context(format!(
                        "Failed to read local file: {}",
                        full_local_path.display()
                    ));
                }
            }
        }

        #[cfg(feature = "http")]
        if let Some(remote_url) = remote_source {
            let full_remote_url = if remote_url.ends_with('/') {
                format!("{}{}", remote_url, relative_path)
            } else {
                format!("{}/{}", remote_url, relative_path)
            };

            let response = ureq::get(&full_remote_url)
                .call()
                .map_err(|e| anyhow!("Failed to fetch from remote: {}", e))?;

            let mut data = Vec::new();
            response
                .into_body()
                .into_reader()
                .read_to_end(&mut data)
                .context("Failed to read response body")?;

            if persist_to_disk {
                if let Some(local_path) = local_path {
                    let full_local_path = local_path.join(relative_path);

                    if let Some(parent) = full_local_path.parent() {
                        create_dir_all(parent)?;
                    }

                    fs::write(&full_local_path, &data).context(format!(
                        "Failed to cache file to: {}",
                        full_local_path.display()
                    ))?;
                }
            }

            return Ok(data);
        }

        let _ = remote_source;
        Err(anyhow!(
            "File not found locally and no remote source configured: {}",
            relative_path
        ))
    }

    /// Ensure a collection is loaded into the store
    pub(crate) fn ensure_collection_loaded(&mut self, collection_digest: &DigestKey) -> Result<()> {
        if self.name_lookup.contains_key(collection_digest) {
            return Ok(());
        }

        let needs_fetch = match self.collections.get(collection_digest) {
            Some(SequenceCollectionRecord::Stub(_)) => true,
            Some(SequenceCollectionRecord::Full { .. }) => false,
            None => true,
        };

        if needs_fetch {
            let digest_str = if let Some(SequenceCollectionRecord::Stub(meta)) =
                self.collections.get(collection_digest)
            {
                meta.digest.clone()
            } else {
                key_to_digest_string(collection_digest)
            };

            let relative_path = format!("collections/{}.rgsi", digest_str);

            if !self.quiet {
                let cached = self
                    .local_path
                    .as_ref()
                    .map(|p| p.join(&relative_path).exists())
                    .unwrap_or(false);
                let verb = if cached { "Loading" } else { "Downloading" };
                eprintln!("{} collection metadata {}...", verb, digest_str);
            }
            let _collection_data =
                Self::fetch_file(&self.local_path, &self.remote_source, &relative_path, true, false)?;

            let local_path = self
                .local_path
                .as_ref()
                .ok_or_else(|| anyhow!("No local path configured"))?;

            let collection_file_path = local_path.join(&relative_path);

            let collection = read_rgsi_file(&collection_file_path)?;

            let loaded_digest = collection.metadata.digest.to_key();
            if loaded_digest != *collection_digest {
                return Err(anyhow!(
                    "Collection digest mismatch: expected {}, got {}",
                    key_to_digest_string(collection_digest),
                    key_to_digest_string(&loaded_digest)
                ));
            }

            let mut name_map = IndexMap::new();
            for sequence_record in &collection.sequences {
                let metadata = sequence_record.metadata();
                let sha512_key = metadata.sha512t24u.to_key();
                name_map.insert(metadata.name.clone(), sha512_key);

                if !self.sequence_store.contains_key(&sha512_key) {
                    self.sequence_store
                        .insert(sha512_key, SequenceRecord::Stub(metadata.clone()));
                    let md5_key = metadata.md5.to_key();
                    self.md5_lookup.insert(md5_key, sha512_key);
                }
            }
            self.name_lookup.insert(*collection_digest, name_map);

            let record = SequenceCollectionRecord::from(collection);
            self.collections.insert(*collection_digest, record);
        } else {
            let sequences_data: Vec<(SequenceMetadata, DigestKey, DigestKey)> =
                if let Some(SequenceCollectionRecord::Full { sequences, .. }) =
                    self.collections.get(collection_digest)
                {
                    sequences
                        .iter()
                        .map(|seq| {
                            let metadata = seq.metadata().clone();
                            let sha512_key = metadata.sha512t24u.to_key();
                            let md5_key = metadata.md5.to_key();
                            (metadata, sha512_key, md5_key)
                        })
                        .collect()
                } else {
                    Vec::new()
                };

            let mut name_map = IndexMap::new();
            for (metadata, sha512_key, md5_key) in sequences_data {
                name_map.insert(metadata.name.clone(), sha512_key);

                if !self.sequence_store.contains_key(&sha512_key) {
                    self.sequence_store
                        .insert(sha512_key, SequenceRecord::Stub(metadata));
                    self.md5_lookup.insert(md5_key, sha512_key);
                }
            }
            self.name_lookup.insert(*collection_digest, name_map);
        }

        Ok(())
    }

    /// Ensure a sequence is loaded into memory
    pub(crate) fn ensure_sequence_loaded(&mut self, digest: &DigestKey) -> Result<()> {
        let record = self
            .sequence_store
            .get(digest)
            .ok_or_else(|| anyhow!("Sequence not found in store"))?;

        // Already loaded (Full or Mmap)
        if record.is_loaded() {
            return Ok(());
        }

        let digest_str = &record.metadata().sha512t24u;
        let template = self
            .seqdata_path_template
            .as_ref()
            .ok_or_else(|| anyhow!("No sequence data path template configured"))?;

        let relative_path = Self::expand_template(digest_str, template)
            .to_string_lossy()
            .into_owned();

        if !self.quiet {
            let cached = self
                .local_path
                .as_ref()
                .map(|p| p.join(&relative_path).exists())
                .unwrap_or(false);
            let verb = if cached { "Loading" } else { "Downloading" };
            eprintln!("{} sequence {}...", verb, digest_str);
        }
        let data = Self::fetch_file(
            &self.local_path,
            &self.remote_source,
            &relative_path,
            self.persist_to_disk,
            false,
        )?;

        self.sequence_store.entry(*digest).and_modify(|r| {
            r.load_data(data);
        });

        Ok(())
    }

    // =========================================================================
    // Write methods
    // =========================================================================

    /// Write the store using its configured paths.
    pub fn write(&self) -> Result<()> {
        if !self.persist_to_disk {
            return Err(anyhow!(
                "write() only works with disk-backed stores - use write_store_to_dir() instead"
            ));
        }
        self.write_index_files()
    }

    /// Write a RefgetStore object to a directory
    pub fn write_store_to_dir<P: AsRef<Path>>(
        &self,
        root_path: P,
        seqdata_path_template: Option<&str>,
    ) -> Result<()> {
        let root_path = root_path.as_ref();

        let template = seqdata_path_template
            .or(self.seqdata_path_template.as_deref())
            .unwrap_or(DEFAULT_SEQDATA_PATH_TEMPLATE);

        if !self.quiet {
            eprintln!(
                "Writing store to directory: {}; Using seqdata path template: {}",
                root_path.display(),
                template
            );
        }

        fs::create_dir_all(root_path)?;

        let sequences_dir = root_path.join("sequences");
        fs::create_dir_all(&sequences_dir)?;

        let collections_dir = root_path.join("collections");
        fs::create_dir_all(&collections_dir)?;

        for record in self.sequence_store.values() {
            match record {
                SequenceRecord::Full { metadata, .. } => {
                    let rel_path = Self::expand_template(&metadata.sha512t24u, template);
                    let full_path = root_path.join(&rel_path);
                    record.to_file(full_path)?;
                }
                SequenceRecord::Stub(_) => {
                    continue;
                }
            }
        }

        for record in self.collections.values() {
            let collection_file_path =
                root_path.join(format!("collections/{}.rgsi", record.metadata().digest));
            record.write_collection_rgsi(&collection_file_path)?;
        }

        let sequence_index_path = root_path.join("sequences.rgsi");
        self.write_sequences_rgsi(&sequence_index_path)?;

        let collection_index_path = root_path.join("collections.rgci");
        self.write_collections_rgci(&collection_index_path)?;

        let aliases_dir = root_path.join("aliases");
        self.aliases.write_to_dir(&aliases_dir)?;

        super::fhr_metadata::write_sidecars(&root_path.join("fhr"), &self.fhr_metadata)?;

        self.write_rgstore_json(root_path, template)?;

        Ok(())
    }

    /// Returns statistics about the store.
    ///
    /// The `*_in_memory` fields are a RAM-residency snapshot, not a record of
    /// what any import run did; see [`StoreStats`].
    pub fn stats(&self) -> StoreStats {
        let n_sequences = self.sequence_store.len();
        let n_sequences_in_memory = self
            .sequence_store
            .values()
            .filter(|record| record.is_loaded())
            .count();
        let n_collections = self.collections.len();
        let n_collections_in_memory = self
            .collections
            .values()
            .filter(|record| record.has_sequences())
            .count();
        let mode_str = match self.mode {
            StorageMode::Raw => "Raw",
            StorageMode::Encoded => "Encoded",
            StorageMode::Zstd => "Zstd",
        };
        StoreStats {
            n_sequences,
            n_sequences_in_memory,
            n_collections,
            n_collections_in_memory,
            storage_mode: mode_str.to_string(),
            logical_sequence_bytes: self.logical_sequence_bytes() as u64,
        }
    }

    /// List alias namespaces available on this store (from manifest).
    pub fn available_alias_namespaces(&self) -> AvailableAliases<'_> {
        AvailableAliases {
            sequences: &self.available_sequence_alias_namespaces,
            collections: &self.available_collection_alias_namespaces,
        }
    }
}

impl Display for ReadonlyRefgetStore {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let total_size = self.logical_sequence_bytes();
        let size_str = format_bytes(total_size);
        writeln!(f, "ReadonlyRefgetStore object:")?;
        writeln!(f, "  Mode: {:?}", self.mode)?;
        writeln!(f, "  Disk size: {} ({} bytes)", size_str, total_size)?;
        writeln!(f, ">Sequences (n={}):", self.sequence_store.len())?;
        for (i, (sha512_digest, sequence_record)) in self.sequence_store.iter().take(10).enumerate()
        {
            let metadata = sequence_record.metadata();
            let first_8_chars = match sequence_record {
                SequenceRecord::Stub(_) => "<stub>".to_string(),
                SequenceRecord::Full {
                    metadata,
                    sequence: seq,
                } => {
                    match self.mode {
                        StorageMode::Encoded => {
                            let alphabet = lookup_alphabet(&metadata.alphabet);
                            let decoded = decode_substring_from_bytes(
                                seq,
                                0,
                                8.min(metadata.length),
                                alphabet,
                            );
                            String::from_utf8(decoded).unwrap_or_else(|_| "???".to_string())
                        }
                        StorageMode::Raw => String::from_utf8(seq[0..8.min(seq.len())].to_vec())
                            .unwrap_or_else(|_| "???".to_string()),
                        StorageMode::Zstd => zstd::decode_all(&seq[..])
                            .ok()
                            .and_then(|ascii| {
                                String::from_utf8(ascii[0..8.min(ascii.len())].to_vec()).ok()
                            })
                            .unwrap_or_else(|| "???".to_string()),
                    }
                }
            };

            writeln!(
                f,
                "   - {}. {:02x?}, MD5: {:02x?}, Length: {}, Alphabet: {:?}, Start: {}",
                i + 1,
                key_to_digest_string(sha512_digest),
                &metadata.md5,
                &metadata.length,
                &metadata.alphabet,
                first_8_chars
            )?;
        }
        writeln!(f, ">Collections (n={:?}):", self.name_lookup.len())?;
        for (i, (digest, name_map)) in self.name_lookup.iter().enumerate() {
            let seqcol_digest_str = key_to_digest_string(digest);
            writeln!(
                f,
                "  {}. Collection Digest: {:02x?} ({} sequences)",
                i + 1,
                seqcol_digest_str,
                name_map.len()
            )?;
            for (name, sha512_digest) in name_map.iter().take(5) {
                let sha512_str = key_to_digest_string(sha512_digest);
                writeln!(f, "   - Name: {}, SHA512: {:02x?}", name, sha512_str)?;
            }
            if name_map.len() > 5 {
                writeln!(f, "   - ... and {} more", name_map.len() - 5)?;
            }
        }

        Ok(())
    }
}

// Extension traits used by collection.rs
use crate::collection::SequenceCollectionRecordExt;

#[cfg(all(test, feature = "http"))]
mod open_remote_range_tests {
    use super::*;
    use std::net::TcpListener;
    use std::sync::{Arc, atomic::{AtomicBool, Ordering}};

    /// Spin up an HTTP server that DELIBERATELY IGNORES the Range header,
    /// responding 200 OK with the full body. Models a misbehaving CDN/origin.
    /// Returns (base_url, shutdown_fn).
    fn start_range_ignoring_server(body: Vec<u8>) -> (String, impl FnOnce()) {
        use std::io::{Read as _, Write as _};

        let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
        let port = listener.local_addr().unwrap().port();
        let base_url = format!("http://127.0.0.1:{}", port);
        let stop = Arc::new(AtomicBool::new(false));
        let stop_clone = Arc::clone(&stop);

        std::thread::spawn(move || {
            listener.set_nonblocking(false).ok();
            while !stop_clone.load(Ordering::Relaxed) {
                match listener.accept() {
                    Ok((mut stream, _)) => {
                        let mut buf = [0u8; 4096];
                        let _ = stream.read(&mut buf).unwrap_or(0);
                        // Respond 200 OK with the full body, ignoring the Range header.
                        let header = format!(
                            "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                            body.len()
                        );
                        let _ = stream.write_all(header.as_bytes());
                        let _ = stream.write_all(&body);
                    }
                    Err(_) => break,
                }
            }
        });

        let shutdown = move || {
            stop.store(true, Ordering::Relaxed);
            let _ = std::net::TcpStream::connect(format!("127.0.0.1:{}", port));
        };

        (base_url, shutdown)
    }

    /// When a remote server ignores the Range header and returns 200 + full body,
    /// `open_remote_range` MUST return an error rather than silently wrapping the
    /// wrong bytes in a StreamingDecoder. Otherwise callers get silent corruption.
    #[test]
    fn test_open_remote_range_rejects_non_206_response() {
        let full_body: Vec<u8> = (0u8..=255).collect();
        let (base_url, shutdown) = start_range_ignoring_server(full_body.clone());

        // Request only a middle slice: bytes 10..20.
        let result = open_remote_range(
            &base_url,
            std::path::Path::new("seq.dat"),
            10,
            20,
        );

        shutdown();

        match result {
            Err(e) => {
                let msg = format!("{}", e);
                assert!(
                    msg.contains("Range") || msg.contains("206") || msg.contains("status"),
                    "expected a Range/206/status error, got: {}",
                    msg
                );
            }
            Ok(mut reader) => {
                use std::io::Read as _;
                let mut got = Vec::new();
                reader.read_to_end(&mut got).unwrap();
                // If we got here, the bug is live: the reader yielded bytes
                // that are NOT the requested 10..20 slice. The `.take(byte_len)`
                // in the buggy code returns the FIRST `byte_len` bytes of the
                // full body, i.e. 0..10, instead of the requested 10..20.
                assert_eq!(
                    got,
                    full_body[10..20],
                    "BUG: open_remote_range silently returned wrong bytes \
                     when server ignored the Range header. Got {:?}, expected {:?}. \
                     The function should have returned an error instead.",
                    got,
                    &full_body[10..20]
                );
            }
        }
    }
}

/// Tests for the flow-1 remote byte-range fallback: a cold `get_substring` /
/// `get_substrings` against a remote-only `Stub` must fetch just the covering
/// bytes over HTTP `Range:`, decode correctly, and persist nothing.
#[cfg(all(test, feature = "http"))]
mod remote_partial_read_tests {
    use super::*;
    use crate::digest::digest_sequence;
    use std::io::{Read as _, Write as _};
    use std::net::TcpListener;
    use std::sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    };

    /// Spin up an HTTP server that HONORS the `Range` header, replying 206 with
    /// the requested byte slice (and 200 + full body if no Range is sent). The
    /// same `body` is served for every path. Returns (base_url, shutdown_fn).
    fn start_range_honoring_server(body: Vec<u8>) -> (String, impl FnOnce()) {
        let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
        let port = listener.local_addr().unwrap().port();
        let base_url = format!("http://127.0.0.1:{}", port);
        let stop = Arc::new(AtomicBool::new(false));
        let stop_clone = Arc::clone(&stop);

        std::thread::spawn(move || {
            while !stop_clone.load(Ordering::Relaxed) {
                match listener.accept() {
                    Ok((mut stream, _)) => {
                        let mut buf = [0u8; 4096];
                        let n = stream.read(&mut buf).unwrap_or(0);
                        let req = String::from_utf8_lossy(&buf[..n]);
                        // Parse "Range: bytes=START-END" (inclusive END).
                        let range = req.lines().find_map(|l| {
                            let l = l.trim();
                            if !l.to_ascii_lowercase().starts_with("range:") {
                                return None;
                            }
                            let v = l.split('=').nth(1)?.trim();
                            let mut parts = v.split('-');
                            let s: usize = parts.next()?.trim().parse().ok()?;
                            let e: usize = parts.next()?.trim().parse().ok()?;
                            Some((s, e))
                        });
                        if let Some((s, e)) = range {
                            let s = s.min(body.len());
                            let end_excl = (e + 1).min(body.len());
                            let slice = &body[s..end_excl];
                            let header = format!(
                                "HTTP/1.1 206 Partial Content\r\nContent-Range: bytes {}-{}/{}\r\n\
                                 Content-Length: {}\r\nConnection: close\r\n\r\n",
                                s,
                                end_excl.saturating_sub(1),
                                body.len(),
                                slice.len()
                            );
                            let _ = stream.write_all(header.as_bytes());
                            let _ = stream.write_all(slice);
                        } else {
                            let header = format!(
                                "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                                body.len()
                            );
                            let _ = stream.write_all(header.as_bytes());
                            let _ = stream.write_all(&body);
                        }
                    }
                    Err(_) => break,
                }
            }
        });

        let shutdown = move || {
            stop.store(true, Ordering::Relaxed);
            let _ = std::net::TcpStream::connect(format!("127.0.0.1:{}", port));
        };

        (base_url, shutdown)
    }

    /// A remote-only store: a `Stub` whose encoded bytes live solely on the
    /// remote server. No `local_path`, so nothing can be (or is) persisted.
    fn remote_only_store(remote: &str, record: &SequenceRecord) -> ReadonlyRefgetStore {
        let mut store = ReadonlyRefgetStore::new(StorageMode::Encoded);
        store.remote_source = Some(remote.to_string());
        store.seqdata_path_template = Some(DEFAULT_SEQDATA_PATH_TEMPLATE.to_string());
        let meta = record.metadata().clone();
        store
            .sequence_store
            .insert(meta.sha512t24u.to_key(), SequenceRecord::Stub(meta));
        store
    }

    #[test]
    fn test_get_substring_cold_remote_byte_range_and_no_persist() {
        // Mixed ACGT + IUPAC (N) bases exercise the variable-bit decode path.
        let bases = b"ACGTACGTACGTTTGGCCAANNNNACGTACGTACGTACGTACGT";
        let record = digest_sequence("chrTest", bases);
        let meta = record.metadata().clone();
        let alphabet = lookup_alphabet(&meta.alphabet);
        let encoded = encode_sequence(&bases[..], alphabet);

        let (base_url, shutdown) = start_range_honoring_server(encoded.clone());
        let store = remote_only_store(&base_url, &record);

        // Cold read of an interior sub-range: must fetch via byte-range + decode.
        let got = store
            .get_substring(meta.sha512t24u.as_bytes(), 4, 12)
            .expect("cold remote get_substring should succeed");
        let expected = String::from_utf8(bases[4..12].to_vec()).unwrap();
        assert_eq!(got, expected, "remote byte-range decode mismatch");

        // Zero-length range on the REMOTE path returns "" (no HTTP request),
        // matching the resident/disk paths and the wasm/JS contract; an
        // inverted range (start > end) still errors.
        assert_eq!(
            store.get_substring(meta.sha512t24u.as_bytes(), 5, 5).unwrap(),
            "",
            "remote: zero-length range should return empty string"
        );
        assert!(
            store.get_substring(meta.sha512t24u.as_bytes(), 8, 4).is_err(),
            "remote: inverted range (start > end) must error"
        );
        let mixed = store
            .get_substrings(meta.sha512t24u.as_bytes(), &[(2, 2), (4, 8)])
            .expect("remote get_substrings with empty range should succeed");
        assert_eq!(mixed[0], "", "remote batch: empty range -> empty string");
        assert_eq!(mixed[1], String::from_utf8(bases[4..8].to_vec()).unwrap());

        // Batch read of several disjoint ranges via the same remote fallback.
        let batch = store
            .get_substrings(meta.sha512t24u.as_bytes(), &[(0, 4), (20, 24), (40, 44)])
            .expect("cold remote get_substrings should succeed");
        shutdown();
        assert_eq!(batch[0], String::from_utf8(bases[0..4].to_vec()).unwrap());
        assert_eq!(batch[1], String::from_utf8(bases[20..24].to_vec()).unwrap());
        assert_eq!(batch[2], String::from_utf8(bases[40..44].to_vec()).unwrap());

        // Persists nothing: no local path, and the record stays a Stub (never
        // promoted to a resident Full by the partial-read path).
        assert!(store.local_path.is_none());
        assert!(
            matches!(
                store.sequence_store.get(&meta.sha512t24u.to_key()).unwrap(),
                SequenceRecord::Stub(_)
            ),
            "remote partial read must not promote the record to Full (no caching)"
        );
    }

    #[test]
    fn test_get_substrings_bulk_remote_promotes_to_whole_download() {
        // 64-base sequence so we can request many disjoint ranges.
        let bases: &[u8] =
            b"ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGT";
        let record = digest_sequence("chrBulk", bases);
        let meta = record.metadata().clone();
        let alphabet = lookup_alphabet(&meta.alphabet);
        let encoded = encode_sequence(bases, alphabet);

        let (base_url, shutdown) = start_range_honoring_server(encoded.clone());

        // Remote store WITH a local cache dir, so the bulk path can promote into it.
        let cache_dir =
            std::env::temp_dir().join(format!("gtars_bulk_fetch_test_{}", meta.sha512t24u));
        let _ = std::fs::remove_dir_all(&cache_dir);
        std::fs::create_dir_all(&cache_dir).expect("create cache dir");

        let mut store = ReadonlyRefgetStore::new(StorageMode::Encoded);
        store.remote_source = Some(base_url);
        store.seqdata_path_template = Some(DEFAULT_SEQDATA_PATH_TEMPLATE.to_string());
        store.local_path = Some(cache_dir.clone());
        store
            .sequence_store
            .insert(meta.sha512t24u.to_key(), SequenceRecord::Stub(meta.clone()));

        let cached_path = cache_dir.join(ReadonlyRefgetStore::expand_template(
            &meta.sha512t24u,
            DEFAULT_SEQDATA_PATH_TEMPLATE,
        ));

        // Sub-threshold batch: served per-range by byte-range; nothing cached.
        let small: Vec<(usize, usize)> = vec![(0, 3), (8, 11), (60, 63)];
        let small_out = store
            .get_substrings(meta.sha512t24u.as_bytes(), &small)
            .expect("small remote get_substrings should succeed");
        for (i, &(s, e)) in small.iter().enumerate() {
            assert_eq!(small_out[i], String::from_utf8(bases[s..e].to_vec()).unwrap());
        }
        assert!(
            !cached_path.exists(),
            "a sub-threshold batch must not download/cache the whole .seq"
        );

        // Bulk batch (>= REMOTE_BULK_FETCH_THRESHOLD): promote to one whole
        // download, cache it, and serve every range from the local file.
        let bulk: Vec<(usize, usize)> = (0..REMOTE_BULK_FETCH_THRESHOLD)
            .map(|i| (i * 4, i * 4 + 3))
            .collect();
        assert_eq!(bulk.len(), REMOTE_BULK_FETCH_THRESHOLD);
        let bulk_out = store
            .get_substrings(meta.sha512t24u.as_bytes(), &bulk)
            .expect("bulk remote get_substrings should succeed");
        shutdown();
        for (i, &(s, e)) in bulk.iter().enumerate() {
            assert_eq!(
                bulk_out[i],
                String::from_utf8(bases[s..e].to_vec()).unwrap(),
                "bulk range {} decode mismatch",
                i
            );
        }

        // The promotion cached the WHOLE encoded `.seq` (not a partial window).
        assert!(
            cached_path.exists(),
            "bulk batch must cache the whole .seq locally"
        );
        let on_disk = std::fs::read(&cached_path).expect("read cached .seq");
        assert_eq!(on_disk, encoded, "cached file must be the full encoded sequence");

        let _ = std::fs::remove_dir_all(&cache_dir);
    }
}