mf4-rs 4.2.0

mf4-rs is a Rust library for working with ASAM MDF 4 (Measurement Data Format) files.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
//! MDF File Indexing System
//!
//! This module provides functionality to create lightweight indexes of MDF files
//! that can be serialized to JSON and used later to read specific channel data
//! without parsing the entire file structure.

use serde::{Deserialize, Serialize};
use crate::api::mdf::Mdf;
use crate::blocks::common::{DataType, BlockHeader, BlockParse};
use crate::blocks::conversion::{ConversionBlock, ConversionType};
use crate::error::MdfError;
#[cfg(feature = "http")]
use crate::fragments::{merge_ranges_bridging, FragmentStore, RecordingRangeReader};
use crate::parsing::decoder::{check_value_validity, decode_channel_value, decode_channel_value_with_validity, decode_f64_from_record, DecodedValue};
use crate::signal::{decoded_opt_to_f64, Signal};
use crate::types::{
    logical_group_members, merge_group_infos, resolve_records, search_time_window, ChannelInfo, ConversionInfo,
    GroupInfo, ReadOptions, TimeRange, Window,
};
use std::collections::HashMap;

/// Largest single read issued when coalescing adjacent data blocks (64 MiB).
const MAX_COALESCED_READ: u64 = 64 * 1024 * 1024;

/// Represents the location and metadata of data blocks in the file
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DataBlockInfo {
    /// File offset where the data block starts
    pub file_offset: u64,
    /// Size of the data block in bytes
    pub size: u64,
    /// Whether this is a compressed block (DZ)
    pub is_compressed: bool,
}

/// Channel metadata needed for decoding values
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IndexedChannel {
    /// Channel name
    pub name: Option<String>,
    /// Physical unit
    pub unit: Option<String>,
    /// Channel comment (`##TX` text, or the raw `##MD` XML)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub comment: Option<String>,
    /// Data type of the channel
    pub data_type: DataType,
    /// Byte offset within each record
    pub byte_offset: u32,
    /// Bit offset within the byte
    pub bit_offset: u8,
    /// Number of bits for this channel
    pub bit_count: u32,
    /// Channel type (0=data, 1=VLSD, 2=master, etc.)
    pub channel_type: u8,
    /// Channel flags (includes invalidation bit flags)
    pub flags: u32,
    /// Position of invalidation bit within invalidation bytes
    pub pos_invalidation_bit: u32,
    /// Conversion block for unit conversion (if any).
    ///
    /// May be `None` even when the channel *has* a conversion: index builds
    /// that read a file over the network ([`MdfIndex::from_url`] /
    /// [`MdfIndex::from_range_reader`]) do **not** fetch and resolve the
    /// conversion block up front — they only record its file offset in
    /// [`conversion_addr`](Self::conversion_addr) and resolve it lazily on the
    /// first value read. Indexes built from a local file or an in-memory buffer
    /// still resolve eagerly, so this stays populated for them. Read paths
    /// prefer a resolved conversion here and otherwise fall back to
    /// `conversion_addr`.
    pub conversion: Option<ConversionBlock>,
    /// File offset of the channel's `##CC` conversion block (0 = none).
    ///
    /// Recorded so the conversion can be resolved lazily at read time when it
    /// was not resolved during index building (the remote / range-reader
    /// path). Defaults to 0 for older serialized indexes, which carry the fully
    /// resolved [`conversion`](Self::conversion) instead.
    #[serde(default)]
    pub conversion_addr: u64,
    /// For VLSD channels: address of signal data blocks
    pub vlsd_data_address: Option<u64>,
    /// For VLSD channels: locations of the ##SD fragments in chain order.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub vlsd_data_blocks: Vec<DataBlockInfo>,
}

impl IndexedChannel {
    /// `true` if this is the group's master channel (usually time): a
    /// regular (`cn_type` 2) or virtual (`cn_type` 3) master.
    pub fn is_master(&self) -> bool {
        self.channel_type == 2 || self.channel_type == 3
    }

    /// `true` for a virtual channel (`cn_type` 3 master or 6 data): it stores
    /// no bytes, its raw value is the record index.
    pub fn is_virtual(&self) -> bool {
        self.channel_type == 3 || self.channel_type == 6
    }

    /// This channel's metadata as a plain [`ChannelInfo`].
    pub fn info(&self) -> ChannelInfo {
        ChannelInfo {
            name: self.name.clone(),
            unit: self.unit.clone(),
            comment: self.comment.clone(),
            data_type: self.data_type.name().to_string(),
            bit_count: self.bit_count,
            is_master: self.is_master(),
            is_vlsd: self.is_vlsd(),
            has_conversion: self.conversion.is_some() || self.conversion_addr != 0,
        }
    }

    /// `true` if this is a variable-length (VLSD) channel.
    pub fn is_vlsd(&self) -> bool {
        self.channel_type == 1 && self.vlsd_data_address.is_some()
    }

    /// Create a temporary `ChannelBlock` for use with the decoder functions.
    /// This should be called once and reused across all records.
    fn to_channel_block(&self) -> crate::blocks::channel_block::ChannelBlock {
        Self::build_channel_block(
            self.channel_type,
            self.data_type.clone(),
            self.bit_offset,
            self.byte_offset,
            self.bit_count,
            self.flags,
            self.pos_invalidation_bit,
            self.name.clone(),
            self.conversion.clone(),
        )
    }

    /// Create a lightweight `ChannelBlock` for decode-only use (f64 fast path).
    /// Skips cloning the name and conversion since the decoder doesn't use them.
    fn to_decode_only_channel_block(&self) -> crate::blocks::channel_block::ChannelBlock {
        Self::build_channel_block(
            self.channel_type,
            self.data_type.clone(),
            self.bit_offset,
            self.byte_offset,
            self.bit_count,
            self.flags,
            self.pos_invalidation_bit,
            None,
            None,
        )
    }

    fn build_channel_block(
        channel_type: u8,
        data_type: DataType,
        bit_offset: u8,
        byte_offset: u32,
        bit_count: u32,
        flags: u32,
        pos_invalidation_bit: u32,
        name: Option<String>,
        conversion: Option<ConversionBlock>,
    ) -> crate::blocks::channel_block::ChannelBlock {
        crate::blocks::channel_block::ChannelBlock {
            header: crate::blocks::common::BlockHeader {
                id: "##CN".to_string(),
                reserved0: 0,
                block_len: 160,
                links_nr: 8,
            },
            next_ch_addr: 0,
            component_addr: 0,
            name_addr: 0,
            source_addr: 0,
            conversion_addr: 0,
            data: 0,
            unit_addr: 0,
            comment_addr: 0,
            channel_type,
            sync_type: 0,
            data_type,
            bit_offset,
            byte_offset,
            bit_count,
            flags,
            pos_invalidation_bit,
            precision: 0,
            reserved1: 0,
            attachment_nr: 0,
            min_raw_value: 0.0,
            max_raw_value: 0.0,
            lower_limit: 0.0,
            upper_limit: 0.0,
            lower_ext_limit: 0.0,
            upper_ext_limit: 0.0,
            name,
            conversion,
        }
    }
}

/// Channel group metadata and layout information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IndexedChannelGroup {
    /// Group name
    pub name: Option<String>,
    /// Comment
    pub comment: Option<String>,
    /// Size of record ID in bytes
    pub record_id_len: u8,
    /// Total size of each record in bytes (excluding record ID and invalidation bytes)
    pub record_size: u32,
    /// Number of invalidation bytes per record
    pub invalidation_bytes: u32,
    /// Number of records in this group
    pub record_count: u64,
    /// Channels in this group
    pub channels: Vec<IndexedChannel>,
    /// Data block locations for this channel group
    pub data_blocks: Vec<DataBlockInfo>,
    /// Index (into [`MdfIndex::channel_groups`]) of the group holding this
    /// group's master channel when it is stored *remotely* — the MDF 4.2
    /// column-oriented layout, where each signal has its own channel group and
    /// points at a shared time group via `cg_cg_master`. `None` when the master
    /// is local (or there is none).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub master_group: Option<usize>,
}

impl IndexedChannelGroup {
    /// Find a channel in this group by name (first match).
    pub fn channel(&self, name: &str) -> Option<&IndexedChannel> {
        self.channels
            .iter()
            .find(|c| c.name.as_deref() == Some(name))
    }

    /// Names of every named channel in this group, in record order.
    pub fn channel_names(&self) -> Vec<&str> {
        self.channels
            .iter()
            .filter_map(|c| c.name.as_deref())
            .collect()
    }

    /// The group's master channel (channel type 2), if any.
    pub fn master_channel(&self) -> Option<&IndexedChannel> {
        self.channels.iter().find(|c| c.is_master())
    }
}

/// Where an [`MdfIndex`] reads sample data from when asked to.
///
/// The source is *not* serialized with the index — after [`MdfIndex::load`]
/// re-attach one with [`MdfIndex::set_source`]. Building an
/// index never reads sample data; the actual byte-range reads happen lazily on
/// [`MdfIndex::read`].
#[derive(Debug, Clone)]
pub enum Source {
    /// A local file path, read via memory map.
    File(String),
    /// An HTTP/S3 URL, read via range requests.
    #[cfg(feature = "http")]
    Url(String),
}

impl Source {
    /// The file path or URL as a string.
    pub fn as_str(&self) -> &str {
        match self {
            Source::File(p) => p,
            #[cfg(feature = "http")]
            Source::Url(u) => u,
        }
    }
}

/// A string is a [`Source`]: `http://` / `https://` URLs become
/// [`Source::Url`] (with the `http` feature), anything else a file path.
/// The URL scheme of `value` (`"https"` for `https://…`), if it has one.
/// A Windows drive path (`C:\\…`, `C:/…`) has none.
fn url_scheme(value: &str) -> Option<&str> {
    let (scheme, _) = value.split_once("://")?;
    let mut chars = scheme.chars();
    let valid = chars.next().is_some_and(|c| c.is_ascii_alphabetic())
        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
    (valid && scheme.len() > 1).then_some(scheme)
}

/// True for an `http://` / `https://` URL (scheme matched case-insensitively).
fn is_http_url(value: &str) -> bool {
    url_scheme(value).is_some_and(|s| s.eq_ignore_ascii_case("http") || s.eq_ignore_ascii_case("https"))
}

impl From<&str> for Source {
    fn from(value: &str) -> Self {
        #[cfg(feature = "http")]
        if is_http_url(value) {
            return Source::Url(value.to_string());
        }
        Source::File(value.to_string())
    }
}

impl From<String> for Source {
    fn from(value: String) -> Self {
        Source::from(value.as_str())
    }
}

/// Ranges recorded in one batched round that lie at most this far apart are
/// fetched as one request (mirrors `WINDOW_BRIDGE_BYTES` in the TS driver).
#[cfg(feature = "http")]
const BATCH_BRIDGE_BYTES: u64 = 4 * 1024;

/// Upper bound on the rounds of [`MdfIndex::batched_reads`].
#[cfg(feature = "http")]
const MAX_BATCH_ROUNDS: usize = 1_000;

/// Batched reads fetch a range larger than this as several concurrent
/// requests of at most this size (8 MiB): one connection to an object store
/// is far slower than several in parallel.
#[cfg(feature = "http")]
const PARALLEL_CHUNK_BYTES: u64 = 8 * 1024 * 1024;

/// Whole-channel URL reads fetch the batch at once (concurrently) only while
/// it needs at most this many bytes (256 MiB); larger reads stream one data
/// section at a time.
#[cfg(feature = "http")]
const BATCH_MEMORY_LIMIT: u64 = 256 * 1024 * 1024;

/// URL reader for streamed whole-channel reads: serves bytes already fetched
/// (deferred conversion blocks) from `store`, and fetches a range larger than
/// [`PARALLEL_CHUNK_BYTES`] as concurrent chunks.
#[cfg(feature = "http")]
struct ChunkedUrlReader {
    http: HttpRangeReader,
    store: FragmentStore,
}

#[cfg(feature = "http")]
impl ByteRangeReader for ChunkedUrlReader {
    type Error = MdfError;

    fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, MdfError> {
        if let crate::fragments::Coverage::Full(bytes) = self.store.assemble(offset, length)? {
            return Ok(bytes);
        }
        if length <= PARALLEL_CHUNK_BYTES {
            return self.http.read_range(offset, length);
        }
        let parts = self.http.read_ranges_parallel(&split_spans(vec![(offset, length)], PARALLEL_CHUNK_BYTES))?;
        let mut out = Vec::with_capacity(usize::try_from(length).unwrap_or(0));
        for part in parts {
            out.extend_from_slice(&part);
        }
        Ok(out)
    }
}

/// Split every `(offset, length)` span longer than `chunk` into consecutive
/// pieces of at most `chunk` bytes.
#[cfg(feature = "http")]
fn split_spans(spans: Vec<(u64, u64)>, chunk: u64) -> Vec<(u64, u64)> {
    let mut out = Vec::with_capacity(spans.len());
    for (offset, length) in spans {
        let mut at = 0;
        while at < length {
            let take = chunk.min(length - at);
            out.push((offset + at, take));
            at += take;
        }
    }
    out
}

/// Reader over an index's attached [`Source`], for windowed reads.
enum SourceReader {
    #[cfg(not(target_arch = "wasm32"))]
    File(MmapRangeReader),
    #[cfg(feature = "http")]
    Url(CachingRangeReader<HttpRangeReader>),
}

impl ByteRangeReader for SourceReader {
    type Error = MdfError;

    #[allow(unused_variables)]
    fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, MdfError> {
        match *self {
            #[cfg(not(target_arch = "wasm32"))]
            SourceReader::File(ref mut r) => r.read_range(offset, length),
            #[cfg(feature = "http")]
            SourceReader::Url(ref mut r) => r.read_range(offset, length),
        }
    }
}

/// Record windows resolved during one `read_many`, keyed by the time axis
/// searched (`None` for a record window) and the group's record count.
type WindowCache = HashMap<(Option<(usize, usize)>, u64), (u64, u64)>;

/// Time axes decoded during one `read_many`, keyed by the master's
/// `(group, channel)` and the record window `(start, count)`.
type AxisCache = HashMap<(usize, usize, u64, u64), Vec<f64>>;

/// Complete MDF file index
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MdfIndex {
    /// File size for validation
    pub file_size: u64,
    /// Start time of the measurement in nanoseconds since epoch (from MDF header)
    /// None if the start time is not set (0) in the file
    pub start_time_ns: Option<u64>,
    /// Channel groups in the file
    pub channel_groups: Vec<IndexedChannelGroup>,
    /// The data source for lazy value reads. Populated by `from_file` /
    /// `from_url`, re-attachable after load via `set_source`. Never
    /// serialized — an index file is portable; the source is environment-local.
    #[serde(skip)]
    pub source: Option<Source>,
}

/// Trait for reading byte ranges from different sources (files, HTTP, etc.)
pub trait ByteRangeReader {
    type Error;

    /// Read bytes from the specified range
    /// Returns the requested bytes or an error
    fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, Self::Error>;

    /// Read an *optional* metadata range that the walk can proceed without.
    ///
    /// Behaves exactly like [`read_range`](Self::read_range) by default, so
    /// on-demand readers (file, HTTP) are unaffected. Incremental readers that
    /// *gather* the ranges they still need — rather than fetching one at a time
    /// — override this to record a gap and return `Ok(None)` instead of
    /// aborting. That lets a single metadata walk collect **every** still-missing
    /// leaf range (channel names, units, group comments) at once, turning an
    /// O(N²) fetch-restart loop into a handful of passes. Returning `None` means
    /// "these bytes are not available yet"; the caller treats the value as
    /// absent for this pass. Structural reads (block headers whose bytes yield
    /// the next link address) must keep using [`read_range`](Self::read_range) —
    /// the walk cannot continue past those without the real bytes.
    fn read_range_optional(
        &mut self,
        offset: u64,
        length: u64,
    ) -> Result<Option<Vec<u8>>, Self::Error> {
        self.read_range(offset, length).map(Some)
    }

    /// True when this reader is a gap-discovery probe: it cannot serve every
    /// range and records the misses instead of returning data. Metadata walks
    /// may then skip an unreadable subtree and keep discovering gaps elsewhere
    /// rather than aborting on the first miss.
    ///
    /// A walk driven by a probing reader produces a **partial** result: callers
    /// MUST discard it and retry once the recorded ranges have been supplied.
    fn is_probing(&self) -> bool {
        false
    }
}

/// Local file reader implementation.
///
/// Not available on `wasm32-unknown-unknown`; implement [`ByteRangeReader`] over
/// a `Cursor<Vec<u8>>` or a JS `Blob`-backed reader instead.
#[cfg(not(target_arch = "wasm32"))]
pub struct FileRangeReader {
    file: std::fs::File,
}

#[cfg(not(target_arch = "wasm32"))]
impl FileRangeReader {
    pub fn new(file_path: &str) -> Result<Self, MdfError> {
        let file = std::fs::File::open(file_path)
            .map_err(MdfError::IOError)?;
        Ok(Self { file })
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl ByteRangeReader for FileRangeReader {
    type Error = MdfError;

    fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, Self::Error> {
        use std::io::{Read, Seek, SeekFrom};

        // Validate against the real file length *before* allocating: a forged
        // or stale index could otherwise request an absurd length and abort
        // the process on allocation failure.
        let file_len = self.file.metadata().map_err(MdfError::IOError)?.len();
        match offset.checked_add(length) {
            Some(end) if end <= file_len => {}
            _ => {
                return Err(MdfError::TooShortBuffer {
                    actual: file_len as usize,
                    expected: offset.saturating_add(length) as usize,
                    file: file!(),
                    line: line!(),
                });
            }
        }

        self.file.seek(SeekFrom::Start(offset))
            .map_err(MdfError::IOError)?;

        let mut buffer = vec![0u8; length as usize];
        self.file.read_exact(&mut buffer)
            .map_err(MdfError::IOError)?;

        Ok(buffer)
    }
}

/// Memory-mapped file reader implementation.
///
/// Not available on `wasm32-unknown-unknown`.
#[cfg(not(target_arch = "wasm32"))]
pub struct MmapRangeReader {
    mmap: memmap2::Mmap,
}

#[cfg(not(target_arch = "wasm32"))]
impl MmapRangeReader {
    pub fn new(file_path: &str) -> Result<Self, MdfError> {
        let file = std::fs::File::open(file_path).map_err(MdfError::IOError)?;
        let mmap = unsafe { memmap2::Mmap::map(&file) }.map_err(MdfError::IOError)?;
        Ok(Self { mmap })
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl ByteRangeReader for MmapRangeReader {
    type Error = MdfError;

    fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, Self::Error> {
        // Checked arithmetic: a forged offset/length must error, not wrap.
        let end = match offset
            .checked_add(length)
            .and_then(|e| usize::try_from(e).ok())
        {
            Some(end) if end <= self.mmap.len() => end,
            _ => {
                return Err(MdfError::TooShortBuffer {
                    actual: self.mmap.len(),
                    expected: offset.saturating_add(length).min(usize::MAX as u64) as usize,
                    file: file!(),
                    line: line!(),
                });
            }
        };
        Ok(self.mmap[offset as usize..end].to_vec())
    }
}

/// In-memory byte-slice reader — available on all targets including WASM.
///
/// Wraps an owned `Vec<u8>` and satisfies [`ByteRangeReader`] by slicing
/// directly into it.  Useful when the entire file has already been loaded
/// into memory (e.g. via `Blob.arrayBuffer()` in a browser Worker).
pub struct SliceRangeReader {
    data: Vec<u8>,
}

impl SliceRangeReader {
    pub fn new(data: Vec<u8>) -> Self {
        Self { data }
    }
}

impl ByteRangeReader for SliceRangeReader {
    type Error = MdfError;

    fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, Self::Error> {
        // Checked arithmetic: a forged offset/length must error, not wrap.
        let end = match offset
            .checked_add(length)
            .and_then(|e| usize::try_from(e).ok())
        {
            Some(end) if end <= self.data.len() => end,
            _ => {
                return Err(MdfError::TooShortBuffer {
                    actual: self.data.len(),
                    expected: offset.saturating_add(length).min(usize::MAX as u64) as usize,
                    file: file!(),
                    line: line!(),
                });
            }
        };
        Ok(self.data[offset as usize..end].to_vec())
    }
}

/// Borrowing counterpart to [`SliceRangeReader`] — a [`ByteRangeReader`] over a
/// borrowed `&[u8]` (e.g. a memory map), so the mmap-based index paths can
/// reuse the generic reader logic without cloning the whole file into a `Vec`.
struct BorrowedSliceReader<'a> {
    data: &'a [u8],
}

impl<'a> ByteRangeReader for BorrowedSliceReader<'a> {
    type Error = MdfError;

    fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, Self::Error> {
        // Checked arithmetic: a forged offset/length must error, not wrap.
        let end = match offset
            .checked_add(length)
            .and_then(|e| usize::try_from(e).ok())
        {
            Some(end) if end <= self.data.len() => end,
            _ => {
                return Err(MdfError::TooShortBuffer {
                    actual: self.data.len(),
                    expected: offset.saturating_add(length).min(usize::MAX as u64) as usize,
                    file: file!(),
                    line: line!(),
                });
            }
        };
        Ok(self.data[offset as usize..end].to_vec())
    }
}

/// Caching wrapper around any [`ByteRangeReader`].
///
/// During the metadata phase of building an [`MdfIndex`], the parser issues
/// many small reads (block headers, channel metadata, text blocks). Without
/// caching, each becomes a round-trip on a remote backend. `CachingRangeReader`
/// fetches in larger aligned chunks (default 1 MiB) and serves overlapping
/// reads from memory, collapsing hundreds of small reads into a handful of
/// underlying requests.
///
/// For value reads — which span large slices of data blocks — call
/// [`CachingRangeReader::set_bypass`] to forward each read directly to the
/// underlying reader without populating the cache.
pub struct CachingRangeReader<R: ByteRangeReader<Error = MdfError>> {
    inner: R,
    chunks: std::collections::BTreeMap<u64, Vec<u8>>,
    chunk_size: u64,
    bypass: bool,
    underlying_requests: u64,
    cache_hits: u64,
    /// Total size of the underlying resource, once learned. Whole-chunk
    /// fetches are clamped against it so strict inner readers (which error on
    /// reads past EOF) still work when the resource size is not a multiple of
    /// `chunk_size`.
    known_size: Option<u64>,
}

impl<R: ByteRangeReader<Error = MdfError>> CachingRangeReader<R> {
    /// The wrapped reader.
    #[allow(dead_code)]
    pub(crate) fn inner_mut(&mut self) -> &mut R {
        &mut self.inner
    }

    /// The wrapped reader and every cached chunk as `(offset, bytes)`.
    #[allow(dead_code)]
    pub(crate) fn into_parts(self) -> (R, Vec<(u64, Vec<u8>)>) {
        let chunk_size = self.chunk_size;
        let chunks = self
            .chunks
            .into_iter()
            .filter(|(_, bytes)| !bytes.is_empty())
            .map(|(i, bytes)| (i * chunk_size, bytes))
            .collect();
        (self.inner, chunks)
    }

    /// Wrap a reader with the default chunk size (1 MiB).
    pub fn new(inner: R) -> Self {
        Self::with_chunk_size(inner, 1 << 20)
    }

    /// Wrap a reader with a custom chunk size in bytes.
    pub fn with_chunk_size(inner: R, chunk_size: u64) -> Self {
        assert!(chunk_size > 0, "chunk_size must be > 0");
        Self {
            inner,
            chunks: std::collections::BTreeMap::new(),
            chunk_size,
            bypass: false,
            underlying_requests: 0,
            cache_hits: 0,
            known_size: None,
        }
    }

    /// Tell the cache the total size of the underlying resource (e.g. from an
    /// HTTP size probe), so the final chunk is requested at its true length
    /// instead of failing short and being re-requested.
    pub fn set_known_size(&mut self, size: u64) {
        self.known_size = Some(size);
    }

    /// When set, reads are served from already-cached chunks when fully
    /// covered, and otherwise forward directly to the underlying reader without
    /// populating the cache. Use during value-read phases so large data-block
    /// fetches do not pollute the cache, while small metadata reads that were
    /// already pulled in during the index walk (such as a conversion block
    /// resolved lazily on first read) remain free.
    pub fn set_bypass(&mut self, bypass: bool) {
        self.bypass = bypass;
    }

    /// Number of read calls forwarded to the underlying reader.
    pub fn underlying_requests(&self) -> u64 {
        self.underlying_requests
    }

    /// Number of read calls fully satisfied from cache.
    pub fn cache_hits(&self) -> u64 {
        self.cache_hits
    }

    /// Pre-fetch a contiguous range into the cache.
    pub fn prefetch(&mut self, offset: u64, length: u64) -> Result<(), MdfError> {
        if length == 0 {
            return Ok(());
        }
        self.read_range(offset, length).map(|_| ())
    }

    /// Try to satisfy a read entirely from chunks already in the cache,
    /// without issuing any underlying request. Returns `None` if any covering
    /// chunk is absent or too short (e.g. an EOF-clamped tail), leaving the
    /// caller to fetch. Used in bypass mode so small reads that land in
    /// already-fetched metadata chunks (e.g. a lazily-resolved conversion
    /// block) stay free, while large uncached data reads still forward straight
    /// through.
    fn try_serve_from_cache(&self, offset: u64, length: u64) -> Option<Vec<u8>> {
        let first = offset / self.chunk_size;
        let last = (offset + length - 1) / self.chunk_size;
        let read_end = offset + length;
        for i in first..=last {
            let chunk = self.chunks.get(&i)?;
            let chunk_start = i * self.chunk_size;
            let cached_end = chunk_start + chunk.len() as u64;
            let needed_end = read_end.min(chunk_start + self.chunk_size);
            if cached_end < needed_end {
                return None;
            }
        }
        let mut out = Vec::with_capacity(length.min(1 << 24) as usize);
        let mut remaining = length as usize;
        let mut cursor = offset;
        while remaining > 0 {
            let chunk_index = cursor / self.chunk_size;
            let chunk_offset = (cursor % self.chunk_size) as usize;
            let chunk = self.chunks.get(&chunk_index)?;
            if chunk_offset >= chunk.len() {
                return None;
            }
            let take = std::cmp::min(remaining, chunk.len() - chunk_offset);
            out.extend_from_slice(&chunk[chunk_offset..chunk_offset + take]);
            cursor += take as u64;
            remaining -= take;
            if take == 0 {
                return None;
            }
        }
        Some(out)
    }

    fn ensure_chunks(&mut self, first: u64, last: u64, requested_end: u64) -> Result<(), MdfError> {
        // Walk [first..=last], find each contiguous run of missing chunks,
        // issue one read per run.
        let mut idx = first;
        while idx <= last {
            if self.chunks.contains_key(&idx) {
                idx += 1;
                continue;
            }
            let run_start = idx;
            while idx <= last && !self.chunks.contains_key(&idx) {
                idx += 1;
            }
            let run_end = idx - 1;
            let read_offset = run_start * self.chunk_size;
            let mut read_len = (run_end - run_start + 1) * self.chunk_size;

            // Clamp against the known end of the resource: strict inner
            // readers reject reads past EOF, and the final chunk is allowed
            // to be short.
            if let Some(size) = self.known_size {
                if read_offset >= size {
                    for slot in run_start..=run_end {
                        self.chunks.insert(slot, Vec::new());
                    }
                    continue;
                }
                read_len = read_len.min(size - read_offset);
            }

            let bytes = match self.inner.read_range(read_offset, read_len) {
                Ok(b) => {
                    self.underlying_requests += 1;
                    b
                }
                Err(e) => {
                    self.underlying_requests += 1;
                    // The whole-chunk read may extend past EOF (the resource
                    // size need not be a multiple of chunk_size). Learn the
                    // true end from the error when it reports one, otherwise
                    // fall back to the span the caller actually asked for,
                    // and retry clamped.
                    let clamp_to = match &e {
                        MdfError::TooShortBuffer { actual, .. }
                            if (*actual as u64) > read_offset
                                && (*actual as u64) < read_offset + read_len =>
                        {
                            self.known_size = Some(*actual as u64);
                            *actual as u64
                        }
                        _ if requested_end > read_offset
                            && requested_end < read_offset + read_len =>
                        {
                            requested_end
                        }
                        _ => return Err(e),
                    };
                    let b = self.inner.read_range(read_offset, clamp_to - read_offset)?;
                    self.underlying_requests += 1;
                    b
                }
            };

            // Split the response into chunk-sized pieces. The last chunk
            // may be short if the file ends partway through it.
            for (i, slot) in (run_start..=run_end).enumerate() {
                let start = i * self.chunk_size as usize;
                if start >= bytes.len() {
                    self.chunks.insert(slot, Vec::new());
                    continue;
                }
                let end = std::cmp::min(start + self.chunk_size as usize, bytes.len());
                self.chunks.insert(slot, bytes[start..end].to_vec());
            }
        }
        Ok(())
    }
}

impl<R: ByteRangeReader<Error = MdfError>> ByteRangeReader for CachingRangeReader<R> {
    type Error = MdfError;

    fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, MdfError> {
        if length == 0 {
            return Ok(Vec::new());
        }
        if self.bypass {
            // Serve from already-cached chunks when possible (e.g. a small
            // conversion block lazily resolved at read time that lands in a
            // metadata chunk fetched during the index walk); otherwise forward
            // the (typically large data-block) read straight through.
            if let Some(bytes) = self.try_serve_from_cache(offset, length) {
                self.cache_hits += 1;
                return Ok(bytes);
            }
            let bytes = self.inner.read_range(offset, length)?;
            self.underlying_requests += 1;
            return Ok(bytes);
        }

        let first = offset / self.chunk_size;
        let last = (offset + length - 1) / self.chunk_size;
        let read_end = offset + length;

        // A chunk cached from an earlier EOF-clamped read may be shorter than
        // the span this read needs from it. Drop such chunks so ensure_chunks
        // refetches them (clamped to this read's span or the known size).
        for i in first..=last {
            if let Some(chunk) = self.chunks.get(&i) {
                let chunk_start = i * self.chunk_size;
                let cached_end = chunk_start + chunk.len() as u64;
                let mut needed_end = read_end.min(chunk_start + self.chunk_size);
                if let Some(size) = self.known_size {
                    needed_end = needed_end.min(size);
                }
                if cached_end < needed_end {
                    self.chunks.remove(&i);
                }
            }
        }

        // Track cache-hit metric only when no underlying read is required.
        let need_fetch = (first..=last).any(|i| !self.chunks.contains_key(&i));
        self.ensure_chunks(first, last, read_end)?;
        if !need_fetch {
            self.cache_hits += 1;
        }

        // Capacity capped so a forged huge length cannot abort on allocation.
        let mut out = Vec::with_capacity(length.min(1 << 24) as usize);
        let mut remaining = length as usize;
        let mut cursor = offset;
        while remaining > 0 {
            let chunk_index = cursor / self.chunk_size;
            let chunk_offset = (cursor % self.chunk_size) as usize;
            let chunk = self.chunks.get(&chunk_index).expect("chunk fetched above");
            if chunk_offset >= chunk.len() {
                return Err(MdfError::TooShortBuffer {
                    actual: chunk.len(),
                    expected: chunk_offset + 1,
                    file: file!(),
                    line: line!(),
                });
            }
            let take = std::cmp::min(remaining, chunk.len() - chunk_offset);
            out.extend_from_slice(&chunk[chunk_offset..chunk_offset + take]);
            cursor += take as u64;
            remaining -= take;
            if take == 0 {
                break;
            }
        }

        if out.len() != length as usize {
            return Err(MdfError::TooShortBuffer {
                actual: out.len(),
                expected: length as usize,
                file: file!(),
                line: line!(),
            });
        }

        Ok(out)
    }
}

/// HTTP range-request reader using the synchronous [`ureq`] client.
///
/// Each [`ByteRangeReader::read_range`] call issues a single
/// `Range: bytes=A-B` GET request and expects an HTTP 206 response. The
/// underlying `ureq::Agent` is reused across calls so TCP keep-alive applies.
///
/// Wrap this in [`CachingRangeReader`] when building an index, otherwise the
/// many small metadata reads will each become a separate round-trip.
#[cfg(feature = "http")]
pub struct HttpRangeReader {
    agent: ureq::Agent,
    url: String,
    request_count: u64,
    /// Size the resource must have (the size an index was built from). Every
    /// ranged response reports the resource's total size in `Content-Range`;
    /// a different total means the file behind the URL was replaced, and is
    /// refused instead of decoding bytes at offsets meant for another file.
    expected_size: Option<u64>,
}

#[cfg(feature = "http")]
impl HttpRangeReader {
    pub fn new(url: impl Into<String>) -> Result<Self, MdfError> {
        Ok(Self {
            agent: shared_http_agent()?,
            url: url.into(),
            request_count: 0,
            expected_size: None,
        })
    }

    /// Require every response to report a resource of `size` bytes (see
    /// [`MdfError::InvalidArgument`] for the mismatch error).
    pub fn expect_size(&mut self, size: u64) {
        self.expected_size = Some(size);
    }

    /// Fetch several byte ranges concurrently (up to
    /// [`MAX_PARALLEL_REQUESTS`] at a time) and return their bytes in order.
    ///
    /// Used by the batched read driver ([`MdfIndex`]'s URL reads): a round of
    /// a time-window search needs a few dozen small, independent ranges, and
    /// fetching them one after another would cost one round-trip each.
    pub(crate) fn read_ranges_parallel(&mut self, spans: &[(u64, u64)]) -> Result<Vec<Vec<u8>>, MdfError> {
        if spans.len() <= 1 {
            return spans.iter().map(|&(o, l)| self.read_range(o, l)).collect();
        }
        let (agent, url, expected) = (&self.agent, self.url.as_str(), self.expected_size);
        let mut out: Vec<Vec<u8>> = Vec::with_capacity(spans.len());
        for chunk in spans.chunks(MAX_PARALLEL_REQUESTS) {
            let results: Vec<Result<Vec<u8>, MdfError>> = std::thread::scope(|scope| {
                let handles: Vec<_> = chunk
                    .iter()
                    .map(|&(offset, length)| scope.spawn(move || http_get_range(agent, url, offset, length, expected)))
                    .collect();
                handles
                    .into_iter()
                    .map(|h| {
                        h.join().unwrap_or_else(|_| {
                            Err(MdfError::BlockSerializationError("HTTP fetch thread panicked".to_string()))
                        })
                    })
                    .collect()
            });
            self.request_count += chunk.len() as u64;
            for r in results {
                out.push(r?);
            }
        }
        Ok(out)
    }

    /// Download the whole resource with one plain `GET`.
    pub(crate) fn fetch_all(&mut self) -> Result<Vec<u8>, MdfError> {
        use std::io::Read;
        self.request_count += 1;
        let (agent, url) = (&self.agent, self.url.as_str());
        with_retries(|| {
            let response = agent.get(url).call().map_err(classify_call_error)?;
            let mut body = Vec::new();
            response
                .into_reader()
                .read_to_end(&mut body)
                .map_err(|e| HttpFailure::Transient(MdfError::IOError(e), None))?;
            Ok(body)
        })
    }

    /// Learn the resource's total size with a single-byte ranged GET.
    ///
    /// Uses `GET` with `Range: bytes=0-0` and parses the total length out of
    /// the `Content-Range: bytes 0-0/<total>` header, rather than issuing a
    /// `HEAD`. Presigned URLs (e.g. AWS S3) are signed for one specific HTTP
    /// method, so a `HEAD` against a GET-signed URL is rejected with 403; a
    /// ranged `GET` matches the method the data reads use.
    pub fn probe_size(&mut self) -> Result<u64, MdfError> {
        use std::io::Read;

        let (agent, url) = (&self.agent, self.url.as_str());
        let resp = with_retries(|| agent.get(url).set("Range", "bytes=0-0").call().map_err(classify_call_error))?;
        self.request_count += 1;

        // Preferred: total size from the Content-Range header of a 206 response.
        let total = resp
            .header("Content-Range")
            .and_then(|cr| cr.rsplit('/').next().map(|s| s.trim().to_string()))
            .filter(|s| s != "*")
            .and_then(|s| s.parse::<u64>().ok());

        // Fallback: a server that ignores the Range header replies 200 with the
        // full body, in which case Content-Length is the total size. Drain the
        // body so the connection can be reused for keep-alive.
        let content_length = resp
            .header("Content-Length")
            .and_then(|s| s.parse::<u64>().ok());
        let status = resp.status();
        let mut sink = Vec::new();
        let _ = resp.into_reader().take(1).read_to_end(&mut sink);

        if let Some(len) = total {
            Ok(len)
        } else if status == 200 {
            content_length.ok_or_else(|| {
                MdfError::BlockSerializationError(
                    "size probe: server ignored Range and sent no Content-Length".into(),
                )
            })
        } else {
            Err(MdfError::BlockSerializationError(
                "size probe: 206 response missing Content-Range total".into(),
            ))
        }
    }

    /// Total number of HTTP requests issued by this reader.
    pub fn request_count(&self) -> u64 {
        self.request_count
    }
}

#[cfg(feature = "http")]
impl ByteRangeReader for HttpRangeReader {
    type Error = MdfError;

    fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, MdfError> {
        let bytes = http_get_range(&self.agent, &self.url, offset, length, self.expected_size);
        if length > 0 {
            self.request_count += 1;
        }
        bytes
    }
}

/// Maximum concurrent range requests issued by
/// [`HttpRangeReader::read_ranges_parallel`].
#[cfg(feature = "http")]
pub(crate) const MAX_PARALLEL_REQUESTS: usize = 8;

/// The process-wide HTTP agent shared by every [`HttpRangeReader`].
///
/// Building a TLS connector loads the system trust store, and each agent has
/// its own connection pool, so a fresh agent per read meant a fresh TCP + TLS
/// handshake for every `read()` / `values()` call. One shared agent keeps
/// connections alive across calls (and across indexes reading the same host).
#[cfg(feature = "http")]
fn shared_http_agent() -> Result<ureq::Agent, MdfError> {
    // Keyed by process id: a forked child (multiprocessing, DataLoader
    // workers) must not reuse the parent's pooled keep-alive sockets, or
    // several processes would interleave requests on one TCP stream.
    static AGENT: std::sync::Mutex<Option<(u32, ureq::Agent)>> = std::sync::Mutex::new(None);
    let pid = std::process::id();
    let mut slot = AGENT.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
    if let Some((owner, agent)) = slot.as_ref()
        && *owner == pid
    {
        return Ok(agent.clone());
    }
    // ureq's native-tls feature is not auto-wired (unlike rustls): the
    // connector must be constructed and attached explicitly, otherwise
    // HTTPS requests fail with "no TLS backend is configured".
    let connector = native_tls::TlsConnector::new().map_err(|e| {
        MdfError::BlockSerializationError(format!("failed to init TLS backend: {e}"))
    })?;
    let agent = ureq::AgentBuilder::new()
        .tls_connector(std::sync::Arc::new(connector))
        .max_idle_connections_per_host(MAX_PARALLEL_REQUESTS)
        // Without a read timeout a stalled connection would block a read
        // (and the Python caller) forever; a timed-out attempt is retried.
        .timeout_connect(HTTP_CONNECT_TIMEOUT)
        .timeout_read(HTTP_READ_TIMEOUT)
        .timeout_write(HTTP_READ_TIMEOUT)
        .build();
    *slot = Some((pid, agent.clone()));
    Ok(agent)
}

/// Time allowed to establish a connection.
#[cfg(feature = "http")]
const HTTP_CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);

/// Longest wait for the next bytes of a response (a stall, not a slow
/// download: every socket read restarts it).
#[cfg(feature = "http")]
const HTTP_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);

/// Retries of a request that failed transiently (connection error, timeout,
/// `408` / `429` / `5xx`) before giving up.
#[cfg(feature = "http")]
const HTTP_MAX_RETRIES: u32 = 3;

/// Delay before the first retry; doubled for each further one.
#[cfg(feature = "http")]
const HTTP_RETRY_BASE_DELAY: std::time::Duration = std::time::Duration::from_millis(200);

/// Upper bound on a single retry delay, including a server's `Retry-After`.
#[cfg(feature = "http")]
const HTTP_MAX_RETRY_DELAY: std::time::Duration = std::time::Duration::from_secs(10);

/// Outcome of one failed HTTP attempt.
#[cfg(feature = "http")]
enum HttpFailure {
    /// Worth retrying (connection error, timeout, throttling, server
    /// error), optionally after the delay the server asked for.
    Transient(MdfError, Option<std::time::Duration>),
    /// Retrying would not help (`404`, `403`, a wrong range, a replaced file).
    Fatal(MdfError),
}

/// Statuses that signal a temporary condition: request timeout, throttling
/// (S3 `503 SlowDown`, `429`) and server/gateway errors.
#[cfg(feature = "http")]
fn is_transient_status(status: u16) -> bool {
    matches!(status, 408 | 429 | 500 | 502 | 503 | 504)
}

/// A `Retry-After: <seconds>` header (the HTTP-date form is ignored).
#[cfg(feature = "http")]
fn retry_after(resp: &ureq::Response) -> Option<std::time::Duration> {
    resp.header("Retry-After")?.trim().parse::<u64>().ok().map(std::time::Duration::from_secs)
}

/// Classify a failed `call()`: connection/IO errors and transient statuses
/// are retried; every other status and transport error is final.
#[cfg(feature = "http")]
fn classify_call_error(error: ureq::Error) -> HttpFailure {
    match error {
        ureq::Error::Status(status, resp) if is_transient_status(status) => {
            let after = retry_after(&resp);
            HttpFailure::Transient(
                MdfError::BlockSerializationError(format!("HTTP request failed with status {status}")),
                after,
            )
        }
        ureq::Error::Status(status, _) => {
            HttpFailure::Fatal(MdfError::BlockSerializationError(format!("HTTP request failed with status {status}")))
        }
        ureq::Error::Transport(transport) => {
            let error = MdfError::BlockSerializationError(format!("HTTP request failed: {transport}"));
            // A dropped or refused connection is worth another try; a bad
            // URL, an unknown host or a proxy misconfiguration is not.
            match transport.kind() {
                ureq::ErrorKind::ConnectionFailed | ureq::ErrorKind::Io | ureq::ErrorKind::ProxyConnect => {
                    HttpFailure::Transient(error, None)
                }
                _ => HttpFailure::Fatal(error),
            }
        }
    }
}

/// Run `attempt` until it succeeds, fails for good, or has been retried
/// [`HTTP_MAX_RETRIES`] times, sleeping with exponential backoff (or the
/// server's `Retry-After`, capped) between attempts.
#[cfg(feature = "http")]
fn with_retries<T>(mut attempt: impl FnMut() -> Result<T, HttpFailure>) -> Result<T, MdfError> {
    let mut delay = HTTP_RETRY_BASE_DELAY;
    let mut retries = 0;
    loop {
        match attempt() {
            Ok(value) => return Ok(value),
            Err(HttpFailure::Fatal(e)) => return Err(e),
            Err(HttpFailure::Transient(e, after)) => {
                if retries == HTTP_MAX_RETRIES {
                    return Err(match e {
                        MdfError::BlockSerializationError(msg) => MdfError::BlockSerializationError(format!(
                            "{msg} (gave up after {} attempts)",
                            HTTP_MAX_RETRIES + 1
                        )),
                        other => other,
                    });
                }
                std::thread::sleep(after.unwrap_or(delay).min(HTTP_MAX_RETRY_DELAY));
                delay *= 2;
                retries += 1;
            }
        }
    }
}

/// Total size from a `Content-Range: bytes A-B/<total>` (or `bytes */<total>`)
/// header, if it states one.
#[cfg(feature = "http")]
fn content_range_total(header: Option<&str>) -> Option<u64> {
    header?.rsplit_once('/')?.1.trim().parse().ok()
}

/// `(A, B)` from a `Content-Range: bytes A-B/<total>` header.
#[cfg(feature = "http")]
fn content_range_span(header: Option<&str>) -> Option<(u64, u64)> {
    let spec = header?.trim().strip_prefix("bytes")?.trim();
    let (a, b) = spec.split_once('/')?.0.split_once('-')?;
    Some((a.trim().parse().ok()?, b.trim().parse().ok()?))
}

/// Refuse a source whose size differs from the one the index was built from.
#[cfg(any(feature = "http", not(target_arch = "wasm32")))]
fn check_resource_size(source: &str, expected: u64, actual: u64) -> Result<(), MdfError> {
    if expected != 0 && actual != expected {
        return Err(MdfError::InvalidArgument(format!(
            "the source does not match the index: the index was built from a {expected}-byte \
             file but '{source}' is {actual} bytes — attach the file the index was built \
             from, or rebuild the index"
        )));
    }
    Ok(())
}

/// One `Range: bytes=A-B` GET of `[offset, offset + length)`, retried on
/// transient failures (see [`with_retries`]).
#[cfg(feature = "http")]
fn http_get_range(
    agent: &ureq::Agent,
    url: &str,
    offset: u64,
    length: u64,
    expected_size: Option<u64>,
) -> Result<Vec<u8>, MdfError> {
    if length == 0 {
        return Ok(Vec::new());
    }
    with_retries(|| http_get_range_once(agent, url, offset, length, expected_size))
}

/// A single attempt of [`http_get_range`].
#[cfg(feature = "http")]
fn http_get_range_once(
    agent: &ureq::Agent,
    url: &str,
    offset: u64,
    length: u64,
    expected_size: Option<u64>,
) -> Result<Vec<u8>, HttpFailure> {
    use std::io::Read;
    use HttpFailure::Fatal;

    let range_header = format!("bytes={}-{}", offset, offset + length - 1);
    let resp = match agent.get(url).set("Range", &range_header).call() {
        Ok(resp) => resp,
        // 416: the range starts past the end of the resource. Its
        // `Content-Range: bytes */<size>` tells whether the file shrank.
        Err(ureq::Error::Status(416, resp)) => {
            let total = content_range_total(resp.header("Content-Range"));
            if let (Some(expected), Some(actual)) = (expected_size, total) {
                check_resource_size(url, expected, actual).map_err(Fatal)?;
            }
            return Err(Fatal(MdfError::BlockSerializationError(format!(
                "HTTP range {offset}..{} is past the end of {url}{}",
                offset + length,
                total.map(|t| format!(" ({t} bytes)")).unwrap_or_default()
            ))));
        }
        Err(e) => return Err(classify_call_error(e)),
    };
    if let (Some(expected), Some(actual)) = (expected_size, content_range_total(resp.header("Content-Range"))) {
        check_resource_size(url, expected, actual).map_err(Fatal)?;
    }
    // A 206 must carry exactly the requested range: a proxy or a shared
    // connection that answers with other bytes of the right length would
    // otherwise be decoded silently.
    if resp.status() == 206 {
        if let Some((start, end)) = content_range_span(resp.header("Content-Range")) {
            let want_end = offset + length - 1;
            // (A shorter range at end-of-file is caught by the short-body check below.)
            if start != offset || end > want_end {
                return Err(Fatal(MdfError::BlockSerializationError(format!(
                    "HTTP server returned bytes {start}-{end} for requested range {offset}-{want_end}"
                ))));
            }
        }
    }

    // 206 Partial Content is the accepted path. A 200 means the server
    // ignored the Range header and sent the whole resource: that is only
    // usable when the requested range starts at offset 0 (the body can be
    // truncated to `length`); for any other offset the first `length`
    // bytes would silently come from the wrong position, so error out.
    let status = resp.status();
    match status {
        206 => {}
        200 => {
            if offset != 0 {
                return Err(Fatal(MdfError::BlockSerializationError(format!(
                    "HTTP server ignored Range request (status 200) for offset {}; \
                     refusing to return bytes from the wrong position",
                    offset
                ))));
            }
        }
        other => {
            return Err(Fatal(MdfError::BlockSerializationError(format!(
                "HTTP range request returned unexpected status {other}"
            ))));
        }
    }

    // Read at most `length` bytes (a 200 response carries the whole
    // resource and must be truncated), then insist we actually received
    // all of them: a short body must be an error, not silently fewer
    // records. Capacity is capped so a forged huge length cannot abort
    // on allocation.
    let mut buf = Vec::with_capacity(length.min(1 << 20) as usize);
    // A connection reset or read timeout mid-body is transient.
    resp.into_reader()
        .take(length)
        .read_to_end(&mut buf)
        .map_err(|e| HttpFailure::Transient(MdfError::IOError(e), None))?;
    if (buf.len() as u64) < length {
        // Report absolute positions so wrappers (e.g. CachingRangeReader)
        // can learn the resource's true end from `actual`.
        return Err(Fatal(MdfError::TooShortBuffer {
            actual: (offset + buf.len() as u64) as usize,
            expected: (offset + length) as usize,
            file: file!(),
            line: line!(),
        }));
    }
    Ok(buf)
}

impl MdfIndex {
    /// Create an index from an MDF file on disk.
    ///
    /// Not available on `wasm32-unknown-unknown`; use [`from_bytes`](Self::from_bytes) instead.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn from_file(file_path: &str) -> Result<Self, MdfError> {
        let mdf = Mdf::from_file(file_path)?;
        let file_size = std::fs::metadata(file_path)
            .map_err(MdfError::IOError)?
            .len();
        let mut index = Self::build_index(mdf, file_size)?;
        index.source = Some(Source::File(file_path.to_string()));
        Ok(index)
    }

    /// Build an index from an MDF file served over HTTP / S3 using range
    /// requests, remembering the URL as the index's [`Source`].
    ///
    /// Only metadata blocks are fetched while building; sample data is read
    /// lazily on [`MdfIndex::read`]. Requires the `http` feature.
    #[cfg(feature = "http")]
    pub fn from_url(url: &str) -> Result<Self, MdfError> {
        Self::from_url_with_chunk_size(url, 1 << 20)
    }

    /// [`MdfIndex::from_url`] with an explicit metadata read-ahead chunk size.
    #[cfg(feature = "http")]
    pub fn from_url_with_chunk_size(url: &str, chunk_size: u64) -> Result<Self, MdfError> {
        let mut http = HttpRangeReader::new(url)?;
        let file_size = http.probe_size()?;
        let mut cached = CachingRangeReader::with_chunk_size(http, chunk_size);
        cached.set_known_size(file_size);
        let mut index = Self::from_range_reader(&mut cached, file_size)?;
        index.source = Some(Source::Url(url.to_string()));
        Ok(index)
    }

    /// Shared index-building logic operating on an already-parsed [`MDF`].
    fn build_index(mdf: Mdf, file_size: u64) -> Result<Self, MdfError> {
        let start_time_ns = mdf.start_time_ns();
        let mut indexed_groups = Vec::new();
        // (own ##CG address, remote master ##CG address) per group.
        let mut cg_links: Vec<(u64, u64)> = Vec::new();

        for group in mdf.channel_groups() {
            let raw_cg = group.raw_channel_group();
            cg_links.push((raw_cg.addr, raw_cg.block.master_cg_addr));
            // Unsorted data groups (a record-ID prefix with several channel
            // groups sharing the same data blocks) would make every CG index
            // the same interleaved records as if they were all its own.
            let raw_dg = group.raw_data_group();
            if raw_dg.block.record_id_len > 0 && raw_dg.channel_groups.len() > 1 {
                return Err(MdfError::BlockSerializationError(
                    "unsorted data groups (record IDs with multiple channel groups) \
                     are not supported by the index"
                        .to_string(),
                ));
            }

            let mut indexed_channels = Vec::new();
            let mmap = group.mmap();

            for channel in group.channels() {
                let block = channel.block();

                let resolved_conversion = if let Some(mut conversion) = block.conversion.clone() {
                    if let Err(e) = conversion.resolve_all_dependencies(mmap) {
                        eprintln!("Warning: Failed to resolve conversion dependencies for channel '{}': {}",
                                 block.name.as_deref().unwrap_or("<unnamed>"), e);
                    }
                    Some(conversion)
                } else {
                    None
                };

                let vlsd_data_blocks = if block.channel_type == 1 && block.data != 0 {
                    let mut slice_reader = BorrowedSliceReader { data: mmap };
                    Self::extract_vlsd_data_blocks(&mut slice_reader, block.data)?
                } else {
                    Vec::new()
                };

                indexed_channels.push(IndexedChannel {
                    name: channel.name()?,
                    unit: channel.unit()?,
                    comment: channel.comment()?,
                    data_type: block.data_type.clone(),
                    byte_offset: block.byte_offset,
                    bit_offset: block.bit_offset,
                    bit_count: block.bit_count,
                    channel_type: block.channel_type,
                    flags: block.flags,
                    pos_invalidation_bit: block.pos_invalidation_bit,
                    conversion: resolved_conversion,
                    conversion_addr: block.conversion_addr,
                    vlsd_data_address: if block.channel_type == 1 && block.data != 0 {
                        Some(block.data)
                    } else {
                        None
                    },
                    vlsd_data_blocks,
                });
            }

            let data_blocks = Self::extract_data_blocks(&group)?;

            indexed_groups.push(IndexedChannelGroup {
                name: group.name()?,
                comment: group.comment()?,
                record_id_len: group.raw_data_group().block.record_id_len,
                record_size: group.raw_channel_group().block.samples_byte_nr,
                invalidation_bytes: group.raw_channel_group().block.invalidation_bytes_nr,
                record_count: group.raw_channel_group().block.cycles_nr,
                channels: indexed_channels,
                data_blocks,
                master_group: None,
            });
        }
        Self::link_remote_masters(&mut indexed_groups, &cg_links);

        Ok(MdfIndex { file_size, start_time_ns, channel_groups: indexed_groups, source: None })
    }

    /// Fill [`IndexedChannelGroup::master_group`] for groups without a local
    /// master whose `##CG` carries an MDF 4.2 remote-master link.
    fn link_remote_masters(groups: &mut [IndexedChannelGroup], cg_links: &[(u64, u64)]) {
        for g in 0..groups.len() {
            let target = cg_links[g].1;
            if target == 0 || groups[g].master_channel().is_some() {
                continue;
            }
            groups[g].master_group = cg_links
                .iter()
                .position(|&(addr, _)| addr == target)
                .filter(|&m| m != g && groups[m].master_channel().is_some());
        }
    }

    /// Extract data block information from a channel group
    fn extract_data_blocks(group: &crate::api::channel_group::ChannelGroup) -> Result<Vec<DataBlockInfo>, MdfError> {
        let mut data_blocks = Vec::new();
        let raw_data_group = group.raw_data_group();
        let mmap = group.mmap();
        
        // Start at the group's primary data pointer
        let mut current_block_address = raw_data_group.block.data_block_addr;
        while current_block_address != 0 {
            let byte_offset = current_block_address as usize;

            // Read the block header
            let block_header = crate::blocks::common::BlockHeader::from_bytes(&mmap[byte_offset..byte_offset + 24])?;

            match block_header.id.as_str() {
                "##DT" | "##DV" => {
                    // Single contiguous DataBlock
                    let data_block_info = DataBlockInfo {
                        file_offset: current_block_address,
                        size: block_header.block_len,
                        is_compressed: false,
                    };
                    data_blocks.push(data_block_info);
                    // No list to follow, we're done
                    current_block_address = 0;
                }
                "##DZ" => {
                    // Compressed data block  
                    let data_block_info = DataBlockInfo {
                        file_offset: current_block_address,
                        size: block_header.block_len,
                        is_compressed: true,
                    };
                    data_blocks.push(data_block_info);
                    current_block_address = 0;
                }
                "##DL" => {
                    // Fragmented list of data blocks
                    let data_list_block = crate::blocks::data_list_block::DataListBlock::from_bytes(&mmap[byte_offset..])?;

                    // Parse each fragment in this list
                    for &fragment_address in &data_list_block.data_links {
                        let fragment_offset = fragment_address as usize;
                        let fragment_header = crate::blocks::common::BlockHeader::from_bytes(&mmap[fragment_offset..fragment_offset + 24])?;
                        
                        let is_compressed = fragment_header.id == "##DZ";
                        let data_block_info = DataBlockInfo {
                            file_offset: fragment_address,
                            size: fragment_header.block_len,
                            is_compressed,
                        };
                        data_blocks.push(data_block_info);
                    }

                    // Move to the next DLBLOCK in the chain (0 = end)
                    current_block_address = data_list_block.next;
                }

                unexpected_id => {
                    return Err(MdfError::BlockIDError {
                        actual: unexpected_id.to_string(),
                        expected: "##DT / ##DV / ##DL / ##DZ".to_string(),
                    });
                }
            }
        }
        
        Ok(data_blocks)
    }

    /// Create an index from an in-memory MDF byte buffer.
    ///
    /// This is the primary constructor on `wasm32-unknown-unknown`.
    pub fn from_bytes(data: Vec<u8>) -> Result<Self, MdfError> {
        let file_size = data.len() as u64;
        let mdf = Mdf::from_bytes(data)?;
        Self::build_index(mdf, file_size)
    }

    /// Build an [`MdfIndex`] using only [`ByteRangeReader`] calls.
    ///
    /// Issues range reads for the file's metadata structures (identification,
    /// header, data groups, channel groups, channels, text and conversion
    /// blocks, and data-block headers) but never reads the sample data
    /// itself. Intended for remote sources such as HTTP-served files; wrap
    /// the underlying reader in [`CachingRangeReader`] to keep the number of
    /// underlying requests low.
    ///
    /// `file_size` is stored on the resulting index for use by later byte-range
    /// calculations. Callers should obtain it from a HEAD request (e.g.
    /// [`HttpRangeReader::probe_size`]) or other out-of-band metadata.
    pub fn from_range_reader<R>(
        reader: &mut R,
        file_size: u64,
    ) -> Result<Self, MdfError>
    where
        R: ByteRangeReader<Error = MdfError>,
    {
        use crate::parsing::reader_walk;

        let walk = reader_walk::walk(reader)?;

        let start_time_ns = if walk.header.abs_time == 0 {
            None
        } else {
            Some(walk.header.abs_time)
        };

        let mut indexed_groups = Vec::with_capacity(walk.groups.len());
        let cg_links: Vec<(u64, u64)> =
            walk.groups.iter().map(|g| (g.cg_addr, g.cg.master_cg_addr)).collect();
        for group in walk.groups {
            let mut indexed_channels = Vec::with_capacity(group.channels.len());
            for ch in group.channels {
                let block = ch.block;
                let vlsd_data_blocks = if block.channel_type == 1 && block.data != 0 {
                    Self::extract_vlsd_data_blocks(reader, block.data)?
                } else {
                    Vec::new()
                };
                indexed_channels.push(IndexedChannel {
                    name: ch.name,
                    unit: ch.unit,
                    comment: ch.comment,
                    data_type: block.data_type.clone(),
                    byte_offset: block.byte_offset,
                    bit_offset: block.bit_offset,
                    bit_count: block.bit_count,
                    channel_type: block.channel_type,
                    flags: block.flags,
                    pos_invalidation_bit: block.pos_invalidation_bit,
                    // Remote / range-reader builds defer conversion resolution:
                    // only the block's location is recorded here; it is fetched
                    // and resolved lazily on the first value read.
                    conversion: None,
                    conversion_addr: ch.conversion_addr,
                    vlsd_data_address: if block.channel_type == 1 && block.data != 0 {
                        Some(block.data)
                    } else {
                        None
                    },
                    vlsd_data_blocks,
                });
            }

            // Bytes of record data the group holds, so equal-length ##DL
            // lists can be sized without touching the data region.
            let expected_bytes = group.cg.cycles_nr.checked_mul(
                group.record_id_len as u64
                    + group.cg.samples_byte_nr as u64
                    + group.cg.invalidation_bytes_nr as u64,
            );
            let data_blocks = Self::extract_data_blocks_via_reader(
                reader,
                group.data_block_addr,
                expected_bytes,
                file_size,
            )?;

            indexed_groups.push(IndexedChannelGroup {
                name: group.cg_name,
                comment: group.cg_comment,
                record_id_len: group.record_id_len,
                record_size: group.cg.samples_byte_nr,
                invalidation_bytes: group.cg.invalidation_bytes_nr,
                record_count: group.cg.cycles_nr,
                channels: indexed_channels,
                data_blocks,
                master_group: None,
            });
        }
        Self::link_remote_masters(&mut indexed_groups, &cg_links);

        Ok(MdfIndex {
            file_size,
            start_time_ns,
            channel_groups: indexed_groups,
            source: None,
        })
    }

    /// Mirror of [`Self::extract_data_blocks`] that fetches headers via a
    /// [`ByteRangeReader`] instead of slicing into a memory map.
    ///
    /// When `reader.is_probing()` (an incremental gap-discovery pass — see
    /// [`ByteRangeReader::is_probing`]), a failed read stops walking this
    /// group's data-block chain and returns what was collected so far instead
    /// of propagating the error: the reader has already recorded the miss, so
    /// the caller can fetch it and retry. The resulting index is **partial**
    /// and must be discarded while any reader miss remains — this is exactly
    /// the batched gap-discovery contract `MdfIndex::from_range_reader`
    /// callers (`buildIndexStep`/`IndexBuilder::step`) already enforce by only
    /// reporting `done` once a pass records zero misses. On-demand readers
    /// (the default `is_probing() == false`) are unaffected: a failed read is
    /// still fatal, exactly as before.
    ///
    /// For an **equal-length** `##DL` list (`dl_flags` bit 0) reached directly
    /// from the data group, the fragment sizes follow from the list itself:
    /// every fragment but the last holds `dl_equal_length` bytes and the last
    /// holds the rest of `expected_bytes` (cycle count × record size). When
    /// that arithmetic is consistent with the number of fragments and the file
    /// size, the fragment headers are **not read** — on a column-oriented file
    /// whose metadata sits at the front this keeps the whole index build inside
    /// the metadata prefix (one or two requests, independent of the number of
    /// data blocks). Reads still verify each fragment header they fetch. Any
    /// inconsistency falls back to reading the headers.
    fn extract_data_blocks_via_reader<R>(
        reader: &mut R,
        data_block_addr: u64,
        expected_bytes: Option<u64>,
        file_size: u64,
    ) -> Result<Vec<DataBlockInfo>, MdfError>
    where
        R: ByteRangeReader<Error = MdfError>,
    {
        let mut data_blocks = Vec::new();

        // Read a range, but when probing and the read fails, stop walking
        // this chain and hand back what's been collected so far rather than
        // aborting the whole build.
        macro_rules! probe_read {
            ($offset:expr, $len:expr) => {
                match reader.read_range($offset, $len) {
                    Ok(b) => b,
                    Err(e) => {
                        if reader.is_probing() {
                            return Ok(data_blocks);
                        }
                        return Err(e);
                    }
                }
            };
        }

        let mut current_block_address = data_block_addr;

        while current_block_address != 0 {
            let header_bytes = probe_read!(current_block_address, 24);
            let block_header =
                crate::blocks::common::BlockHeader::from_bytes(&header_bytes)?;

            match block_header.id.as_str() {
                "##DT" | "##DV" => {
                    data_blocks.push(DataBlockInfo {
                        file_offset: current_block_address,
                        size: block_header.block_len,
                        is_compressed: false,
                    });
                    current_block_address = 0;
                }
                "##DZ" => {
                    data_blocks.push(DataBlockInfo {
                        file_offset: current_block_address,
                        size: block_header.block_len,
                        is_compressed: true,
                    });
                    current_block_address = 0;
                }
                "##DL" => {
                    let dl_bytes = probe_read!(current_block_address, block_header.block_len);
                    let data_list_block =
                        crate::blocks::data_list_block::DataListBlock::from_bytes(&dl_bytes)?;

                    if current_block_address == data_block_addr && data_list_block.next == 0
                        && let Some(derived) = Self::derive_equal_length_fragments(
                            &data_list_block,
                            expected_bytes,
                            file_size,
                        ) {
                            data_blocks.extend(derived);
                            break;
                        }

                    for &fragment_address in &data_list_block.data_links {
                        let frag_header_bytes = probe_read!(fragment_address, 24);
                        let fragment_header = crate::blocks::common::BlockHeader::from_bytes(
                            &frag_header_bytes,
                        )?;
                        let is_compressed = fragment_header.id == "##DZ";
                        data_blocks.push(DataBlockInfo {
                            file_offset: fragment_address,
                            size: fragment_header.block_len,
                            is_compressed,
                        });
                    }

                    current_block_address = data_list_block.next;
                }
                unexpected_id => {
                    return Err(MdfError::BlockIDError {
                        actual: unexpected_id.to_string(),
                        expected: "##DT / ##DV / ##DL / ##DZ".to_string(),
                    });
                }
            }
        }

        Ok(data_blocks)
    }

    /// Fragment locations of an equal-length `##DL` derived without reading
    /// the fragments (see [`Self::extract_data_blocks_via_reader`]); `None`
    /// when the list is not equal-length or the numbers do not add up.
    fn derive_equal_length_fragments(
        dl: &crate::blocks::data_list_block::DataListBlock,
        expected_bytes: Option<u64>,
        file_size: u64,
    ) -> Option<Vec<DataBlockInfo>> {
        let equal = dl.data_block_len.filter(|_| dl.flags & 1 != 0)?;
        let total = expected_bytes?;
        let n = dl.data_links.len() as u64;
        if equal == 0 || n == 0 || total == 0 || dl.data_links.contains(&0) {
            return None;
        }
        // (n-1) full fragments plus a non-empty last one must hold exactly `total`.
        let full = (n - 1).checked_mul(equal)?;
        if total <= full || total > full.checked_add(equal)? {
            return None;
        }
        let last = total - full;
        let mut out: Vec<DataBlockInfo> = Vec::with_capacity(n as usize);
        for (i, &addr) in dl.data_links.iter().enumerate() {
            let data = if i as u64 + 1 == n { last } else { equal };
            let size = data.checked_add(24)?;
            if file_size > 0 && addr.checked_add(size)? > file_size {
                return None;
            }
            // Fragments must not overlap (ascending, each starting after the
            // previous one ends); anything else is left to the headers.
            if let Some(prev) = out.last()
                && addr < prev.file_offset.checked_add(prev.size)?
            {
                return None;
            }
            out.push(DataBlockInfo { file_offset: addr, size, is_compressed: false });
        }
        Some(out)
    }

    /// Read the data sections of `blocks` in order, coalescing blocks that sit
    /// back to back in the file (at most 7 bytes of alignment padding apart)
    /// into a single read of up to [`MAX_COALESCED_READ`] bytes, and call `f`
    /// with each block's data section.
    ///
    /// A column-oriented file stores each signal's blocks contiguously, so a
    /// whole signal arrives in one range request instead of one per block.
    /// Every read starts at a block header, and each block's header is
    /// verified (`##DT`/`##DV`) before its data is decoded. The header's own
    /// length is authoritative: when it disagrees with the indexed size (e.g.
    /// fragment sizes derived from an equal-length `##DL` and a stale cycle
    /// count), the block's real data section is used — re-read if it extends
    /// beyond the coalesced read — so bytes beyond a block are never decoded.
    fn for_each_data_section<R, F>(
        reader: &mut R,
        blocks: &[DataBlockInfo],
        mut f: F,
    ) -> Result<(), MdfError>
    where
        R: ByteRangeReader<Error = MdfError>,
        F: FnMut(&[u8]) -> Result<(), MdfError>,
    {
        // With a probing reader every missing section is recorded in one
        // pass (sections after a miss are requested but not decoded), so a
        // batched read needs one round, not one per section.
        let mut first_err = None;
        let mut i = 0;
        while i < blocks.len() {
            let start = blocks[i].file_offset;
            Self::data_section_size(&blocks[i])?;
            let mut end = start.checked_add(blocks[i].size).ok_or_else(|| {
                MdfError::BlockSerializationError("data block offset overflows".to_string())
            })?;
            let mut j = i + 1;
            while j < blocks.len() {
                let b = &blocks[j];
                let b_end = b.file_offset.saturating_add(b.size);
                if b.file_offset < end
                    || b.file_offset - end > 7
                    || b.size < 24
                    || b_end - start > MAX_COALESCED_READ
                {
                    break;
                }
                end = b_end;
                j += 1;
            }
            let buf = match reader.read_range(start, end - start) {
                Ok(buf) if first_err.is_none() => buf,
                Ok(_) => {
                    i = j;
                    continue;
                }
                Err(e) if reader.is_probing() => {
                    first_err.get_or_insert(e);
                    i = j;
                    continue;
                }
                Err(e) => return Err(e),
            };
            for b in &blocks[i..j] {
                let header_start = (b.file_offset - start) as usize;
                let data_start = header_start + 24;
                let len = Self::verified_data_len(buf.get(header_start..data_start), b)?;
                match usize::try_from(len).ok().and_then(|l| buf.get(data_start..data_start.checked_add(l)?)) {
                    Some(data) => f(data)?,
                    None => f(&reader.read_range(b.file_offset + 24, len)?)?,
                }
            }
            i = j;
        }
        match first_err {
            Some(e) => Err(e),
            None => Ok(()),
        }
    }

    /// Check that `header` (the 24 header bytes of `block`, if available) is an
    /// uncompressed `##DT`/`##DV` block and return the length of its data
    /// section according to the header (which wins over the indexed size).
    fn verified_data_len(header: Option<&[u8]>, block: &DataBlockInfo) -> Result<u64, MdfError> {
        let h = BlockHeader::from_bytes(header.unwrap_or(&[]))?;
        if (h.id == "##DT" || h.id == "##DV") && h.block_len >= 24 {
            return Ok(h.block_len - 24);
        }
        Err(MdfError::BlockSerializationError(format!(
            "data block at offset {} is {} with length {} but the index expects an \
             uncompressed ##DT/##DV block of {} bytes (compressed or inconsistent \
             file; rebuild the index)",
            block.file_offset, h.id, h.block_len, block.size
        )))
    }

    /// Walk a VLSD channel's `data` chain (a single `##SD`, or a `##DL` chain
    /// of `##SD`/`##DZ` fragments) and record each fragment's location in chain
    /// order.
    ///
    /// Generic over [`ByteRangeReader`] so the mmap path (via
    /// [`BorrowedSliceReader`]) and the remote path share one implementation.
    /// Cycle-detects the `##DL` `next` chain, rejects unexpected block IDs, and
    /// validates that a variable-length `##DL`'s per-fragment virtual offsets
    /// reproduce the running sum of prior fragments' data-section sizes — the
    /// invariant the offset-based reader relies on.
    ///
    /// When `reader.is_probing()`, a failed read stops walking this VLSD
    /// chain and returns what was collected so far instead of propagating the
    /// error — see the identical rationale on
    /// [`Self::extract_data_blocks_via_reader`]. Non-probing readers keep
    /// today's fatal-on-first-miss behavior.
    fn extract_vlsd_data_blocks<R>(
        reader: &mut R,
        data_addr: u64,
    ) -> Result<Vec<DataBlockInfo>, MdfError>
    where
        R: ByteRangeReader<Error = MdfError>,
    {
        let mut data_blocks: Vec<DataBlockInfo> = Vec::new();

        // See `extract_data_blocks_via_reader`'s `probe_read!` for the
        // rationale: batched gap discovery skips an unreadable subtree
        // instead of aborting the whole pass, but only when probing.
        macro_rules! probe_read {
            ($offset:expr, $len:expr) => {
                match reader.read_range($offset, $len) {
                    Ok(b) => b,
                    Err(e) => {
                        if reader.is_probing() {
                            return Ok(data_blocks);
                        }
                        return Err(e);
                    }
                }
            };
        }

        let mut visited: std::collections::HashSet<u64> = std::collections::HashSet::new();
        // Running sum of fragment data-section sizes (size - 24), i.e. the
        // virtual start offset of the next fragment in the concatenated stream.
        let mut running_offset: u64 = 0;
        let mut current = data_addr;

        while current != 0 {
            let header_bytes = probe_read!(current, 24);
            let header = crate::blocks::common::BlockHeader::from_bytes(&header_bytes)?;

            match header.id.as_str() {
                "##SD" => {
                    data_blocks.push(DataBlockInfo {
                        file_offset: current,
                        size: header.block_len,
                        is_compressed: false,
                    });
                    current = 0;
                }
                "##DZ" => {
                    data_blocks.push(DataBlockInfo {
                        file_offset: current,
                        size: header.block_len,
                        is_compressed: true,
                    });
                    current = 0;
                }
                "##DL" => {
                    // Cycle detection on the DL chain: a chain revisiting an
                    // address would otherwise loop forever.
                    if !visited.insert(current) {
                        return Err(MdfError::BlockLinkError(format!(
                            "cycle detected in VLSD data list chain at address {:#x}",
                            current
                        )));
                    }
                    let dl_bytes = probe_read!(current, header.block_len);
                    let dl = crate::blocks::data_list_block::DataListBlock::from_bytes(&dl_bytes)?;

                    for (i, &fragment_address) in dl.data_links.iter().enumerate() {
                        if fragment_address == 0 {
                            continue;
                        }
                        let frag_header_bytes = probe_read!(fragment_address, 24);
                        let frag_header =
                            crate::blocks::common::BlockHeader::from_bytes(&frag_header_bytes)?;
                        let is_compressed = match frag_header.id.as_str() {
                            "##SD" => false,
                            "##DZ" => true,
                            other => {
                                return Err(MdfError::BlockIDError {
                                    actual: other.to_string(),
                                    expected: "##SD / ##DZ".to_string(),
                                });
                            }
                        };

                        // A variable-length DL carries an explicit virtual
                        // offset per fragment. The offset-based read path maps
                        // an inline offset to a fragment via cumulative
                        // data-section sizes, so a non-contiguous chain would
                        // silently mislocate entries — reject it here.
                        if let Some(offsets) = &dl.offsets
                            && let Some(&declared) = offsets.get(i)
                                && declared != running_offset {
                                    return Err(MdfError::BlockSerializationError(format!(
                                        "non-contiguous VLSD ##SD chain is unsupported: \
                                         fragment at offset {} declares virtual start {} \
                                         but the running data-section sum is {}",
                                        fragment_address, declared, running_offset
                                    )));
                                }

                        let data_section = frag_header.block_len.checked_sub(24).ok_or_else(|| {
                            MdfError::BlockSerializationError(format!(
                                "VLSD fragment at offset {} has size {} \
                                 (smaller than the 24-byte block header)",
                                fragment_address, frag_header.block_len
                            ))
                        })?;
                        running_offset = running_offset.checked_add(data_section).ok_or_else(|| {
                            MdfError::BlockSerializationError(
                                "VLSD ##SD chain total size overflows the address space"
                                    .to_string(),
                            )
                        })?;

                        data_blocks.push(DataBlockInfo {
                            file_offset: fragment_address,
                            size: frag_header.block_len,
                            is_compressed,
                        });
                    }

                    current = dl.next;
                }
                other => {
                    return Err(MdfError::BlockIDError {
                        actual: other.to_string(),
                        expected: "##SD / ##DL / ##DZ".to_string(),
                    });
                }
            }
        }

        Ok(data_blocks)
    }

    /// Save the index to a JSON file.
    ///
    /// Not available on `wasm32-unknown-unknown`; use [`to_json`](Self::to_json) instead.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn save(&self, index_path: &str) -> Result<(), MdfError> {
        let json = self.to_json()?;
        std::fs::write(index_path, json)
            .map_err(MdfError::IOError)?;
        Ok(())
    }

    /// Load an index from a JSON file.
    ///
    /// Not available on `wasm32-unknown-unknown`; use [`from_json`](Self::from_json) instead.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn load(index_path: &str) -> Result<Self, MdfError> {
        let json = std::fs::read_to_string(index_path)
            .map_err(MdfError::IOError)?;
        Self::from_json(&json)
    }

    /// Serialize the index to a JSON string (available on all targets).
    pub fn to_json(&self) -> Result<String, MdfError> {
        serde_json::to_string_pretty(self)
            .map_err(|e| MdfError::BlockSerializationError(format!("JSON serialization failed: {}", e)))
    }

    /// Deserialize an index from a JSON string (available on all targets).
    ///
    /// The deserialized index is [validated](Self::validate) so hostile or
    /// stale index data errors here instead of panicking later during reads.
    pub fn from_json(json: &str) -> Result<Self, MdfError> {
        let index: Self = serde_json::from_str(json)
            .map_err(|e| MdfError::BlockSerializationError(format!("JSON deserialization failed: {}", e)))?;
        index.validate()?;
        Ok(index)
    }

    /// Validate structural invariants of the index.
    ///
    /// Called from [`Self::from_json`] / [`Self::load`] so that
    /// malformed (hostile or stale) index data returns an error instead of
    /// causing panics, integer underflow, or huge allocations during reads.
    pub fn validate(&self) -> Result<(), MdfError> {
        for group in &self.channel_groups {
            let group_name = group.name.as_deref().unwrap_or("<unnamed>");
            for db in &group.data_blocks {
                if db.size < 24 {
                    return Err(MdfError::BlockSerializationError(format!(
                        "invalid index: group '{}' data block at offset {} has size {} \
                         (smaller than the 24-byte block header)",
                        group_name, db.file_offset, db.size
                    )));
                }
                if db.file_offset.checked_add(db.size).is_none() {
                    return Err(MdfError::BlockSerializationError(format!(
                        "invalid index: group '{}' data block at offset {} with size {} \
                         overflows the file address space",
                        group_name, db.file_offset, db.size
                    )));
                }
            }
            if !group.data_blocks.is_empty() {
                Self::checked_record_size(group)?;
            }
            for channel in &group.channels {
                for db in &channel.vlsd_data_blocks {
                    if db.size < 24 {
                        return Err(MdfError::BlockSerializationError(format!(
                            "invalid index: group '{}' VLSD data block at offset {} has size {} \
                             (smaller than the 24-byte block header)",
                            group_name, db.file_offset, db.size
                        )));
                    }
                    if db.file_offset.checked_add(db.size).is_none() {
                        return Err(MdfError::BlockSerializationError(format!(
                            "invalid index: group '{}' VLSD data block at offset {} with size {} \
                             overflows the file address space",
                            group_name, db.file_offset, db.size
                        )));
                    }
                }
            }
        }
        Ok(())
    }

    /// Total on-disk record size (record id + data + invalidation bytes) for
    /// a group, validated non-zero so callers can safely divide by it.
    fn checked_record_size(group: &IndexedChannelGroup) -> Result<usize, MdfError> {
        let size = group.record_id_len as usize
            + group.record_size as usize
            + group.invalidation_bytes as usize;
        if size == 0 {
            return Err(MdfError::BlockSerializationError(format!(
                "invalid index: channel group '{}' has record size 0",
                group.name.as_deref().unwrap_or("<unnamed>")
            )));
        }
        Ok(size)
    }

    /// Size of a data block's data section (block size minus the 24-byte
    /// header), validated so a corrupt/forged block size cannot underflow.
    fn data_section_size(data_block: &DataBlockInfo) -> Result<u64, MdfError> {
        data_block.size.checked_sub(24).ok_or_else(|| {
            MdfError::BlockSerializationError(format!(
                "invalid index: data block at offset {} has size {} \
                 (smaller than the 24-byte block header)",
                data_block.file_offset, data_block.size
            ))
        })
    }

    /// Number of whole records in a data block's data section.
    ///
    /// Errors if the block size underflows the header or if the data section
    /// is not a multiple of the record size — a record spanning data-block
    /// fragments is unsupported and silently flooring would decode garbage
    /// for every record after the split.
    fn records_in_block(data_block: &DataBlockInfo, record_size: usize) -> Result<u64, MdfError> {
        let data_len = Self::data_section_size(data_block)?;
        if data_len % record_size as u64 != 0 {
            return Err(MdfError::BlockSerializationError(format!(
                "data block at offset {}: data section of {} bytes is not a multiple of \
                 the {}-byte record — record spans data block fragments, which is unsupported",
                data_block.file_offset, data_len, record_size
            )));
        }
        Ok(data_len / record_size as u64)
    }

    /// Error for VLSD channels on the byte-range calculation paths.
    ///
    /// A VLSD channel's fixed record field holds an 8-byte offset into a
    /// separate `##SD` stream, not the value bytes, so a static
    /// `(offset, length)` range cannot describe where a sample's payload
    /// lives. Value reads (`read` / `values`) resolve the indirection and are
    /// fully supported; only byte-range calculation refuses VLSD channels.
    fn ensure_not_vlsd(channel: &IndexedChannel) -> Result<(), MdfError> {
        if channel.channel_type == 1 {
            return Err(MdfError::BlockSerializationError(format!(
                "byte ranges cannot represent offset-indirected VLSD channel '{}'; \
                 use read()/values() instead",
                channel.name.as_deref().unwrap_or("<unnamed>")
            )));
        }
        Ok(())
    }

    /// Read channel values using the index and a byte range reader.
    ///
    /// Internal positional helper — the public entry point is
    /// [`MdfReader::values`], which resolves channels by name.
    ///
    /// # Returns
    /// A vector of `Option<DecodedValue>` where:
    /// - `Some(value)` represents a valid decoded value
    /// - `None` represents an invalid value (invalidation bit set or decoding failed)
    pub(crate) fn read_channel_values<R: ByteRangeReader<Error = MdfError>>(
        &self,
        group_index: usize,
        channel_index: usize,
        raw: bool,
        reader: &mut R
    ) -> Result<Vec<Option<DecodedValue>>, MdfError> {
        let group = self.channel_groups.get(group_index)
            .ok_or_else(|| MdfError::BlockSerializationError("Invalid group index".to_string()))?;
        
        let channel = group.channels.get(channel_index)
            .ok_or_else(|| MdfError::BlockSerializationError("Invalid channel index".to_string()))?;

        let conversion = Self::read_conversion(channel, reader, raw)?;

        if channel.is_virtual() {
            return self.virtual_values(group, 0, group.record_count, conversion.as_ref());
        }
        if channel.channel_type == 1 {
            return self.read_vlsd_channel_values(group, channel, conversion.as_ref(), reader);
        }

        // For regular channels, read from data blocks
        self.read_regular_channel_values(group, channel, conversion.as_ref(), reader)
    }

    /// Values of a virtual channel (`cn_type` 3/6) for records
    /// `[start, start + count)`: the raw value is the record index, converted
    /// through the channel's conversion (MDF 4.1 §6.6.3).
    fn virtual_values(
        &self,
        group: &IndexedChannelGroup,
        start: u64,
        count: u64,
        conversion: Option<&ConversionBlock>,
    ) -> Result<Vec<Option<DecodedValue>>, MdfError> {
        // Nothing is read for a virtual channel, so bound the record count by
        // stored data instead of trusting a possibly forged `record_count`:
        // the group's own data blocks, or — for a byte-less time group (the
        // virtual master `to_column_oriented` writes) — the largest
        // data-backed group using it as its remote master.
        let available = if !group.data_blocks.is_empty() {
            Self::stored_records(group)?
        } else {
            let me = self.channel_groups.iter().position(|g| std::ptr::eq(g, group));
            self.channel_groups
                .iter()
                .filter(|g| me.is_some() && g.master_group == me && !g.data_blocks.is_empty())
                .filter_map(|g| Self::stored_records(g).ok())
                .max()
                // Nothing stored to check against: trust the group.
                .unwrap_or(group.record_count)
        };
        match start.checked_add(count) {
            Some(end) if end <= available => {}
            _ => {
                return Err(MdfError::BlockSerializationError(format!(
                    "virtual channel read of {} records from {} exceeds the {} records the \
                     group's data holds (rebuild the index)",
                    count, start, available
                )))
            }
        }
        let mut values = Vec::with_capacity((count as usize).min(1 << 24));
        for i in start..start + count {
            let raw = DecodedValue::UnsignedInteger(i);
            values.push(Some(match conversion {
                Some(conv) => conv.apply_decoded(raw, &[])?,
                None => raw,
            }));
        }
        Ok(values)
    }

    /// Read the samples of the channel at `(g, c)` for the record window
    /// `[start, start + count)` only.
    ///
    /// For a regular channel only the bytes of the window's records are read
    /// (one range per data block the window touches, plus that block's
    /// 24-byte header, which is verified). A VLSD channel is read in full and
    /// sliced, since its payloads sit in a separate stream.
    pub(crate) fn read_channel_values_window<R: ByteRangeReader<Error = MdfError>>(
        &self,
        g: usize,
        c: usize,
        start: u64,
        count: u64,
        raw: bool,
        reader: &mut R,
    ) -> Result<Vec<Option<DecodedValue>>, MdfError> {
        let (group, channel) = self.group_and_channel(g, c)?;
        Self::check_window(group, start, count)?;
        let conversion = Self::read_conversion(channel, reader, raw)?;
        self.window_values(group, channel, conversion.as_ref(), start, count, reader)
    }

    fn window_values<R: ByteRangeReader<Error = MdfError>>(
        &self,
        group: &IndexedChannelGroup,
        channel: &IndexedChannel,
        conversion: Option<&ConversionBlock>,
        start: u64,
        count: u64,
        reader: &mut R,
    ) -> Result<Vec<Option<DecodedValue>>, MdfError> {
        if channel.is_virtual() {
            return self.virtual_values(group, start, count, conversion);
        }
        if channel.channel_type == 1 {
            return self.read_vlsd_window_values(group, channel, conversion, start, count, reader);
        }
        let record_size = Self::checked_record_size(group)?;
        let temp_cb = channel.to_channel_block();
        let mut values = Vec::with_capacity((count as usize).min(1 << 24));
        Self::for_each_window_section(reader, group, record_size, start, count, |data| {
            Self::decode_records_to_values(data, record_size, group, conversion, &temp_cb, &mut values)
        })?;
        Ok(values)
    }

    /// `f64` variant of [`window_values`](Self::window_values) (invalid or
    /// non-numeric samples are NaN).
    fn window_values_f64<R: ByteRangeReader<Error = MdfError>>(
        &self,
        group: &IndexedChannelGroup,
        channel: &IndexedChannel,
        conversion: Option<&ConversionBlock>,
        start: u64,
        count: u64,
        reader: &mut R,
    ) -> Result<Vec<f64>, MdfError> {
        if channel.is_virtual() || channel.channel_type == 1 {
            let vals = self.window_values(group, channel, conversion, start, count, reader)?;
            return Ok(Self::vlsd_values_to_f64(vals));
        }
        let record_size = Self::checked_record_size(group)?;
        let temp_cb = channel.to_decode_only_channel_block();
        let linear_coeffs = Self::get_linear_coeffs(conversion);
        let mut values = Vec::with_capacity((count as usize).min(1 << 24));
        Self::for_each_window_section(reader, group, record_size, start, count, |data| {
            Self::decode_records_to_f64(data, record_size, group, channel, conversion, &temp_cb, linear_coeffs, conversion.is_some(), &mut values)
        })?;
        Ok(values)
    }

    /// Call `f` with the bytes of the records `[start, start + count)` of
    /// `group`, one slice per data block the window touches.
    fn for_each_window_section<R, F>(
        reader: &mut R,
        group: &IndexedChannelGroup,
        record_size: usize,
        start: u64,
        count: u64,
        mut f: F,
    ) -> Result<(), MdfError>
    where
        R: ByteRangeReader<Error = MdfError>,
        F: FnMut(&[u8]) -> Result<(), MdfError>,
    {
        let end = start + count;
        let mut block_start = 0u64;
        // A probing reader (the wasm fragment driver) records every missing
        // block of the window in one pass instead of stopping at the first.
        let mut first_err = None;
        for block in &group.data_blocks {
            if block_start >= end {
                break;
            }
            if block.is_compressed {
                return Err(MdfError::BlockSerializationError(
                    "Compressed blocks not yet supported in index reader".to_string(),
                ));
            }
            let block_end = block_start + Self::records_in_block(block, record_size)?;
            let (from, to) = (start.max(block_start), end.min(block_end));
            if from < to {
                let rel = (from - block_start) * record_size as u64;
                let len = (to - from) * record_size as u64;
                // Verify the block header like the full read path does (the
                // header wins over the index): a window starting at the
                // block's first record reads header and data in one request.
                let read = if rel == 0 {
                    reader.read_range(block.file_offset, 24 + len).map(|mut bytes| {
                        let data = bytes.split_off(24.min(bytes.len()));
                        (bytes, data)
                    })
                } else {
                    let header = reader.read_range(block.file_offset, 24);
                    let data = reader.read_range(block.file_offset + 24 + rel, len);
                    header.and_then(|h| data.map(|d| (h, d)))
                };
                match read {
                    Ok((header, data)) if first_err.is_none() => {
                        let real_len = Self::verified_data_len(Some(&header), block)?;
                        if rel + len > real_len {
                            return Err(MdfError::BlockSerializationError(format!(
                                "data block at offset {} holds {} data bytes but the index \
                                 expects at least {} (inconsistent file; rebuild the index)",
                                block.file_offset, real_len, rel + len
                            )));
                        }
                        f(&data)?
                    }
                    Ok(_) => {}
                    Err(e) if reader.is_probing() => {
                        first_err.get_or_insert(e);
                    }
                    Err(e) => return Err(e),
                }
            }
            block_start = block_end;
        }
        if let Some(e) = first_err {
            return Err(e);
        }
        if block_start < end {
            return Err(MdfError::BlockSerializationError(format!(
                "record window ending at {} exceeds the {} records held by the data blocks",
                end, block_start
            )));
        }
        Ok(())
    }

    /// Records held by a group's data blocks.
    fn stored_records(group: &IndexedChannelGroup) -> Result<u64, MdfError> {
        let record_size = Self::checked_record_size(group)?;
        let mut total = 0u64;
        for block in &group.data_blocks {
            total = total.saturating_add(Self::records_in_block(block, record_size)?);
        }
        Ok(total)
    }

    fn group_and_channel(&self, g: usize, c: usize) -> Result<(&IndexedChannelGroup, &IndexedChannel), MdfError> {
        let group = self.channel_groups.get(g)
            .ok_or_else(|| MdfError::BlockSerializationError("Invalid group index".to_string()))?;
        let channel = group.channels.get(c)
            .ok_or_else(|| MdfError::BlockSerializationError("Invalid channel index".to_string()))?;
        Ok((group, channel))
    }

    fn check_window(group: &IndexedChannelGroup, start: u64, count: u64) -> Result<(), MdfError> {
        match start.checked_add(count) {
            Some(end) if end <= group.record_count => Ok(()),
            _ => Err(MdfError::BlockSerializationError(format!(
                "record window starting at {} for {} records exceeds the group's {} records",
                start, count, group.record_count
            ))),
        }
    }

    /// `(group, channel)` of the time axis for `(g, c)`: its master, or the
    /// channel itself when it *is* the master.
    fn time_axis_location(&self, g: usize, c: usize) -> Option<(usize, usize)> {
        match self.master_location(g, c) {
            Some(m) => Some(m),
            None => self.channel_groups.get(g)?.channels.get(c)?.is_master().then_some((g, c)),
        }
    }

    /// Record window `(start, count)` of the group owning `(g, c)` whose
    /// master (time) values lie in `[t_start, t_end]` (either bound optional).
    ///
    /// The master must be non-decreasing, as MDF requires for a time master.
    /// It is searched rather than read (see [`search_time_window`], shared
    /// with the in-memory reader so both select the same records): each step reads 16
    /// single records, so a window is found in a handful of small reads
    /// (`log16(records)` rounds per bound). With a probing reader (the wasm
    /// fragment driver) both bounds' probes of a round are attempted before the
    /// first miss is returned, so every gap of the round is recorded at once.
    pub(crate) fn record_window_for_time<R: ByteRangeReader<Error = MdfError>>(
        &self,
        g: usize,
        c: usize,
        t_start: Option<f64>,
        t_end: Option<f64>,
        reader: &mut R,
    ) -> Result<(u64, u64), MdfError> {
        let (group, channel) = self.group_and_channel(g, c)?;
        let Some((mg, m)) = self.time_axis_location(g, c) else {
            // Same rule as the in-memory reader (`types::slice_signal`): an
            // empty group selects nothing, otherwise a master is required.
            if group.record_count == 0 {
                return Ok((0, 0));
            }
            return Err(MdfError::InvalidArgument(format!(
                "channel '{}' has no master (time) channel; cannot select by time",
                channel.name.as_deref().unwrap_or_default()
            )));
        };
        let (mgroup, mchannel) = self.group_and_channel(mg, m)?;
        let n = group.record_count.min(mgroup.record_count);
        let conversion = Self::resolve_conversion(mchannel, reader)?;
        search_time_window(n, t_start, t_end, |i| {
            Ok(self.window_values_f64(mgroup, mchannel, conversion.as_ref(), i, 1, reader)?[0])
        })
    }

    /// Resolve a channel's conversion for reading.
    ///
    /// Prefers a conversion already resolved into the index (local-file /
    /// in-memory builds, and older serialized indexes). Otherwise — the remote
    /// / range-reader build path, which records only
    /// [`IndexedChannel::conversion_addr`] — it fetches the `##CC` block and
    /// resolves its dependency chain through `reader`, exactly when the caller
    /// asks to read values. Returns `None` when the channel has no conversion.
    fn resolve_conversion<R: ByteRangeReader<Error = MdfError>>(
        channel: &IndexedChannel,
        reader: &mut R,
    ) -> Result<Option<ConversionBlock>, MdfError> {
        if let Some(conv) = &channel.conversion {
            return Ok(Some(conv.clone()));
        }
        if channel.conversion_addr == 0 {
            return Ok(None);
        }
        let addr = channel.conversion_addr;
        let header_bytes = reader.read_range(addr, 24)?;
        let header = BlockHeader::from_bytes(&header_bytes)?;
        if header.id != "##CC" {
            return Err(MdfError::BlockIDError {
                actual: header.id,
                expected: "##CC".to_string(),
            });
        }
        let full = reader.read_range(addr, header.block_len)?;
        let mut cc = ConversionBlock::from_bytes(&full)?;
        cc.resolve_all_dependencies_via_reader(reader, addr)?;
        Ok(Some(cc))
    }

    /// The conversion a read applies: none for a `raw` read (the stored
    /// values are wanted, so a deferred conversion is not even fetched),
    /// else [`resolve_conversion`](Self::resolve_conversion).
    fn read_conversion<R: ByteRangeReader<Error = MdfError>>(
        channel: &IndexedChannel,
        reader: &mut R,
        raw: bool,
    ) -> Result<Option<ConversionBlock>, MdfError> {
        if raw {
            return Ok(None);
        }
        Self::resolve_conversion(channel, reader)
    }

    /// Resolve the conversion of the channel at `(g, c)` using `reader`,
    /// following the same lazy rules as the read paths. Crate-visible so the
    /// wasm bindings can drive fragment-based conversion resolution: pointing a
    /// gap-reporting reader at this lets the JS side discover exactly which
    /// conversion-block byte ranges it must fetch before a fragment read.
    #[allow(dead_code)] // used by the wasm bindings (wasm feature)
    pub(crate) fn resolve_channel_conversion<R: ByteRangeReader<Error = MdfError>>(
        &self,
        g: usize,
        c: usize,
        reader: &mut R,
    ) -> Result<Option<ConversionBlock>, MdfError> {
        let channel = self
            .channel_groups
            .get(g)
            .and_then(|grp| grp.channels.get(c))
            .ok_or_else(|| {
                MdfError::BlockSerializationError("Invalid channel index".to_string())
            })?;
        Self::resolve_conversion(channel, reader)
    }

    /// Extract linear conversion coefficients (a, b) for inline application.
    fn get_linear_coeffs(conversion: Option<&ConversionBlock>) -> Option<(f64, f64)> {
        conversion.and_then(|conv| {
            if conv.cc_type == ConversionType::Linear && conv.cc_val.len() >= 2 {
                Some((conv.cc_val[0], conv.cc_val[1]))
            } else {
                None
            }
        })
    }

    /// Read values for a regular (non-VLSD) channel using byte range reader
    fn read_regular_channel_values<R: ByteRangeReader<Error = MdfError>>(
        &self,
        group: &IndexedChannelGroup,
        channel: &IndexedChannel,
        conversion: Option<&ConversionBlock>,
        reader: &mut R,
    ) -> Result<Vec<Option<DecodedValue>>, MdfError> {
        let record_size = Self::checked_record_size(group)?;
        let mut total_records: usize = 0;
        for data_block in &group.data_blocks {
            if data_block.is_compressed {
                return Err(MdfError::BlockSerializationError(
                    "Compressed blocks not yet supported in index reader".to_string()
                ));
            }
            total_records += Self::records_in_block(data_block, record_size)? as usize;
        }
        // Cap the pre-allocation: `total_records` derives from index-supplied
        // block sizes, and a forged value must not abort on allocation. The
        // vector still grows as needed; real reads fail earlier at the reader.
        let mut values = Vec::with_capacity(total_records.min(1 << 24));
        let temp_cb = channel.to_channel_block();

        Self::for_each_data_section(reader, &group.data_blocks, |block_data| {
            Self::decode_records_to_values(block_data, record_size, group, conversion, &temp_cb, &mut values)
        })?;

        Ok(values)
    }

    /// Read values for a VLSD channel (channel type 1) via a byte-range reader.
    ///
    /// The channel's fixed record field holds an 8-byte little-endian virtual
    /// offset into the concatenation of the `##SD` fragments' data sections;
    /// at that offset lives one `[u32 length][payload]` entry. This resolves
    /// each record's offset into the captured fragment chain and decodes the
    /// payload, preserving one value per record so [`Signal`] timestamps stay
    /// aligned and per-record invalidation can be honoured.
    fn read_vlsd_channel_values<R: ByteRangeReader<Error = MdfError>>(
        &self,
        group: &IndexedChannelGroup,
        channel: &IndexedChannel,
        conversion: Option<&ConversionBlock>,
        reader: &mut R,
    ) -> Result<Vec<Option<DecodedValue>>, MdfError> {
        Self::check_vlsd_readable(group, channel)?;

        // Fetch each SD fragment's data section, tracking each fragment's
        // virtual start offset in the concatenated stream.
        let mut fragments: Vec<Vec<u8>> = Vec::with_capacity(channel.vlsd_data_blocks.len());
        let mut frag_starts: Vec<u64> = Vec::with_capacity(channel.vlsd_data_blocks.len());
        let mut running: u64 = 0;
        for db in &channel.vlsd_data_blocks {
            let data_len = Self::data_section_size(db)?;
            let bytes = reader.read_range(db.file_offset + 24, data_len)?;
            frag_starts.push(running);
            running = running.checked_add(bytes.len() as u64).ok_or_else(|| {
                MdfError::BlockSerializationError(
                    "VLSD ##SD chain total size overflows the address space".to_string(),
                )
            })?;
            fragments.push(bytes);
        }
        let stream_len = running;

        let record_size = Self::checked_record_size(group)?;
        let record_id_len = group.record_id_len as usize;
        let cg_data_bytes = group.record_size;
        let has_invalidation = group.invalidation_bytes > 0;
        let all_invalid = channel.flags & 0x1 != 0;
        let offset_pos = record_id_len + channel.byte_offset as usize;

        // A fixed-record channel block (data == 0) drives the validity check;
        // a separate VLSD block (data != 0) drives payload decoding.
        let validity_cb = channel.to_channel_block();
        let mut payload_cb = channel.to_channel_block();
        payload_cb.data = 1;

        let mut total_records: usize = 0;
        for data_block in &group.data_blocks {
            total_records += Self::records_in_block(data_block, record_size)? as usize;
        }
        let mut values = Vec::with_capacity(total_records.min(1 << 24));

        Self::for_each_data_section(reader, &group.data_blocks, |block_data| {
            if block_data.len() % record_size != 0 {
                return Err(MdfError::BlockSerializationError(format!(
                    "data block length {} is not a multiple of the {}-byte record — \
                     record spans data block fragments, which is unsupported",
                    block_data.len(),
                    record_size
                )));
            }
            let record_count = block_data.len() / record_size;
            for i in 0..record_count {
                let record = &block_data[i * record_size..(i + 1) * record_size];

                if all_invalid
                    || (has_invalidation
                        && !check_value_validity(record, record_id_len, cg_data_bytes, &validity_cb))
                {
                    values.push(None);
                    continue;
                }

                // Read the inline 8-byte virtual offset.
                if offset_pos + 8 > record.len() {
                    return Err(MdfError::TooShortBuffer {
                        actual: record.len(),
                        expected: offset_pos + 8,
                        file: file!(),
                        line: line!(),
                    });
                }
                let virtual_offset =
                    u64::from_le_bytes(record[offset_pos..offset_pos + 8].try_into().unwrap());

                if virtual_offset >= stream_len {
                    return Err(MdfError::BlockSerializationError(format!(
                        "VLSD inline offset {} is past the end of the {}-byte signal-data stream",
                        virtual_offset, stream_len
                    )));
                }

                // Locate the fragment whose virtual span contains the offset.
                let frag_idx = frag_starts.partition_point(|&s| s <= virtual_offset) - 1;
                let frag = &fragments[frag_idx];
                let pos = (virtual_offset - frag_starts[frag_idx]) as usize;

                if pos + 4 > frag.len() {
                    return Err(MdfError::BlockSerializationError(format!(
                        "VLSD entry at virtual offset {} is truncated: no room for its \
                         length prefix in fragment {}",
                        virtual_offset, frag_idx
                    )));
                }
                let len = u32::from_le_bytes(frag[pos..pos + 4].try_into().unwrap()) as usize;
                let start = pos + 4;
                let end = match start.checked_add(len) {
                    Some(e) if e <= frag.len() => e,
                    _ => {
                        return Err(MdfError::BlockSerializationError(format!(
                            "VLSD entry at virtual offset {} declares length {} which \
                             exceeds fragment {} (size {})",
                            virtual_offset, len, frag_idx, frag.len()
                        )));
                    }
                };
                let payload = &frag[start..end];

                if let Some(value) = decode_channel_value(payload, 0, &payload_cb) {
                    let final_value = if let Some(conversion) = conversion {
                        conversion.apply_decoded(value, &[])?
                    } else {
                        value
                    };
                    values.push(Some(final_value));
                } else {
                    values.push(None);
                }
            }
            Ok(())
        })?;

        Ok(values)
    }

    /// Refuse VLSD channels the index reader cannot decode (compressed
    /// fragments, missing signal data, a malformed offset field).
    fn check_vlsd_readable(group: &IndexedChannelGroup, channel: &IndexedChannel) -> Result<(), MdfError> {
        // Compressed fragments (either the fixed records or the SD stream) are
        // not decodable yet.
        if group.data_blocks.iter().any(|b| b.is_compressed)
            || channel.vlsd_data_blocks.iter().any(|b| b.is_compressed)
        {
            return Err(MdfError::BlockSerializationError(
                "Compressed blocks not yet supported in index reader".to_string(),
            ));
        }

        // A VLSD channel without a data link has no signal data at all —
        // rebuilding the index cannot help, so distinguish it from an index
        // built before VLSD chains were captured.
        if channel.vlsd_data_blocks.is_empty() {
            if channel.vlsd_data_address.is_none() {
                return Err(MdfError::BlockSerializationError(format!(
                    "VLSD channel '{}' has no signal data (its ##SD data link is 0)",
                    channel.name.as_deref().unwrap_or("<unnamed>")
                )));
            }
            return Err(MdfError::BlockSerializationError(format!(
                "VLSD channel '{}' has no signal-data fragments recorded in the index; \
                 rebuild the index with this version to read it",
                channel.name.as_deref().unwrap_or("<unnamed>")
            )));
        }

        // The VLSD offset field is fixed at 64 bits by the spec and is
        // byte-aligned; a nonzero bit offset would silently shift every
        // resolved stream offset.
        if channel.bit_count != 64 || channel.bit_offset != 0 {
            return Err(MdfError::BlockSerializationError(format!(
                "VLSD channel '{}' has a {}-bit record field at bit offset {}; the \
                 inline VLSD offset must be a byte-aligned 64-bit field",
                channel.name.as_deref().unwrap_or("<unnamed>"),
                channel.bit_count,
                channel.bit_offset
            )));
        }
        Ok(())
    }

    /// Window read of a VLSD channel: decode only records
    /// `[start, start + count)`, fetching their inline offsets and then just
    /// the slice of the signal-data stream those offsets point into (one
    /// read, plus one more if the last entry runs past it) — not the whole
    /// stream.
    fn read_vlsd_window_values<R: ByteRangeReader<Error = MdfError>>(
        &self,
        group: &IndexedChannelGroup,
        channel: &IndexedChannel,
        conversion: Option<&ConversionBlock>,
        start: u64,
        count: u64,
        reader: &mut R,
    ) -> Result<Vec<Option<DecodedValue>>, MdfError> {
        Self::check_vlsd_readable(group, channel)?;
        let record_size = Self::checked_record_size(group)?;
        let record_id_len = group.record_id_len as usize;
        let has_invalidation = group.invalidation_bytes > 0;
        let all_invalid = channel.flags & 0x1 != 0;
        let offset_pos = record_id_len + channel.byte_offset as usize;
        let validity_cb = channel.to_channel_block();
        let mut payload_cb = channel.to_channel_block();
        payload_cb.data = 1;

        // Inline offsets of the window's records (None = invalid sample).
        let mut offsets: Vec<Option<u64>> = Vec::with_capacity((count as usize).min(1 << 24));
        Self::for_each_window_section(reader, group, record_size, start, count, |data| {
            for record in data.chunks_exact(record_size) {
                if all_invalid
                    || (has_invalidation
                        && !check_value_validity(record, record_id_len, group.record_size, &validity_cb))
                {
                    offsets.push(None);
                    continue;
                }
                let field = record.get(offset_pos..offset_pos + 8).ok_or(MdfError::TooShortBuffer {
                    actual: record.len(),
                    expected: offset_pos + 8,
                    file: file!(),
                    line: line!(),
                })?;
                offsets.push(Some(u64::from_le_bytes(field.try_into().unwrap())));
            }
            Ok(())
        })?;

        // Virtual start of each ##SD fragment in the concatenated stream.
        let mut frag_starts = Vec::with_capacity(channel.vlsd_data_blocks.len());
        let mut stream_len = 0u64;
        for db in &channel.vlsd_data_blocks {
            frag_starts.push(stream_len);
            stream_len = stream_len.checked_add(Self::data_section_size(db)?).ok_or_else(|| {
                MdfError::BlockSerializationError("VLSD ##SD chain total size overflows the address space".to_string())
            })?;
        }
        let present = || offsets.iter().flatten().copied();
        let (Some(lo), Some(hi)) = (present().min(), present().max()) else {
            return Ok(vec![None; offsets.len()]);
        };
        let prefix_end = hi.checked_add(4).filter(|&e| e <= stream_len).ok_or_else(|| {
            MdfError::BlockSerializationError(format!(
                "VLSD inline offset {hi} leaves no room for a length prefix in the {stream_len}-byte signal-data stream"
            ))
        })?;
        let mut buf = Self::read_vlsd_stream(reader, channel, &frag_starts, lo, prefix_end - lo)?;
        let entry_len = |buf: &[u8], off: u64| -> usize {
            let p = (off - lo) as usize;
            u32::from_le_bytes(buf[p..p + 4].try_into().unwrap()) as usize
        };
        let end = present().map(|off| off + 4 + entry_len(&buf, off) as u64).max().unwrap_or(prefix_end);
        if end > stream_len {
            return Err(MdfError::BlockSerializationError(format!(
                "VLSD entry ending at virtual offset {end} is past the end of the {stream_len}-byte signal-data stream"
            )));
        }
        if end > prefix_end {
            let more = Self::read_vlsd_stream(reader, channel, &frag_starts, prefix_end, end - prefix_end)?;
            buf.extend_from_slice(&more);
        }

        let mut values = Vec::with_capacity(offsets.len());
        for off in &offsets {
            let Some(off) = *off else {
                values.push(None);
                continue;
            };
            // Like the full read, refuse an entry that does not fit in the
            // ##SD fragment it starts in.
            let frag_idx = frag_starts.partition_point(|&s| s <= off) - 1;
            let frag_end = frag_starts.get(frag_idx + 1).copied().unwrap_or(stream_len);
            let len = entry_len(&buf, off);
            if off + 4 + len as u64 > frag_end {
                return Err(MdfError::BlockSerializationError(format!(
                    "VLSD entry at virtual offset {} declares length {} which exceeds fragment {} (size {})",
                    off,
                    len,
                    frag_idx,
                    frag_end - frag_starts[frag_idx]
                )));
            }
            let p = (off - lo) as usize + 4;
            let payload = &buf[p..p + entry_len(&buf, off)];
            values.push(match decode_channel_value(payload, 0, &payload_cb) {
                Some(value) => Some(match conversion {
                    Some(conversion) => conversion.apply_decoded(value, &[])?,
                    None => value,
                }),
                None => None,
            });
        }
        Ok(values)
    }

    /// Bytes `[from, from + len)` of a VLSD channel's concatenated
    /// signal-data stream, read from the ##SD fragments they fall in.
    fn read_vlsd_stream<R: ByteRangeReader<Error = MdfError>>(
        reader: &mut R,
        channel: &IndexedChannel,
        frag_starts: &[u64],
        from: u64,
        len: u64,
    ) -> Result<Vec<u8>, MdfError> {
        let to = from + len;
        let mut out = Vec::with_capacity(len as usize);
        // Attempt every fragment's read before failing, so a probing reader
        // records all gaps in one pass.
        let mut first_err = None;
        for (db, &fs) in channel.vlsd_data_blocks.iter().zip(frag_starts) {
            let fe = fs + Self::data_section_size(db)?;
            let (a, b) = (from.max(fs), to.min(fe));
            if a >= b {
                continue;
            }
            match reader.read_range(db.file_offset + 24 + (a - fs), b - a) {
                // A custom reader that returns fewer bytes (e.g. clamped at
                // EOF) must surface as an error, not an out-of-bounds slice.
                Ok(bytes) if bytes.len() as u64 != b - a => {
                    return Err(MdfError::TooShortBuffer {
                        actual: bytes.len(),
                        expected: (b - a) as usize,
                        file: file!(),
                        line: line!(),
                    });
                }
                Ok(bytes) => out.extend_from_slice(&bytes),
                Err(e) if reader.is_probing() => {
                    first_err.get_or_insert(e);
                }
                Err(e) => return Err(e),
            }
        }
        if let Some(e) = first_err {
            return Err(e);
        }
        Ok(out)
    }

    /// Map VLSD decoded values to `f64`, matching `Channel::values`:
    /// numeric variants convert, everything else (strings, bytes, invalid) is
    /// NaN.
    fn vlsd_values_to_f64(values: Vec<Option<DecodedValue>>) -> Vec<f64> {
        values
            .into_iter()
            .map(|v| match v {
                Some(DecodedValue::Float(f)) => f,
                Some(DecodedValue::UnsignedInteger(u)) => u as f64,
                Some(DecodedValue::SignedInteger(i)) => i as f64,
                _ => f64::NAN,
            })
            .collect()
    }

    /// Decode records from a data block slice into values vec.
    /// Shared by both the reader-based and slice-based paths.
    fn decode_records_to_values(
        block_data: &[u8],
        record_size: usize,
        group: &IndexedChannelGroup,
        conversion: Option<&ConversionBlock>,
        temp_cb: &crate::blocks::channel_block::ChannelBlock,
        values: &mut Vec<Option<DecodedValue>>,
    ) -> Result<(), MdfError> {
        if record_size == 0 {
            return Err(MdfError::BlockSerializationError(
                "invalid index: record size is 0".to_string(),
            ));
        }
        if !block_data.len().is_multiple_of(record_size) {
            return Err(MdfError::BlockSerializationError(format!(
                "data block length {} is not a multiple of the {}-byte record — \
                 record spans data block fragments, which is unsupported",
                block_data.len(),
                record_size
            )));
        }
        let record_count = block_data.len() / record_size;
        let record_id_len = group.record_id_len as usize;
        let cg_data_bytes = group.record_size;

        for i in 0..record_count {
            let record = &block_data[i * record_size..(i + 1) * record_size];
            if let Some(decoded) = decode_channel_value_with_validity(
                record, record_id_len, cg_data_bytes, temp_cb,
            ) {
                if decoded.is_valid {
                    let final_value = if let Some(conversion) = conversion {
                        conversion.apply_decoded(decoded.value, &[])?
                    } else {
                        decoded.value
                    };
                    values.push(Some(final_value));
                } else {
                    values.push(None);
                }
            } else {
                values.push(None);
            }
        }
        Ok(())
    }

    /// Decode records from a data block as f64 values.
    /// Uses the fast decode_f64_from_record path and applies conversions inline.
    /// For channels without invalidation bytes, skips validity checking entirely.
    fn decode_records_to_f64(
        block_data: &[u8],
        record_size: usize,
        group: &IndexedChannelGroup,
        channel: &IndexedChannel,
        conversion: Option<&ConversionBlock>,
        temp_cb: &crate::blocks::channel_block::ChannelBlock,
        linear_coeffs: Option<(f64, f64)>,
        has_conversion: bool,
        values: &mut Vec<f64>,
    ) -> Result<(), MdfError> {
        if record_size == 0 {
            return Err(MdfError::BlockSerializationError(
                "invalid index: record size is 0".to_string(),
            ));
        }
        if !block_data.len().is_multiple_of(record_size) {
            return Err(MdfError::BlockSerializationError(format!(
                "data block length {} is not a multiple of the {}-byte record — \
                 record spans data block fragments, which is unsupported",
                block_data.len(),
                record_size
            )));
        }
        let record_count = block_data.len() / record_size;
        let record_id_len = group.record_id_len as usize;
        let cg_data_bytes = group.record_size;
        let has_invalidation = group.invalidation_bytes > 0;

        // MDF 4.1: cn_flags bit 0 ("all values invalid") applies regardless
        // of whether the group carries invalidation bytes. Short-circuit to
        // NaN for every sample, matching decode_records_to_values.
        if channel.flags & 0x1 != 0 {
            values.extend(std::iter::repeat_n(f64::NAN, record_count));
            return Ok(());
        }

        if !has_invalidation && !has_conversion {
            // Fastest path: no invalidation, no conversion - just decode f64 directly
            for i in 0..record_count {
                let record = &block_data[i * record_size..(i + 1) * record_size];
                values.push(decode_f64_from_record(record, record_id_len, temp_cb));
            }
        } else if !has_invalidation && linear_coeffs.is_some() {
            // Fast path: no invalidation, linear conversion
            let (a, b) = linear_coeffs.unwrap();
            for i in 0..record_count {
                let record = &block_data[i * record_size..(i + 1) * record_size];
                let raw = decode_f64_from_record(record, record_id_len, temp_cb);
                values.push(a + b * raw);
            }
        } else if !has_invalidation {
            // No invalidation but non-linear conversion - need full decode for conversion
            for i in 0..record_count {
                let record = &block_data[i * record_size..(i + 1) * record_size];
                let raw = decode_f64_from_record(record, record_id_len, temp_cb);
                if let Some(coeffs) = linear_coeffs {
                    values.push(coeffs.0 + coeffs.1 * raw);
                } else if has_conversion {
                    // Need to decode via DecodedValue for complex conversions
                    if let Some(decoded) = decode_channel_value_with_validity(
                        record, record_id_len, cg_data_bytes, temp_cb,
                    ) {
                        match conversion.unwrap().apply_decoded(decoded.value, &[])? {
                            DecodedValue::Float(v) => values.push(v),
                            DecodedValue::UnsignedInteger(v) => values.push(v as f64),
                            DecodedValue::SignedInteger(v) => values.push(v as f64),
                            _ => values.push(f64::NAN),
                        }
                    } else {
                        values.push(f64::NAN);
                    }
                } else {
                    values.push(raw);
                }
            }
        } else {
            // Has invalidation bytes - must check validity
            for i in 0..record_count {
                let record = &block_data[i * record_size..(i + 1) * record_size];
                let is_valid = check_value_validity(record, record_id_len, cg_data_bytes, temp_cb);
                if is_valid {
                    let raw = decode_f64_from_record(record, record_id_len, temp_cb);
                    if let Some((a, b)) = linear_coeffs {
                        values.push(a + b * raw);
                    } else if has_conversion {
                        if let Some(decoded) = decode_channel_value_with_validity(
                            record, record_id_len, cg_data_bytes, temp_cb,
                        ) {
                            match conversion.unwrap().apply_decoded(decoded.value, &[])? {
                                DecodedValue::Float(v) => values.push(v),
                                DecodedValue::UnsignedInteger(v) => values.push(v as f64),
                                DecodedValue::SignedInteger(v) => values.push(v as f64),
                                _ => values.push(f64::NAN),
                            }
                        } else {
                            values.push(f64::NAN);
                        }
                    } else {
                        values.push(raw);
                    }
                } else {
                    values.push(f64::NAN);
                }
            }
        }
        Ok(())
    }

    // ----- metadata (cross-language contract) -----------------------------

    /// Metadata of every channel group, in file order.
    ///
    /// The raw indexed structures (record layout, data-block locations) are
    /// available through the public [`channel_groups`](Self::channel_groups)
    /// field.
    pub fn groups(&self) -> Result<Vec<GroupInfo>, MdfError> {
        Ok((0..self.channel_groups.len()).map(|g| self.group_info(g)).collect())
    }

    /// Metadata of the first channel group named `name`, or `None`.
    ///
    /// The groups of a column-oriented (MDF 4.2) file are merged back into
    /// their source group, as [`Mdf::group`] does.
    pub fn group(&self, name: &str) -> Result<Option<GroupInfo>, MdfError> {
        let names = self.group_names();
        let Some(first) = names.iter().position(|n| n.as_deref() == Some(name)) else {
            return Ok(None);
        };
        let channel_counts: Vec<usize> = self.channel_groups.iter().map(|g| g.channels.len()).collect();
        let members = logical_group_members(&names, &self.time_groups(), &channel_counts, first);
        Ok(Some(merge_group_infos(
            self.group_info(first),
            members.iter().map(|&m| self.group_info(m)),
        )))
    }

    fn group_names(&self) -> Vec<Option<String>> {
        self.channel_groups.iter().map(|g| g.name.clone()).collect()
    }

    /// For each group, the group holding its time axis: itself for a local
    /// master, the remote master group of an MDF 4.2 column-oriented group,
    /// `None` when untimed.
    fn time_groups(&self) -> Vec<Option<usize>> {
        (0..self.channel_groups.len()).map(|g| self.time_group(g)).collect()
    }

    fn time_group(&self, g: usize) -> Option<usize> {
        let group = self.channel_groups.get(g)?;
        if group.master_channel().is_some() {
            return Some(g);
        }
        group
            .master_group
            .filter(|&m| m != g && self.channel_groups.get(m).is_some_and(|mg| mg.master_channel().is_some()))
    }

    /// Metadata of the first channel named `name`, or `None`. Pass `group` to
    /// look only in the group(s) with that name.
    pub fn channel(&self, name: &str, group: Option<&str>) -> Result<Option<ChannelInfo>, MdfError> {
        Ok(self.indexed_channel(name, group).map(IndexedChannel::info))
    }

    /// Names of every named channel across all groups (duplicates kept).
    pub fn channel_names(&self) -> Result<Vec<String>, MdfError> {
        Ok(self
            .channel_groups
            .iter()
            .flat_map(|g| g.channels.iter())
            .filter_map(|c| c.name.clone())
            .collect())
    }

    /// Measurement start time in nanoseconds since the Unix epoch, or `None`
    /// if the file header does not record one.
    pub fn start_time_ns(&self) -> Option<u64> {
        self.start_time_ns
    }

    /// Size in bytes of the indexed MDF file.
    pub fn file_size(&self) -> u64 {
        self.file_size
    }

    /// The raw [`IndexedChannel`] of the first channel named `name` (in the
    /// group(s) named `group`, when given). Rust-only access to the record
    /// layout behind [`channel`](Self::channel).
    pub fn indexed_channel(&self, name: &str, group: Option<&str>) -> Option<&IndexedChannel> {
        let (g, c) = self.locate_opt(name, group)?;
        self.channel_groups.get(g)?.channels.get(c)
    }

    fn group_info(&self, g: usize) -> GroupInfo {
        let group = &self.channel_groups[g];
        GroupInfo {
            name: group.name.clone(),
            comment: group.comment.clone(),
            record_count: group.record_count,
            channel_names: group.channels.iter().filter_map(|c| c.name.clone()).collect(),
            // A column-oriented (MDF 4.2) signal group reports the shared
            // time channel it references.
            master_channel: group
                .master_channel()
                .or_else(|| {
                    group
                        .master_group
                        .and_then(|mg| self.channel_groups.get(mg))
                        .and_then(|mg| mg.master_channel())
                })
                .and_then(|c| c.name.clone()),
            channels: group.channels.iter().map(IndexedChannel::info).collect(),
        }
    }

    /// Position of a channel by name, optionally restricted to a group name.
    pub(crate) fn locate_opt(&self, name: &str, group: Option<&str>) -> Option<(usize, usize)> {
        match group {
            Some(group) => self.locate_in(group, name),
            None => self.locate(name),
        }
    }

    /// [`locate_opt`](Self::locate_opt), erroring with `ChannelNotFound`.
    pub(crate) fn locate_checked(&self, name: &str, group: Option<&str>) -> Result<(usize, usize), MdfError> {
        self.locate_opt(name, group)
            .ok_or_else(|| MdfError::channel_not_found(name, group))
    }

    /// Resolve a channel name to its `(group_index, channel_index)` position.
    ///
    /// Returns the first match across all groups. Internal helper backing the
    /// name-based public methods.
    pub(crate) fn locate(&self, name: &str) -> Option<(usize, usize)> {
        for (g, group) in self.channel_groups.iter().enumerate() {
            for (c, channel) in group.channels.iter().enumerate() {
                if channel.name.as_deref() == Some(name) {
                    return Some((g, c));
                }
            }
        }
        None
    }

    /// Resolve a `(group name, channel name)` pair to indices.
    ///
    /// Every group carrying that name is searched (a column-oriented file has
    /// one channel group per signal, all named after the source group), then
    /// the time groups they reference under another name — a time axis shared
    /// by several source groups carries only one of their names.
    pub(crate) fn locate_in(&self, group: &str, name: &str) -> Option<(usize, usize)> {
        let named: Vec<usize> = (0..self.channel_groups.len())
            .filter(|&g| self.channel_groups[g].name.as_deref() == Some(group))
            .collect();
        let remote = named
            .iter()
            .filter_map(|&g| self.time_group(g))
            .filter(|&t| self.channel_groups[t].name.as_deref() != Some(group));
        named.iter().copied().chain(remote).find_map(|g| {
            self.channel_groups[g]
                .channels
                .iter()
                .position(|ch| ch.name.as_deref() == Some(name))
                .map(|c| (g, c))
        })
    }

    /// `(group, channel)` of the master (time) channel for the channel at
    /// `(g, c)`: the group's own master, or the remote master of an MDF 4.2
    /// column-oriented group. `None` when there is none or `(g, c)` is itself
    /// the master.
    pub(crate) fn master_location(&self, g: usize, c: usize) -> Option<(usize, usize)> {
        let grp = self.channel_groups.get(g)?;
        if let Some(m) = grp.channels.iter().position(|ch| ch.is_master()) {
            return (m != c).then_some((g, m));
        }
        let mg = grp.master_group?;
        let m = self.channel_groups.get(mg)?.channels.iter().position(|ch| ch.is_master())?;
        Some((mg, m))
    }

    /// Bind this index to a byte-range source for reading sample data.
    ///
    /// The returned [`MdfReader`] borrows the index and owns `reader`; read
    /// values by channel name without re-supplying the source each time.
    pub fn open<R: ByteRangeReader<Error = MdfError>>(&self, reader: R) -> MdfReader<'_, R> {
        MdfReader { index: self, reader }
    }

    /// Bind this index to a local file (via memory map) for reading.
    ///
    /// Convenience wrapper around [`MdfIndex::open`] using [`MmapRangeReader`].
    /// Not available on `wasm32-unknown-unknown`.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn open_file(&self, path: &str) -> Result<MdfReader<'_, MmapRangeReader>, MdfError> {
        Ok(self.open(MmapRangeReader { mmap: self.map_source_file(path)? }))
    }

    /// The data source `read` / `values` fetch sample bytes from, if any.
    pub fn source(&self) -> Option<&Source> {
        self.source.as_ref()
    }

    /// Attach (or replace) the data source used by `read` / `values`.
    ///
    /// Accepts a [`Source`] or a string: `http(s)://` URLs are read with range
    /// requests (with the `http` feature), anything else is a file path.
    pub fn set_source(&mut self, source: impl Into<Source>) {
        self.source = Some(source.into());
    }

    /// Detach the data source.
    pub fn clear_source(&mut self) {
        self.source = None;
    }

    // ----- data (cross-language contract) ---------------------------------

    /// Read a channel as a [`Signal`]: its values (conversions applied,
    /// `None` = invalid sample) paired with the group's time axis. For the
    /// master channel itself `timestamps` is empty.
    ///
    /// This is the lazy read path: bytes are fetched from the attached
    /// [`Source`] now, not at index build time. Errors with
    /// [`MdfError::ChannelNotFound`] if no such channel exists, or if no
    /// source is attached (see [`set_source`](Self::set_source)).
    ///
    /// `options` is `None` for the whole channel, or a [`ReadOptions`] with a
    /// group filter and/or a time or record window. A window fetches only the
    /// selected records: a time window is located by searching the master
    /// channel (a few single-record reads), not by downloading it.
    pub fn read<'o>(&self, name: &str, options: impl Into<Option<&'o ReadOptions>>) -> Result<Signal, MdfError> {
        let default = ReadOptions::default();
        let options = options.into().unwrap_or(&default);
        let window = options.window()?;
        let (g, c) = self.locate_checked(name, options.group_name())?;
        // Over a URL the channel and its time axis are fetched concurrently.
        #[cfg(feature = "http")]
        if let Source::Url(url) = self.require_source()? {
            let mut signals = self.read_many_url(url, &[(g, c)], window, options.raw)?;
            return signals.pop().ok_or_else(|| MdfError::BlockSerializationError("no signal read".to_string()));
        }
        if window == Window::All {
            return self.read_signal(g, c, options.raw);
        }
        let mut reader = self.source_reader(g, c, options.raw, true)?;
        let (start, count) = self.resolve_window_via(g, c, window, &mut reader)?;
        read_signal_window(self, g, c, start, count, options.raw, &mut reader)
    }

    /// Read several channels at once, with the same `options` for all of
    /// them: one [`Signal`] per name, in the order given.
    ///
    /// Equivalent to calling [`read`](Self::read) for each name, but each
    /// time axis shared by several of the channels is fetched and decoded
    /// once (in a column-oriented file every signal of a source group shares
    /// one), a time window is searched once per time axis, and over a URL
    /// every byte range of the whole batch is fetched concurrently. Errors
    /// with [`MdfError::ChannelNotFound`] — before fetching anything — if any
    /// name is unknown.
    pub fn read_many<'o, S: AsRef<str>>(
        &self,
        names: &[S],
        options: impl Into<Option<&'o ReadOptions>>,
    ) -> Result<Vec<Signal>, MdfError> {
        let default = ReadOptions::default();
        let options = options.into().unwrap_or(&default);
        let window = options.window()?;
        let targets = self.locate_all(names, options.group_name())?;
        if targets.is_empty() {
            return Ok(Vec::new());
        }
        #[cfg(all(target_arch = "wasm32", not(feature = "http")))]
        let _ = window;
        match self.require_source()? {
            #[cfg(not(target_arch = "wasm32"))]
            Source::File(path) => {
                let mmap = self.map_source_file(path)?;
                if window == Window::All {
                    return self.read_many_from_slice(&targets, options.raw, &mmap);
                }
                self.read_many_at(&targets, window, options.raw, &mut MmapRangeReader { mmap })
            }
            #[cfg(target_arch = "wasm32")]
            Source::File(_) => Err(MdfError::BlockSerializationError(
                "file sources are not available on wasm32".to_string(),
            )),
            #[cfg(feature = "http")]
            Source::Url(url) => self.read_many_url(url, &targets, window, options.raw),
        }
    }

    /// Read a numeric channel as plain `f64` values (no timestamps).
    /// Conversions are applied; invalid and non-numeric samples are `NaN`.
    /// `options` as for [`read`](Self::read).
    pub fn values<'o>(&self, name: &str, options: impl Into<Option<&'o ReadOptions>>) -> Result<Vec<f64>, MdfError> {
        let default = ReadOptions::default();
        let options = options.into().unwrap_or(&default);
        let window = options.window()?;
        let (g, c) = self.locate_checked(name, options.group_name())?;
        if window == Window::All {
            return self.read_values_f64_via_source(g, c, options.raw);
        }
        let mut reader = self.source_reader(g, c, options.raw, false)?;
        let (start, count) = self.resolve_window_via(g, c, window, &mut reader)?;
        self.values_f64_window(g, c, start, count, options.raw, &mut reader)
    }

    /// First and last master (time) value of the group holding `name`, or
    /// `None` for an empty group. Reads just two records. Errors if the group
    /// has no master channel.
    pub fn time_range(&self, name: &str, group: Option<&str>) -> Result<Option<TimeRange>, MdfError> {
        let (g, c) = self.locate_checked(name, group)?;
        // Over a URL only the master is read (in batched rounds), so skip
        // `source_reader`, which would also fetch channel `c`'s conversion.
        #[cfg(feature = "http")]
        if let Source::Url(url) = self.require_source()? {
            let mut http = self.http_source(url)?;
            return self.batched_reads(&mut http, |r| self.time_range_at(g, c, r));
        }
        // Only a file source is left here; `raw` would only matter for a URL.
        let mut reader = self.source_reader(g, c, false, true)?;
        self.time_range_at(g, c, &mut reader)
    }

    /// [`resolve_window`](Self::resolve_window) over a [`SourceReader`]: a
    /// time window over a URL is searched in batched rounds (see
    /// [`batched_reads`](Self::batched_reads)) instead of one blocking
    /// request per probe.
    fn resolve_window_via(
        &self,
        g: usize,
        c: usize,
        window: Window,
        reader: &mut SourceReader,
    ) -> Result<(u64, u64), MdfError> {
        match (window, reader) {
            #[cfg(feature = "http")]
            (Window::Time(..), SourceReader::Url(cached)) => {
                self.batched_reads(cached.inner_mut(), |r| self.resolve_window(g, c, window, r))
            }
            (_, reader) => self.resolve_window(g, c, window, reader),
        }
    }

    /// Run `op` against the bytes fetched so far, recording every range it
    /// could not read; fetch all of them **concurrently**, and run it again
    /// until it needs nothing more — the native twin of the wasm gap loop
    /// (`js/src/mdf-index.ts`). A time-window search then costs
    /// ~`log16(records)` rounds of parallel requests instead of one blocking
    /// round-trip per probed record (and per data-block header).
    #[cfg(feature = "http")]
    fn batched_reads<T>(
        &self,
        http: &mut HttpRangeReader,
        op: impl FnMut(&mut RecordingRangeReader<'_>) -> Result<T, MdfError>,
    ) -> Result<T, MdfError> {
        self.batched_reads_seeded(http, &mut FragmentStore::new(), op)
    }

    /// [`batched_reads`](Self::batched_reads) starting from bytes already
    /// fetched (`store`). Large gaps are split into
    /// [`PARALLEL_CHUNK_BYTES`] pieces so one big signal is also fetched over
    /// several connections at once.
    #[cfg(feature = "http")]
    fn batched_reads_seeded<T>(
        &self,
        http: &mut HttpRangeReader,
        store: &mut FragmentStore,
        mut op: impl FnMut(&mut RecordingRangeReader<'_>) -> Result<T, MdfError>,
    ) -> Result<T, MdfError> {
        for _ in 0..MAX_BATCH_ROUNDS {
            let mut recorder = RecordingRangeReader { store: &*store, misses: Vec::new(), whole_request: true };
            let result = op(&mut recorder);
            let misses = std::mem::take(&mut recorder.misses);
            if misses.is_empty() {
                return result;
            }
            let spans = split_spans(merge_ranges_bridging(misses, BATCH_BRIDGE_BYTES), PARALLEL_CHUNK_BYTES);
            let fetched = http.read_ranges_parallel(&spans)?;
            for ((offset, _), bytes) in spans.iter().zip(fetched) {
                store.push(*offset, bytes)?;
            }
        }
        Err(MdfError::BlockSerializationError(
            "batched read did not converge; the index or source may be inconsistent".to_string(),
        ))
    }

    /// The conversion `read` / `values` apply to channel `name`, fully
    /// resolved, or `None` when the channel has none.
    ///
    /// Indexes built over the network record only a conversion's location;
    /// it is then fetched through the attached source on demand.
    pub fn conversion(&self, name: &str, group: Option<&str>) -> Result<Option<ConversionInfo>, MdfError> {
        Ok(self.conversion_block(name, group)?.as_ref().map(ConversionInfo::from))
    }

    /// Locate every name (in the group(s) named `group`, when given), failing
    /// with `ChannelNotFound` on the first unknown one.
    pub(crate) fn locate_all<S: AsRef<str>>(&self, names: &[S], group: Option<&str>) -> Result<Vec<(usize, usize)>, MdfError> {
        names.iter().map(|name| self.locate_checked(name.as_ref(), group)).collect()
    }

    /// A [`Signal`] for channel `(g, c)` from its decoded parts.
    fn make_signal(&self, g: usize, c: usize, timestamps: Vec<f64>, values: Vec<Option<DecodedValue>>) -> Signal {
        let channel = &self.channel_groups[g].channels[c];
        Signal { name: channel.name.clone().unwrap_or_default(), unit: channel.unit.clone(), timestamps, values }
    }

    /// `read_many` of whole channels from an in-memory file (a mapped file
    /// source): the same decoding as [`read`](Self::read), each time axis once.
    #[cfg(not(target_arch = "wasm32"))]
    fn read_many_from_slice(&self, targets: &[(usize, usize)], raw: bool, data: &[u8]) -> Result<Vec<Signal>, MdfError> {
        let mut axes: HashMap<(usize, usize), Vec<f64>> = HashMap::new();
        let mut out = Vec::with_capacity(targets.len());
        for &(g, c) in targets {
            let values = self.read_channel_values_from_slice(g, c, raw, data)?;
            let timestamps = match self.master_location(g, c) {
                Some(m) => match axes.get(&m) {
                    Some(axis) => axis.clone(),
                    None => {
                        let axis = self.read_channel_values_from_slice_as_f64(m.0, m.1, false, data)?;
                        axes.insert(m, axis.clone());
                        axis
                    }
                },
                None => Vec::new(),
            };
            out.push(self.make_signal(g, c, timestamps, values));
        }
        Ok(out)
    }

    /// `read_many` over any byte-range reader — the shared core of the URL,
    /// wasm-fragment and [`MdfReader`] paths.
    ///
    /// With a probing reader
    /// ([`RecordingRangeReader`](crate::fragments::RecordingRangeReader))
    /// every channel is attempted even after one fails, so the gaps of the
    /// whole batch are recorded in one pass, and the first error is
    /// returned; any other reader stops at the first error. Within the call, a window is resolved once per time axis and
    /// each time axis (or its window) is decoded once.
    pub(crate) fn read_many_at<R: ByteRangeReader<Error = MdfError>>(
        &self,
        targets: &[(usize, usize)],
        window: Window,
        raw: bool,
        reader: &mut R,
    ) -> Result<Vec<Signal>, MdfError> {
        let mut windows = WindowCache::new();
        let mut axes = AxisCache::new();
        let mut out = Vec::with_capacity(targets.len());
        let mut first_error = None;
        for &(g, c) in targets {
            match self.read_one_at(g, c, window, raw, reader, &mut windows, &mut axes) {
                Ok(signal) => out.push(signal),
                // Only a probing reader gains from going on (it records the
                // remaining channels' gaps); any other reader stops here, as a
                // loop of `read` would.
                Err(e) if reader.is_probing() => {
                    first_error.get_or_insert(e);
                }
                Err(e) => return Err(e),
            }
        }
        match first_error {
            Some(e) => Err(e),
            None => Ok(out),
        }
    }

    /// One channel of [`read_many_at`](Self::read_many_at): the same reads
    /// as [`read`](Self::read) (`read_signal` / [`read_signal_window`]), with
    /// resolved windows and time axes shared through the two caches.
    #[allow(clippy::too_many_arguments)]
    fn read_one_at<R: ByteRangeReader<Error = MdfError>>(
        &self,
        g: usize,
        c: usize,
        window: Window,
        raw: bool,
        reader: &mut R,
        windows: &mut WindowCache,
        axes: &mut AxisCache,
    ) -> Result<Signal, MdfError> {
        let master = self.master_location(g, c);
        if window == Window::All {
            let values = self.read_channel_values(g, c, raw, reader);
            // Read the time axis even when the values failed, so a probing
            // reader records both gaps in one pass.
            let timestamps = match master {
                Some((mg, m)) => Self::cached_axis(axes, (mg, m, 0, u64::MAX), || {
                    self.read_channel_values_as_f64(mg, m, false, reader)
                }),
                None => Ok(Vec::new()),
            };
            // The channel's own error first, as `read` reports it.
            let values = values?;
            return Ok(self.make_signal(g, c, timestamps?, values));
        }
        let (start, count) = self.cached_window(g, c, window, reader, windows)?;
        let values = self.read_channel_values_window(g, c, start, count, raw, reader);
        let timestamps = match master {
            Some((mg, m)) => Self::cached_axis(axes, (mg, m, start, count), || {
                Ok(self
                    .read_channel_values_window(mg, m, start, count, false, reader)?
                    .iter()
                    .map(decoded_opt_to_f64)
                    .collect())
            }),
            None => Ok(Vec::new()),
        };
        let values = values?;
        Ok(self.make_signal(g, c, timestamps?, values))
    }

    /// [`resolve_window`](Self::resolve_window) through `cache`: a time window
    /// depends on the time axis searched, a record window only on the
    /// group's record count.
    fn cached_window<R: ByteRangeReader<Error = MdfError>>(
        &self,
        g: usize,
        c: usize,
        window: Window,
        reader: &mut R,
        cache: &mut WindowCache,
    ) -> Result<(u64, u64), MdfError> {
        let axis = match window {
            Window::Time(..) => self.time_axis_location(g, c),
            _ => None,
        };
        let key = (axis, self.channel_groups[g].record_count);
        if let Some(&resolved) = cache.get(&key) {
            return Ok(resolved);
        }
        let resolved = self.resolve_window(g, c, window, reader)?;
        cache.insert(key, resolved);
        Ok(resolved)
    }

    fn cached_axis(
        axes: &mut AxisCache,
        key: (usize, usize, u64, u64),
        decode: impl FnOnce() -> Result<Vec<f64>, MdfError>,
    ) -> Result<Vec<f64>, MdfError> {
        if let Some(axis) = axes.get(&key) {
            return Ok(axis.clone());
        }
        let axis = decode()?;
        axes.insert(key, axis.clone());
        Ok(axis)
    }

    /// `read_many` over a URL: deferred conversions are fetched first through
    /// a small read-ahead cache (a `##CC` block and the blocks it references
    /// usually sit together, so this costs one request instead of one round
    /// per chain level), then every data range of the batch — channels and
    /// time axes — is fetched concurrently in [`batched_reads_seeded`]
    /// rounds (one round for whole channels; a few more to search a time
    /// window).
    ///
    /// [`batched_reads_seeded`]: Self::batched_reads_seeded
    #[cfg(feature = "http")]
    fn read_many_url(
        &self,
        url: &str,
        targets: &[(usize, usize)],
        window: Window,
        raw: bool,
    ) -> Result<Vec<Signal>, MdfError> {
        self.read_many_url_limited(url, targets, window, raw, BATCH_MEMORY_LIMIT)
    }

    /// [`read_many_url`](Self::read_many_url) with the size above which
    /// whole channels are streamed instead of fetched as one batch.
    #[cfg(feature = "http")]
    fn read_many_url_limited(
        &self,
        url: &str,
        targets: &[(usize, usize)],
        window: Window,
        raw: bool,
        batch_limit: u64,
    ) -> Result<Vec<Signal>, MdfError> {
        let mut cached = CachingRangeReader::with_chunk_size(self.http_source(url)?, 64 * 1024);
        if self.file_size > 0 {
            cached.set_known_size(self.file_size);
        }
        let mut primed = std::collections::HashSet::new();
        for &(g, c) in targets {
            let mut conversions = Vec::with_capacity(3);
            if !raw {
                conversions.push((g, c));
            }
            conversions.extend(self.master_location(g, c));
            if matches!(window, Window::Time(..)) {
                conversions.extend(self.time_axis_location(g, c));
            }
            for (tg, tc) in conversions {
                let channel = &self.channel_groups[tg].channels[tc];
                if channel.conversion.is_none() && channel.conversion_addr != 0 && primed.insert(channel.conversion_addr) {
                    self.resolve_channel_conversion(tg, tc, &mut cached)?;
                }
            }
        }
        let (mut http, fetched) = cached.into_parts();
        let mut store = FragmentStore::from_pairs(fetched)?;
        let bytes = if window == Window::All {
            self.whole_read_bytes(targets)
        } else {
            // Locate every window first (a few rounds of single-record
            // probes), to know how much the read itself will fetch.
            // A failure here is left to the read below — the streaming
            // path, a plain sequential read that keeps memory bounded and
            // reports the channels' errors in the same order as a loop of
            // `read`.
            match self.batched_reads_seeded(&mut http, &mut store, |r| self.resolve_windows(targets, window, r)) {
                Ok(resolved) => self.window_read_bytes(targets, &resolved),
                Err(_) => u64::MAX,
            }
        };
        if bytes > batch_limit {
            // Too much to hold at once: stream channel by channel (one
            // section in memory at a time), each large section still fetched
            // as concurrent chunks; time axes are still read once, and the
            // window probes are served from the bytes already fetched.
            let mut reader = ChunkedUrlReader { http, store };
            return self.read_many_at(targets, window, raw, &mut reader);
        }
        self.batched_reads_seeded(&mut http, &mut store, |r| self.read_many_at(targets, window, raw, r))
    }

    /// The record window `(start, count)` of every target, resolved as
    /// [`read_many_at`](Self::read_many_at) does (once per time axis). Every
    /// target is attempted, so a probing reader records all probes of a round.
    #[cfg(feature = "http")]
    fn resolve_windows<R: ByteRangeReader<Error = MdfError>>(
        &self,
        targets: &[(usize, usize)],
        window: Window,
        reader: &mut R,
    ) -> Result<Vec<(u64, u64)>, MdfError> {
        let mut cache = WindowCache::new();
        let mut out = Vec::with_capacity(targets.len());
        let mut first_error = None;
        for &(g, c) in targets {
            match self.cached_window(g, c, window, reader, &mut cache) {
                Ok(resolved) => out.push(resolved),
                Err(e) => {
                    first_error.get_or_insert(e);
                }
            }
        }
        match first_error {
            Some(e) => Err(e),
            None => Ok(out),
        }
    }

    /// Upper bound of the bytes a windowed `read_many` fetches once its
    /// windows are resolved: the selected records of every group involved
    /// (each group once, at its widest window) plus the `##SD` streams of
    /// VLSD channels.
    #[cfg(feature = "http")]
    fn window_read_bytes(&self, targets: &[(usize, usize)], resolved: &[(u64, u64)]) -> u64 {
        let mut records: std::collections::BTreeMap<usize, u64> = std::collections::BTreeMap::new();
        let mut total = 0u64;
        for (&(g, c), &(_, count)) in targets.iter().zip(resolved) {
            for group in std::iter::once(g).chain(self.master_location(g, c).map(|(mg, _)| mg)) {
                let widest = records.entry(group).or_default();
                *widest = (*widest).max(count);
            }
            let channel = &self.channel_groups[g].channels[c];
            total = total.saturating_add(channel.vlsd_data_blocks.iter().map(|b| b.size).sum());
        }
        records.into_iter().fold(total, |sum, (g, count)| {
            let record = Self::checked_record_size(&self.channel_groups[g]).unwrap_or(0) as u64;
            sum.saturating_add(count.saturating_mul(record))
        })
    }

    /// Bytes a whole-channel `read_many` of `targets` fetches: every data
    /// block of their groups and of their time groups (each group once),
    /// plus the `##SD` streams of VLSD channels.
    #[cfg(feature = "http")]
    fn whole_read_bytes(&self, targets: &[(usize, usize)]) -> u64 {
        let mut groups = std::collections::BTreeSet::new();
        let mut total = 0u64;
        for &(g, c) in targets {
            groups.insert(g);
            if let Some((mg, _)) = self.master_location(g, c) {
                groups.insert(mg);
            }
            let channel = &self.channel_groups[g].channels[c];
            total = total.saturating_add(channel.vlsd_data_blocks.iter().map(|b| b.size).sum());
        }
        groups
            .iter()
            .flat_map(|&g| self.channel_groups[g].data_blocks.iter())
            .fold(total, |sum, b| sum.saturating_add(b.size))
    }

    /// Records `[start, start + count)` a window selects in the group of `(g, c)`.
    pub(crate) fn resolve_window<R: ByteRangeReader<Error = MdfError>>(
        &self,
        g: usize,
        c: usize,
        window: Window,
        reader: &mut R,
    ) -> Result<(u64, u64), MdfError> {
        let total = self.channel_groups[g].record_count;
        match window {
            Window::All => Ok((0, total)),
            Window::Records(start, count) => resolve_records(start, count, total),
            Window::Time(t_start, t_end) => self.record_window_for_time(g, c, t_start, t_end, reader),
        }
    }

    /// `f64` values of records `[start, start + count)` of `(g, c)`.
    pub(crate) fn values_f64_window<R: ByteRangeReader<Error = MdfError>>(
        &self,
        g: usize,
        c: usize,
        start: u64,
        count: u64,
        raw: bool,
        reader: &mut R,
    ) -> Result<Vec<f64>, MdfError> {
        Ok(self
            .read_channel_values_window(g, c, start, count, raw, reader)?
            .iter()
            .map(decoded_opt_to_f64)
            .collect())
    }

    /// First and last value of the time axis of `(g, c)` (two single-record reads).
    pub(crate) fn time_range_at<R: ByteRangeReader<Error = MdfError>>(
        &self,
        g: usize,
        c: usize,
        reader: &mut R,
    ) -> Result<Option<TimeRange>, MdfError> {
        let total = self.channel_groups[g].record_count;
        let Some((mg, m)) = self.time_axis_location(g, c) else {
            if total == 0 {
                return Ok(None);
            }
            let name = self.channel_groups[g].channels[c].name.clone().unwrap_or_default();
            return Err(MdfError::InvalidArgument(format!(
                "channel '{name}' has no master (time) channel"
            )));
        };
        let n = total.min(self.channel_groups[mg].record_count);
        if n == 0 {
            return Ok(None);
        }
        let first = self.values_f64_window(mg, m, 0, 1, false, reader);
        // Attempt the second read even when the first failed, so a probing
        // reader records both gaps in one pass.
        let last = self.values_f64_window(mg, m, n - 1, 1, false, reader)?;
        Ok(Some(TimeRange { start: first?[0], end: last[0] }))
    }

    /// Memory-map a file source, naming it in the error when it cannot be
    /// opened and refusing it when its size differs from the indexed file.
    #[cfg(not(target_arch = "wasm32"))]
    fn map_source_file(&self, path: &str) -> Result<memmap2::Mmap, MdfError> {
        if is_http_url(path) {
            #[cfg(not(feature = "http"))]
            return Err(MdfError::InvalidArgument(format!(
                "'{path}' is a URL, but mf4-rs was built without the `http` feature"
            )));
            #[cfg(feature = "http")]
            return Err(MdfError::InvalidArgument(format!(
                "'{path}' is a URL, not a local file: attach URLs with `set_source` or build the \
                 index with `from_url`"
            )));
        }
        if let Some(scheme) = url_scheme(path) {
            return Err(MdfError::InvalidArgument(format!(
                "unsupported source '{path}': {scheme}:// URLs cannot be read directly — use a \
                 local file path or an http(s):// URL (e.g. a presigned S3 / GCS / Azure URL)"
            )));
        }
        let file = std::fs::File::open(path).map_err(|e| {
            MdfError::IOError(std::io::Error::new(e.kind(), format!("cannot open source '{path}': {e}")))
        })?;
        let mmap = unsafe { memmap2::Mmap::map(&file) }.map_err(MdfError::IOError)?;
        check_resource_size(path, self.file_size, mmap.len() as u64)?;
        Ok(mmap)
    }

    /// An HTTP reader for a URL source that checks every response against
    /// the indexed file size.
    #[cfg(feature = "http")]
    fn http_source(&self, url: &str) -> Result<HttpRangeReader, MdfError> {
        let mut http = HttpRangeReader::new(url)?;
        if self.file_size > 0 {
            http.expect_size(self.file_size);
        }
        Ok(http)
    }

    /// A byte-range reader over the attached source, with the conversion of
    /// `(g, c)` resolved up front for URL sources (unless `raw`).
    /// `with_master`: the read decodes the time axis through this reader (a
    /// signal), so the master's conversion is primed too. A URL time-window
    /// search runs through `batched_reads`, which bypasses this cache.
    fn source_reader(&self, g: usize, c: usize, raw: bool, with_master: bool) -> Result<SourceReader, MdfError> {
        let _ = (g, c, raw, with_master);
        match self.require_source()? {
            #[cfg(not(target_arch = "wasm32"))]
            Source::File(path) => Ok(SourceReader::File(MmapRangeReader { mmap: self.map_source_file(path)? })),
            #[cfg(target_arch = "wasm32")]
            Source::File(_) => Err(MdfError::BlockSerializationError(
                "file sources are not available on wasm32".to_string(),
            )),
            #[cfg(feature = "http")]
            Source::Url(url) => {
                let http = self.http_source(url)?;
                Ok(SourceReader::Url(self.url_reader_with_conversion(http, g, c, raw, with_master)?))
            }
        }
    }

    /// Decode a channel + its group master from the attached source.
    fn read_signal(&self, g: usize, c: usize, raw: bool) -> Result<Signal, MdfError> {
        let channel = &self.channel_groups[g].channels[c];
        let (name, unit) = (channel.name.clone().unwrap_or_default(), channel.unit.clone());

        let values = self.read_values_via_source(g, c, raw)?;
        let timestamps = match self.master_location(g, c) {
            Some((mg, m)) => self.read_values_f64_via_source(mg, m, false)?,
            None => Vec::new(),
        };

        Ok(Signal { name, unit, timestamps, values })
    }

    /// Wrap `http` for a value read of `(g, c)`: a deferred conversion is
    /// fetched first through a small (64 KiB) read-ahead cache — the `##CC`
    /// block and the text/conversion blocks it references usually sit next to
    /// each other, so this costs one request instead of one per block — then
    /// the cache switches to bypass mode so the bulk data is streamed directly
    /// (cached conversion bytes are still served from memory).
    ///
    /// A `raw` read skips the channel's conversion. `with_master` also primes
    /// the group master's, for reads that decode the time axis through this
    /// reader (windows, signals): otherwise a raw read would resolve it later
    /// in bypass mode, one sequential request per block.
    #[cfg(feature = "http")]
    fn url_reader_with_conversion(
        &self,
        http: HttpRangeReader,
        g: usize,
        c: usize,
        raw: bool,
        with_master: bool,
    ) -> Result<CachingRangeReader<HttpRangeReader>, MdfError> {
        let mut cached = CachingRangeReader::with_chunk_size(http, 64 * 1024);
        if self.file_size > 0 {
            cached.set_known_size(self.file_size);
        }
        let mut targets = Vec::with_capacity(2);
        if !raw {
            targets.push((g, c));
        }
        if with_master {
            targets.extend(self.master_location(g, c));
        }
        for (tg, tc) in targets {
            let channel = &self.channel_groups[tg].channels[tc];
            if channel.conversion.is_none() && channel.conversion_addr != 0 {
                self.resolve_channel_conversion(tg, tc, &mut cached)?;
            }
        }
        cached.set_bypass(true);
        Ok(cached)
    }

    /// Resolve the attached [`Source`], erroring with a helpful message if none.
    fn require_source(&self) -> Result<&Source, MdfError> {
        let source = self.source.as_ref().ok_or_else(|| {
            MdfError::BlockSerializationError(
                "no data source attached to index; build with from_file/from_url or call set_source".to_string(),
            )
        })?;
        #[cfg(not(feature = "http"))]
        {
            let Source::File(path) = source;
            if is_http_url(path) {
                return Err(MdfError::InvalidArgument(format!(
                    "'{path}' is a URL, but mf4-rs was built without the `http` feature"
                )));
            }
        }
        Ok(source)
    }

    /// Read one channel's decoded values lazily through the attached source.
    pub(crate) fn read_values_via_source(
        &self,
        g: usize,
        c: usize,
        raw: bool,
    ) -> Result<Vec<Option<DecodedValue>>, MdfError> {
        #[cfg(target_arch = "wasm32")]
        let _ = (g, c, raw);
        match self.require_source()? {
            #[cfg(not(target_arch = "wasm32"))]
            Source::File(path) => {
                let mmap = self.map_source_file(path)?;
                self.read_channel_values_from_slice(g, c, raw, &mmap)
            }
            #[cfg(target_arch = "wasm32")]
            Source::File(_) => Err(MdfError::BlockSerializationError(
                "file sources are not available on wasm32".to_string(),
            )),
            #[cfg(feature = "http")]
            Source::Url(url) => {
                let http = self.http_source(url)?;
                let mut cached = self.url_reader_with_conversion(http, g, c, raw, false)?;
                self.read_channel_values(g, c, raw, &mut cached)
            }
        }
    }

    /// Resolve a channel's conversion, fetching it through the attached source
    /// if it was not resolved at index-build time (the remote / range-reader
    /// path records only its location — see [`IndexedChannel::conversion_addr`]).
    ///
    /// Returns `None` when the channel has no conversion. Errors if resolution
    /// needs the source (a deferred conversion) but none is attached — attach
    /// one with [`set_source`](Self::set_source).
    ///
    /// This returns the raw [`ConversionBlock`]; [`conversion`](Self::conversion)
    /// is the contract method returning a plain [`ConversionInfo`].
    pub fn conversion_block(&self, name: &str, group: Option<&str>) -> Result<Option<ConversionBlock>, MdfError> {
        let (g, c) = self.locate_checked(name, group)?;
        let channel = &self.channel_groups[g].channels[c];
        if let Some(conv) = &channel.conversion {
            return Ok(Some(conv.clone()));
        }
        if channel.conversion_addr == 0 {
            return Ok(None);
        }
        match self.require_source()? {
            #[cfg(not(target_arch = "wasm32"))]
            Source::File(path) => {
                let mmap = self.map_source_file(path)?;
                let mut slice_reader = BorrowedSliceReader { data: &mmap };
                Self::resolve_conversion(channel, &mut slice_reader)
            }
            #[cfg(target_arch = "wasm32")]
            Source::File(_) => Err(MdfError::BlockSerializationError(
                "file sources are not available on wasm32".to_string(),
            )),
            #[cfg(feature = "http")]
            Source::Url(url) => {
                let http = self.http_source(url)?;
                let mut cached = CachingRangeReader::new(http);
                Self::resolve_conversion(channel, &mut cached)
            }
        }
    }

    /// Read one channel's values as `f64` lazily through the attached source.
    pub(crate) fn read_values_f64_via_source(
        &self,
        g: usize,
        c: usize,
        raw: bool,
    ) -> Result<Vec<f64>, MdfError> {
        #[cfg(target_arch = "wasm32")]
        let _ = (g, c, raw);
        match self.require_source()? {
            #[cfg(not(target_arch = "wasm32"))]
            Source::File(path) => {
                let mmap = self.map_source_file(path)?;
                self.read_channel_values_from_slice_as_f64(g, c, raw, &mmap)
            }
            #[cfg(target_arch = "wasm32")]
            Source::File(_) => Err(MdfError::BlockSerializationError(
                "file sources are not available on wasm32".to_string(),
            )),
            #[cfg(feature = "http")]
            Source::Url(url) => {
                let http = self.http_source(url)?;
                let mut cached = self.url_reader_with_conversion(http, g, c, raw, false)?;
                self.read_channel_values_as_f64(g, c, raw, &mut cached)
            }
        }
    }

    /// Get the exact byte ranges needed to read all data for a specific channel
    /// 
    /// Returns a vector of (file_offset, length) tuples representing the byte ranges
    /// that need to be read from the file to get all data for the specified channel.
    /// 
    /// # Arguments
    /// * `group_index` - Index of the channel group
    /// * `channel_index` - Index of the channel within the group
    /// 
    /// # Returns
    /// * `Ok(Vec<(u64, u64)>)` - Vector of (offset, length) byte ranges
    /// * `Err(MdfError)` - If indices are invalid or channel type not supported
    pub(crate) fn get_channel_byte_ranges(
        &self,
        group_index: usize,
        channel_index: usize,
    ) -> Result<Vec<(u64, u64)>, MdfError> {
        let group = self.channel_groups.get(group_index)
            .ok_or_else(|| MdfError::BlockSerializationError("Invalid group index".to_string()))?;
        
        let channel = group.channels.get(channel_index)
            .ok_or_else(|| MdfError::BlockSerializationError("Invalid channel index".to_string()))?;

        // VLSD channels not supported for byte range calculation
        Self::ensure_not_vlsd(channel)?;

        // For regular channels, calculate byte ranges from data blocks
        self.calculate_regular_channel_byte_ranges(group, channel)
    }

    /// Get the exact byte ranges for a specific record range of a channel
    /// 
    /// This is useful when you only want to read a subset of records rather than all data.
    /// 
    /// # Arguments
    /// * `group_index` - Index of the channel group
    /// * `channel_index` - Index of the channel within the group
    /// * `start_record` - Starting record index (0-based)
    /// * `record_count` - Number of records to read
    /// 
    /// # Returns
    /// * `Ok(Vec<(u64, u64)>)` - Vector of (offset, length) byte ranges
    /// * `Err(MdfError)` - If indices are invalid, range is out of bounds, or channel type not supported
    pub(crate) fn get_channel_byte_ranges_for_records(
        &self,
        group_index: usize,
        channel_index: usize,
        start_record: u64,
        record_count: u64,
    ) -> Result<Vec<(u64, u64)>, MdfError> {
        let group = self.channel_groups.get(group_index)
            .ok_or_else(|| MdfError::BlockSerializationError("Invalid group index".to_string()))?;
        
        let channel = group.channels.get(channel_index)
            .ok_or_else(|| MdfError::BlockSerializationError("Invalid channel index".to_string()))?;

        // Validate record range with checked arithmetic (forged inputs must
        // error, not wrap), and without underflowing when record_count == 0.
        let end_record = start_record.checked_add(record_count).ok_or_else(|| {
            MdfError::BlockSerializationError(format!(
                "Record range overflow: start {} + count {}",
                start_record, record_count
            ))
        })?;
        if end_record > group.record_count {
            return Err(MdfError::BlockSerializationError(
                format!("Record range starting at {} for {} records exceeds total records {}",
                    start_record, record_count, group.record_count)
            ));
        }

        // VLSD channels not supported for byte range calculation
        Self::ensure_not_vlsd(channel)?;

        self.calculate_channel_byte_ranges_for_records(group, channel, start_record, record_count)
    }

    /// Calculate byte ranges for a regular (non-VLSD) channel for all records
    fn calculate_regular_channel_byte_ranges(
        &self,
        group: &IndexedChannelGroup,
        channel: &IndexedChannel,
    ) -> Result<Vec<(u64, u64)>, MdfError> {
        self.calculate_channel_byte_ranges_for_records(group, channel, 0, group.record_count)
    }

    /// Calculate byte ranges for a regular channel for a specific record range
    fn calculate_channel_byte_ranges_for_records(
        &self,
        group: &IndexedChannelGroup,
        channel: &IndexedChannel,
        start_record: u64,
        record_count: u64,
    ) -> Result<Vec<(u64, u64)>, MdfError> {
        // Record structure: record_id + data_bytes + invalidation_bytes
        let record_size = Self::checked_record_size(group)?;
        let channel_offset_in_record = group.record_id_len as usize + channel.byte_offset as usize;
        
        // Calculate how many bytes this channel needs per record
        let channel_bytes_per_record = if matches!(channel.data_type,
            DataType::StringLatin1 | DataType::StringUtf8 | DataType::StringUtf16LE | 
            DataType::StringUtf16BE | DataType::ByteArray | DataType::MimeSample | DataType::MimeStream)
        {
            channel.bit_count as usize / 8
        } else {
            (channel.bit_offset as usize + channel.bit_count as usize).div_ceil(8).max(1)
        };

        let mut byte_ranges = Vec::new();
        let mut records_processed = 0u64;
        
        for data_block in &group.data_blocks {
            if data_block.is_compressed {
                return Err(MdfError::BlockSerializationError(
                    "Compressed blocks not supported for byte range calculation".to_string()
                ));
            }

            let block_data_start = data_block.file_offset + 24; // Skip block header
            let records_in_block = Self::records_in_block(data_block, record_size)?;
            
            // Determine which records from this block we need
            let block_start_record = records_processed;
            let block_end_record = records_processed + records_in_block;
            
            let need_start = start_record.max(block_start_record);
            let need_end = (start_record + record_count).min(block_end_record);
            
            if need_start < need_end {
                // We need some records from this block
                let first_record_in_block = need_start - block_start_record;
                let last_record_in_block = need_end - block_start_record - 1;
                
                // Calculate byte range for the channel data in these records
                let first_channel_byte = block_data_start + 
                    first_record_in_block * record_size as u64 + 
                    channel_offset_in_record as u64;
                
                let last_channel_byte = block_data_start + 
                    last_record_in_block * record_size as u64 + 
                    channel_offset_in_record as u64 + 
                    channel_bytes_per_record as u64 - 1;
                
                let range_length = last_channel_byte - first_channel_byte + 1;
                byte_ranges.push((first_channel_byte, range_length));
            }
            
            records_processed = block_end_record;
            
            // Early exit if we've processed all needed records
            if records_processed >= start_record + record_count {
                break;
            }
        }
        
        Ok(byte_ranges)
    }

    /// Byte ranges occupied by a channel across the whole file, by name.
    ///
    /// Each tuple is `(offset, length)`, accounting for the channel's position
    /// in the record layout and any data-block splitting. Resolves the first
    /// channel matching `name`. Power-user entry point for issuing HTTP-range
    /// or S3 partial reads yourself.
    ///
    /// Note: each returned range is one *coalesced* span per data-block
    /// fragment, running from the first byte of the channel in the fragment's
    /// first record to its last byte in the fragment's last record. Because
    /// records interleave all channels of the group, the span **includes the
    /// bytes of the other channels** lying between this channel's samples.
    ///
    /// Pass `group` to resolve the channel in the group(s) with that name.
    /// Refused for VLSD channels (use `read` / `values`).
    pub fn byte_ranges(&self, name: &str, group: Option<&str>) -> Result<Vec<(u64, u64)>, MdfError> {
        let (g, c) = self.locate_checked(name, group)?;
        self.get_channel_byte_ranges(g, c)
    }

    /// Byte ranges for a record window of a channel, by name.
    ///
    /// `start_record` is 0-based. Errors if `start_record + record_count`
    /// exceeds the records available. Useful for paging through a large
    /// channel. See [`MdfIndex::byte_ranges`] for what each returned span
    /// covers.
    pub fn byte_ranges_for_records(
        &self,
        name: &str,
        start_record: u64,
        record_count: u64,
        group: Option<&str>,
    ) -> Result<Vec<(u64, u64)>, MdfError> {
        let (g, c) = self.locate_checked(name, group)?;
        self.get_channel_byte_ranges_for_records(g, c, start_record, record_count)
    }

    /// Fast path: read channel values as `Vec<f64>` using a byte range reader.
    ///
    /// This avoids boxing `DecodedValue` enums and applies linear conversions inline.
    /// For channels without invalidation bytes (the common case), validity checking
    /// is skipped entirely. Invalid samples are represented as `f64::NAN`.
    pub(crate) fn read_channel_values_as_f64<R: ByteRangeReader<Error = MdfError>>(
        &self,
        group_index: usize,
        channel_index: usize,
        raw: bool,
        reader: &mut R,
    ) -> Result<Vec<f64>, MdfError> {
        let group = self.channel_groups.get(group_index)
            .ok_or_else(|| MdfError::BlockSerializationError("Invalid group index".to_string()))?;
        let channel = group.channels.get(channel_index)
            .ok_or_else(|| MdfError::BlockSerializationError("Invalid channel index".to_string()))?;

        let conversion = Self::read_conversion(channel, reader, raw)?;

        if channel.is_virtual() {
            let vals = self.virtual_values(group, 0, group.record_count, conversion.as_ref())?;
            return Ok(Self::vlsd_values_to_f64(vals));
        }
        if channel.channel_type == 1 {
            let vals = self.read_vlsd_channel_values(group, channel, conversion.as_ref(), reader)?;
            return Ok(Self::vlsd_values_to_f64(vals));
        }

        let record_size = Self::checked_record_size(group)?;

        let mut total_records: usize = 0;
        for data_block in &group.data_blocks {
            if data_block.is_compressed {
                return Err(MdfError::BlockSerializationError(
                    "Compressed blocks not yet supported in index reader".to_string()
                ));
            }
            total_records += Self::records_in_block(data_block, record_size)? as usize;
        }
        // Cap the pre-allocation: `total_records` derives from index-supplied
        // block sizes, and a forged value must not abort on allocation. The
        // vector still grows as needed; real reads fail earlier at the reader.
        let mut values = Vec::with_capacity(total_records.min(1 << 24));

        let temp_cb = channel.to_decode_only_channel_block();
        let linear_coeffs = Self::get_linear_coeffs(conversion.as_ref());
        let has_conversion = conversion.is_some();

        Self::for_each_data_section(reader, &group.data_blocks, |block_data| {
            Self::decode_records_to_f64(block_data, record_size, group, channel, conversion.as_ref(), &temp_cb, linear_coeffs, has_conversion, &mut values)
        })?;

        Ok(values)
    }

    /// Zero-copy fast path: read channel values directly from an `&[u8]` mmap slice.
    ///
    /// Avoids all per-block heap allocation by slicing directly into the provided
    /// memory-mapped region. This is the fastest `DecodedValue` read path when the
    /// entire file is already mapped into memory.
    #[allow(dead_code)] // used by the Python bindings (pyo3 feature)
    pub(crate) fn read_channel_values_from_slice(
        &self,
        group_index: usize,
        channel_index: usize,
        raw: bool,
        file_data: &[u8],
    ) -> Result<Vec<Option<DecodedValue>>, MdfError> {
        let group = self.channel_groups.get(group_index)
            .ok_or_else(|| MdfError::BlockSerializationError("Invalid group index".to_string()))?;
        let channel = group.channels.get(channel_index)
            .ok_or_else(|| MdfError::BlockSerializationError("Invalid channel index".to_string()))?;

        let mut slice_reader = BorrowedSliceReader { data: file_data };
        let conversion = Self::read_conversion(channel, &mut slice_reader, raw)?;

        if channel.is_virtual() {
            return self.virtual_values(group, 0, group.record_count, conversion.as_ref());
        }
        if channel.channel_type == 1 {
            return self.read_vlsd_channel_values(group, channel, conversion.as_ref(), &mut slice_reader);
        }

        let record_size = Self::checked_record_size(group)?;
        let mut total_records: usize = 0;
        for data_block in &group.data_blocks {
            if data_block.is_compressed {
                return Err(MdfError::BlockSerializationError(
                    "Compressed blocks not yet supported in index reader".to_string()
                ));
            }
            total_records += Self::records_in_block(data_block, record_size)? as usize;
        }
        // Cap the pre-allocation: `total_records` derives from index-supplied
        // block sizes, and a forged value must not abort on allocation. The
        // vector still grows as needed; real reads fail earlier at the reader.
        let mut values = Vec::with_capacity(total_records.min(1 << 24));
        let temp_cb = channel.to_channel_block();

        for data_block in &group.data_blocks {
            let block_data = Self::slice_data_block(file_data, data_block)?;
            Self::decode_records_to_values(block_data, record_size, group, conversion.as_ref(), &temp_cb, &mut values)?;
        }

        Ok(values)
    }

    /// Zero-copy fast path: read channel values as `Vec<f64>` directly from an `&[u8]` mmap slice.
    ///
    /// Combines zero-copy slice access with the f64 fast decode path. No per-block
    /// allocation, no `DecodedValue` enum boxing. This is the fastest possible read
    /// path. Invalid or undecodable samples are `f64::NAN`.
    #[allow(dead_code)] // used by the Python bindings (pyo3 feature)
    pub(crate) fn read_channel_values_from_slice_as_f64(
        &self,
        group_index: usize,
        channel_index: usize,
        raw: bool,
        file_data: &[u8],
    ) -> Result<Vec<f64>, MdfError> {
        let group = self.channel_groups.get(group_index)
            .ok_or_else(|| MdfError::BlockSerializationError("Invalid group index".to_string()))?;
        let channel = group.channels.get(channel_index)
            .ok_or_else(|| MdfError::BlockSerializationError("Invalid channel index".to_string()))?;

        let mut slice_reader = BorrowedSliceReader { data: file_data };
        let conversion = Self::read_conversion(channel, &mut slice_reader, raw)?;

        if channel.is_virtual() {
            let vals = self.virtual_values(group, 0, group.record_count, conversion.as_ref())?;
            return Ok(Self::vlsd_values_to_f64(vals));
        }
        if channel.channel_type == 1 {
            let vals = self.read_vlsd_channel_values(group, channel, conversion.as_ref(), &mut slice_reader)?;
            return Ok(Self::vlsd_values_to_f64(vals));
        }

        let record_size = Self::checked_record_size(group)?;
        let mut total_records: usize = 0;
        for data_block in &group.data_blocks {
            if data_block.is_compressed {
                return Err(MdfError::BlockSerializationError(
                    "Compressed blocks not yet supported in index reader".to_string()
                ));
            }
            total_records += Self::records_in_block(data_block, record_size)? as usize;
        }
        // Cap the pre-allocation: `total_records` derives from index-supplied
        // block sizes, and a forged value must not abort on allocation. The
        // vector still grows as needed; real reads fail earlier at the reader.
        let mut values = Vec::with_capacity(total_records.min(1 << 24));
        let temp_cb = channel.to_decode_only_channel_block();
        let linear_coeffs = Self::get_linear_coeffs(conversion.as_ref());
        let has_conversion = conversion.is_some();

        for data_block in &group.data_blocks {
            let block_data = Self::slice_data_block(file_data, data_block)?;
            Self::decode_records_to_f64(block_data, record_size, group, channel, conversion.as_ref(), &temp_cb, linear_coeffs, has_conversion, &mut values)?;
        }

        Ok(values)
    }

    /// Slice a data block from file_data, skipping the 24-byte block header.
    /// Uses checked arithmetic so a forged offset/size errors instead of
    /// wrapping or panicking.
    #[allow(dead_code)] // used by the Python bindings (pyo3 feature)
    fn slice_data_block<'a>(file_data: &'a [u8], data_block: &DataBlockInfo) -> Result<&'a [u8], MdfError> {
        Self::data_section_size(data_block)?;
        let too_short = |expected: usize| MdfError::TooShortBuffer {
            actual: file_data.len(),
            expected,
            file: file!(),
            line: line!(),
        };
        let data_start = usize::try_from(data_block.file_offset)
            .ok()
            .and_then(|o| o.checked_add(24))
            .ok_or_else(|| too_short(usize::MAX))?;
        // The block header's own length wins over the indexed size.
        let data_len = Self::verified_data_len(file_data.get(data_start - 24..data_start), data_block)?;
        let data_end = usize::try_from(data_len)
            .ok()
            .and_then(|l| data_start.checked_add(l))
            .ok_or_else(|| too_short(usize::MAX))?;
        file_data.get(data_start..data_end).ok_or_else(|| too_short(data_end))
    }
}

/// A reader bound to an [`MdfIndex`] and a single byte-range data source.
///
/// Obtained from [`MdfIndex::open`] / [`MdfIndex::open_file`]. The source is
/// supplied once; afterwards channels are read by name. Reads of the same
/// channel re-fetch from the underlying source, so cache or memory-map the
/// source (e.g. [`MmapRangeReader`], [`CachingRangeReader`]) when reading many
/// channels.
pub struct MdfReader<'a, R: ByteRangeReader<Error = MdfError>> {
    index: &'a MdfIndex,
    reader: R,
}

impl<'a, R: ByteRangeReader<Error = MdfError>> MdfReader<'a, R> {
    /// The index this reader was opened against.
    pub fn index(&self) -> &MdfIndex {
        self.index
    }

    /// Mutable access to the underlying byte-range reader (e.g. to toggle
    /// [`CachingRangeReader::set_bypass`] or inspect request counters).
    pub fn reader_mut(&mut self) -> &mut R {
        &mut self.reader
    }

    /// Consume the reader, returning the underlying byte-range source.
    pub fn into_inner(self) -> R {
        self.reader
    }

    /// Read a channel as a [`Signal`] — see [`MdfIndex::read`].
    pub fn read<'o>(&mut self, name: &str, options: impl Into<Option<&'o ReadOptions>>) -> Result<Signal, MdfError> {
        let default = ReadOptions::default();
        let options = options.into().unwrap_or(&default);
        let window = options.window()?;
        let (g, c) = self.index.locate_checked(name, options.group_name())?;
        if window == Window::All {
            return self.read_signal(g, c, options.raw);
        }
        let (start, count) = self.index.resolve_window(g, c, window, &mut self.reader)?;
        read_signal_window(self.index, g, c, start, count, options.raw, &mut self.reader)
    }

    /// Read several channels at once — see [`MdfIndex::read_many`].
    pub fn read_many<'o, S: AsRef<str>>(
        &mut self,
        names: &[S],
        options: impl Into<Option<&'o ReadOptions>>,
    ) -> Result<Vec<Signal>, MdfError> {
        let default = ReadOptions::default();
        let options = options.into().unwrap_or(&default);
        let window = options.window()?;
        let targets = self.index.locate_all(names, options.group_name())?;
        self.index.read_many_at(&targets, window, options.raw, &mut self.reader)
    }

    /// Read a numeric channel as plain `f64` values — see [`MdfIndex::values`].
    pub fn values<'o>(&mut self, name: &str, options: impl Into<Option<&'o ReadOptions>>) -> Result<Vec<f64>, MdfError> {
        let default = ReadOptions::default();
        let options = options.into().unwrap_or(&default);
        let window = options.window()?;
        let (g, c) = self.index.locate_checked(name, options.group_name())?;
        if window == Window::All {
            return self.index.read_channel_values_as_f64(g, c, options.raw, &mut self.reader);
        }
        let (start, count) = self.index.resolve_window(g, c, window, &mut self.reader)?;
        self.index.values_f64_window(g, c, start, count, options.raw, &mut self.reader)
    }

    /// Rust-only: all samples of a channel as decoded values (no time axis),
    /// keeping text and byte values that `values` would turn into `NaN`.
    pub fn decoded_values(&mut self, name: &str, group: Option<&str>) -> Result<Vec<Option<DecodedValue>>, MdfError> {
        let (g, c) = self.index.locate_checked(name, group)?;
        self.index.read_channel_values(g, c, false, &mut self.reader)
    }

    /// First and last master (time) value of the group holding `name` — see
    /// [`MdfIndex::time_range`].
    pub fn time_range(&mut self, name: &str, group: Option<&str>) -> Result<Option<TimeRange>, MdfError> {
        let (g, c) = self.index.locate_checked(name, group)?;
        self.index.time_range_at(g, c, &mut self.reader)
    }

    fn read_signal(&mut self, g: usize, c: usize, raw: bool) -> Result<Signal, MdfError> {
        let channel = &self.index.channel_groups[g].channels[c];
        let (name, unit) = (channel.name.clone().unwrap_or_default(), channel.unit.clone());

        let values = self.index.read_channel_values(g, c, raw, &mut self.reader)?;
        let timestamps = match self.index.master_location(g, c) {
            Some((mg, m)) => self
                .index
                .read_channel_values(mg, m, false, &mut self.reader)?
                .iter()
                .map(decoded_opt_to_f64)
                .collect(),
            None => Vec::new(),
        };
        Ok(Signal { name, unit, timestamps, values })
    }
}

/// Window read shared by [`MdfReader`] and the wasm fragment driver: records
/// `[start, start + count)` of `(g, c)` paired with the same window of its
/// time axis.
pub(crate) fn read_signal_window<R: ByteRangeReader<Error = MdfError>>(
    index: &MdfIndex,
    g: usize,
    c: usize,
    start: u64,
    count: u64,
    raw: bool,
    reader: &mut R,
) -> Result<Signal, MdfError> {
    let channel = &index.channel_groups[g].channels[c];
    let (name, unit) = (channel.name.clone().unwrap_or_default(), channel.unit.clone());
    let values = index.read_channel_values_window(g, c, start, count, raw, reader);
    // Read the master even when the values failed, so a probing reader
    // records both gaps in one pass. Like a full read, the master itself
    // carries no separate timestamps.
    let timestamps = match index.master_location(g, c) {
        Some((mg, m)) => index
            .read_channel_values_window(mg, m, start, count, false, reader)?
            .iter()
            .map(decoded_opt_to_f64)
            .collect(),
        None => Vec::new(),
    };
    Ok(Signal { name, unit, timestamps, values: values? })
}

#[cfg(all(test, feature = "http"))]
mod http_header_tests {
    use super::{content_range_span, content_range_total};

    #[test]
    fn parses_content_range() {
        assert_eq!(content_range_span(Some("bytes 10-19/100")), Some((10, 19)));
        assert_eq!(content_range_span(Some(" bytes 0-0/*")), Some((0, 0)));
        assert_eq!(content_range_span(Some("bytes */100")), None);
        assert_eq!(content_range_span(None), None);
        assert_eq!(content_range_total(Some("bytes 10-19/100")), Some(100));
        assert_eq!(content_range_total(Some("bytes */100")), Some(100));
        assert_eq!(content_range_total(Some("bytes 0-0/*")), None);
    }
}

#[cfg(all(test, feature = "http"))]
mod http_retry_tests {
    use super::{ByteRangeReader, HttpRangeReader};
    use std::collections::VecDeque;
    use std::io::{Read, Write};
    use std::sync::atomic::{AtomicU64, Ordering};
    use std::sync::{Arc, Mutex};

    const OK: &str = "HTTP/1.1 206 Partial Content\r\nContent-Range: bytes 0-3/10\r\nContent-Length: 4\r\n\
                      Connection: close\r\n\r\nabcd";
    const BUSY: &str = "HTTP/1.1 503 Slow Down\r\nRetry-After: 0\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
    const MISSING: &str = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";

    /// Serve `script` (one response per connection) and count requests.
    fn serve(script: &[&'static str]) -> (String, Arc<AtomicU64>) {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let url = format!("http://{}/file.mf4", listener.local_addr().unwrap());
        let script = Arc::new(Mutex::new(script.iter().copied().collect::<VecDeque<_>>()));
        let count = Arc::new(AtomicU64::new(0));
        let served = count.clone();
        std::thread::spawn(move || {
            for stream in listener.incoming() {
                let Ok(mut stream) = stream else { return };
                let mut head = Vec::new();
                let mut byte = [0u8; 1];
                while !head.ends_with(b"\r\n\r\n") && stream.read(&mut byte).unwrap_or(0) == 1 {
                    head.push(byte[0]);
                }
                served.fetch_add(1, Ordering::SeqCst);
                let response = script.lock().unwrap().pop_front().unwrap_or(MISSING);
                let _ = stream.write_all(response.as_bytes());
            }
        });
        (url, count)
    }

    #[test]
    fn transient_failures_are_retried() {
        let (url, count) = serve(&[BUSY, BUSY, OK]);
        let bytes = HttpRangeReader::new(url).unwrap().read_range(0, 4).unwrap();
        assert_eq!(bytes, b"abcd");
        assert_eq!(count.load(Ordering::SeqCst), 3);
    }

    #[test]
    fn retries_are_bounded() {
        let (url, count) = serve(&[BUSY, BUSY, BUSY, BUSY, BUSY, OK]);
        let error = HttpRangeReader::new(url).unwrap().read_range(0, 4).unwrap_err().to_string();
        assert!(error.contains("503") && error.contains("gave up after 4 attempts"), "{error}");
        assert_eq!(count.load(Ordering::SeqCst), 4);
    }

    #[test]
    fn permanent_failures_are_not_retried() {
        let (url, count) = serve(&[MISSING, OK]);
        let error = HttpRangeReader::new(url).unwrap().read_range(0, 4).unwrap_err().to_string();
        assert!(error.contains("404"), "{error}");
        assert_eq!(count.load(Ordering::SeqCst), 1);
    }
}

#[cfg(all(test, feature = "http"))]
mod url_read_tests {
    use super::{DataBlockInfo, MdfIndex, Window};
    use crate::fragments::{FragmentStore, RecordingRangeReader};
    use crate::{ColumnData, Mdf, MdfWriter, ReadOptions};
    use std::io::{BufRead, BufReader, Write};
    use std::sync::Arc;

    /// Thread-per-connection server honouring single `Range` requests.
    fn serve(bytes: Vec<u8>) -> String {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let url = format!("http://{}/f.mf4", listener.local_addr().unwrap());
        let bytes = Arc::new(bytes);
        std::thread::spawn(move || {
            for stream in listener.incoming() {
                let Ok(stream) = stream else { return };
                let bytes = bytes.clone();
                std::thread::spawn(move || {
                    let mut reader = BufReader::new(stream.try_clone().unwrap());
                    let mut stream = stream;
                    loop {
                        let mut range = None;
                        let mut line = String::new();
                        loop {
                            line.clear();
                            if reader.read_line(&mut line).unwrap_or(0) == 0 {
                                return;
                            }
                            if line == "\r\n" {
                                break;
                            }
                            if let Some(v) = line.to_ascii_lowercase().strip_prefix("range: bytes=") {
                                let (a, b) = v.trim().split_once('-').unwrap();
                                range = Some((a.parse::<usize>().unwrap(), b.parse::<usize>().unwrap()));
                            }
                        }
                        let (a, b) = range.unwrap_or((0, bytes.len() - 1));
                        let b = b.min(bytes.len() - 1);
                        let head = format!(
                            "HTTP/1.1 206 Partial Content\r\nContent-Range: bytes {a}-{b}/{}\r\nContent-Length: {}\r\n\r\n",
                            bytes.len(),
                            b + 1 - a
                        );
                        if stream.write_all(head.as_bytes()).is_err() || stream.write_all(&bytes[a..=b]).is_err() {
                            return;
                        }
                    }
                });
            }
        });
        url
    }

    fn build(path: &std::path::Path) {
        let mut w = MdfWriter::new(path.to_str().unwrap()).unwrap();
        w.init_mdf_file().unwrap();
        let g = w.add_channel_group(Some("G")).unwrap();
        w.add_time_channel(&g, "t").unwrap();
        let a = w.add_float_channel(&g, "A").unwrap();
        w.add_float_channel(&g, "B").unwrap();
        w.add_linear_conversion(&a, 1.0, 2.0).unwrap();
        let n = 300_000;
        let t: Vec<f64> = (0..n).map(|i| i as f64 * 1e-3).collect();
        let x: Vec<f64> = (0..n).map(|i| (i % 977) as f64).collect();
        w.start_data_block(&g).unwrap();
        w.write_columns(&g, &[ColumnData::F64(&t), ColumnData::F64(&x), ColumnData::F64(&x)]).unwrap();
        w.finish_data_block(&g).unwrap();
        w.finalize().unwrap();
    }

    /// Whole channels and windows over a URL give the same signals batched
    /// and streamed (the path taken above the memory limit), on a row-oriented file split
    /// into several data blocks and on its column-oriented conversion.
    #[test]
    fn streamed_and_batched_whole_reads_agree() {
        let dir = tempfile::tempdir().unwrap();
        let (row, col) = (dir.path().join("row.mf4"), dir.path().join("col.mf4"));
        build(&row);
        let opts = crate::ColumnOptions { block_size: 256 * 1024, ..Default::default() };
        crate::to_column_oriented(&row, &col, &opts).unwrap();
        for path in [&row, &col] {
            let mdf = Mdf::from_file(path.to_str().unwrap()).unwrap();
            let index = MdfIndex::from_file(path.to_str().unwrap()).unwrap();
            assert!(index.channel_groups.iter().any(|g| g.data_blocks.len() > 1), "several data blocks");
            let url = serve(std::fs::read(path).unwrap());
            let names = ["A", "t", "B", "A"];
            let targets = index.locate_all(&names, None).unwrap();
            let option_sets = [
                ReadOptions::new(),
                ReadOptions::new().raw(true),
                ReadOptions::new().time(Some(12.5), Some(250.0)),
                ReadOptions::new().time(Some(100.0), None).raw(true),
                ReadOptions::new().records(1000, 150_000),
            ];
            for options in &option_sets {
                let want = mdf.read_many(&names, options).unwrap();
                let window = options.window().unwrap();
                for limit in [0, u64::MAX] {
                    let got = index.read_many_url_limited(&url, &targets, window, options.raw, limit).unwrap();
                    for (g, w) in got.iter().zip(&want) {
                        assert_eq!((&g.values, &g.timestamps), (&w.values, &w.timestamps), "limit {limit} {options:?}");
                    }
                }
            }
        }
    }

    /// A probing reader records every missing data section in one pass.
    #[test]
    fn probing_whole_reads_record_every_section() {
        let blocks: Vec<DataBlockInfo> = [0u64, 10_000, 20_000]
            .iter()
            .map(|&o| DataBlockInfo { file_offset: o, size: 24 + 800, is_compressed: false })
            .collect();
        let store = FragmentStore::new();
        let mut reader = RecordingRangeReader { store: &store, misses: Vec::new(), whole_request: true };
        let result = MdfIndex::for_each_data_section(&mut reader, &blocks, |_| Ok(()));
        assert!(result.is_err());
        assert_eq!(reader.misses, vec![(0, 824), (10_000, 824), (20_000, 824)]);
    }
}