supercov-engine 0.0.44

Rust instrumentation, evidence, attribution, and query engine for Supercov
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
//! Typed coverage columns stored in the immutable query-index container.
//!
//! This is not a serialized report. Records contain fixed-width values and
//! checked references into an interned UTF-8 string table. New query surfaces
//! add sections without forcing existing readers to parse unrelated data.

use std::collections::{BTreeMap, BTreeSet, HashMap};

use serde::Serialize;
use supercov_contracts::COVERAGE_MODEL_SCHEMA_VERSION;

use crate::{
    coverage_analysis::{
        CoverageCount, CoverageSummary, McdcVector, find_witnesses_for_conditions,
    },
    coverage_report::{
        CoverageModel, CoverageReport, CoverageView, TransportStats, coverage_summary_for_tests,
    },
    query_index::{QueryIndex, QueryIndexError, QueryIndexSection},
};

pub const SECTION_STRING_BYTES: u32 = 1;
pub const SECTION_STRINGS: u32 = 2;
pub const SECTION_STRING_RELATIONS: u32 = 3;
pub const SECTION_VIEW_SUMMARIES: u32 = 10;
pub const SECTION_FILE_GAPS: u32 = 11;
pub const SECTION_DECISION_GAPS: u32 = 12;
pub const SECTION_DIMENSIONS: u32 = 13;
pub const SECTION_PROJECTIONS: u32 = 14;
pub const SECTION_SCOPE_ENTRIES: u32 = 15;
pub const SECTION_CONFIDENCE: u32 = 16;
pub const SECTION_LINES: u32 = 17;
pub const SECTION_TEST_SUMMARIES: u32 = 18;
pub const SECTION_PHASE_SUMMARIES: u32 = 19;
pub const SECTION_ANCHORS: u32 = 20;
pub const SECTION_TEST_RETRIES: u32 = 21;
pub const SECTION_TEST_ATTEMPTS: u32 = 22;
pub const SECTION_TEST_LINES: u32 = 23;
pub const SECTION_TEST_HITS: u32 = 24;
pub const SECTION_TEST_DECISIONS: u32 = 25;
pub const SECTION_TEST_VECTORS: u32 = 26;
pub const SECTION_VECTOR_VALUES: u32 = 27;
pub const SECTION_HIT_METADATA: u32 = 28;
pub const SECTION_DECISION_METADATA: u32 = 29;
pub const SECTION_DECISION_DETAILS: u32 = 30;
pub const SECTION_DECISION_VECTOR_OBSERVATIONS: u32 = 31;
pub const SECTION_DECISION_CONDITIONS: u32 = 32;
pub const SECTION_LIMITATIONS: u32 = 33;
pub const SECTION_COVERAGE_MODEL: u32 = 34;

const STRING_RECORD_SIZE: usize = 16;
const SUMMARY_RECORD_SIZE: usize = 176;
const FILE_GAP_RECORD_SIZE: usize = 176;
const DECISION_GAP_RECORD_SIZE: usize = 96;
const DIMENSION_RECORD_SIZE: usize = 192;
const PROJECTION_RECORD_SIZE: usize = 536;
const SCOPE_ENTRY_RECORD_SIZE: usize = 96;
const CONFIDENCE_RECORD_SIZE: usize = 96;
const LINE_RECORD_SIZE: usize = 80;
const TEST_SUMMARY_RECORD_SIZE: usize = 64;
const PHASE_SUMMARY_RECORD_SIZE: usize = 64;
const ANCHOR_RECORD_SIZE: usize = 64;
const TEST_RETRY_RECORD_SIZE: usize = 16;
const TEST_ATTEMPT_RECORD_SIZE: usize = 24;
const TEST_LINE_RECORD_SIZE: usize = 24;
const TEST_HIT_RECORD_SIZE: usize = 16;
const TEST_DECISION_RECORD_SIZE: usize = 32;
const TEST_VECTOR_RECORD_SIZE: usize = 24;
const HIT_METADATA_RECORD_SIZE: usize = 64;
const DECISION_METADATA_RECORD_SIZE: usize = 64;
const DECISION_DETAIL_RECORD_SIZE: usize = 64;
const DECISION_VECTOR_OBSERVATION_RECORD_SIZE: usize = 64;
const DECISION_CONDITION_RECORD_SIZE: usize = 64;
const LIMITATION_RECORD_SIZE: usize = 64;
const COVERAGE_MODEL_RECORD_SIZE: usize = 48;
const NO_STRING: u32 = u32::MAX;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum CoverageViewId {
    All = 0,
    Passed = 1,
    Failed = 2,
}

impl TryFrom<u8> for CoverageViewId {
    type Error = CoverageIndexError;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            0 => Ok(Self::All),
            1 => Ok(Self::Passed),
            2 => Ok(Self::Failed),
            _ => Err(CoverageIndexError::InvalidRecord("coverage view")),
        }
    }
}

#[derive(Debug)]
pub enum CoverageIndexError {
    Container(QueryIndexError),
    InvalidRecord(&'static str),
    InvalidUtf8,
    SizeOverflow,
}

impl From<QueryIndexError> for CoverageIndexError {
    fn from(value: QueryIndexError) -> Self {
        Self::Container(value)
    }
}

impl std::fmt::Display for CoverageIndexError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Container(error) => write!(formatter, "{error}"),
            Self::InvalidRecord(reason) => write!(formatter, "invalid coverage index: {reason}"),
            Self::InvalidUtf8 => write!(formatter, "invalid UTF-8 in coverage index"),
            Self::SizeOverflow => write!(formatter, "coverage index exceeds format limits"),
        }
    }
}

impl std::error::Error for CoverageIndexError {}

fn put_u32(bytes: &mut [u8], offset: usize, value: u32) {
    bytes[offset..offset + 4].copy_from_slice(&value.to_le_bytes());
}

fn put_u64(bytes: &mut [u8], offset: usize, value: u64) {
    bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
}

fn get_u32(bytes: &[u8], offset: usize) -> Result<u32, CoverageIndexError> {
    Ok(u32::from_le_bytes(
        bytes
            .get(offset..offset + 4)
            .and_then(|value| value.try_into().ok())
            .ok_or(CoverageIndexError::InvalidRecord("truncated u32"))?,
    ))
}

fn get_u64(bytes: &[u8], offset: usize) -> Result<u64, CoverageIndexError> {
    Ok(u64::from_le_bytes(
        bytes
            .get(offset..offset + 8)
            .and_then(|value| value.try_into().ok())
            .ok_or(CoverageIndexError::InvalidRecord("truncated u64"))?,
    ))
}

fn usize_u64(value: usize) -> Result<u64, CoverageIndexError> {
    u64::try_from(value).map_err(|_| CoverageIndexError::SizeOverflow)
}

fn usize_u32(value: usize) -> Result<u32, CoverageIndexError> {
    u32::try_from(value).map_err(|_| CoverageIndexError::SizeOverflow)
}

#[derive(Default)]
struct StringTable {
    ids: HashMap<String, u32>,
    strings: Vec<String>,
}

#[derive(Default)]
struct StringRelations {
    values: Vec<u32>,
}

impl StringRelations {
    fn push(
        &mut self,
        values: impl IntoIterator<Item = String>,
        strings: &mut StringTable,
    ) -> Result<(u64, u64), CoverageIndexError> {
        let offset = usize_u64(self.values.len())?;
        for value in values {
            self.values.push(strings.intern(&value)?);
        }
        Ok((offset, usize_u64(self.values.len())? - offset))
    }

    fn section(self) -> Result<QueryIndexSection, CoverageIndexError> {
        let mut bytes = Vec::with_capacity(self.values.len() * 4);
        for value in self.values {
            bytes.extend_from_slice(&value.to_le_bytes());
        }
        Ok(QueryIndexSection {
            kind: SECTION_STRING_RELATIONS,
            record_size: 4,
            count: usize_u64(bytes.len() / 4)?,
            bytes,
        })
    }
}

impl StringTable {
    fn intern(&mut self, value: &str) -> Result<u32, CoverageIndexError> {
        if let Some(id) = self.ids.get(value) {
            return Ok(*id);
        }
        let id = usize_u32(self.strings.len())?;
        self.ids.insert(value.into(), id);
        self.strings.push(value.into());
        Ok(id)
    }

    fn sections(self) -> Result<[QueryIndexSection; 2], CoverageIndexError> {
        let mut blob = Vec::new();
        let mut records = Vec::with_capacity(self.strings.len() * STRING_RECORD_SIZE);
        for string in self.strings {
            let offset = usize_u64(blob.len())?;
            let value = string.as_bytes();
            let length = usize_u32(value.len())?;
            blob.extend_from_slice(value);
            let mut record = [0_u8; STRING_RECORD_SIZE];
            put_u64(&mut record, 0, offset);
            put_u32(&mut record, 8, length);
            records.extend_from_slice(&record);
        }
        Ok([
            QueryIndexSection {
                kind: SECTION_STRING_BYTES,
                record_size: 0,
                count: usize_u64(blob.len())?,
                bytes: blob,
            },
            QueryIndexSection {
                kind: SECTION_STRINGS,
                record_size: STRING_RECORD_SIZE as u32,
                count: usize_u64(records.len() / STRING_RECORD_SIZE)?,
                bytes: records,
            },
        ])
    }
}

fn put_count(
    bytes: &mut [u8],
    offset: usize,
    count: &CoverageCount,
) -> Result<(), CoverageIndexError> {
    put_u64(bytes, offset, usize_u64(count.covered)?);
    put_u64(bytes, offset + 8, usize_u64(count.total)?);
    Ok(())
}

fn summary_record(
    id: CoverageViewId,
    view: &CoverageView,
    strings: &mut StringTable,
) -> Result<[u8; SUMMARY_RECORD_SIZE], CoverageIndexError> {
    let mut record = [0_u8; SUMMARY_RECORD_SIZE];
    record[0] = id as u8;
    record[1] = u8::from(view.summary.coverage_complete);
    record[2] = match view.summary.completeness_blocked {
        None => 0,
        Some(false) => 1,
        Some(true) => 2,
    };
    put_u32(&mut record, 4, strings.intern(&view.generated_at)?);
    put_u32(&mut record, 8, strings.intern(&view.variant)?);
    let values = [
        view.summary.decisions,
        view.summary.executed_decisions,
        view.summary.covered_decisions,
        view.summary.conditions,
        view.summary.covered_conditions,
    ];
    for (index, value) in values.into_iter().enumerate() {
        put_u64(&mut record, 16 + index * 8, usize_u64(value)?);
    }
    for (index, count) in [
        &view.summary.lines,
        &view.summary.statements,
        &view.summary.functions,
        &view.summary.branches,
        &view.summary.decision_outcomes,
        &view.summary.condition_outcomes,
        &view.summary.value_selections,
    ]
    .into_iter()
    .enumerate()
    {
        put_count(&mut record, 56 + index * 16, count)?;
    }
    Ok(record)
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IndexedFileGap {
    #[serde(skip)]
    pub view: CoverageViewId,
    pub file: String,
    pub uncovered_lines: usize,
    pub uncovered_statements: usize,
    pub uncovered_functions: usize,
    pub missing_branches: usize,
    pub missing_mcdc_conditions: usize,
    pub measurement_limitations: usize,
    pub limitation_kinds: Vec<String>,
    pub covered_by_other_tests: IndexedGapDimensions,
    pub uncovered_everywhere: IndexedGapDimensions,
    pub score: usize,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IndexedGapDimensions {
    pub lines: usize,
    pub statements: usize,
    pub functions: usize,
    pub branches: usize,
    pub mcdc_conditions: usize,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IndexedCoverageSnapshot {
    pub all_summary: CoverageSummary,
    pub passed_summary: CoverageSummary,
    pub failed_summary: CoverageSummary,
    pub all_files: Vec<IndexedFileGap>,
    pub passed_files: Vec<IndexedFileGap>,
    pub failed_files: Vec<IndexedFileGap>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IndexedDecisionGap {
    #[serde(skip)]
    pub view: CoverageViewId,
    #[serde(skip)]
    pub file: String,
    pub id: String,
    pub line: usize,
    pub column: usize,
    pub kind: String,
    pub conditions: usize,
    pub missing_conditions: usize,
    pub source: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CoverageDimension {
    Kind = 0,
    Runner = 1,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IndexedDimensionCoverage {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub kind: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub runner: Option<String>,
    pub tests: usize,
    pub setups: usize,
    pub summary: CoverageSummary,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IndexedAttribution {
    pub browser_explicit: usize,
    pub browser_fallback: usize,
    pub server_explicit: usize,
    pub server_fallback: usize,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IndexedOutcomeCounts {
    pub passed: usize,
    pub failed: usize,
    pub flaky: usize,
    pub skipped: usize,
    pub timed_out: usize,
    pub interrupted: usize,
    pub unknown: usize,
    pub unstarted: usize,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IndexedMeasurementKinds {
    #[serde(rename = "dynamic-code")]
    pub dynamic_code: usize,
    #[serde(rename = "semantic-safety")]
    pub semantic_safety: usize,
    #[serde(rename = "source-scope")]
    pub source_scope: usize,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IndexedMeasurement {
    pub complete: bool,
    pub limitations: usize,
    pub evidence_corruptions: usize,
    pub blocking: usize,
    /// Limitations that declare a boundary of the denominator rather than
    /// blocking measurement inside it.
    pub declared: usize,
    pub files: usize,
    pub by_kind: IndexedMeasurementKinds,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IndexedConfidenceLines {
    pub unexecuted: usize,
    pub executed: usize,
    pub action: usize,
    pub asserted: usize,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IndexedSummaryConfidence {
    pub lines: IndexedConfidenceLines,
    pub assertion_covered_mcdc_conditions: usize,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IndexedCoverageModel {
    pub schema_version: u32,
    pub variant: String,
    pub name: String,
    pub completeness_meaning: String,
    pub measured: Vec<String>,
    pub not_measured: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IndexedSourceScope {
    pub kind: String,
    pub language: String,
    pub model: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mode: Option<String>,
    pub roots: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unit: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub measurement_complete: Option<bool>,
    pub included: usize,
    pub excluded: usize,
    pub ambiguous: usize,
}

#[derive(Debug, Clone, PartialEq)]
pub struct IndexedProjection {
    pub view: CoverageViewId,
    pub kind: Option<String>,
    pub runner: Option<String>,
    pub generated_at: String,
    pub summary: CoverageSummary,
    pub measurement: IndexedMeasurement,
    pub attribution: IndexedAttribution,
    pub transport: Option<TransportStats>,
    pub empty_evidence_tests: usize,
    pub first_empty_evidence_test: Option<String>,
    pub confidence: IndexedSummaryConfidence,
    pub files_with_gaps: usize,
    pub files_with_coverage_gaps: usize,
    pub tests: usize,
    pub setups: usize,
    pub test_outcomes: IndexedOutcomeCounts,
    pub source_scope: Option<IndexedSourceScope>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IndexedScopeEntry {
    pub file: String,
    pub status: String,
    pub reason: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub package_root: Option<String>,
    pub measurement_limitations: usize,
    pub limitation_kinds: Vec<String>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct IndexedLine {
    pub file: String,
    pub line: usize,
    pub covered: bool,
    /// False when every obligation on the line was declined: the line stays
    /// addressable and carries its limitation, but it is neither covered nor
    /// uncovered.
    pub measured: bool,
    pub tests: Vec<String>,
    pub phases: Vec<String>,
    pub confidence: crate::coverage_report::CoverageConfidence,
}

#[derive(Debug, Clone, PartialEq)]
pub struct IndexedTestSummary {
    pub id: String,
    pub name: String,
    pub file: Option<String>,
    pub title: Option<String>,
    pub outcome: String,
    pub role: String,
    pub provenance: crate::coverage_report::TestProvenance,
}

#[derive(Debug, Clone, PartialEq)]
pub struct IndexedPhaseSummary {
    pub id: String,
    pub kind: String,
    pub operation: String,
    pub source: Option<String>,
    pub test: String,
    pub status: Option<String>,
    pub caused_by_phase_id: Option<String>,
    pub lines: usize,
    pub decisions: usize,
}

#[derive(Debug, Clone, PartialEq)]
pub struct IndexedAnchor {
    pub kind: String,
    pub id: String,
    pub file: String,
    pub line: usize,
    pub column: usize,
    pub covered: bool,
    pub conditions: Option<usize>,
    pub covered_conditions: Option<usize>,
    pub tests: Vec<String>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct IndexedTestDetail {
    pub summary: IndexedTestSummary,
    pub retries: Vec<usize>,
    pub attempts: Vec<crate::coverage_report::TestAttempt>,
    pub hits: Vec<String>,
    pub decisions: Vec<crate::coverage_report::TestDecisionResult>,
    pub lines: Vec<crate::coverage_report::SourceLine>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IndexedHitMetadata {
    pub id: String,
    pub obligation: String,
    pub branch_kind: Option<String>,
    pub file: String,
    pub line: usize,
    pub column: usize,
    pub label: Option<String>,
    pub alternative: Option<String>,
    pub parent_id: Option<String>,
    pub source: String,
    pub tests: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct IndexedLimitation {
    pub id: String,
    pub kind: String,
    pub file: String,
    pub line: usize,
    pub column: usize,
    pub source: String,
    pub reason: String,
    /// Whether this blocks measurement of the denominator, as opposed to
    /// declaring a boundary of it.
    pub blocking: bool,
}

#[derive(Default)]
struct MutableFileGap {
    uncovered_lines: usize,
    uncovered_statements: usize,
    uncovered_functions: usize,
    missing_branches: usize,
    missing_mcdc_conditions: usize,
    measurement_limitations: usize,
    limitation_mask: u32,
    covered_by_other_tests: [usize; 5],
    uncovered_everywhere: [usize; 5],
}

fn limitation_kind(value: &serde_json::Value) -> Option<(&str, &str)> {
    Some((value.get("file")?.as_str()?, value.get("kind")?.as_str()?))
}

fn includes_selected(tests: &[String], selected: Option<&BTreeSet<String>>, covered: bool) -> bool {
    selected.map_or(covered, |selected| {
        tests.iter().any(|test| selected.contains(test))
    })
}

fn classify(
    gap: &mut MutableFileGap,
    dimension: usize,
    selected: Option<&BTreeSet<String>>,
    covered_overall: bool,
) {
    if selected.is_some() && covered_overall {
        gap.covered_by_other_tests[dimension] += 1;
    } else {
        gap.uncovered_everywhere[dimension] += 1;
    }
}

fn file_gaps(
    view: &CoverageView,
    selected: Option<&BTreeSet<String>>,
) -> Result<Vec<(String, MutableFileGap)>, CoverageIndexError> {
    let mut files = BTreeMap::<String, MutableFileGap>::new();
    for line in &view.lines {
        let gap = files.entry(line.file.clone()).or_default();
        if !includes_selected(&line.tests, selected, line.covered) {
            gap.uncovered_lines += 1;
            classify(gap, 0, selected, line.covered);
        }
    }
    for point in &view.points {
        let gap = files.entry(point.meta.file.clone()).or_default();
        if !includes_selected(&point.tests, selected, point.covered) {
            match point.meta.kind {
                crate::coverage_analysis::PointKind::Statement => {
                    gap.uncovered_statements += 1;
                    classify(gap, 1, selected, point.covered);
                }
                crate::coverage_analysis::PointKind::Function => {
                    gap.uncovered_functions += 1;
                    classify(gap, 2, selected, point.covered);
                }
            }
        }
    }
    for branch in &view.branches {
        let gap = files.entry(branch.meta.file.clone()).or_default();
        for alternative in &branch.alternatives {
            if !includes_selected(&alternative.tests, selected, alternative.covered) {
                gap.missing_branches += 1;
                classify(gap, 3, selected, alternative.covered);
            }
        }
    }
    for decision in &view.decisions {
        let gap = files.entry(decision.meta.file.clone()).or_default();
        let selected_vectors = decision
            .vector_observations
            .iter()
            .filter(|observation| includes_selected(&observation.tests, selected, true))
            .map(|observation| observation.vector.clone())
            .collect::<Vec<_>>();
        let witnesses =
            find_witnesses_for_conditions(&selected_vectors, decision.meta.conditions.len())
                .map_err(|_| CoverageIndexError::InvalidRecord("MC/DC vector width"))?;
        for (index, witness) in witnesses.into_iter().enumerate() {
            if witness.is_none() {
                gap.missing_mcdc_conditions += 1;
                classify(gap, 4, selected, decision.conditions[index].covered);
            }
        }
    }
    for limitation in &view.limitations {
        let Some((file, kind)) = limitation_kind(limitation) else {
            continue;
        };
        let gap = files.entry(file.into()).or_default();
        gap.measurement_limitations += 1;
        gap.limitation_mask |= match kind {
            "dynamic-code" => 1,
            "semantic-safety" => 2,
            "source-scope" => 4,
            _ => 8,
        };
    }
    Ok(files.into_iter().collect())
}

fn file_gap_record(
    view_id: CoverageViewId,
    file: &str,
    gap: &MutableFileGap,
    kind: Option<&str>,
    runner: Option<&str>,
    strings: &mut StringTable,
) -> Result<[u8; FILE_GAP_RECORD_SIZE], CoverageIndexError> {
    let mut record = [0_u8; FILE_GAP_RECORD_SIZE];
    record[0] = view_id as u8;
    put_u32(&mut record, 4, strings.intern(file)?);
    for (index, value) in [
        gap.uncovered_lines,
        gap.uncovered_statements,
        gap.uncovered_functions,
        gap.missing_branches,
        gap.missing_mcdc_conditions,
        gap.measurement_limitations,
    ]
    .into_iter()
    .enumerate()
    {
        put_u64(&mut record, 8 + index * 8, usize_u64(value)?);
    }
    put_u32(&mut record, 56, gap.limitation_mask);
    let score = gap.uncovered_lines
        + gap.uncovered_functions * 2
        + gap.missing_branches * 2
        + gap.missing_mcdc_conditions * 3
        + gap.measurement_limitations * 3;
    put_u64(&mut record, 64, usize_u64(score)?);
    put_u32(
        &mut record,
        72,
        kind.map_or(Ok(NO_STRING), |value| strings.intern(value))?,
    );
    put_u32(
        &mut record,
        76,
        runner.map_or(Ok(NO_STRING), |value| strings.intern(value))?,
    );
    for (index, value) in gap.covered_by_other_tests.into_iter().enumerate() {
        put_u64(&mut record, 80 + index * 8, usize_u64(value)?);
    }
    for (index, value) in gap.uncovered_everywhere.into_iter().enumerate() {
        put_u64(&mut record, 120 + index * 8, usize_u64(value)?);
    }
    Ok(record)
}

fn projections(view: &CoverageView) -> Vec<(Option<String>, Option<String>, BTreeSet<String>)> {
    let kinds = view
        .tests
        .iter()
        .map(|test| test.provenance.kind.clone())
        .collect::<BTreeSet<_>>();
    let runners = view
        .tests
        .iter()
        .map(|test| test.provenance.runner.clone())
        .collect::<BTreeSet<_>>();
    let mut selectors = Vec::new();
    for kind in &kinds {
        selectors.push((Some(kind.clone()), None));
    }
    for runner in &runners {
        selectors.push((None, Some(runner.clone())));
    }
    for kind in &kinds {
        for runner in &runners {
            selectors.push((Some(kind.clone()), Some(runner.clone())));
        }
    }
    selectors
        .into_iter()
        .filter_map(|(kind, runner)| {
            let selected = view
                .tests
                .iter()
                .filter(|test| {
                    kind.as_ref()
                        .is_none_or(|value| test.provenance.kind == *value)
                        && runner
                            .as_ref()
                            .is_none_or(|value| test.provenance.runner == *value)
                })
                .map(|test| test.id.clone())
                .collect::<BTreeSet<_>>();
            (!selected.is_empty()).then_some((kind, runner, selected))
        })
        .collect()
}

fn decision_gap_record(
    view_id: CoverageViewId,
    decision: &crate::coverage_report::DecisionResult,
    selected: Option<&BTreeSet<String>>,
    kind: Option<&str>,
    runner: Option<&str>,
    strings: &mut StringTable,
) -> Result<[u8; DECISION_GAP_RECORD_SIZE], CoverageIndexError> {
    let vectors = decision
        .vector_observations
        .iter()
        .filter(|observation| includes_selected(&observation.tests, selected, true))
        .map(|observation| observation.vector.clone())
        .collect::<Vec<_>>();
    let witnesses = find_witnesses_for_conditions(&vectors, decision.meta.conditions.len())
        .map_err(|_| CoverageIndexError::InvalidRecord("MC/DC vector width"))?;
    let mut record = [0_u8; DECISION_GAP_RECORD_SIZE];
    record[0] = view_id as u8;
    put_u32(
        &mut record,
        4,
        kind.map_or(Ok(NO_STRING), |value| strings.intern(value))?,
    );
    put_u32(
        &mut record,
        8,
        runner.map_or(Ok(NO_STRING), |value| strings.intern(value))?,
    );
    put_u32(&mut record, 12, strings.intern(&decision.meta.id)?);
    put_u32(&mut record, 16, strings.intern(&decision.meta.file)?);
    put_u32(&mut record, 20, strings.intern(&decision.meta.kind)?);
    put_u32(
        &mut record,
        24,
        strings.intern(
            &decision
                .meta
                .source
                .split_whitespace()
                .collect::<Vec<_>>()
                .join(" "),
        )?,
    );
    put_u64(&mut record, 32, usize_u64(decision.meta.line)?);
    put_u64(&mut record, 40, usize_u64(decision.meta.column)?);
    put_u64(&mut record, 48, usize_u64(decision.meta.conditions.len())?);
    put_u64(
        &mut record,
        56,
        usize_u64(witnesses.iter().filter(|witness| witness.is_none()).count())?,
    );
    Ok(record)
}

fn put_summary_payload(
    record: &mut [u8],
    flags_offset: usize,
    base: usize,
    summary: &CoverageSummary,
) -> Result<(), CoverageIndexError> {
    record[flags_offset] = u8::from(summary.coverage_complete);
    record[flags_offset + 1] = match summary.completeness_blocked {
        None => 0,
        Some(false) => 1,
        Some(true) => 2,
    };
    for (index, value) in [
        summary.decisions,
        summary.executed_decisions,
        summary.covered_decisions,
        summary.conditions,
        summary.covered_conditions,
    ]
    .into_iter()
    .enumerate()
    {
        put_u64(record, base + index * 8, usize_u64(value)?);
    }
    for (index, count) in [
        &summary.lines,
        &summary.statements,
        &summary.functions,
        &summary.branches,
        &summary.decision_outcomes,
        &summary.condition_outcomes,
        &summary.value_selections,
    ]
    .into_iter()
    .enumerate()
    {
        put_count(record, base + 40 + index * 16, count)?;
    }
    Ok(())
}

fn dimension_record(
    view_id: CoverageViewId,
    dimension: CoverageDimension,
    value: &crate::coverage_report::DimensionCoverage,
    strings: &mut StringTable,
) -> Result<[u8; DIMENSION_RECORD_SIZE], CoverageIndexError> {
    let mut record = [0_u8; DIMENSION_RECORD_SIZE];
    record[0] = view_id as u8;
    record[1] = dimension as u8;
    let name = match dimension {
        CoverageDimension::Kind => value.kind.as_deref(),
        CoverageDimension::Runner => value.runner.as_deref(),
    }
    .ok_or(CoverageIndexError::InvalidRecord("dimension name"))?;
    put_u32(&mut record, 4, strings.intern(name)?);
    put_u64(&mut record, 8, usize_u64(value.tests)?);
    put_u64(&mut record, 16, usize_u64(value.setups)?);
    put_summary_payload(&mut record, 24, 32, &value.summary)?;
    Ok(record)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ScopeKind {
    SourceDiscovery = 1,
    Compiler = 2,
}

struct ScopeProjection<'a> {
    kind: ScopeKind,
    language: &'a str,
    model: &'a str,
    mode: Option<&'a str>,
    roots: Vec<String>,
    unit: Option<&'a str>,
    measurement_complete: Option<bool>,
    entries: Option<&'a Vec<serde_json::Value>>,
}

fn scope_projection<'a>(
    scope: Option<&'a serde_json::Value>,
    coverage_model: &'a str,
) -> Result<Option<ScopeProjection<'a>>, CoverageIndexError> {
    let Some(scope) = scope else {
        return Ok(None);
    };
    let object = scope
        .as_object()
        .ok_or(CoverageIndexError::InvalidRecord("coverage scope"))?;
    if let Some(mode) = object.get("mode") {
        let mode = mode
            .as_str()
            .ok_or(CoverageIndexError::InvalidRecord("source-scope mode"))?;
        let roots = object
            .get("roots")
            .and_then(serde_json::Value::as_array)
            .ok_or(CoverageIndexError::InvalidRecord("source-scope roots"))?
            .iter()
            .map(|root| {
                root.as_str()
                    .map(str::to_owned)
                    .ok_or(CoverageIndexError::InvalidRecord("source-scope root"))
            })
            .collect::<Result<Vec<_>, _>>()?;
        let entries = object
            .get("entries")
            .and_then(serde_json::Value::as_array)
            .ok_or(CoverageIndexError::InvalidRecord("source-scope entries"))?;
        return Ok(Some(ScopeProjection {
            kind: ScopeKind::SourceDiscovery,
            language: "javascript",
            model: coverage_model,
            mode: Some(mode),
            roots,
            unit: None,
            measurement_complete: None,
            entries: Some(entries),
        }));
    }

    let language = object
        .get("language")
        .and_then(serde_json::Value::as_str)
        .ok_or(CoverageIndexError::InvalidRecord("compiler-scope language"))?;
    let model = object
        .get("model")
        .and_then(serde_json::Value::as_str)
        .ok_or(CoverageIndexError::InvalidRecord("compiler-scope model"))?;
    let unit = object
        .get("crate")
        .and_then(serde_json::Value::as_str)
        .ok_or(CoverageIndexError::InvalidRecord("compiler-scope unit"))?;
    let measurement_complete = object
        .get("measurementComplete")
        .and_then(serde_json::Value::as_bool)
        .ok_or(CoverageIndexError::InvalidRecord(
            "compiler-scope measurement completeness",
        ))?;
    Ok(Some(ScopeProjection {
        kind: ScopeKind::Compiler,
        language,
        model,
        mode: None,
        roots: Vec::new(),
        unit: Some(unit),
        measurement_complete: Some(measurement_complete),
        entries: None,
    }))
}

fn projection_record(
    view_id: CoverageViewId,
    view: &CoverageView,
    selected: Option<&BTreeSet<String>>,
    kind: Option<&str>,
    runner: Option<&str>,
    strings: &mut StringTable,
    relations: &mut StringRelations,
) -> Result<[u8; PROJECTION_RECORD_SIZE], CoverageIndexError> {
    let mut record = [0_u8; PROJECTION_RECORD_SIZE];
    record[0] = view_id as u8;
    put_u32(
        &mut record,
        4,
        kind.map_or(Ok(NO_STRING), |value| strings.intern(value))?,
    );
    put_u32(
        &mut record,
        8,
        runner.map_or(Ok(NO_STRING), |value| strings.intern(value))?,
    );
    put_u32(&mut record, 12, strings.intern(&view.generated_at)?);

    let scope = scope_projection(view.scope.as_ref(), &view.model.name)?;
    record[2] = u8::from(scope.is_some());
    record[3] = scope.as_ref().map_or(0, |scope| scope.kind as u8);
    put_u32(
        &mut record,
        16,
        scope
            .as_ref()
            .and_then(|scope| scope.mode)
            .map_or(Ok(NO_STRING), |value| strings.intern(value))?,
    );
    let roots = scope
        .as_ref()
        .map_or_else(Vec::new, |scope| scope.roots.clone());
    let (roots_offset, roots_count) = relations.push(roots, strings)?;
    put_u64(&mut record, 24, roots_offset);
    put_u32(
        &mut record,
        32,
        u32::try_from(roots_count).map_err(|_| CoverageIndexError::SizeOverflow)?,
    );

    let summary = selected.map_or_else(
        || Ok(view.summary.clone()),
        |ids| {
            coverage_summary_for_tests(view, ids)
                .map_err(|_| CoverageIndexError::InvalidRecord("projection summary"))
        },
    )?;
    put_summary_payload(&mut record, 36, 40, &summary)?;

    let mut limitation_kinds = [0_usize; 3];
    let mut limitation_files = BTreeSet::new();
    for limitation in &view.limitations {
        if let Some((file, kind)) = limitation_kind(limitation) {
            limitation_files.insert(file);
            match kind {
                "dynamic-code" => limitation_kinds[0] += 1,
                "semantic-safety" => limitation_kinds[1] += 1,
                "source-scope" => limitation_kinds[2] += 1,
                _ => {}
            }
        }
    }
    let corrupt_records = view
        .transport
        .as_ref()
        .map_or(0, |value| value.corrupt_records);
    let corrupt_files = view
        .transport
        .as_ref()
        .map_or(0, |value| value.corrupt_files);
    // A limitation that declares a boundary of the denominator does not block
    // measurement inside it; corrupt evidence always does.
    let declared = view
        .limitations
        .iter()
        .filter(|limitation| !crate::coverage_report::blocking_limitation(limitation))
        .count();
    for (offset, value) in [
        (192, view.limitations.len()),
        (200, corrupt_records),
        (208, view.limitations.len() - declared + corrupt_records),
        (528, declared),
        (216, limitation_files.len() + corrupt_files),
        (224, limitation_kinds[0]),
        (232, limitation_kinds[1]),
        (240, limitation_kinds[2]),
    ] {
        put_u64(&mut record, offset, usize_u64(value)?);
    }

    let phases = view
        .phases
        .iter()
        .filter(|phase| selected.is_none_or(|selected| selected.contains(&phase.test)));
    let mut attribution = [0_usize; 4];
    for phase in phases {
        attribution[0] += phase.explicit_browser_events;
        attribution[1] += phase.inferred_browser_events;
        attribution[2] += phase.explicit_server_events;
        attribution[3] += phase.inferred_server_events;
    }
    for (index, value) in attribution.into_iter().enumerate() {
        put_u64(&mut record, 248 + index * 8, usize_u64(value)?);
    }

    let confidence_levels = ["unexecuted", "executed", "action", "asserted"];
    for (index, level) in confidence_levels.into_iter().enumerate() {
        put_u64(
            &mut record,
            280 + index * 8,
            usize_u64(
                view.lines
                    .iter()
                    .filter(|line| line.confidence.level == level)
                    .count(),
            )?,
        );
    }
    put_u64(
        &mut record,
        312,
        usize_u64(
            view.decisions
                .iter()
                .flat_map(|decision| &decision.conditions)
                .filter(|condition| condition.assertion_covered)
                .count(),
        )?,
    );

    let gaps = file_gaps(view, selected)?;
    put_u64(
        &mut record,
        320,
        usize_u64(
            gaps.iter()
                .filter(|(_, gap)| {
                    gap.uncovered_lines > 0
                        || gap.uncovered_statements > 0
                        || gap.uncovered_functions > 0
                        || gap.missing_branches > 0
                        || gap.missing_mcdc_conditions > 0
                        || gap.measurement_limitations > 0
                })
                .count(),
        )?,
    );
    put_u64(
        &mut record,
        328,
        usize_u64(
            gaps.iter()
                .filter(|(_, gap)| {
                    gap.uncovered_lines > 0
                        || gap.uncovered_statements > 0
                        || gap.uncovered_functions > 0
                        || gap.missing_branches > 0
                        || gap.missing_mcdc_conditions > 0
                })
                .count(),
        )?,
    );

    let selected_tests = view
        .tests
        .iter()
        .filter(|test| selected.is_none_or(|selected| selected.contains(&test.id)))
        .collect::<Vec<_>>();
    put_u64(
        &mut record,
        336,
        usize_u64(
            selected_tests
                .iter()
                .filter(|test| test.role == "test")
                .count(),
        )?,
    );
    put_u64(
        &mut record,
        344,
        usize_u64(
            selected_tests
                .iter()
                .filter(|test| test.role == "setup")
                .count(),
        )?,
    );
    for (index, outcome) in [
        "passed",
        "failed",
        "flaky",
        "skipped",
        "timedOut",
        "interrupted",
        "unknown",
    ]
    .into_iter()
    .enumerate()
    {
        put_u64(
            &mut record,
            352 + index * 8,
            usize_u64(
                selected_tests
                    .iter()
                    .filter(|test| test.role == "test" && test.outcome == outcome)
                    .count(),
            )?,
        );
    }
    put_u64(
        &mut record,
        520,
        usize_u64(
            selected_tests
                .iter()
                .filter(|test| test.role == "test" && test.outcome == "unstarted")
                .count(),
        )?,
    );

    if let Some(transport) = &view.transport {
        record[1] = 1;
        for (index, value) in [
            transport.processes,
            transport.child_launches,
            transport.remote_launches,
            transport.workspace_capabilities,
            transport.scoped_server_records,
            transport.background_server_records,
            transport.corrupt_records,
            transport.corrupt_files,
        ]
        .into_iter()
        .enumerate()
        {
            put_u64(&mut record, 408 + index * 8, usize_u64(value)?);
        }
    }

    let phase_tests = view
        .phases
        .iter()
        .map(|phase| phase.test.as_str())
        .collect::<BTreeSet<_>>();
    let empty_tests = selected_tests
        .iter()
        .filter(|test| {
            test.role == "test"
                && test.lines.is_empty()
                && test.hits.is_empty()
                && test.decisions.is_empty()
                && phase_tests.contains(test.id.as_str())
        })
        .collect::<Vec<_>>();
    put_u64(&mut record, 472, usize_u64(empty_tests.len())?);
    put_u32(
        &mut record,
        20,
        empty_tests
            .first()
            .map_or(Ok(NO_STRING), |test| strings.intern(&test.name))?,
    );

    let entries = scope.as_ref().and_then(|scope| scope.entries);
    for (index, status) in ["included", "excluded", "ambiguous"]
        .into_iter()
        .enumerate()
    {
        put_u64(
            &mut record,
            480 + index * 8,
            usize_u64(entries.map_or(0, |entries| {
                entries
                    .iter()
                    .filter(|entry| {
                        entry.get("status").and_then(serde_json::Value::as_str) == Some(status)
                    })
                    .count()
            }))?,
        );
    }
    put_u32(
        &mut record,
        504,
        scope
            .as_ref()
            .map_or(Ok(NO_STRING), |scope| strings.intern(scope.language))?,
    );
    put_u32(
        &mut record,
        508,
        scope
            .as_ref()
            .map_or(Ok(NO_STRING), |scope| strings.intern(scope.model))?,
    );
    put_u32(
        &mut record,
        512,
        scope
            .as_ref()
            .and_then(|scope| scope.unit)
            .map_or(Ok(NO_STRING), |value| strings.intern(value))?,
    );
    if let Some(measurement_complete) = scope.as_ref().and_then(|scope| scope.measurement_complete)
    {
        record[516] = 1;
        record[517] = u8::from(measurement_complete);
    }
    Ok(record)
}

fn scope_entry_records(
    view_id: CoverageViewId,
    view: &CoverageView,
    strings: &mut StringTable,
) -> Result<Vec<[u8; SCOPE_ENTRY_RECORD_SIZE]>, CoverageIndexError> {
    let Some(scope) = &view.scope else {
        return Ok(Vec::new());
    };
    if scope.get("mode").is_none() {
        return Ok(Vec::new());
    }
    let entries = scope
        .get("entries")
        .and_then(serde_json::Value::as_array)
        .ok_or(CoverageIndexError::InvalidRecord("source-scope entries"))?;
    let mut limitations = BTreeMap::<&str, (usize, u32)>::new();
    for limitation in &view.limitations {
        let Some((file, kind)) = limitation_kind(limitation) else {
            return Err(CoverageIndexError::InvalidRecord("coverage limitation"));
        };
        let value = limitations.entry(file).or_default();
        value.0 += 1;
        value.1 |= match kind {
            "dynamic-code" => 1,
            "semantic-safety" => 2,
            "source-scope" => 4,
            _ => {
                return Err(CoverageIndexError::InvalidRecord(
                    "coverage limitation kind",
                ));
            }
        };
    }
    entries
        .iter()
        .map(|entry| {
            let file = entry
                .get("file")
                .and_then(serde_json::Value::as_str)
                .ok_or(CoverageIndexError::InvalidRecord("source-scope file"))?;
            let status = entry
                .get("status")
                .and_then(serde_json::Value::as_str)
                .ok_or(CoverageIndexError::InvalidRecord("source-scope status"))?;
            let reason = entry
                .get("reason")
                .and_then(serde_json::Value::as_str)
                .ok_or(CoverageIndexError::InvalidRecord("source-scope reason"))?;
            let package_root = entry
                .get("packageRoot")
                .map(|value| {
                    value.as_str().ok_or(CoverageIndexError::InvalidRecord(
                        "source-scope package root",
                    ))
                })
                .transpose()?;
            let mut record = [0_u8; SCOPE_ENTRY_RECORD_SIZE];
            record[0] = view_id as u8;
            record[1] = match status {
                "included" => 0,
                "excluded" => 1,
                "ambiguous" => 2,
                _ => return Err(CoverageIndexError::InvalidRecord("source-scope status")),
            };
            put_u32(&mut record, 4, strings.intern(file)?);
            put_u32(&mut record, 8, strings.intern(reason)?);
            put_u32(
                &mut record,
                12,
                package_root.map_or(Ok(NO_STRING), |value| strings.intern(value))?,
            );
            let (count, mask) = limitations.get(file).copied().unwrap_or_default();
            put_u64(&mut record, 16, usize_u64(count)?);
            put_u32(&mut record, 24, mask);
            Ok(record)
        })
        .collect()
}

fn optional_string_id(
    value: Option<&str>,
    strings: &mut StringTable,
) -> Result<u32, CoverageIndexError> {
    value.map_or(Ok(NO_STRING), |value| strings.intern(value))
}

fn confidence_record(
    confidence: &crate::coverage_report::CoverageConfidence,
    strings: &mut StringTable,
    relations: &mut StringRelations,
) -> Result<[u8; CONFIDENCE_RECORD_SIZE], CoverageIndexError> {
    let mut record = [0_u8; CONFIDENCE_RECORD_SIZE];
    record[0] = match confidence.level.as_str() {
        "unexecuted" => 0,
        "executed" => 1,
        "action" => 2,
        "asserted" => 3,
        _ => return Err(CoverageIndexError::InvalidRecord("confidence level")),
    };
    record[1] = u8::from(confidence.setup_only)
        | (u8::from(confidence.background_only) << 1)
        | (u8::from(confidence.asserted) << 2)
        | (u8::from(confidence.e2e) << 3);
    for (index, values) in [
        confidence.tests.clone(),
        confidence.asserted_tests.clone(),
        confidence.runners.clone(),
        confidence.kinds.clone(),
    ]
    .into_iter()
    .enumerate()
    {
        let (offset, count) = relations.push(values, strings)?;
        put_u64(&mut record, 8 + index * 16, offset);
        put_u64(&mut record, 16 + index * 16, count);
    }
    Ok(record)
}

fn line_record(
    view_id: CoverageViewId,
    line: &crate::coverage_report::LineResult,
    confidence_index: usize,
    strings: &mut StringTable,
    relations: &mut StringRelations,
) -> Result<[u8; LINE_RECORD_SIZE], CoverageIndexError> {
    let mut record = [0_u8; LINE_RECORD_SIZE];
    record[0] = view_id as u8;
    record[1] = u8::from(line.covered);
    // Inverted: a line every frontend declined is the exception, and a zeroed
    // byte then still reads as measured.
    record[2] = u8::from(!line.measured);
    put_u32(&mut record, 4, strings.intern(&line.file)?);
    put_u64(&mut record, 8, usize_u64(line.line)?);
    let (tests_offset, tests_count) = relations.push(line.tests.clone(), strings)?;
    put_u64(&mut record, 16, tests_offset);
    put_u64(&mut record, 24, tests_count);
    let (phases_offset, phases_count) = relations.push(line.phases.clone(), strings)?;
    put_u64(&mut record, 32, phases_offset);
    put_u64(&mut record, 40, phases_count);
    put_u64(&mut record, 48, usize_u64(confidence_index)?);
    Ok(record)
}

fn test_summary_record(
    view_id: CoverageViewId,
    test: &crate::coverage_report::TestCoverageResult,
    strings: &mut StringTable,
) -> Result<[u8; TEST_SUMMARY_RECORD_SIZE], CoverageIndexError> {
    let mut record = [0_u8; TEST_SUMMARY_RECORD_SIZE];
    record[0] = view_id as u8;
    record[1] = match test.role.as_str() {
        "test" => 0,
        "setup" => 1,
        "background" => 2,
        _ => return Err(CoverageIndexError::InvalidRecord("test role")),
    };
    record[2] = match test.outcome.as_str() {
        "passed" => 0,
        "failed" => 1,
        "flaky" => 2,
        "skipped" => 3,
        "timedOut" => 4,
        "interrupted" => 5,
        "unknown" => 6,
        "unstarted" => 7,
        _ => return Err(CoverageIndexError::InvalidRecord("test outcome")),
    };
    put_u32(&mut record, 4, strings.intern(&test.id)?);
    put_u32(&mut record, 8, strings.intern(&test.name)?);
    put_u32(
        &mut record,
        12,
        optional_string_id(test.file.as_deref(), strings)?,
    );
    put_u32(
        &mut record,
        16,
        optional_string_id(test.title.as_deref(), strings)?,
    );
    put_u32(&mut record, 20, strings.intern(&test.provenance.runner)?);
    put_u32(&mut record, 24, strings.intern(&test.provenance.kind)?);
    put_u32(
        &mut record,
        28,
        optional_string_id(test.provenance.project.as_deref(), strings)?,
    );
    put_u32(&mut record, 32, strings.intern(&test.provenance.source)?);
    Ok(record)
}

fn phase_summary_record(
    view_id: CoverageViewId,
    phase: &crate::coverage_report::PhaseResult,
    strings: &mut StringTable,
) -> Result<[u8; PHASE_SUMMARY_RECORD_SIZE], CoverageIndexError> {
    let mut record = [0_u8; PHASE_SUMMARY_RECORD_SIZE];
    record[0] = view_id as u8;
    put_u32(&mut record, 4, strings.intern(&phase.phase.id)?);
    put_u32(&mut record, 8, strings.intern(&phase.phase.kind)?);
    put_u32(&mut record, 12, strings.intern(&phase.phase.operation)?);
    put_u32(
        &mut record,
        16,
        optional_string_id(phase.phase.source.as_deref(), strings)?,
    );
    put_u32(&mut record, 20, strings.intern(&phase.test)?);
    put_u32(
        &mut record,
        24,
        optional_string_id(phase.phase.status.as_deref(), strings)?,
    );
    put_u32(
        &mut record,
        28,
        optional_string_id(phase.phase.caused_by_phase_id.as_deref(), strings)?,
    );
    put_u64(&mut record, 32, usize_u64(phase.lines.len())?);
    put_u64(
        &mut record,
        40,
        usize_u64(
            phase
                .decisions
                .iter()
                .map(|decision| decision.vectors.len())
                .sum(),
        )?,
    );
    Ok(record)
}

struct AnchorInput<'a> {
    view_id: CoverageViewId,
    kind: u8,
    id: &'a str,
    file: &'a str,
    line: usize,
    column: usize,
    covered: bool,
    conditions: Option<(usize, usize)>,
    tests: &'a [String],
}

fn anchor_record(
    input: AnchorInput<'_>,
    strings: &mut StringTable,
    relations: &mut StringRelations,
) -> Result<[u8; ANCHOR_RECORD_SIZE], CoverageIndexError> {
    let mut record = [0_u8; ANCHOR_RECORD_SIZE];
    record[0] = input.view_id as u8;
    record[1] = input.kind;
    record[2] = u8::from(input.covered);
    put_u32(&mut record, 4, strings.intern(input.id)?);
    put_u32(&mut record, 8, strings.intern(input.file)?);
    put_u64(&mut record, 16, usize_u64(input.line)?);
    put_u64(&mut record, 24, usize_u64(input.column)?);
    if let Some((covered, total)) = input.conditions {
        put_u64(&mut record, 32, usize_u64(total)?);
        put_u64(&mut record, 40, usize_u64(covered)?);
    }
    let (tests_offset, tests_count) = relations.push(input.tests.iter().cloned(), strings)?;
    put_u64(&mut record, 48, tests_offset);
    put_u64(&mut record, 56, tests_count);
    Ok(record)
}

fn test_retry_record(
    view_id: CoverageViewId,
    test_id: &str,
    retry: usize,
    strings: &mut StringTable,
) -> Result<[u8; TEST_RETRY_RECORD_SIZE], CoverageIndexError> {
    let mut record = [0_u8; TEST_RETRY_RECORD_SIZE];
    record[0] = view_id as u8;
    put_u32(&mut record, 4, strings.intern(test_id)?);
    put_u64(&mut record, 8, usize_u64(retry)?);
    Ok(record)
}

fn test_attempt_record(
    view_id: CoverageViewId,
    test_id: &str,
    attempt: &crate::coverage_report::TestAttempt,
    strings: &mut StringTable,
) -> Result<[u8; TEST_ATTEMPT_RECORD_SIZE], CoverageIndexError> {
    let mut record = [0_u8; TEST_ATTEMPT_RECORD_SIZE];
    record[0] = view_id as u8;
    put_u32(&mut record, 4, strings.intern(test_id)?);
    put_u64(&mut record, 8, usize_u64(attempt.retry)?);
    put_u32(&mut record, 16, strings.intern(&attempt.status)?);
    put_u32(
        &mut record,
        20,
        optional_string_id(attempt.expected_status.as_deref(), strings)?,
    );
    Ok(record)
}

fn test_line_record(
    view_id: CoverageViewId,
    test_id: &str,
    line: &crate::coverage_report::SourceLine,
    strings: &mut StringTable,
) -> Result<[u8; TEST_LINE_RECORD_SIZE], CoverageIndexError> {
    let mut record = [0_u8; TEST_LINE_RECORD_SIZE];
    record[0] = view_id as u8;
    put_u32(&mut record, 4, strings.intern(test_id)?);
    put_u32(&mut record, 8, strings.intern(&line.file)?);
    put_u64(&mut record, 16, usize_u64(line.line)?);
    Ok(record)
}

fn test_hit_record(
    view_id: CoverageViewId,
    test_id: &str,
    hit: &str,
    strings: &mut StringTable,
) -> Result<[u8; TEST_HIT_RECORD_SIZE], CoverageIndexError> {
    let mut record = [0_u8; TEST_HIT_RECORD_SIZE];
    record[0] = view_id as u8;
    put_u32(&mut record, 4, strings.intern(test_id)?);
    put_u32(&mut record, 8, strings.intern(hit)?);
    Ok(record)
}

fn test_vector_record(
    vector: &McdcVector,
    values: &mut Vec<u8>,
) -> Result<[u8; TEST_VECTOR_RECORD_SIZE], CoverageIndexError> {
    let mut record = [0_u8; TEST_VECTOR_RECORD_SIZE];
    record[0] = u8::from(vector.outcome);
    put_u64(&mut record, 8, usize_u64(values.len())?);
    put_u64(&mut record, 16, usize_u64(vector.values.len())?);
    values.extend(vector.values.iter().map(|value| match value {
        None => 0,
        Some(false) => 1,
        Some(true) => 2,
    }));
    Ok(record)
}

fn test_decision_record(
    view_id: CoverageViewId,
    test_id: &str,
    decision_id: &str,
    vectors_offset: usize,
    vectors_count: usize,
    strings: &mut StringTable,
) -> Result<[u8; TEST_DECISION_RECORD_SIZE], CoverageIndexError> {
    let mut record = [0_u8; TEST_DECISION_RECORD_SIZE];
    record[0] = view_id as u8;
    put_u32(&mut record, 4, strings.intern(test_id)?);
    put_u32(&mut record, 8, strings.intern(decision_id)?);
    put_u64(&mut record, 16, usize_u64(vectors_offset)?);
    put_u64(&mut record, 24, usize_u64(vectors_count)?);
    Ok(record)
}

struct HitMetadataInput<'a> {
    view_id: CoverageViewId,
    kind: u8,
    id: &'a str,
    file: &'a str,
    line: usize,
    column: usize,
    branch_kind: Option<&'a str>,
    label: Option<&'a str>,
    alternative: Option<&'a str>,
    source: &'a str,
    tests: &'a [String],
}

fn hit_metadata_record(
    input: HitMetadataInput<'_>,
    strings: &mut StringTable,
    relations: &mut StringRelations,
) -> Result<[u8; HIT_METADATA_RECORD_SIZE], CoverageIndexError> {
    let mut record = [0_u8; HIT_METADATA_RECORD_SIZE];
    record[0] = input.view_id as u8;
    record[1] = input.kind;
    put_u32(&mut record, 4, strings.intern(input.id)?);
    put_u32(&mut record, 8, strings.intern(input.file)?);
    put_u64(&mut record, 16, usize_u64(input.line)?);
    put_u64(&mut record, 24, usize_u64(input.column)?);
    put_u32(
        &mut record,
        32,
        optional_string_id(input.branch_kind, strings)?,
    );
    put_u32(&mut record, 36, optional_string_id(input.label, strings)?);
    put_u32(
        &mut record,
        40,
        optional_string_id(input.alternative, strings)?,
    );
    put_u32(&mut record, 44, strings.intern(input.source)?);
    let (tests_offset, tests_count) = relations.push(input.tests.iter().cloned(), strings)?;
    put_u64(&mut record, 48, tests_offset);
    put_u64(&mut record, 56, tests_count);
    Ok(record)
}

fn limitation_record(
    view_id: CoverageViewId,
    limitation: &serde_json::Value,
    strings: &mut StringTable,
) -> Result<[u8; LIMITATION_RECORD_SIZE], CoverageIndexError> {
    let field = |name| {
        limitation
            .get(name)
            .and_then(serde_json::Value::as_str)
            .ok_or(CoverageIndexError::InvalidRecord("coverage limitation"))
    };
    let number = |name| {
        limitation
            .get(name)
            .and_then(serde_json::Value::as_u64)
            .ok_or(CoverageIndexError::InvalidRecord("coverage limitation"))
    };
    let mut record = [0_u8; LIMITATION_RECORD_SIZE];
    record[0] = view_id as u8;
    record[1] = u8::from(crate::coverage_report::blocking_limitation(limitation));
    put_u32(&mut record, 4, strings.intern(field("id")?)?);
    put_u32(&mut record, 8, strings.intern(field("kind")?)?);
    put_u32(&mut record, 12, strings.intern(field("file")?)?);
    put_u32(&mut record, 16, strings.intern(field("source")?)?);
    put_u32(&mut record, 20, strings.intern(field("reason")?)?);
    put_u64(&mut record, 24, number("line")?);
    put_u64(&mut record, 32, number("column")?);
    Ok(record)
}

fn decision_metadata_record(
    view_id: CoverageViewId,
    decision: &crate::coverage_report::DecisionResult,
    strings: &mut StringTable,
    relations: &mut StringRelations,
) -> Result<[u8; DECISION_METADATA_RECORD_SIZE], CoverageIndexError> {
    let mut record = [0_u8; DECISION_METADATA_RECORD_SIZE];
    record[0] = view_id as u8;
    put_u32(&mut record, 4, strings.intern(&decision.meta.id)?);
    put_u32(&mut record, 8, strings.intern(&decision.meta.file)?);
    put_u32(&mut record, 12, strings.intern(&decision.meta.source)?);
    put_u32(&mut record, 16, strings.intern(&decision.meta.kind)?);
    put_u64(&mut record, 24, usize_u64(decision.meta.line)?);
    put_u64(&mut record, 32, usize_u64(decision.meta.column)?);
    let (conditions_offset, conditions_count) =
        relations.push(decision.meta.conditions.clone(), strings)?;
    put_u64(&mut record, 40, conditions_offset);
    put_u64(&mut record, 48, conditions_count);
    Ok(record)
}

fn decision_vector_observation_record(
    observation: &crate::coverage_report::VectorObservation,
    confidence_index: usize,
    vector_index: usize,
    strings: &mut StringTable,
    relations: &mut StringRelations,
) -> Result<[u8; DECISION_VECTOR_OBSERVATION_RECORD_SIZE], CoverageIndexError> {
    let mut record = [0_u8; DECISION_VECTOR_OBSERVATION_RECORD_SIZE];
    put_u64(&mut record, 0, usize_u64(confidence_index)?);
    put_u64(&mut record, 8, usize_u64(vector_index)?);
    for (offset, values) in [
        (16, observation.tests.clone()),
        (32, observation.phases.clone()),
        (48, observation.explicit_phases.clone()),
    ] {
        let (relation_offset, relation_count) = relations.push(values, strings)?;
        put_u64(&mut record, offset, relation_offset);
        put_u64(&mut record, offset + 8, relation_count);
    }
    Ok(record)
}

fn decision_condition_record(
    condition: &crate::coverage_report::ConditionResult,
    witness_vectors: Option<(usize, usize)>,
    strings: &mut StringTable,
    relations: &mut StringRelations,
) -> Result<[u8; DECISION_CONDITION_RECORD_SIZE], CoverageIndexError> {
    let mut record = [0_u8; DECISION_CONDITION_RECORD_SIZE];
    record[0] = u8::from(condition.covered)
        | (u8::from(condition.assertion_covered) << 1)
        | (u8::from(condition.witness.is_some()) << 2);
    put_u32(&mut record, 4, strings.intern(&condition.source)?);
    put_u64(&mut record, 8, usize_u64(condition.index)?);
    if let Some((first, second)) = witness_vectors {
        put_u64(&mut record, 16, usize_u64(first)?);
        put_u64(&mut record, 24, usize_u64(second)?);
    }
    let witness_tests = condition.witness_tests.clone().unwrap_or_default();
    for (offset, values) in [
        (32, witness_tests[0].clone()),
        (48, witness_tests[1].clone()),
    ] {
        let (relation_offset, relation_count) = relations.push(values, strings)?;
        put_u64(&mut record, offset, relation_offset);
        put_u64(&mut record, offset + 8, relation_count);
    }
    Ok(record)
}

struct DecisionDetailInput<'a> {
    view_id: CoverageViewId,
    decision: &'a crate::coverage_report::DecisionResult,
    confidence_index: usize,
    observations: (usize, usize),
    conditions: (usize, usize),
}

fn decision_detail_record(
    input: DecisionDetailInput<'_>,
    strings: &mut StringTable,
    relations: &mut StringRelations,
) -> Result<[u8; DECISION_DETAIL_RECORD_SIZE], CoverageIndexError> {
    let mut record = [0_u8; DECISION_DETAIL_RECORD_SIZE];
    record[0] = input.view_id as u8;
    record[1] = u8::from(input.decision.executed) | (u8::from(input.decision.covered) << 1);
    put_u32(&mut record, 4, strings.intern(&input.decision.meta.id)?);
    put_u64(&mut record, 8, usize_u64(input.confidence_index)?);
    let (tests_offset, tests_count) = relations.push(input.decision.tests.clone(), strings)?;
    put_u64(&mut record, 16, tests_offset);
    put_u64(&mut record, 24, tests_count);
    put_u64(&mut record, 32, usize_u64(input.observations.0)?);
    put_u64(&mut record, 40, usize_u64(input.observations.1)?);
    put_u64(&mut record, 48, usize_u64(input.conditions.0)?);
    put_u64(&mut record, 56, usize_u64(input.conditions.1)?);
    Ok(record)
}

fn coverage_model_record(
    variant: &str,
    model: &CoverageModel,
    strings: &mut StringTable,
    relations: &mut StringRelations,
) -> Result<[u8; COVERAGE_MODEL_RECORD_SIZE], CoverageIndexError> {
    let mut record = [0_u8; COVERAGE_MODEL_RECORD_SIZE];
    put_u32(&mut record, 0, strings.intern(variant)?);
    put_u32(&mut record, 4, strings.intern(&model.name)?);
    put_u32(&mut record, 8, strings.intern(&model.completeness_meaning)?);
    let (measured_offset, measured_count) = relations.push(model.measured.clone(), strings)?;
    put_u64(&mut record, 16, measured_offset);
    put_u64(&mut record, 24, measured_count);
    let (not_measured_offset, not_measured_count) =
        relations.push(model.not_measured.clone(), strings)?;
    put_u64(&mut record, 32, not_measured_offset);
    put_u64(&mut record, 40, not_measured_count);
    Ok(record)
}

pub fn coverage_index_sections(
    report: &CoverageReport,
) -> Result<Vec<QueryIndexSection>, CoverageIndexError> {
    let views = [
        (CoverageViewId::All, &report.view),
        (CoverageViewId::Passed, &report.filters.passed),
        (CoverageViewId::Failed, &report.filters.failed),
    ];
    let mut strings = StringTable::default();
    let mut relations = StringRelations::default();
    let mut summaries = Vec::with_capacity(views.len() * SUMMARY_RECORD_SIZE);
    let mut gaps = Vec::new();
    let mut decision_gaps = Vec::new();
    let mut dimensions = Vec::new();
    let mut projection_records = Vec::new();
    let mut scope_entries = Vec::new();
    let mut confidence_records = Vec::new();
    let mut line_records = Vec::new();
    let mut test_summaries = Vec::new();
    let mut phase_summaries = Vec::new();
    let mut anchors = Vec::new();
    let mut test_retries = Vec::new();
    let mut test_attempts = Vec::new();
    let mut test_lines = Vec::new();
    let mut test_hits = Vec::new();
    let mut test_decisions = Vec::new();
    let mut test_vectors = Vec::new();
    let mut vector_values = Vec::new();
    let mut hit_metadata = Vec::new();
    let mut decision_metadata = Vec::new();
    let mut decision_details = Vec::new();
    let mut decision_vector_observations = Vec::new();
    let mut decision_conditions = Vec::new();
    let mut limitations = Vec::new();
    for (id, view) in views {
        summaries.extend_from_slice(&summary_record(id, view, &mut strings)?);
        projection_records.extend_from_slice(&projection_record(
            id,
            view,
            None,
            None,
            None,
            &mut strings,
            &mut relations,
        )?);
        for entry in scope_entry_records(id, view, &mut strings)? {
            scope_entries.extend_from_slice(&entry);
        }
        for limitation in &view.limitations {
            limitations.extend_from_slice(&limitation_record(id, limitation, &mut strings)?);
        }
        for line in &view.lines {
            let confidence_index = confidence_records.len() / CONFIDENCE_RECORD_SIZE;
            confidence_records.extend_from_slice(&confidence_record(
                &line.confidence,
                &mut strings,
                &mut relations,
            )?);
            line_records.extend_from_slice(&line_record(
                id,
                line,
                confidence_index,
                &mut strings,
                &mut relations,
            )?);
        }
        for test in &view.tests {
            test_summaries.extend_from_slice(&test_summary_record(id, test, &mut strings)?);
            for retry in &test.retries {
                test_retries.extend_from_slice(&test_retry_record(
                    id,
                    &test.id,
                    *retry,
                    &mut strings,
                )?);
            }
            for attempt in &test.attempts {
                test_attempts.extend_from_slice(&test_attempt_record(
                    id,
                    &test.id,
                    attempt,
                    &mut strings,
                )?);
            }
            for line in &test.lines {
                test_lines.extend_from_slice(&test_line_record(id, &test.id, line, &mut strings)?);
            }
            for hit in &test.hits {
                test_hits.extend_from_slice(&test_hit_record(id, &test.id, hit, &mut strings)?);
            }
            for decision in &test.decisions {
                let vectors_offset = test_vectors.len() / TEST_VECTOR_RECORD_SIZE;
                for vector in &decision.vectors {
                    test_vectors
                        .extend_from_slice(&test_vector_record(vector, &mut vector_values)?);
                }
                test_decisions.extend_from_slice(&test_decision_record(
                    id,
                    &test.id,
                    &decision.id,
                    vectors_offset,
                    decision.vectors.len(),
                    &mut strings,
                )?);
            }
        }
        for phase in &view.phases {
            phase_summaries.extend_from_slice(&phase_summary_record(id, phase, &mut strings)?);
        }
        for decision in &view.decisions {
            let confidence_index = confidence_records.len() / CONFIDENCE_RECORD_SIZE;
            confidence_records.extend_from_slice(&confidence_record(
                &decision.confidence,
                &mut strings,
                &mut relations,
            )?);
            let observations_offset =
                decision_vector_observations.len() / DECISION_VECTOR_OBSERVATION_RECORD_SIZE;
            for observation in &decision.vector_observations {
                let observation_confidence = confidence_records.len() / CONFIDENCE_RECORD_SIZE;
                confidence_records.extend_from_slice(&confidence_record(
                    &observation.confidence,
                    &mut strings,
                    &mut relations,
                )?);
                let vector_index = test_vectors.len() / TEST_VECTOR_RECORD_SIZE;
                test_vectors.extend_from_slice(&test_vector_record(
                    &observation.vector,
                    &mut vector_values,
                )?);
                decision_vector_observations.extend_from_slice(
                    &decision_vector_observation_record(
                        observation,
                        observation_confidence,
                        vector_index,
                        &mut strings,
                        &mut relations,
                    )?,
                );
            }
            let conditions_offset = decision_conditions.len() / DECISION_CONDITION_RECORD_SIZE;
            for condition in &decision.conditions {
                let witness_vectors = if let Some(witness) = &condition.witness {
                    let first = test_vectors.len() / TEST_VECTOR_RECORD_SIZE;
                    test_vectors
                        .extend_from_slice(&test_vector_record(&witness[0], &mut vector_values)?);
                    let second = test_vectors.len() / TEST_VECTOR_RECORD_SIZE;
                    test_vectors
                        .extend_from_slice(&test_vector_record(&witness[1], &mut vector_values)?);
                    Some((first, second))
                } else {
                    None
                };
                decision_conditions.extend_from_slice(&decision_condition_record(
                    condition,
                    witness_vectors,
                    &mut strings,
                    &mut relations,
                )?);
            }
            decision_details.extend_from_slice(&decision_detail_record(
                DecisionDetailInput {
                    view_id: id,
                    decision,
                    confidence_index,
                    observations: (observations_offset, decision.vector_observations.len()),
                    conditions: (conditions_offset, decision.conditions.len()),
                },
                &mut strings,
                &mut relations,
            )?);
            decision_metadata.extend_from_slice(&decision_metadata_record(
                id,
                decision,
                &mut strings,
                &mut relations,
            )?);
            anchors.extend_from_slice(&anchor_record(
                AnchorInput {
                    view_id: id,
                    kind: 0,
                    id: &decision.meta.id,
                    file: &decision.meta.file,
                    line: decision.meta.line,
                    column: decision.meta.column,
                    covered: decision.covered,
                    conditions: Some((
                        decision
                            .conditions
                            .iter()
                            .filter(|condition| condition.covered)
                            .count(),
                        decision.conditions.len(),
                    )),
                    tests: &decision.tests,
                },
                &mut strings,
                &mut relations,
            )?);
        }
        for branch in &view.branches {
            anchors.extend_from_slice(&anchor_record(
                AnchorInput {
                    view_id: id,
                    kind: 1,
                    id: &branch.meta.id,
                    file: &branch.meta.file,
                    line: branch.meta.line,
                    column: branch.meta.column,
                    covered: branch.covered,
                    conditions: None,
                    tests: &[],
                },
                &mut strings,
                &mut relations,
            )?);
            for alternative in &branch.alternatives {
                hit_metadata.extend_from_slice(&hit_metadata_record(
                    HitMetadataInput {
                        view_id: id,
                        kind: 2,
                        id: &alternative.id,
                        file: &branch.meta.file,
                        line: branch.meta.line,
                        column: branch.meta.column,
                        branch_kind: Some(&branch.meta.kind),
                        label: Some(&branch.meta.id),
                        alternative: Some(&alternative.label),
                        source: &branch.meta.source,
                        tests: &alternative.tests,
                    },
                    &mut strings,
                    &mut relations,
                )?);
            }
        }
        for point in &view.points {
            anchors.extend_from_slice(&anchor_record(
                AnchorInput {
                    view_id: id,
                    kind: match point.meta.kind {
                        crate::coverage_analysis::PointKind::Statement => 2,
                        crate::coverage_analysis::PointKind::Function => 3,
                    },
                    id: &point.meta.id,
                    file: &point.meta.file,
                    line: point.meta.line,
                    column: point.meta.column,
                    covered: point.covered,
                    conditions: None,
                    tests: &point.tests,
                },
                &mut strings,
                &mut relations,
            )?);
            hit_metadata.extend_from_slice(&hit_metadata_record(
                HitMetadataInput {
                    view_id: id,
                    kind: match point.meta.kind {
                        crate::coverage_analysis::PointKind::Statement => 0,
                        crate::coverage_analysis::PointKind::Function => 1,
                    },
                    id: &point.meta.id,
                    file: &point.meta.file,
                    line: point.meta.line,
                    column: point.meta.column,
                    branch_kind: None,
                    label: point.meta.label.as_deref(),
                    alternative: None,
                    source: &point.meta.source,
                    tests: &point.tests,
                },
                &mut strings,
                &mut relations,
            )?);
        }
        for value in &view.coverage_by_kind {
            dimensions.extend_from_slice(&dimension_record(
                id,
                CoverageDimension::Kind,
                value,
                &mut strings,
            )?);
        }
        for value in &view.coverage_by_runner {
            dimensions.extend_from_slice(&dimension_record(
                id,
                CoverageDimension::Runner,
                value,
                &mut strings,
            )?);
        }
        for decision in &view.decisions {
            decision_gaps.extend_from_slice(&decision_gap_record(
                id,
                decision,
                None,
                None,
                None,
                &mut strings,
            )?);
        }
        for (file, gap) in file_gaps(view, None)? {
            gaps.extend_from_slice(&file_gap_record(id, &file, &gap, None, None, &mut strings)?);
        }
        for (kind, runner, selected) in projections(view) {
            projection_records.extend_from_slice(&projection_record(
                id,
                view,
                Some(&selected),
                kind.as_deref(),
                runner.as_deref(),
                &mut strings,
                &mut relations,
            )?);
            for decision in &view.decisions {
                decision_gaps.extend_from_slice(&decision_gap_record(
                    id,
                    decision,
                    Some(&selected),
                    kind.as_deref(),
                    runner.as_deref(),
                    &mut strings,
                )?);
            }
            for (file, gap) in file_gaps(view, Some(&selected))? {
                gaps.extend_from_slice(&file_gap_record(
                    id,
                    &file,
                    &gap,
                    kind.as_deref(),
                    runner.as_deref(),
                    &mut strings,
                )?);
            }
        }
    }
    let model = coverage_model_record(
        &report.view.variant,
        &report.view.model,
        &mut strings,
        &mut relations,
    )?;
    let [blob, string_records] = strings.sections()?;
    let string_relations = relations.section()?;
    Ok(vec![
        blob,
        string_records,
        string_relations,
        QueryIndexSection {
            kind: SECTION_VIEW_SUMMARIES,
            record_size: SUMMARY_RECORD_SIZE as u32,
            count: usize_u64(summaries.len() / SUMMARY_RECORD_SIZE)?,
            bytes: summaries,
        },
        QueryIndexSection {
            kind: SECTION_FILE_GAPS,
            record_size: FILE_GAP_RECORD_SIZE as u32,
            count: usize_u64(gaps.len() / FILE_GAP_RECORD_SIZE)?,
            bytes: gaps,
        },
        QueryIndexSection {
            kind: SECTION_DECISION_GAPS,
            record_size: DECISION_GAP_RECORD_SIZE as u32,
            count: usize_u64(decision_gaps.len() / DECISION_GAP_RECORD_SIZE)?,
            bytes: decision_gaps,
        },
        QueryIndexSection {
            kind: SECTION_DIMENSIONS,
            record_size: DIMENSION_RECORD_SIZE as u32,
            count: usize_u64(dimensions.len() / DIMENSION_RECORD_SIZE)?,
            bytes: dimensions,
        },
        QueryIndexSection {
            kind: SECTION_PROJECTIONS,
            record_size: PROJECTION_RECORD_SIZE as u32,
            count: usize_u64(projection_records.len() / PROJECTION_RECORD_SIZE)?,
            bytes: projection_records,
        },
        QueryIndexSection {
            kind: SECTION_SCOPE_ENTRIES,
            record_size: SCOPE_ENTRY_RECORD_SIZE as u32,
            count: usize_u64(scope_entries.len() / SCOPE_ENTRY_RECORD_SIZE)?,
            bytes: scope_entries,
        },
        QueryIndexSection {
            kind: SECTION_CONFIDENCE,
            record_size: CONFIDENCE_RECORD_SIZE as u32,
            count: usize_u64(confidence_records.len() / CONFIDENCE_RECORD_SIZE)?,
            bytes: confidence_records,
        },
        QueryIndexSection {
            kind: SECTION_LINES,
            record_size: LINE_RECORD_SIZE as u32,
            count: usize_u64(line_records.len() / LINE_RECORD_SIZE)?,
            bytes: line_records,
        },
        QueryIndexSection {
            kind: SECTION_TEST_SUMMARIES,
            record_size: TEST_SUMMARY_RECORD_SIZE as u32,
            count: usize_u64(test_summaries.len() / TEST_SUMMARY_RECORD_SIZE)?,
            bytes: test_summaries,
        },
        QueryIndexSection {
            kind: SECTION_PHASE_SUMMARIES,
            record_size: PHASE_SUMMARY_RECORD_SIZE as u32,
            count: usize_u64(phase_summaries.len() / PHASE_SUMMARY_RECORD_SIZE)?,
            bytes: phase_summaries,
        },
        QueryIndexSection {
            kind: SECTION_ANCHORS,
            record_size: ANCHOR_RECORD_SIZE as u32,
            count: usize_u64(anchors.len() / ANCHOR_RECORD_SIZE)?,
            bytes: anchors,
        },
        QueryIndexSection {
            kind: SECTION_TEST_RETRIES,
            record_size: TEST_RETRY_RECORD_SIZE as u32,
            count: usize_u64(test_retries.len() / TEST_RETRY_RECORD_SIZE)?,
            bytes: test_retries,
        },
        QueryIndexSection {
            kind: SECTION_TEST_ATTEMPTS,
            record_size: TEST_ATTEMPT_RECORD_SIZE as u32,
            count: usize_u64(test_attempts.len() / TEST_ATTEMPT_RECORD_SIZE)?,
            bytes: test_attempts,
        },
        QueryIndexSection {
            kind: SECTION_TEST_LINES,
            record_size: TEST_LINE_RECORD_SIZE as u32,
            count: usize_u64(test_lines.len() / TEST_LINE_RECORD_SIZE)?,
            bytes: test_lines,
        },
        QueryIndexSection {
            kind: SECTION_TEST_HITS,
            record_size: TEST_HIT_RECORD_SIZE as u32,
            count: usize_u64(test_hits.len() / TEST_HIT_RECORD_SIZE)?,
            bytes: test_hits,
        },
        QueryIndexSection {
            kind: SECTION_TEST_DECISIONS,
            record_size: TEST_DECISION_RECORD_SIZE as u32,
            count: usize_u64(test_decisions.len() / TEST_DECISION_RECORD_SIZE)?,
            bytes: test_decisions,
        },
        QueryIndexSection {
            kind: SECTION_TEST_VECTORS,
            record_size: TEST_VECTOR_RECORD_SIZE as u32,
            count: usize_u64(test_vectors.len() / TEST_VECTOR_RECORD_SIZE)?,
            bytes: test_vectors,
        },
        QueryIndexSection {
            kind: SECTION_VECTOR_VALUES,
            record_size: 1,
            count: usize_u64(vector_values.len())?,
            bytes: vector_values,
        },
        QueryIndexSection {
            kind: SECTION_HIT_METADATA,
            record_size: HIT_METADATA_RECORD_SIZE as u32,
            count: usize_u64(hit_metadata.len() / HIT_METADATA_RECORD_SIZE)?,
            bytes: hit_metadata,
        },
        QueryIndexSection {
            kind: SECTION_DECISION_METADATA,
            record_size: DECISION_METADATA_RECORD_SIZE as u32,
            count: usize_u64(decision_metadata.len() / DECISION_METADATA_RECORD_SIZE)?,
            bytes: decision_metadata,
        },
        QueryIndexSection {
            kind: SECTION_DECISION_DETAILS,
            record_size: DECISION_DETAIL_RECORD_SIZE as u32,
            count: usize_u64(decision_details.len() / DECISION_DETAIL_RECORD_SIZE)?,
            bytes: decision_details,
        },
        QueryIndexSection {
            kind: SECTION_DECISION_VECTOR_OBSERVATIONS,
            record_size: DECISION_VECTOR_OBSERVATION_RECORD_SIZE as u32,
            count: usize_u64(
                decision_vector_observations.len() / DECISION_VECTOR_OBSERVATION_RECORD_SIZE,
            )?,
            bytes: decision_vector_observations,
        },
        QueryIndexSection {
            kind: SECTION_DECISION_CONDITIONS,
            record_size: DECISION_CONDITION_RECORD_SIZE as u32,
            count: usize_u64(decision_conditions.len() / DECISION_CONDITION_RECORD_SIZE)?,
            bytes: decision_conditions,
        },
        QueryIndexSection {
            kind: SECTION_LIMITATIONS,
            record_size: LIMITATION_RECORD_SIZE as u32,
            count: usize_u64(limitations.len() / LIMITATION_RECORD_SIZE)?,
            bytes: limitations,
        },
        QueryIndexSection {
            kind: SECTION_COVERAGE_MODEL,
            record_size: COVERAGE_MODEL_RECORD_SIZE as u32,
            count: 1,
            bytes: model.to_vec(),
        },
    ])
}

pub struct CoverageIndex<'a> {
    index: &'a QueryIndex,
}

impl<'a> CoverageIndex<'a> {
    pub fn new(index: &'a QueryIndex) -> Result<Self, CoverageIndexError> {
        for (kind, size) in [
            (SECTION_STRINGS, STRING_RECORD_SIZE),
            (SECTION_VIEW_SUMMARIES, SUMMARY_RECORD_SIZE),
            (SECTION_FILE_GAPS, FILE_GAP_RECORD_SIZE),
            (SECTION_DECISION_GAPS, DECISION_GAP_RECORD_SIZE),
            (SECTION_DIMENSIONS, DIMENSION_RECORD_SIZE),
            (SECTION_PROJECTIONS, PROJECTION_RECORD_SIZE),
            (SECTION_SCOPE_ENTRIES, SCOPE_ENTRY_RECORD_SIZE),
            (SECTION_CONFIDENCE, CONFIDENCE_RECORD_SIZE),
            (SECTION_LINES, LINE_RECORD_SIZE),
            (SECTION_TEST_SUMMARIES, TEST_SUMMARY_RECORD_SIZE),
            (SECTION_PHASE_SUMMARIES, PHASE_SUMMARY_RECORD_SIZE),
            (SECTION_ANCHORS, ANCHOR_RECORD_SIZE),
            (SECTION_TEST_RETRIES, TEST_RETRY_RECORD_SIZE),
            (SECTION_TEST_ATTEMPTS, TEST_ATTEMPT_RECORD_SIZE),
            (SECTION_TEST_LINES, TEST_LINE_RECORD_SIZE),
            (SECTION_TEST_HITS, TEST_HIT_RECORD_SIZE),
            (SECTION_TEST_DECISIONS, TEST_DECISION_RECORD_SIZE),
            (SECTION_TEST_VECTORS, TEST_VECTOR_RECORD_SIZE),
            (SECTION_VECTOR_VALUES, 1),
            (SECTION_HIT_METADATA, HIT_METADATA_RECORD_SIZE),
            (SECTION_DECISION_METADATA, DECISION_METADATA_RECORD_SIZE),
            (SECTION_DECISION_DETAILS, DECISION_DETAIL_RECORD_SIZE),
            (
                SECTION_DECISION_VECTOR_OBSERVATIONS,
                DECISION_VECTOR_OBSERVATION_RECORD_SIZE,
            ),
            (SECTION_DECISION_CONDITIONS, DECISION_CONDITION_RECORD_SIZE),
            (SECTION_LIMITATIONS, LIMITATION_RECORD_SIZE),
            (SECTION_COVERAGE_MODEL, COVERAGE_MODEL_RECORD_SIZE),
        ] {
            if index.descriptor(kind)?.record_size as usize != size {
                return Err(CoverageIndexError::InvalidRecord("record size"));
            }
        }
        index.descriptor(SECTION_STRING_BYTES)?;
        if index.descriptor(SECTION_STRING_RELATIONS)?.record_size != 4 {
            return Err(CoverageIndexError::InvalidRecord(
                "string-relation record size",
            ));
        }
        Ok(Self { index })
    }

    pub fn model(&self) -> Result<IndexedCoverageModel, CoverageIndexError> {
        let descriptor = self.index.descriptor(SECTION_COVERAGE_MODEL)?;
        if descriptor.count != 1 {
            return Err(CoverageIndexError::InvalidRecord(
                "coverage model record count",
            ));
        }
        let record = self.index.record(SECTION_COVERAGE_MODEL, 0)?;
        if record[12..16].iter().any(|byte| *byte != 0) {
            return Err(CoverageIndexError::InvalidRecord(
                "coverage model reserved bytes",
            ));
        }
        Ok(IndexedCoverageModel {
            schema_version: COVERAGE_MODEL_SCHEMA_VERSION,
            variant: self.string(get_u32(record, 0)?)?,
            name: self.string(get_u32(record, 4)?)?,
            completeness_meaning: self.string(get_u32(record, 8)?)?,
            measured: self.relation_strings(get_u64(record, 16)?, get_u64(record, 24)?)?,
            not_measured: self.relation_strings(get_u64(record, 32)?, get_u64(record, 40)?)?,
        })
    }

    fn string(&self, id: u32) -> Result<String, CoverageIndexError> {
        let record = self.index.record(SECTION_STRINGS, u64::from(id))?;
        if record[12..].iter().any(|byte| *byte != 0) {
            return Err(CoverageIndexError::InvalidRecord("string reserved bytes"));
        }
        let offset = get_u64(record, 0)?;
        let length = u64::from(get_u32(record, 8)?);
        let value = self.index.bytes(SECTION_STRING_BYTES, offset, length)?;
        std::str::from_utf8(value)
            .map(str::to_owned)
            .map_err(|_| CoverageIndexError::InvalidUtf8)
    }

    pub fn summary(&self, view: CoverageViewId) -> Result<CoverageSummary, CoverageIndexError> {
        let descriptor = self.index.descriptor(SECTION_VIEW_SUMMARIES)?;
        if descriptor.count != 3 {
            return Err(CoverageIndexError::InvalidRecord("summary view count"));
        }
        let mut found = None;
        for index in 0..descriptor.count {
            let record = self.index.record(SECTION_VIEW_SUMMARIES, index)?;
            if CoverageViewId::try_from(record[0])? != view {
                continue;
            }
            if record[3] != 0 || record[12..16].iter().any(|byte| *byte != 0) {
                return Err(CoverageIndexError::InvalidRecord("summary reserved bytes"));
            }
            self.string(get_u32(record, 4)?)?;
            self.string(get_u32(record, 8)?)?;
            let count = |offset: usize| -> Result<CoverageCount, CoverageIndexError> {
                let covered = usize::try_from(get_u64(record, offset)?)
                    .map_err(|_| CoverageIndexError::SizeOverflow)?;
                let total = usize::try_from(get_u64(record, offset + 8)?)
                    .map_err(|_| CoverageIndexError::SizeOverflow)?;
                if covered > total {
                    return Err(CoverageIndexError::InvalidRecord("covered exceeds total"));
                }
                Ok(CoverageCount {
                    covered,
                    total,
                    percentage: percentage(covered, total),
                })
            };
            let value = |offset: usize| -> Result<usize, CoverageIndexError> {
                usize::try_from(get_u64(record, offset)?)
                    .map_err(|_| CoverageIndexError::SizeOverflow)
            };
            let conditions = value(40)?;
            let covered_conditions = value(48)?;
            if covered_conditions > conditions {
                return Err(CoverageIndexError::InvalidRecord(
                    "covered conditions exceed total",
                ));
            }
            let decisions = value(16)?;
            let executed_decisions = value(24)?;
            let covered_decisions = value(32)?;
            if covered_decisions > executed_decisions || executed_decisions > decisions {
                return Err(CoverageIndexError::InvalidRecord("decision count ordering"));
            }
            let summary = CoverageSummary {
                unmeasured_obligations: None,
                exact_fraction_pct: None,
                decisions,
                executed_decisions,
                covered_decisions,
                conditions,
                covered_conditions,
                condition_coverage_pct: percentage(covered_conditions, conditions),
                lines: count(56)?,
                statements: count(72)?,
                functions: count(88)?,
                branches: count(104)?,
                decision_outcomes: count(120)?,
                condition_outcomes: count(136)?,
                value_selections: count(152)?,
                coverage_complete: bool_field(record[1])?,
                completeness_blocked: match record[2] {
                    0 => None,
                    1 => Some(false),
                    2 => Some(true),
                    _ => return Err(CoverageIndexError::InvalidRecord("optional boolean")),
                },
            };
            if found.replace(summary).is_some() {
                return Err(CoverageIndexError::InvalidRecord("duplicate coverage view"));
            }
        }
        found.ok_or(CoverageIndexError::InvalidRecord("missing coverage view"))
    }

    pub fn file_gaps(
        &self,
        view: CoverageViewId,
        kind: Option<&str>,
        runner: Option<&str>,
    ) -> Result<Vec<IndexedFileGap>, CoverageIndexError> {
        let descriptor = self.index.descriptor(SECTION_FILE_GAPS)?;
        let mut gaps = Vec::new();
        for index in 0..descriptor.count {
            let record = self.index.record(SECTION_FILE_GAPS, index)?;
            if CoverageViewId::try_from(record[0])? != view {
                continue;
            }
            if record[1..4].iter().any(|byte| *byte != 0)
                || record[60..64].iter().any(|byte| *byte != 0)
                || record[160..].iter().any(|byte| *byte != 0)
            {
                return Err(CoverageIndexError::InvalidRecord("file-gap reserved bytes"));
            }
            let number = |offset: usize| -> Result<usize, CoverageIndexError> {
                usize::try_from(get_u64(record, offset)?)
                    .map_err(|_| CoverageIndexError::SizeOverflow)
            };
            let mask = get_u32(record, 56)?;
            if mask & !15 != 0 {
                return Err(CoverageIndexError::InvalidRecord("limitation mask"));
            }
            let measurement_limitations = number(48)?;
            if (measurement_limitations == 0) != (mask == 0) {
                return Err(CoverageIndexError::InvalidRecord(
                    "limitation count and kinds disagree",
                ));
            }
            let uncovered_lines = number(8)?;
            let uncovered_statements = number(16)?;
            let uncovered_functions = number(24)?;
            let missing_branches = number(32)?;
            let missing_mcdc_conditions = number(40)?;
            let score = number(64)?;
            let expected_score = uncovered_lines
                + uncovered_functions * 2
                + missing_branches * 2
                + missing_mcdc_conditions * 3
                + measurement_limitations * 3;
            if score != expected_score {
                return Err(CoverageIndexError::InvalidRecord("file-gap score"));
            }
            let record_kind = self.optional_string(get_u32(record, 72)?)?;
            let record_runner = self.optional_string(get_u32(record, 76)?)?;
            if record_kind.as_deref() != kind || record_runner.as_deref() != runner {
                continue;
            }
            let mut limitation_kinds = Vec::new();
            for (bit, kind) in [
                (1, "dynamic-code"),
                (2, "semantic-safety"),
                (4, "source-scope"),
                (8, "unknown"),
            ] {
                if mask & bit != 0 {
                    limitation_kinds.push(kind.into());
                }
            }
            gaps.push(IndexedFileGap {
                view,
                file: self.string(get_u32(record, 4)?)?,
                uncovered_lines,
                uncovered_statements,
                uncovered_functions,
                missing_branches,
                missing_mcdc_conditions,
                measurement_limitations,
                limitation_kinds,
                covered_by_other_tests: IndexedGapDimensions {
                    lines: number(80)?,
                    statements: number(88)?,
                    functions: number(96)?,
                    branches: number(104)?,
                    mcdc_conditions: number(112)?,
                },
                uncovered_everywhere: IndexedGapDimensions {
                    lines: number(120)?,
                    statements: number(128)?,
                    functions: number(136)?,
                    branches: number(144)?,
                    mcdc_conditions: number(152)?,
                },
                score,
            });
        }
        gaps.sort_by(|left, right| {
            right
                .score
                .cmp(&left.score)
                .then_with(|| left.file.cmp(&right.file))
        });
        Ok(gaps)
    }

    fn optional_string(&self, id: u32) -> Result<Option<String>, CoverageIndexError> {
        if id == NO_STRING {
            Ok(None)
        } else {
            self.string(id).map(Some)
        }
    }

    fn relation_strings(&self, offset: u64, count: u64) -> Result<Vec<String>, CoverageIndexError> {
        let end = offset
            .checked_add(count)
            .ok_or(CoverageIndexError::SizeOverflow)?;
        let descriptor = self.index.descriptor(SECTION_STRING_RELATIONS)?;
        if end > descriptor.count {
            return Err(CoverageIndexError::InvalidRecord("string relation range"));
        }
        (offset..end)
            .map(|index| {
                let record = self.index.record(SECTION_STRING_RELATIONS, index)?;
                self.string(get_u32(record, 0)?)
            })
            .collect()
    }

    pub fn projection(
        &self,
        view: CoverageViewId,
        kind: Option<&str>,
        runner: Option<&str>,
    ) -> Result<IndexedProjection, CoverageIndexError> {
        let descriptor = self.index.descriptor(SECTION_PROJECTIONS)?;
        let mut found = None;
        for index in 0..descriptor.count {
            let record = self.index.record(SECTION_PROJECTIONS, index)?;
            if CoverageViewId::try_from(record[0])? != view {
                continue;
            }
            if record[38..40].iter().any(|byte| *byte != 0)
                || record[518..520].iter().any(|byte| *byte != 0)
            {
                return Err(CoverageIndexError::InvalidRecord(
                    "projection reserved bytes",
                ));
            }
            let record_kind = self.optional_string(get_u32(record, 4)?)?;
            let record_runner = self.optional_string(get_u32(record, 8)?)?;
            if record_kind.as_deref() != kind || record_runner.as_deref() != runner {
                continue;
            }
            if found.is_some() {
                return Err(CoverageIndexError::InvalidRecord(
                    "duplicate coverage projection",
                ));
            }
            let number = |offset: usize| -> Result<usize, CoverageIndexError> {
                usize::try_from(get_u64(record, offset)?)
                    .map_err(|_| CoverageIndexError::SizeOverflow)
            };
            let limitations = number(192)?;
            let evidence_corruptions = number(200)?;
            let blocking = number(208)?;
            let declared = number(528)?;
            if blocking + declared != limitations + evidence_corruptions {
                return Err(CoverageIndexError::InvalidRecord(
                    "measurement blocking count",
                ));
            }
            let transport_values = (0..8)
                .map(|index| number(408 + index * 8))
                .collect::<Result<Vec<_>, _>>()?;
            let transport = if bool_field(record[1])? {
                Some(TransportStats {
                    processes: transport_values[0],
                    child_launches: transport_values[1],
                    remote_launches: transport_values[2],
                    workspace_capabilities: transport_values[3],
                    scoped_server_records: transport_values[4],
                    background_server_records: transport_values[5],
                    corrupt_records: transport_values[6],
                    corrupt_files: transport_values[7],
                })
            } else {
                if transport_values.iter().any(|value| *value != 0) {
                    return Err(CoverageIndexError::InvalidRecord("transport presence flag"));
                }
                None
            };
            let has_scope = bool_field(record[2])?;
            let scope_kind = match record[3] {
                0 => None,
                1 => Some((ScopeKind::SourceDiscovery, "source-discovery")),
                2 => Some((ScopeKind::Compiler, "compiler")),
                _ => return Err(CoverageIndexError::InvalidRecord("coverage scope kind")),
            };
            let scope_mode = self.optional_string(get_u32(record, 16)?)?;
            let scope_language = self.optional_string(get_u32(record, 504)?)?;
            let scope_model = self.optional_string(get_u32(record, 508)?)?;
            let scope_unit = self.optional_string(get_u32(record, 512)?)?;
            let has_measurement_complete = bool_field(record[516])?;
            let measurement_complete = bool_field(record[517])?;
            if !has_measurement_complete && measurement_complete {
                return Err(CoverageIndexError::InvalidRecord(
                    "scope measurement completeness flag",
                ));
            }
            if has_scope
                != (scope_kind.is_some() && scope_language.is_some() && scope_model.is_some())
            {
                return Err(CoverageIndexError::InvalidRecord("scope presence flag"));
            }
            let source_scope = if let Some((kind, kind_name)) = scope_kind {
                match kind {
                    ScopeKind::SourceDiscovery => {
                        if scope_mode.is_none() || scope_unit.is_some() || has_measurement_complete
                        {
                            return Err(CoverageIndexError::InvalidRecord(
                                "source-discovery scope shape",
                            ));
                        }
                    }
                    ScopeKind::Compiler => {
                        if scope_mode.is_some()
                            || scope_unit.is_none()
                            || !has_measurement_complete
                            || get_u32(record, 32)? != 0
                            || number(480)? != 0
                            || number(488)? != 0
                            || number(496)? != 0
                        {
                            return Err(CoverageIndexError::InvalidRecord("compiler scope shape"));
                        }
                    }
                }
                Some(IndexedSourceScope {
                    kind: kind_name.into(),
                    language: scope_language.expect("validated scope language"),
                    model: scope_model.expect("validated scope model"),
                    mode: scope_mode,
                    roots: self
                        .relation_strings(get_u64(record, 24)?, u64::from(get_u32(record, 32)?))?,
                    unit: scope_unit,
                    measurement_complete: has_measurement_complete.then_some(measurement_complete),
                    included: number(480)?,
                    excluded: number(488)?,
                    ambiguous: number(496)?,
                })
            } else {
                if get_u32(record, 32)? != 0
                    || scope_mode.is_some()
                    || scope_language.is_some()
                    || scope_model.is_some()
                    || scope_unit.is_some()
                    || has_measurement_complete
                    || number(480)? != 0
                    || number(488)? != 0
                    || number(496)? != 0
                {
                    return Err(CoverageIndexError::InvalidRecord("absent scope data"));
                }
                None
            };
            let empty_evidence_tests = number(472)?;
            let first_empty_evidence_test = self.optional_string(get_u32(record, 20)?)?;
            if (empty_evidence_tests == 0) != first_empty_evidence_test.is_none() {
                return Err(CoverageIndexError::InvalidRecord(
                    "empty-evidence diagnostic identity",
                ));
            }
            found = Some(IndexedProjection {
                view,
                kind: record_kind,
                runner: record_runner,
                generated_at: self.string(get_u32(record, 12)?)?,
                summary: decode_summary(record, 36, 40)?,
                measurement: IndexedMeasurement {
                    complete: blocking == 0,
                    limitations,
                    evidence_corruptions,
                    blocking,
                    declared,
                    files: number(216)?,
                    by_kind: IndexedMeasurementKinds {
                        dynamic_code: number(224)?,
                        semantic_safety: number(232)?,
                        source_scope: number(240)?,
                    },
                },
                attribution: IndexedAttribution {
                    browser_explicit: number(248)?,
                    browser_fallback: number(256)?,
                    server_explicit: number(264)?,
                    server_fallback: number(272)?,
                },
                transport,
                empty_evidence_tests,
                first_empty_evidence_test,
                confidence: IndexedSummaryConfidence {
                    lines: IndexedConfidenceLines {
                        unexecuted: number(280)?,
                        executed: number(288)?,
                        action: number(296)?,
                        asserted: number(304)?,
                    },
                    assertion_covered_mcdc_conditions: number(312)?,
                },
                files_with_gaps: number(320)?,
                files_with_coverage_gaps: number(328)?,
                tests: number(336)?,
                setups: number(344)?,
                test_outcomes: IndexedOutcomeCounts {
                    passed: number(352)?,
                    failed: number(360)?,
                    flaky: number(368)?,
                    skipped: number(376)?,
                    timed_out: number(384)?,
                    interrupted: number(392)?,
                    unknown: number(400)?,
                    unstarted: number(520)?,
                },
                source_scope,
            });
        }
        found.ok_or(CoverageIndexError::InvalidRecord(
            "missing coverage projection",
        ))
    }

    pub fn decision_gaps(
        &self,
        view: CoverageViewId,
        kind: Option<&str>,
        runner: Option<&str>,
        file: &str,
    ) -> Result<Vec<IndexedDecisionGap>, CoverageIndexError> {
        let descriptor = self.index.descriptor(SECTION_DECISION_GAPS)?;
        let mut decisions = Vec::new();
        for index in 0..descriptor.count {
            let record = self.index.record(SECTION_DECISION_GAPS, index)?;
            if CoverageViewId::try_from(record[0])? != view {
                continue;
            }
            if record[1..4].iter().any(|byte| *byte != 0)
                || record[28..32].iter().any(|byte| *byte != 0)
                || record[64..].iter().any(|byte| *byte != 0)
            {
                return Err(CoverageIndexError::InvalidRecord(
                    "decision-gap reserved bytes",
                ));
            }
            let record_kind = self.optional_string(get_u32(record, 4)?)?;
            let record_runner = self.optional_string(get_u32(record, 8)?)?;
            if record_kind.as_deref() != kind || record_runner.as_deref() != runner {
                continue;
            }
            let record_file = self.string(get_u32(record, 16)?)?;
            if record_file != file {
                continue;
            }
            let number = |offset: usize| -> Result<usize, CoverageIndexError> {
                usize::try_from(get_u64(record, offset)?)
                    .map_err(|_| CoverageIndexError::SizeOverflow)
            };
            let conditions = number(48)?;
            let missing_conditions = number(56)?;
            if conditions == 0 || missing_conditions > conditions {
                return Err(CoverageIndexError::InvalidRecord(
                    "decision condition counts",
                ));
            }
            decisions.push(IndexedDecisionGap {
                view,
                file: record_file,
                id: self.string(get_u32(record, 12)?)?,
                line: number(32)?,
                column: number(40)?,
                kind: self.string(get_u32(record, 20)?)?,
                conditions,
                missing_conditions,
                source: self.string(get_u32(record, 24)?)?,
            });
        }
        Ok(decisions)
    }

    pub fn dimensions(
        &self,
        view: CoverageViewId,
        dimension: CoverageDimension,
    ) -> Result<Vec<IndexedDimensionCoverage>, CoverageIndexError> {
        let descriptor = self.index.descriptor(SECTION_DIMENSIONS)?;
        let mut values = Vec::new();
        for index in 0..descriptor.count {
            let record = self.index.record(SECTION_DIMENSIONS, index)?;
            if CoverageViewId::try_from(record[0])? != view {
                continue;
            }
            let record_dimension = match record[1] {
                0 => CoverageDimension::Kind,
                1 => CoverageDimension::Runner,
                _ => return Err(CoverageIndexError::InvalidRecord("dimension type")),
            };
            if record_dimension != dimension {
                continue;
            }
            if record[26..32].iter().any(|byte| *byte != 0)
                || record[184..].iter().any(|byte| *byte != 0)
            {
                return Err(CoverageIndexError::InvalidRecord(
                    "dimension reserved bytes",
                ));
            }
            let name = self.string(get_u32(record, 4)?)?;
            values.push(IndexedDimensionCoverage {
                kind: (dimension == CoverageDimension::Kind).then(|| name.clone()),
                runner: (dimension == CoverageDimension::Runner).then_some(name),
                tests: usize::try_from(get_u64(record, 8)?)
                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
                setups: usize::try_from(get_u64(record, 16)?)
                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
                summary: decode_summary(record, 24, 32)?,
            });
        }
        Ok(values)
    }

    pub fn scope_entries(
        &self,
        view: CoverageViewId,
    ) -> Result<Vec<IndexedScopeEntry>, CoverageIndexError> {
        let descriptor = self.index.descriptor(SECTION_SCOPE_ENTRIES)?;
        let mut entries = Vec::new();
        for index in 0..descriptor.count {
            let record = self.index.record(SECTION_SCOPE_ENTRIES, index)?;
            if CoverageViewId::try_from(record[0])? != view {
                continue;
            }
            if record[2..4].iter().any(|byte| *byte != 0)
                || record[28..].iter().any(|byte| *byte != 0)
            {
                return Err(CoverageIndexError::InvalidRecord(
                    "source-scope reserved bytes",
                ));
            }
            let status = match record[1] {
                0 => "included",
                1 => "excluded",
                2 => "ambiguous",
                _ => return Err(CoverageIndexError::InvalidRecord("source-scope status")),
            };
            let measurement_limitations = usize::try_from(get_u64(record, 16)?)
                .map_err(|_| CoverageIndexError::SizeOverflow)?;
            let mask = get_u32(record, 24)?;
            if mask & !7 != 0 || (measurement_limitations == 0) != (mask == 0) {
                return Err(CoverageIndexError::InvalidRecord(
                    "source-scope limitation annotation",
                ));
            }
            let mut limitation_kinds = Vec::new();
            for (bit, kind) in [
                (1, "dynamic-code"),
                (2, "semantic-safety"),
                (4, "source-scope"),
            ] {
                if mask & bit != 0 {
                    limitation_kinds.push(kind.into());
                }
            }
            entries.push(IndexedScopeEntry {
                file: self.string(get_u32(record, 4)?)?,
                status: status.into(),
                reason: self.string(get_u32(record, 8)?)?,
                package_root: self.optional_string(get_u32(record, 12)?)?,
                measurement_limitations,
                limitation_kinds,
            });
        }
        Ok(entries)
    }

    fn confidence(
        &self,
        index: u64,
    ) -> Result<crate::coverage_report::CoverageConfidence, CoverageIndexError> {
        let record = self.index.record(SECTION_CONFIDENCE, index)?;
        if record[2..8].iter().any(|byte| *byte != 0)
            || record[72..].iter().any(|byte| *byte != 0)
            || record[1] & !15 != 0
        {
            return Err(CoverageIndexError::InvalidRecord("confidence record"));
        }
        let values = (0..4)
            .map(|index| {
                self.relation_strings(
                    get_u64(record, 8 + index * 16)?,
                    get_u64(record, 16 + index * 16)?,
                )
            })
            .collect::<Result<Vec<_>, _>>()?;
        Ok(crate::coverage_report::CoverageConfidence {
            level: match record[0] {
                0 => "unexecuted",
                1 => "executed",
                2 => "action",
                3 => "asserted",
                _ => return Err(CoverageIndexError::InvalidRecord("confidence level")),
            }
            .into(),
            setup_only: record[1] & 1 != 0,
            background_only: record[1] & 2 != 0,
            asserted: record[1] & 4 != 0,
            e2e: record[1] & 8 != 0,
            tests: values[0].clone(),
            asserted_tests: values[1].clone(),
            runners: values[2].clone(),
            kinds: values[3].clone(),
        })
    }

    pub fn line(
        &self,
        view: CoverageViewId,
        file: &str,
        line: usize,
    ) -> Result<Option<IndexedLine>, CoverageIndexError> {
        let descriptor = self.index.descriptor(SECTION_LINES)?;
        let mut found = None;
        for index in 0..descriptor.count {
            let record = self.index.record(SECTION_LINES, index)?;
            if CoverageViewId::try_from(record[0])? != view {
                continue;
            }
            if record[3] != 0 || record[56..].iter().any(|byte| *byte != 0) {
                return Err(CoverageIndexError::InvalidRecord("line record"));
            }
            let record_file = self.string(get_u32(record, 4)?)?;
            let record_line = usize::try_from(get_u64(record, 8)?)
                .map_err(|_| CoverageIndexError::SizeOverflow)?;
            if record_file != file || record_line != line {
                continue;
            }
            if found.is_some() {
                return Err(CoverageIndexError::InvalidRecord("duplicate line"));
            }
            found = Some(IndexedLine {
                file: record_file,
                line: record_line,
                covered: bool_field(record[1])?,
                measured: !bool_field(record[2])?,
                tests: self.relation_strings(get_u64(record, 16)?, get_u64(record, 24)?)?,
                phases: self.relation_strings(get_u64(record, 32)?, get_u64(record, 40)?)?,
                confidence: self.confidence(get_u64(record, 48)?)?,
            });
        }
        Ok(found)
    }

    pub fn lines(&self, view: CoverageViewId) -> Result<Vec<IndexedLine>, CoverageIndexError> {
        let descriptor = self.index.descriptor(SECTION_LINES)?;
        let mut lines = Vec::new();
        for index in 0..descriptor.count {
            let record = self.index.record(SECTION_LINES, index)?;
            if CoverageViewId::try_from(record[0])? != view {
                continue;
            }
            if record[3] != 0 || record[56..].iter().any(|byte| *byte != 0) {
                return Err(CoverageIndexError::InvalidRecord("line record"));
            }
            lines.push(IndexedLine {
                file: self.string(get_u32(record, 4)?)?,
                line: usize::try_from(get_u64(record, 8)?)
                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
                covered: bool_field(record[1])?,
                measured: !bool_field(record[2])?,
                tests: self.relation_strings(get_u64(record, 16)?, get_u64(record, 24)?)?,
                phases: self.relation_strings(get_u64(record, 32)?, get_u64(record, 40)?)?,
                confidence: self.confidence(get_u64(record, 48)?)?,
            });
        }
        Ok(lines)
    }

    pub fn test_summaries(
        &self,
        view: CoverageViewId,
    ) -> Result<Vec<IndexedTestSummary>, CoverageIndexError> {
        let descriptor = self.index.descriptor(SECTION_TEST_SUMMARIES)?;
        let mut tests = Vec::new();
        for index in 0..descriptor.count {
            let record = self.index.record(SECTION_TEST_SUMMARIES, index)?;
            if CoverageViewId::try_from(record[0])? != view {
                continue;
            }
            if record[3] != 0 || record[36..].iter().any(|byte| *byte != 0) {
                return Err(CoverageIndexError::InvalidRecord("test summary record"));
            }
            tests.push(IndexedTestSummary {
                id: self.string(get_u32(record, 4)?)?,
                name: self.string(get_u32(record, 8)?)?,
                file: self.optional_string(get_u32(record, 12)?)?,
                title: self.optional_string(get_u32(record, 16)?)?,
                role: match record[1] {
                    0 => "test",
                    1 => "setup",
                    2 => "background",
                    _ => return Err(CoverageIndexError::InvalidRecord("test role")),
                }
                .into(),
                outcome: match record[2] {
                    0 => "passed",
                    1 => "failed",
                    2 => "flaky",
                    3 => "skipped",
                    4 => "timedOut",
                    5 => "interrupted",
                    6 => "unknown",
                    7 => "unstarted",
                    _ => return Err(CoverageIndexError::InvalidRecord("test outcome")),
                }
                .into(),
                provenance: crate::coverage_report::TestProvenance {
                    runner: self.string(get_u32(record, 20)?)?,
                    kind: self.string(get_u32(record, 24)?)?,
                    project: self.optional_string(get_u32(record, 28)?)?,
                    source: self.string(get_u32(record, 32)?)?,
                },
            });
        }
        Ok(tests)
    }

    fn test_vector(&self, index: u64) -> Result<McdcVector, CoverageIndexError> {
        let record = self.index.record(SECTION_TEST_VECTORS, index)?;
        if record[1..8].iter().any(|byte| *byte != 0) {
            return Err(CoverageIndexError::InvalidRecord("test vector record"));
        }
        let offset = get_u64(record, 8)?;
        let count = get_u64(record, 16)?;
        let descriptor = self.index.descriptor(SECTION_VECTOR_VALUES)?;
        let end = offset
            .checked_add(count)
            .ok_or(CoverageIndexError::InvalidRecord("vector value range"))?;
        if end > descriptor.count {
            return Err(CoverageIndexError::InvalidRecord("vector value range"));
        }
        let mut values = Vec::with_capacity(
            usize::try_from(count).map_err(|_| CoverageIndexError::SizeOverflow)?,
        );
        for index in offset..end {
            values.push(match self.index.record(SECTION_VECTOR_VALUES, index)?[0] {
                0 => None,
                1 => Some(false),
                2 => Some(true),
                _ => return Err(CoverageIndexError::InvalidRecord("vector value")),
            });
        }
        Ok(McdcVector {
            values,
            outcome: bool_field(record[0])?,
        })
    }

    pub fn test_details(
        &self,
        view: CoverageViewId,
    ) -> Result<Vec<IndexedTestDetail>, CoverageIndexError> {
        let summaries = self.test_summaries(view)?;
        let positions = summaries
            .iter()
            .enumerate()
            .map(|(index, test)| (test.id.clone(), index))
            .collect::<HashMap<_, _>>();
        if positions.len() != summaries.len() {
            return Err(CoverageIndexError::InvalidRecord("duplicate test summary"));
        }
        let mut details = summaries
            .into_iter()
            .map(|summary| IndexedTestDetail {
                summary,
                retries: Vec::new(),
                attempts: Vec::new(),
                hits: Vec::new(),
                decisions: Vec::new(),
                lines: Vec::new(),
            })
            .collect::<Vec<_>>();
        let position = |record: &[u8]| -> Result<Option<usize>, CoverageIndexError> {
            if CoverageViewId::try_from(record[0])? != view {
                return Ok(None);
            }
            let id = self.string(get_u32(record, 4)?)?;
            positions
                .get(&id)
                .copied()
                .map(Some)
                .ok_or(CoverageIndexError::InvalidRecord("unknown test relation"))
        };
        let descriptor = self.index.descriptor(SECTION_TEST_RETRIES)?;
        for index in 0..descriptor.count {
            let record = self.index.record(SECTION_TEST_RETRIES, index)?;
            if record[1..4].iter().any(|byte| *byte != 0) {
                return Err(CoverageIndexError::InvalidRecord("test retry record"));
            }
            if let Some(position) = position(record)? {
                details[position].retries.push(
                    usize::try_from(get_u64(record, 8)?)
                        .map_err(|_| CoverageIndexError::SizeOverflow)?,
                );
            }
        }
        let descriptor = self.index.descriptor(SECTION_TEST_ATTEMPTS)?;
        for index in 0..descriptor.count {
            let record = self.index.record(SECTION_TEST_ATTEMPTS, index)?;
            if record[1..4].iter().any(|byte| *byte != 0) {
                return Err(CoverageIndexError::InvalidRecord("test attempt record"));
            }
            if let Some(position) = position(record)? {
                details[position]
                    .attempts
                    .push(crate::coverage_report::TestAttempt {
                        retry: usize::try_from(get_u64(record, 8)?)
                            .map_err(|_| CoverageIndexError::SizeOverflow)?,
                        status: self.string(get_u32(record, 16)?)?,
                        expected_status: self.optional_string(get_u32(record, 20)?)?,
                    });
            }
        }
        let descriptor = self.index.descriptor(SECTION_TEST_LINES)?;
        for index in 0..descriptor.count {
            let record = self.index.record(SECTION_TEST_LINES, index)?;
            if record[1..4].iter().any(|byte| *byte != 0)
                || record[12..16].iter().any(|byte| *byte != 0)
            {
                return Err(CoverageIndexError::InvalidRecord("test line record"));
            }
            if let Some(position) = position(record)? {
                details[position]
                    .lines
                    .push(crate::coverage_report::SourceLine {
                        file: self.string(get_u32(record, 8)?)?,
                        line: usize::try_from(get_u64(record, 16)?)
                            .map_err(|_| CoverageIndexError::SizeOverflow)?,
                    });
            }
        }
        let descriptor = self.index.descriptor(SECTION_TEST_HITS)?;
        for index in 0..descriptor.count {
            let record = self.index.record(SECTION_TEST_HITS, index)?;
            if record[1..4].iter().any(|byte| *byte != 0)
                || record[12..].iter().any(|byte| *byte != 0)
            {
                return Err(CoverageIndexError::InvalidRecord("test hit record"));
            }
            if let Some(position) = position(record)? {
                details[position]
                    .hits
                    .push(self.string(get_u32(record, 8)?)?);
            }
        }
        let descriptor = self.index.descriptor(SECTION_TEST_DECISIONS)?;
        let vectors = self.index.descriptor(SECTION_TEST_VECTORS)?.count;
        for index in 0..descriptor.count {
            let record = self.index.record(SECTION_TEST_DECISIONS, index)?;
            if record[1..4].iter().any(|byte| *byte != 0)
                || record[12..16].iter().any(|byte| *byte != 0)
            {
                return Err(CoverageIndexError::InvalidRecord("test decision record"));
            }
            if let Some(position) = position(record)? {
                let offset = get_u64(record, 16)?;
                let count = get_u64(record, 24)?;
                let end = offset
                    .checked_add(count)
                    .ok_or(CoverageIndexError::InvalidRecord("test vector range"))?;
                if end > vectors {
                    return Err(CoverageIndexError::InvalidRecord("test vector range"));
                }
                let mut observed = Vec::with_capacity(
                    usize::try_from(count).map_err(|_| CoverageIndexError::SizeOverflow)?,
                );
                for vector in offset..end {
                    observed.push(self.test_vector(vector)?);
                }
                details[position]
                    .decisions
                    .push(crate::coverage_report::TestDecisionResult {
                        id: self.string(get_u32(record, 8)?)?,
                        vectors: observed,
                    });
            }
        }
        Ok(details)
    }

    pub fn hit_metadata(
        &self,
        view: CoverageViewId,
    ) -> Result<Vec<IndexedHitMetadata>, CoverageIndexError> {
        let descriptor = self.index.descriptor(SECTION_HIT_METADATA)?;
        let mut metadata = Vec::new();
        for index in 0..descriptor.count {
            let record = self.index.record(SECTION_HIT_METADATA, index)?;
            if CoverageViewId::try_from(record[0])? != view {
                continue;
            }
            if record[2..4].iter().any(|byte| *byte != 0)
                || record[12..16].iter().any(|byte| *byte != 0)
            {
                return Err(CoverageIndexError::InvalidRecord("hit metadata record"));
            }
            let obligation = match record[1] {
                0 => "statement",
                1 => "function",
                2 => "branch",
                _ => return Err(CoverageIndexError::InvalidRecord("hit obligation")),
            };
            let metadata_label = self.optional_string(get_u32(record, 36)?)?;
            metadata.push(IndexedHitMetadata {
                id: self.string(get_u32(record, 4)?)?,
                obligation: obligation.into(),
                file: self.string(get_u32(record, 8)?)?,
                line: usize::try_from(get_u64(record, 16)?)
                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
                column: usize::try_from(get_u64(record, 24)?)
                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
                branch_kind: self.optional_string(get_u32(record, 32)?)?,
                label: (obligation != "branch")
                    .then_some(metadata_label.clone())
                    .flatten(),
                alternative: self.optional_string(get_u32(record, 40)?)?,
                parent_id: (obligation == "branch").then_some(metadata_label).flatten(),
                source: self.string(get_u32(record, 44)?)?,
                tests: self.relation_strings(get_u64(record, 48)?, get_u64(record, 56)?)?,
            });
        }
        Ok(metadata)
    }

    pub fn limitations(
        &self,
        view: CoverageViewId,
    ) -> Result<Vec<IndexedLimitation>, CoverageIndexError> {
        let descriptor = self.index.descriptor(SECTION_LIMITATIONS)?;
        let mut limitations = Vec::new();
        for index in 0..descriptor.count {
            let record = self.index.record(SECTION_LIMITATIONS, index)?;
            if CoverageViewId::try_from(record[0])? != view {
                continue;
            }
            if record[2..4].iter().any(|byte| *byte != 0)
                || record[40..].iter().any(|byte| *byte != 0)
            {
                return Err(CoverageIndexError::InvalidRecord("limitation record"));
            }
            limitations.push(IndexedLimitation {
                id: self.string(get_u32(record, 4)?)?,
                kind: self.string(get_u32(record, 8)?)?,
                file: self.string(get_u32(record, 12)?)?,
                source: self.string(get_u32(record, 16)?)?,
                reason: self.string(get_u32(record, 20)?)?,
                line: usize::try_from(get_u64(record, 24)?)
                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
                column: usize::try_from(get_u64(record, 32)?)
                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
                blocking: bool_field(record[1])?,
            });
        }
        Ok(limitations)
    }

    pub fn decision_metadata(
        &self,
        view: CoverageViewId,
    ) -> Result<Vec<crate::coverage_report::DecisionMeta>, CoverageIndexError> {
        let descriptor = self.index.descriptor(SECTION_DECISION_METADATA)?;
        let mut metadata = Vec::new();
        for index in 0..descriptor.count {
            let record = self.index.record(SECTION_DECISION_METADATA, index)?;
            if CoverageViewId::try_from(record[0])? != view {
                continue;
            }
            if record[1..4].iter().any(|byte| *byte != 0)
                || record[20..24].iter().any(|byte| *byte != 0)
                || record[56..].iter().any(|byte| *byte != 0)
            {
                return Err(CoverageIndexError::InvalidRecord(
                    "decision metadata record",
                ));
            }
            metadata.push(crate::coverage_report::DecisionMeta {
                id: self.string(get_u32(record, 4)?)?,
                file: self.string(get_u32(record, 8)?)?,
                source: self.string(get_u32(record, 12)?)?,
                kind: self.string(get_u32(record, 16)?)?,
                line: usize::try_from(get_u64(record, 24)?)
                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
                column: usize::try_from(get_u64(record, 32)?)
                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
                conditions: self.relation_strings(get_u64(record, 40)?, get_u64(record, 48)?)?,
            });
        }
        Ok(metadata)
    }

    fn decision_vector_observation(
        &self,
        index: u64,
    ) -> Result<crate::coverage_report::VectorObservation, CoverageIndexError> {
        let record = self
            .index
            .record(SECTION_DECISION_VECTOR_OBSERVATIONS, index)?;
        Ok(crate::coverage_report::VectorObservation {
            confidence: self.confidence(get_u64(record, 0)?)?,
            vector: self.test_vector(get_u64(record, 8)?)?,
            tests: self.relation_strings(get_u64(record, 16)?, get_u64(record, 24)?)?,
            phases: self.relation_strings(get_u64(record, 32)?, get_u64(record, 40)?)?,
            explicit_phases: self.relation_strings(get_u64(record, 48)?, get_u64(record, 56)?)?,
        })
    }

    fn decision_condition(
        &self,
        index: u64,
    ) -> Result<crate::coverage_report::ConditionResult, CoverageIndexError> {
        let record = self.index.record(SECTION_DECISION_CONDITIONS, index)?;
        if record[0] & !7 != 0 || record[1..4].iter().any(|byte| *byte != 0) {
            return Err(CoverageIndexError::InvalidRecord(
                "decision condition record",
            ));
        }
        let has_witness = record[0] & 4 != 0;
        let witness = if has_witness {
            Some([
                self.test_vector(get_u64(record, 16)?)?,
                self.test_vector(get_u64(record, 24)?)?,
            ])
        } else {
            None
        };
        let first_tests = self.relation_strings(get_u64(record, 32)?, get_u64(record, 40)?)?;
        let second_tests = self.relation_strings(get_u64(record, 48)?, get_u64(record, 56)?)?;
        if !has_witness && (!first_tests.is_empty() || !second_tests.is_empty()) {
            return Err(CoverageIndexError::InvalidRecord(
                "condition witness tests without witness",
            ));
        }
        Ok(crate::coverage_report::ConditionResult {
            index: usize::try_from(get_u64(record, 8)?)
                .map_err(|_| CoverageIndexError::SizeOverflow)?,
            source: self.string(get_u32(record, 4)?)?,
            covered: record[0] & 1 != 0,
            assertion_covered: record[0] & 2 != 0,
            witness,
            witness_tests: has_witness.then_some([first_tests, second_tests]),
        })
    }

    pub fn decision_details(
        &self,
        view: CoverageViewId,
    ) -> Result<Vec<crate::coverage_report::DecisionResult>, CoverageIndexError> {
        let metadata = self
            .decision_metadata(view)?
            .into_iter()
            .map(|meta| (meta.id.clone(), meta))
            .collect::<HashMap<_, _>>();
        let descriptor = self.index.descriptor(SECTION_DECISION_DETAILS)?;
        let observation_count = self
            .index
            .descriptor(SECTION_DECISION_VECTOR_OBSERVATIONS)?
            .count;
        let condition_count = self.index.descriptor(SECTION_DECISION_CONDITIONS)?.count;
        let mut decisions = Vec::new();
        for index in 0..descriptor.count {
            let record = self.index.record(SECTION_DECISION_DETAILS, index)?;
            if CoverageViewId::try_from(record[0])? != view {
                continue;
            }
            if record[1] & !3 != 0 || record[2..4].iter().any(|byte| *byte != 0) {
                return Err(CoverageIndexError::InvalidRecord("decision detail record"));
            }
            let executed = record[1] & 1 != 0;
            let covered = record[1] & 2 != 0;
            if covered && !executed {
                return Err(CoverageIndexError::InvalidRecord(
                    "covered unexecuted decision",
                ));
            }
            let range = |offset: usize,
                         available: u64,
                         label: &'static str|
             -> Result<std::ops::Range<u64>, CoverageIndexError> {
                let start = get_u64(record, offset)?;
                let count = get_u64(record, offset + 8)?;
                let end = start
                    .checked_add(count)
                    .ok_or(CoverageIndexError::InvalidRecord(label))?;
                if end > available {
                    return Err(CoverageIndexError::InvalidRecord(label));
                }
                Ok(start..end)
            };
            let observations = range(32, observation_count, "decision observation range")?
                .map(|index| self.decision_vector_observation(index))
                .collect::<Result<Vec<_>, _>>()?;
            let conditions = range(48, condition_count, "decision condition range")?
                .map(|index| self.decision_condition(index))
                .collect::<Result<Vec<_>, _>>()?;
            let id = self.string(get_u32(record, 4)?)?;
            let meta = metadata
                .get(&id)
                .cloned()
                .ok_or(CoverageIndexError::InvalidRecord(
                    "missing decision metadata",
                ))?;
            if conditions.len() != meta.conditions.len()
                || conditions.iter().enumerate().any(|(index, condition)| {
                    condition.index != index || condition.source != meta.conditions[index]
                })
            {
                return Err(CoverageIndexError::InvalidRecord(
                    "decision condition denominator",
                ));
            }
            decisions.push(crate::coverage_report::DecisionResult {
                meta,
                executed,
                covered,
                vectors: observations
                    .iter()
                    .map(|observation| observation.vector.clone())
                    .collect(),
                vector_observations: observations,
                conditions,
                tests: self.relation_strings(get_u64(record, 16)?, get_u64(record, 24)?)?,
                confidence: self.confidence(get_u64(record, 8)?)?,
            });
        }
        Ok(decisions)
    }

    pub fn phase_summaries(
        &self,
        view: CoverageViewId,
    ) -> Result<Vec<IndexedPhaseSummary>, CoverageIndexError> {
        let descriptor = self.index.descriptor(SECTION_PHASE_SUMMARIES)?;
        let mut phases = Vec::new();
        for index in 0..descriptor.count {
            let record = self.index.record(SECTION_PHASE_SUMMARIES, index)?;
            if CoverageViewId::try_from(record[0])? != view {
                continue;
            }
            if record[1..4].iter().any(|byte| *byte != 0)
                || record[48..].iter().any(|byte| *byte != 0)
            {
                return Err(CoverageIndexError::InvalidRecord("phase summary record"));
            }
            phases.push(IndexedPhaseSummary {
                id: self.string(get_u32(record, 4)?)?,
                kind: self.string(get_u32(record, 8)?)?,
                operation: self.string(get_u32(record, 12)?)?,
                source: self.optional_string(get_u32(record, 16)?)?,
                test: self.string(get_u32(record, 20)?)?,
                status: self.optional_string(get_u32(record, 24)?)?,
                caused_by_phase_id: self.optional_string(get_u32(record, 28)?)?,
                lines: usize::try_from(get_u64(record, 32)?)
                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
                decisions: usize::try_from(get_u64(record, 40)?)
                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
            });
        }
        Ok(phases)
    }

    pub fn anchors(
        &self,
        view: CoverageViewId,
        file: &str,
        line: usize,
    ) -> Result<Vec<IndexedAnchor>, CoverageIndexError> {
        let descriptor = self.index.descriptor(SECTION_ANCHORS)?;
        let mut anchors = Vec::new();
        for index in 0..descriptor.count {
            let record = self.index.record(SECTION_ANCHORS, index)?;
            if CoverageViewId::try_from(record[0])? != view {
                continue;
            }
            if record[3] != 0 || record[12..16].iter().any(|byte| *byte != 0) {
                return Err(CoverageIndexError::InvalidRecord("anchor record"));
            }
            let record_file = self.string(get_u32(record, 8)?)?;
            let record_line = usize::try_from(get_u64(record, 16)?)
                .map_err(|_| CoverageIndexError::SizeOverflow)?;
            if record_file != file || record_line != line {
                continue;
            }
            let total = usize::try_from(get_u64(record, 32)?)
                .map_err(|_| CoverageIndexError::SizeOverflow)?;
            let covered_conditions = usize::try_from(get_u64(record, 40)?)
                .map_err(|_| CoverageIndexError::SizeOverflow)?;
            let (kind, conditions, covered_conditions) = match record[1] {
                0 => {
                    if total == 0 || covered_conditions > total {
                        return Err(CoverageIndexError::InvalidRecord(
                            "decision anchor conditions",
                        ));
                    }
                    ("decision", Some(total), Some(covered_conditions))
                }
                1 => ("branch", None, None),
                2 => ("statement", None, None),
                3 => ("function", None, None),
                _ => return Err(CoverageIndexError::InvalidRecord("anchor kind")),
            };
            if kind != "decision" && (total != 0 || covered_conditions.is_some()) {
                return Err(CoverageIndexError::InvalidRecord("anchor conditions"));
            }
            anchors.push(IndexedAnchor {
                kind: kind.into(),
                id: self.string(get_u32(record, 4)?)?,
                file: record_file,
                line: record_line,
                column: usize::try_from(get_u64(record, 24)?)
                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
                covered: bool_field(record[2])?,
                conditions,
                covered_conditions,
                tests: self.relation_strings(get_u64(record, 48)?, get_u64(record, 56)?)?,
            });
        }
        anchors.sort_by_key(|anchor| anchor.column);
        Ok(anchors)
    }

    pub fn snapshot(&self) -> Result<IndexedCoverageSnapshot, CoverageIndexError> {
        Ok(IndexedCoverageSnapshot {
            all_summary: self.summary(CoverageViewId::All)?,
            passed_summary: self.summary(CoverageViewId::Passed)?,
            failed_summary: self.summary(CoverageViewId::Failed)?,
            all_files: self.file_gaps(CoverageViewId::All, None, None)?,
            passed_files: self.file_gaps(CoverageViewId::Passed, None, None)?,
            failed_files: self.file_gaps(CoverageViewId::Failed, None, None)?,
        })
    }
}

fn bool_field(value: u8) -> Result<bool, CoverageIndexError> {
    match value {
        0 => Ok(false),
        1 => Ok(true),
        _ => Err(CoverageIndexError::InvalidRecord("boolean")),
    }
}

fn decode_summary(
    record: &[u8],
    flags_offset: usize,
    base: usize,
) -> Result<CoverageSummary, CoverageIndexError> {
    let number = |offset: usize| -> Result<usize, CoverageIndexError> {
        usize::try_from(get_u64(record, offset)?).map_err(|_| CoverageIndexError::SizeOverflow)
    };
    let count = |offset: usize| -> Result<CoverageCount, CoverageIndexError> {
        let covered = number(offset)?;
        let total = number(offset + 8)?;
        if covered > total {
            return Err(CoverageIndexError::InvalidRecord("covered exceeds total"));
        }
        Ok(CoverageCount {
            covered,
            total,
            percentage: percentage(covered, total),
        })
    };
    let decisions = number(base)?;
    let executed_decisions = number(base + 8)?;
    let covered_decisions = number(base + 16)?;
    let conditions = number(base + 24)?;
    let covered_conditions = number(base + 32)?;
    if covered_decisions > executed_decisions
        || executed_decisions > decisions
        || covered_conditions > conditions
    {
        return Err(CoverageIndexError::InvalidRecord("summary count ordering"));
    }
    Ok(CoverageSummary {
        unmeasured_obligations: None,
        exact_fraction_pct: None,
        decisions,
        executed_decisions,
        covered_decisions,
        conditions,
        covered_conditions,
        condition_coverage_pct: percentage(covered_conditions, conditions),
        lines: count(base + 40)?,
        statements: count(base + 56)?,
        functions: count(base + 72)?,
        branches: count(base + 88)?,
        decision_outcomes: count(base + 104)?,
        condition_outcomes: count(base + 120)?,
        value_selections: count(base + 136)?,
        coverage_complete: bool_field(record[flags_offset])?,
        completeness_blocked: match record[flags_offset + 1] {
            0 => None,
            1 => Some(false),
            2 => Some(true),
            _ => return Err(CoverageIndexError::InvalidRecord("optional boolean")),
        },
    })
}

fn percentage(covered: usize, total: usize) -> f64 {
    if total == 0 {
        100.0
    } else {
        ((covered as f64 / total as f64) * 10_000.0).round() / 100.0
    }
}

#[cfg(test)]
mod tests {
    use std::{
        fs,
        path::PathBuf,
        sync::atomic::{AtomicU64, Ordering},
        time::{SystemTime, UNIX_EPOCH},
    };

    use crate::{
        coverage_analysis::{McdcVector, PointKind},
        coverage_report::{
            CoverageManifest, CoverageReportRequest, DecisionMeta, ExitCodeInput, PointMeta,
            RawTestResult, RuntimeSnapshot, TestProvenance, analyze_coverage_results,
        },
        query_index::{QueryIndexIdentity, write_query_index},
    };

    use super::*;

    static ROOT_SEQUENCE: AtomicU64 = AtomicU64::new(0);

    fn root() -> PathBuf {
        let nonce = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let root = std::env::temp_dir().join(format!(
            "supercov-coverage-index-{}-{nonce}-{}",
            std::process::id(),
            ROOT_SEQUENCE.fetch_add(1, Ordering::Relaxed),
        ));
        fs::create_dir_all(&root).unwrap();
        root
    }

    fn identity() -> QueryIndexIdentity {
        QueryIndexIdentity {
            evidence_sha256: [1; 32],
            evidence_bytes: 100,
            analysis_sha256: [2; 32],
            producer_sha256: [3; 32],
            archive_schema_version: 2,
        }
    }

    fn report() -> CoverageReport {
        let decision = DecisionMeta {
            id: "d".into(),
            file: "src/a.js".into(),
            line: 1,
            column: 1,
            source: "a && b".into(),
            conditions: vec!["a".into(), "b".into()],
            kind: "if".into(),
        };
        analyze_coverage_results(&CoverageReportRequest {
            run_id: "run".into(),
            manifest: CoverageManifest {
                unmeasured: Vec::new(),
                decisions: vec![decision.clone()],
                points: vec![PointMeta {
                    id: "point".into(),
                    kind: PointKind::Statement,
                    file: "src/a.js".into(),
                    line: 2,
                    column: 3,
                    source: "work();".into(),
                    label: None,
                }],
                branches: Vec::new(),
                limitations: vec![serde_json::json!({
                    "id": "dynamic",
                    "kind": "dynamic-code",
                    "file": "src/a.js",
                    "line": 3,
                    "column": 1,
                    "source": "eval(code)",
                    "reason": "dynamic source"
                })],
                scope: None,
            },
            raw_results: vec![RawTestResult {
                test_id: Some("test".into()),
                scope: None,
                test: "test".into(),
                test_file: Some("tests/a.js".into()),
                title: None,
                retry: Some(0),
                status: Some("passed".into()),
                expected_status: None,
                flaky: false,
                provenance: TestProvenance {
                    runner: "node:test".into(),
                    kind: "unit".into(),
                    project: None,
                    source: "runner-default".into(),
                },
                role: "test".into(),
                phases: Vec::new(),
                runtime: vec![RuntimeSnapshot {
                    decisions: vec![crate::coverage_report::DecisionSnapshot {
                        meta: decision,
                        vectors: vec![McdcVector {
                            values: vec![Some(false), None],
                            outcome: false,
                        }],
                    }],
                    hits: vec!["point".into()],
                    events: Vec::new(),
                    logicals: Vec::new(),
                }],
                browser: Vec::new(),
                server: Vec::new(),
            }],
            generated_at: "time".into(),
            coverage_model: None,
            integrity: None,
            test_exit_code: ExitCodeInput::Present(Some(0)),
        })
        .unwrap()
    }

    #[test]
    fn typed_columns_round_trip_all_outcome_views_without_json() {
        let report = report();
        let root = root();
        let path = root.join("query-index.v1.bin");
        write_query_index(
            &coverage_index_sections(&report).unwrap(),
            &identity(),
            &path,
        )
        .unwrap();
        let container = QueryIndex::open(&path, &identity()).unwrap();
        let index = CoverageIndex::new(&container).unwrap();
        assert_eq!(
            index.model().unwrap(),
            IndexedCoverageModel {
                schema_version: COVERAGE_MODEL_SCHEMA_VERSION,
                variant: report.view.variant.clone(),
                name: report.view.model.name.clone(),
                completeness_meaning: report.view.model.completeness_meaning.clone(),
                measured: report.view.model.measured.clone(),
                not_measured: report.view.model.not_measured.clone(),
            }
        );
        for (id, view) in [
            (CoverageViewId::All, &report.view),
            (CoverageViewId::Passed, &report.filters.passed),
            (CoverageViewId::Failed, &report.filters.failed),
        ] {
            assert_eq!(index.summary(id).unwrap(), view.summary);
        }
        let gaps = index.file_gaps(CoverageViewId::All, None, None).unwrap();
        assert_eq!(gaps.len(), 1);
        assert_eq!(gaps[0].file, "src/a.js");
        assert_eq!(gaps[0].missing_mcdc_conditions, 2);
        let projection = index.projection(CoverageViewId::All, None, None).unwrap();
        assert_eq!(projection.summary, report.view.summary);
        assert_eq!(projection.tests, 1);
        assert_eq!(projection.setups, 0);
        assert_eq!(projection.test_outcomes.passed, 1);
        assert!(projection.source_scope.is_none());
        let line = index
            .line(CoverageViewId::All, "src/a.js", 2)
            .unwrap()
            .unwrap();
        assert!(line.covered);
        assert_eq!(line.tests, ["test"]);
        assert_eq!(line.confidence.level, "executed");
        let tests = index.test_summaries(CoverageViewId::All).unwrap();
        assert_eq!(tests.len(), 1);
        assert_eq!(tests[0].provenance.runner, "node:test");
        let decision = index.anchors(CoverageViewId::All, "src/a.js", 1).unwrap();
        assert_eq!(decision.len(), 1);
        assert_eq!(decision[0].kind, "decision");
        assert_eq!(decision[0].conditions, Some(2));
        assert_eq!(decision[0].tests, ["test"]);
        let point = index.anchors(CoverageViewId::All, "src/a.js", 2).unwrap();
        assert_eq!(point.len(), 1);
        assert_eq!(point[0].kind, "statement");
        assert_eq!(point[0].tests, ["test"]);
        let details = index.test_details(CoverageViewId::All).unwrap();
        assert_eq!(details.len(), 1);
        assert_eq!(details[0].retries, [0]);
        assert_eq!(details[0].attempts.len(), 1);
        assert_eq!(details[0].hits, ["point"]);
        assert_eq!(details[0].lines.len(), 1);
        assert_eq!(details[0].lines[0].line, 2);
        assert_eq!(details[0].decisions.len(), 1);
        assert_eq!(details[0].decisions[0].vectors.len(), 1);
        assert_eq!(
            details[0].decisions[0].vectors[0].values,
            [Some(false), None]
        );
        let hits = index.hit_metadata(CoverageViewId::All).unwrap();
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].id, "point");
        assert_eq!(hits[0].source, "work();");
        assert_eq!(hits[0].tests, ["test"]);
        let decisions = index.decision_metadata(CoverageViewId::All).unwrap();
        assert_eq!(decisions.len(), 1);
        assert_eq!(decisions[0].conditions, ["a", "b"]);
        assert_eq!(
            index.decision_details(CoverageViewId::All).unwrap(),
            report.view.decisions
        );
        let limitations = index.limitations(CoverageViewId::All).unwrap();
        assert_eq!(limitations.len(), 1);
        assert_eq!(limitations[0].kind, "dynamic-code");
        assert_eq!(limitations[0].line, 3);
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn index_preserves_catalogued_unstarted_tests_without_attempts() {
        let report = analyze_coverage_results(&CoverageReportRequest {
            run_id: "run".into(),
            manifest: CoverageManifest {
                unmeasured: Vec::new(),
                decisions: Vec::new(),
                points: Vec::new(),
                branches: Vec::new(),
                limitations: Vec::new(),
                scope: None,
            },
            raw_results: vec![RawTestResult {
                test_id: Some("unstarted".into()),
                scope: None,
                test: "unstarted".into(),
                test_file: Some("tests/a.rs".into()),
                title: None,
                retry: None,
                status: Some("unstarted".into()),
                expected_status: Some("passed".into()),
                flaky: false,
                provenance: TestProvenance {
                    runner: "rust-nextest".into(),
                    kind: "unit".into(),
                    project: None,
                    source: "selected-but-not-started".into(),
                },
                role: "test".into(),
                phases: Vec::new(),
                runtime: Vec::new(),
                browser: Vec::new(),
                server: Vec::new(),
            }],
            generated_at: "time".into(),
            coverage_model: None,
            integrity: None,
            test_exit_code: ExitCodeInput::Present(Some(100)),
        })
        .unwrap();
        let root = root();
        let path = root.join("query-index.v1.bin");
        write_query_index(
            &coverage_index_sections(&report).unwrap(),
            &identity(),
            &path,
        )
        .unwrap();
        let container = QueryIndex::open(&path, &identity()).unwrap();
        let index = CoverageIndex::new(&container).unwrap();
        let summaries = index.test_summaries(CoverageViewId::All).unwrap();
        assert_eq!(summaries.len(), 1);
        assert_eq!(summaries[0].outcome, "unstarted");
        let details = index.test_details(CoverageViewId::All).unwrap();
        assert!(details[0].retries.is_empty());
        assert!(details[0].attempts.is_empty());
        let projection = index.projection(CoverageViewId::All, None, None).unwrap();
        assert_eq!(projection.tests, 1);
        assert_eq!(projection.test_outcomes.unstarted, 1);
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn compiler_owned_scope_round_trips_without_javascript_scope_fields() {
        let mut report = report();
        let scope = serde_json::json!({
            "language": "rust",
            "model": "rust-source-v1",
            "crate": "fixture",
            "measurementComplete": false
        });
        report.view.scope = Some(scope.clone());
        report.filters.passed.scope = Some(scope.clone());
        report.filters.failed.scope = Some(scope);
        let root = root();
        let path = root.join("query-index.v2.bin");
        write_query_index(
            &coverage_index_sections(&report).unwrap(),
            &identity(),
            &path,
        )
        .unwrap();
        let container = QueryIndex::open(&path, &identity()).unwrap();
        let index = CoverageIndex::new(&container).unwrap();
        let projection = index.projection(CoverageViewId::All, None, None).unwrap();
        assert_eq!(
            projection.source_scope,
            Some(IndexedSourceScope {
                kind: "compiler".into(),
                language: "rust".into(),
                model: "rust-source-v1".into(),
                mode: None,
                roots: Vec::new(),
                unit: Some("fixture".into()),
                measurement_complete: Some(false),
                included: 0,
                excluded: 0,
                ambiguous: 0,
            })
        );
        assert!(index.scope_entries(CoverageViewId::All).unwrap().is_empty());
        fs::remove_dir_all(root).unwrap();
    }
}